Compare commits

..
557 Commits
Author SHA1 Message Date
shinyobjectz 1be8199c85 FP1b, FP14d, FP10a: tagged done. FP14d's every clause is built (teach, approve, pair, read and learn-notes label the one that judges; move takes rows up). FP1b's scripts, briefs and pages are EmbeddingGemma 2 rows and its stills and sounds go through the encoders picture and sound axes already read, as its status says; FP10a's one stuck axis (glow) holds out 0.90 on another on-device encoder, so no adapter or trainer was needed 2026-11-12 23:11:04 -08:00
shinyobjectz 3599e18b6f FP13a: a render's camera path is its own and a thing's vector is its patch tokens. things.rs moved(): from the AOV pass's motion vectors (NAME.aov/motion), the median move of every pixel as the pan and the median move out from the middle after the pan as the zoom, eight times a second, with no model run; footage keeps raea-perceive flow. On the lurch red-team render it reads -0.063 then -0.190 frames a second (the scene trucks 0.02 then 0.06 a frame), where flow read -0.015 then -0.066, and 0 on the two renders whose camera holds still. pooled(): a thing's one vector is its frame's SigLIP 2 patch tokens averaged over the cells its mask covers half of or more, in place of the box pooled; fingerprint-things no longer needs image. Not yet: footage's camera path from Depth Anything 3 (the port gives depth only). 2026-11-12 23:11:04 -08:00
shinyobjectz 923163e7b9 FP5a: a reading keeps the layers under its pin. On a render with a layer pass, pinned() reads the layer-pass names under the pin's x,y at its moment (located.rs layers, now public) into the reading, and the reader's prompt says "pinned on NAME". On the things red-team render a pin on a block reads Box and one on the empty sky none (ignored test layers_under_a_pin). FP5a is tagged done with its status: read, readings, learn-notes 2026-11-12 22:34:25 -08:00
shinyobjectz 691673f616 FP11b: a mark on a defect note is followed through its whole shot. grow.rs through: the shot around the note from raea-perceive cuts (at most 8 s either side), EdgeTAM forward and back at 4 frames a second, and one region for each 2 s window where it kept the thing on half its frames or more, the box around it there; the note's own window always, at the mark. learn-notes makes one row a kept window (one row over the label's span without raea-perceive). cuts() moves from things.rs to grow.rs for both. On the things red-team renders a mark on a still block kept both windows at its layer-pass box (overlap 0.97) and one on a moving block followed it across the frame (0.41) 2026-11-12 22:29:45 -08:00
shinyobjectz edd00ee9ca CI installs cargo-shear 1.14.0 and cargo-dupes 0.2.1, the versions L0 runs, not whatever is newest: cargo-shear 1.14.1 (out 11-13) calls engine/cli's ignores for its feature-only dependencies on raea-runtime-bake and raea-runtime-sound redundant, which 1.14.0 needs, so main's gates went red from 43cfe8712 on 2026-11-12 22:25:18 -08:00
shinyobjectz 23f5a5ce53 Skills: raea-skills 7c835cc (release-012) for 0.1.2: fingerprint-where 9cad448 (score names where in the frame and the layers there; cli.md from raea's help after FP12a) merged with raea-skills main (#52, #53: the plugin's directory edition), the directory edition rebuilt from the skill, and reference/files.md from the app 0.1.2 ships (~/.raea/fingerprints, the storage files). skillcheck --strict and tools/skills.sh check with SKILLS_STRICT=1 pass 2026-11-12 22:19:06 -08:00
shinyobjectz a5a81f22b8 The manual's raea fingerprint page from raea's help after FP12a: bootstrap also trains patch heads that say where in the frame a picture defect is, and score's first moments say where and the layers there 2026-11-12 22:15:11 -08:00
shinyobjectz e05cee0c73 Windows app launch (#124): bytes become a string a 32 KB slice at a time, not String.fromCharCode(...bytes), which passed every byte as an argument and overflowed the stack on a blob of a few hundred KB (FileReader's readAsDataURL and readAsBinaryString, fetch's request body, a WebSocket's binary send, and the node shim's Buffer toString latin1); @raea/ui's platform has one latin1() for all of them, with a test of a 4 MB buffer. A frame's root-absolute script (/artifact.js) is found under the page's roots on Windows too: against a page at file:///C:/... it is C:\artifact.js, which only a leading / was taken for 2026-11-12 22:11:45 -08:00
shinyobjectz 50a695f0fb FP3b, FP5b, FP5c, FP12b, FP13b: decided for 0.1.2. FP3b closes on its first clause and its second moves to FP5c; FP5b's gate stays (no readings are checked yet, so notes train nothing); FP5c isn't measured on unchecked readings; FP12b and FP13b wait on Shane's own marks, so no grounder ships 2026-11-12 22:08:25 -08:00
shinyobjectz c65baf2c81 FP12a: patch heads say where in the frame a picture defect is. raea fingerprint bootstrap also puts FP0f's local defects in a random box of up to 6 frames a source (a blurred patch, a black hole, heavy grain, flat grey, a local glow; one that changes its box by under 6 levels is left out) and fits a logistic on SigLIP 2's 196 patch tokens per axis. Held out by source from 8 frames on 27 real renders: barren 0.92, glitch 0.90, blur 0.88 (0.79 before the visible rule), glow 0.49; an axis says where only at 0.85. score gives a flagged moment its place and the layers under it, by name (raea-sys-layers reads names); --json has at, the sheet boxes it in amber 2026-11-12 22:08:25 -08:00
shinyobjectz d679fa1cc4 LR10, LR11: done. LR0 lists the gap left after LR1-LR10 (23 of 33 pass; the 10 still off are LR10's list, each with its cause); #54 is closed with the harness's before and after and the cost per read, and #13 is answered with what now matches Chrome; the skills' motion router (raea-skills #50) merges into raea-skills main when 0.1.2 is published 2026-11-12 22:06:32 -08:00
shinyobjectz bf74492d50 docs/sdk-coverage.md retaken from main: 1557 of 1671 things reached (1548 before), the 3D camera's Hdr and feathers' theme components now typed in sdk/render, and seven more CSS longhands Blitz draws; the floor rises to 1557 2026-11-12 22:02:44 -08:00
shinyobjectz 43cfe87121 The SDK reference names the manual's examples where they use a component (hello, title, turntable), regenerated from main and these pages; the names check leaves a release's published notes as they were (docs/manual/whats-new: 0.1.0's canaries name the motion package by its name then) 2026-11-12 21:54:52 -08:00
shinyobjectz a2477cd71e Install page: raea skills install's hooks and Blender MCP server for every agent (and --no-hooks, --no-mcp), the Claude plugin from raea-skills with RAEA_NO_SKILLS=1 beside it, and the ALSA and fontconfig libraries Linux needs 2026-11-12 21:54:09 -08:00
shinyobjectz 33896c4518 The manual's install page says which GPUs raea draws on, and what runs without one (#110): a Windows PC with no DirectX 12 or Vulkan GPU (3rd-generation Intel graphics, for one) can't open the app's window or draw 3D; 2D video still renders on the CPU 2026-11-12 21:54:09 -08:00
shinyobjectz c7d7b59dfb The manual's install page for v0.1.1: pinning shows 0.1.1, and it says the desktop app comes from raea.io for the Mac, Windows and Linux and tells you when a new version is out 2026-11-12 21:54:09 -08:00
shinyobjectz 33380411d8 The manual's pages that raea.io/docs has served since 11-08 but no repository held until now (start/, concepts/, guides/3d|apps|words, examples/, whats-new/, index.md, and docs/manual.feature): written 11-08 by a session that has since ended and deployed from a working tree, they were parked on a branch so they couldn't be lost, and land for 0.1.2 so main's manual and the site are the same pages (16 links on main went to pages only the site had). It also holds the What's new pages for 0.1.0 and 0.1.1, made from their release notes by the release folder's whats-new.sh 2026-11-12 21:54:09 -08:00
shinyobjectz b537bcfffd The tour says how to consolidate the Inbox or a feed into a summary on its timeline, and that a working agent has a stop button beside it in the Agents list, the Feed's chat and the Inbox (raea-feed PR #1: c43ff66, 8fe9953) 2026-11-12 21:48:09 -08:00
shinyobjectz af293fcc35 Agents docs: each AI's own settings (agents.feature A7). Settings → Agents lists the AIs signed in on this Mac, each with what its ACP session reports it can be set to (thinking, mode, its own switches such as Claude's fast mode) plus environment and extra arguments; an agent on that AI shows the same settings, each defaulting to the AI's; they layer AI default, the Mac's defaults, the agent's, then the chat's model, and one that no longer applies becomes a notice 2026-11-12 21:48:09 -08:00
shinyobjectz e81d06dd8b Agents docs: no Director. The workspace has one primary, the harness at its root that takes whatever nothing else was picked for (a connected AI on a model, or one of the person's agents); New chat's menu picks a connected AI's model or an agent; an agent is a provider with more on top, kept in the workspace's folder (agents.feature A1c, A6) 2026-11-12 21:48:09 -08:00
shinyobjectz 96d2820589 A ShaderMaterial's shader is its colour pass's only: a prepass keeps Bevy's own fragment, which writes the normals and motion the prepass targets expect. Under Solari the camera has a normal and motion prepass, and the colour shader in it failed validation ("Error matching ShaderStages(FRAGMENT) ... prepass_pipeline") and Stay's fern dropped out. The three.js host draws <Instances> at each placement its data-at gives (sdk/render instances.tsx), as one InstancedMesh, instead of one mesh at the origin (sdk/r3f test/instances.test.tsx). docs/linux.feature is Shane's 11-11 plan for a faster Linux engine in the cloud: where a frame's time goes on Modal's GPUs, and the scenarios to test, validate and improve it (none started) 2026-11-12 21:46:51 -08:00
shinyobjectz 09eeb21fe9 LR10: getBoundingClientRect through a perspective is the box of the four corners as drawn, as Chrome's is. blitz-dom's transformed_bounds took each node's affine transform only, so a card turned under a perspective (its Projection) read at its flat size and place; one in a preserve-3d context maps from its context root's parent. A blitz-dom test holds Chrome's numbers for a 400x200 card under a 1000px perspective, rotateY(60deg), flat (379.05, 379.05, 206.19, 241.90) and in a world turned rotateX(10deg). transformed_rect maps any rect in a node's box, and a render manifest text's ink goes through it. snapcn 21 -> 23 of 33: card-rail 161.4 px off -> 0.6, announce-title 11504 -> 43.5, punch-lines and text-rewrite pass; P26 unchanged (185 of 215, every frame at the same SSIM) 2026-11-12 21:45:09 -08:00
shinyobjectz ea5fc2e5ef MX1, MX2: raea-sys-mlx, MLX on Apple silicon's GPU beside raea-sys-ml's ONNX Runtime (docs/mlx.feature)
On mlx-rs =0.34.0 (MIT OR Apache-2.0), which builds MLX v0.32.2 from source with cmake at build time. The dependency
is macOS-only, so the crate is empty on Linux and Windows. A model's MLX path is plain functions over its safetensors,
read by the checkpoint's own tensor names (weights.rs), with f32 tensors in and out (tensor.rs) and layers that do
PyTorch's maths (nn.rs): a Linear runs in its weight's dtype; LayerNorm, GELU and SiLU run in f32; attention is MLX's
fused kernel. Tests check each layer against the same maths in plain Rust on the CPU. f32 matmuls run in TF32 on the
GPU by default (within 3e-3; 1e-5 with MLX_ENABLE_TF32=0). use_metallib points MLX at a fetched metallib (MX4). No
model uses it yet: IDOL, which was to be first, is held.
2026-11-12 21:28:48 -08:00
shinyobjectz d415e0c59d Skills: raea-skills d5100dc (fingerprint-docs, on component-name 278f4ff): the skill teaches raea fingerprint things with raea check --things on a 3D shot (and its copy of the scenes guide), the post-mortem when a project is finished, and that a script scores on text axes only; cli.md gains check --things and fingerprint things (merged to raea-skills main when 0.1.3 is published) 2026-11-12 21:28:00 -08:00
shinyobjectz 7452b0d90c FP13: the scene guide's motion step runs raea fingerprint things and raea check --things on a moving shot (lands with raea-skills d5100dc, the guide's copy) 2026-11-12 21:25:42 -08:00
shinyobjectz d6d97c3b8d FP13, FP2f, FP1b: the manual and the scene guide teach fingerprint things with raea check --things, the post-mortem and scripts; docs/fingerprint.md says realness was measured and not shipped, and what FP1b's text column and FP13's things read 2026-11-12 21:24:34 -08:00
shinyobjectz 6c106fb8f4 FP1b: an axis judges only what a file has. A script scored with raea's own taxonomy came back blurry, glowing and frozen, because picture heads scored its empty picture columns; now each axis needs rows of its own modality, and a script's windows say nothing until an axis reads text (tested) 2026-11-12 21:22:19 -08:00
shinyobjectz 869318073a LR10: a family raea/text's loadFont asked for gets Google's faces in the page even where raea bundles faces of that name, as a linked stylesheet's @font-face shadows a local font in Chrome. Inter is bundled (static 400 and 700), so it was never a missing family and Google's never came: 300, 400 and 500 drew alike ("snapcn" at 100px 345.45 px; Chrome 340.39, 345.47, 350.45) and 600 as 700. Now 340.33, 345.45, 350.48, 355.38, 360.45. snapcn 18 -> 21 of 33 (wordmark-cut, text-select, hero-launch pass; punch-lines 18.1 -> 0.9, text-rewrite 7.4 -> 0.2); P26 unchanged (185 of 215, every frame at the same SSIM). LR10 records the read cost: the first read in a frame about 0.39 ms, each further one about 0.01 ms (300 frames, median of 6), and karaoke-captions' reads under the run's noise 2026-11-12 21:21:05 -08:00
shinyobjectz cd268ef764 FP7a: archiving a project runs the post-mortem in the background (raea-feed PR #5) 2026-11-12 21:11:27 -08:00
shinyobjectz b8d21bf712 FP2f: raea-sys-fingerprint-things holds things and geometry (the camera-speed, floating, passing-through and empty-frame reads), split from raea-sys-fingerprint-use to keep each crate under 2,000 lines 2026-11-12 21:09:35 -08:00
shinyobjectz e652168202 FP2f: realness measured, not shipped. A head on a sound's CLAP and YAMNet means, labels by construction: raea's SAO foley, TokenSynth notes and Fish narration against recorded foley, instrument notes and speech under CC0 and CC BY (Clotho, NSynth, LibriSpeech). Held out by generator it scores TokenSynth 0.90, Fish 0.80 and SAO 0.57, under the 0.85 it needs on all three, so it isn't an axis 2026-11-12 21:06:06 -08:00
shinyobjectz 6abeb6ed43 LR10: a Google family from raea/text's loadFont is fetched when loadFont is called, and a canvas's measureText and svg text have it. The page fetched it at the first layout that named it, after a component's first effect had measured (its canvas found the fallback), and a family the page fetched first was cached without ever reaching usvg's font database, so document.fonts.load found it already known and gave the canvas nothing. Figtree's "scene" at 600 64px measured 145.72 (the fallback) against Chrome's 171.25; now 171.26. blitz-dom leaves out an app-bundled svg face of a family the page already gave (Geist fetched at import came before the bundled Geist, and both stayed; tested). snapcn 17 -> 18 of 33: bloom-lockup passes (40.8 px off before), word-gather 25.5 -> 1.2; P26 unchanged (185 of 215, every frame at the same SSIM) 2026-11-12 21:04:41 -08:00
shinyobjectz 3dc3096963 Skills: raea-skills 278f4ff (component-name, on fingerprint-fix 6047418): the graphics router teaches raea component list, add and --shared, and the motion guides' copies say raea component add (merged to raea-skills main when 0.1.3 is published) 2026-11-12 21:00:01 -08:00
shinyobjectz 55d9eeaa50 raea component, raea part's new name in 0.1.3 (Layout LY1-LY4), in what teaches it: each ready component's header (examples/parts, the registry the CLI copies from), the edit template, the craft guides (motion.md, motion/parts.md, motion/footage.md) and the manual's raea part page, now the old name of raea component. The graphics router in raea-skills teaches component list, add and --shared (raea-skills component-name 278f4ff); the skills check's coverage no longer finds raea component untaught 2026-11-12 20:36:08 -08:00
shinyobjectz bf984d4656 Skills: raea-skills 6047418 (fingerprint-fix): SKILL.md tells an agent to check a fix with raea fingerprint score NEW --was OLD, and reference/cli.md is regenerated 2026-11-12 20:34:49 -08:00
shinyobjectz 0902d43201 FP10a: glow, stuck under the gate on its look columns (held out 0.79 on 580 labels in the 'me' fingerprint), holds out 0.90 on SigLIP 2's picture columns, an encoder already on the device, so raea's base taxonomy reads glow from pictures, as FP4b's bootstrap already measured it; no adapter was needed 2026-11-12 20:32:56 -08:00
shinyobjectz 5189132ef8 LR10: a canvas's system-ui and BlinkMacSystemFont are macOS's SF ("System Font", variable in weight and optical size), as Chrome's canvas takes them. fontdb knew neither name, so a font list headed by them (snapcn's '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif') was measured and drawn in Helvetica, about 10% wider at 72px, and 600 measured as 700. -apple-system alone stays as it is: Chrome's canvas finds no face for it either. text-build, which places its words from measureText, goes from 9 px off Chrome to 1.3; the rest is SF's trak table, which CoreText applies and usvg doesn't 2026-11-12 20:30:01 -08:00
shinyobjectz 0f9da00368 LR10: kerning across spans, hidden inline words, and a render manifest read as Chrome draws. blitz-dom gave every composition span a border edge (with border-style none a border's computed width is still medium, and inline_edges read the width alone), so each plain span got a spacer box at both ends and parley split the shaping there: a line set a letter a span lost its kerning (AVAWATAVAWAT 632 px, Chrome 578; snapcn's word-flip 5.6 px wide). sdk/ui/parity's p13-text/kerning-spans holds it. blitz-paint doesn't draw a visibility: hidden inline element's glyph runs, though they keep their place (#13: word-flip's strut drew as a fake word). A still drawn again after an all-black first draw replaces its manifest entry instead of adding one (every later frame was listed a place late), and check.sh finds frames by number. A manifest text's ink spans its glyph runs and inline-blocks, not the padding at a line's ends. snapcn 12 -> 17 of 33 (word-flip, text-reveal, text-swell, karaoke-captions, word-captions); P26 unchanged (185 of 215, the same frames at the same SSIM). The web-components guide lists innerHTML and outerHTML as missing 2026-11-12 20:30:01 -08:00
shinyobjectz 9632d542cd LR10: the 2D context's roundRect and arcTo geometry move to paths.ts beside the Path they draw on (context.ts was 517 lines with letterSpacing and wordSpacing, over the 500 limit); the motion guide's rule 2 (sdk/guides/craft/motion.md, which raea-skills copies) says what a composition's DOM answers 2026-11-12 20:30:01 -08:00
shinyobjectz d9a5296796 Skills: raea-skills 1a321b5 (on fingerprint-ref), the motion router's rule 2 names the web APIs a composition's DOM answers and the raea modules that install them (raea-skills #50, merged to raea-skills main when 0.1.3 is published) 2026-11-12 20:30:01 -08:00
shinyobjectz 53d5f94888 LR2: every host that runs a composition answers its layout reads. Live play (preview, raea play, the app's stage, an exported game) answers from its live page, synced mid-settle as a render's is. Live play's lite runtime set no refs (a ref was null, a canvas drawn through one drew nothing): its hosts now keep bevy-react's BevyElement, BevyCanvasElement and BevyTextNode linked as React's tree is and set and clear refs, and entry_lite installs canvas2d and the DOM reads. raea world answers from the page it lays its frames out with; a baked timeline (raea play --baked) refuses a read plainly instead of baking it as 0. #54's repro played live puts "here" at x 342 (x 0 before); every layout-reads probe played live is its render's frame (SSIM 1.000), and the games replay (pong, platformer, lite against React) stays 1.000. A read costs a live frame about 1.5 ms (step p50 0.4 -> 1.9 ms, one read a frame on a 40-line page) 2026-11-12 20:30:01 -08:00
shinyobjectz a504787ad3 LR11: where the docs stand (the manual's web-components guide, raea-skills #50 held until 0.1.3 is published) and what's open (#54, #13) 2026-11-12 20:30:01 -08:00
shinyobjectz 05fb89ab72 LR11: the manual's guide to web components that measure (docs/manual/guides/web-components.md): what a ref, document and window answer as Chrome does, the frame held until a measure lands, and what a composition's DOM lacks (MutationObserver and IntersectionObserver never call back, an img's onError never fires, one rect for a wrapped Range) 2026-11-12 20:30:01 -08:00
shinyobjectz 44ca3f16d6 LR10: a page's fonts as Chrome finds them, in svg and canvas text. An @font-face face is found by its own weight and style, not its file's (Google serves one variable Inter as every weight, whose file says 400, so 500 drew as 400 and 600 as raea's bundled 700); a face given twice (document.fonts.load and the page's @font-face) is added once; a page's faces of a family shadow the app's bundled ones, as @font-face shadows a local font (raea's static Inter 400 beside Google's 400 read to canvas text as a family split by unicode-range); and a character's advance is read at the weight asked for (a space's moves with a variable face). The canvas has letterSpacing and wordSpacing, shaped by the host. snapcn: title-sweep 3.7 -> 0.3, spec-sweep 4.4 -> 0.3, sky-lockup 15.7 -> 0.3; the corpus 12 of 33 (7 before LR10) 2026-11-12 20:30:01 -08:00
shinyobjectz 8a51aa0433 LR10: svg text spaces its last letter as Chrome does. usvg 0.48.1 left letter-spacing off a text chunk's last cluster, so an svg <text> with letter-spacing and a middle or end anchor was drawn half or a whole spacing off where Chrome draws it, and its box was a spacing short. vendor/usvg patches apply_letter_spacing (marked raea:), canvas.svgText's length drops the tracking it added to make up for it, and the layout-reads box reader skips an svg's <title> and <desc>, which are never drawn. snapcn: drop-line 1.3 -> 0.2 and hello-zoom pass; P26 unchanged (the six fixtures under the bar fail the same frames at the same SSIM on a binary without the patch) 2026-11-12 20:30:01 -08:00
shinyobjectz 677ca278ba FP13a, FP13c, FP10a: raea fingerprint things FILE finds a piece's shots, its things with their depth and the ground under them every half second and a SigLIP 2 vector each (a render's things from its layer pass, NAME.layers, and its depth from its AOV pass when beside it, with no model run; footage's from the marks on its notes, followed by EdgeTAM, on Depth Anything 3 Small), and the camera's path (Lucas-Kanade flow); geometry.rs measures floating, passing through, a camera that changes speed mid-move and an empty frame, each with red-team cases, and raea check --things reports them as findings, never heads. The layers file reader moves from runtime/world into raea-sys-layers so both read it, and raea-perceive depth-values takes many frames to one model load. report names the axes stuck under the gate with 300 labels or more, the only ones that may try another encoder or an adapter 2026-11-12 20:28:09 -08:00
shinyobjectz 9eb649bf98 FP1b: scripts, briefs and pages get EmbeddingGemma 2 rows, a passage a step on their timeline (raea-sys-columns gemma.rs on ort with the q8 export the app's library keeps in ~/.raea/models, the same vectors transformers.js gives), and an axis with modality "text" scores its words as EmbeddingGemma 2 queries against 24 ordinary passages; a still or storyboard frame is one frame through SigLIP 2. Evidence written before the text column reads as the same rows with no text, and a fingerprint pinned before EmbeddingGemma 2 was on the machine keeps working 2026-11-12 20:28:08 -08:00
shinyobjectz 1e8c404738 FP11b: grow.rs's union widens a box in a loop 2026-11-12 19:24:22 -08:00
shinyobjectz 535acb5a4f FP11b: a mark's region and a matte's box share one union (grow.rs), and raea-perceive is looked for beside raea, then on PATH, in a loop of its own 2026-11-12 19:23:25 -08:00
shinyobjectz 8579b43228 FP9a, FP7a: the CLI reference describes score --was and postmortem's --ask and --tally, regenerated from raea help 2026-11-12 19:22:18 -08:00
shinyobjectz e367fe8190 FP9a, FP7a: a fix checked against the flag it claims to fix, and a postmortem. raea fingerprint score NEW --was OLD says whether each of OLD's gating flags is fixed, still there, or looks disguised (nearer the axis's disguised defects than its clean work), and exits 1 unless all are fixed (fixed.rs). raea fingerprint postmortem [PROJECT] [--ask N] [--tally] scores every version in the project's feed, asks at most ten yes/no questions in the app where a head goes against the person's labels or is least sure, each with its moment as a clip, and --tally makes the answers evidence and prints each head's held-out AUC before and after (postmortem.rs) 2026-11-12 19:20:35 -08:00
shinyobjectz c6acc16633 FP11a, FP11b: a note's marks teach. learn-notes makes a defect note's mark, box and lasso its row's region, grown and tracked over the label's span by EdgeTAM (raea-perceive track, from the note's frame forward and back; frames it loses dropped; grow.rs in raea-sys-fingerprint-use), and a span pin the row's time. The review player's marks and the agent's reading of arrows and strikes are in raea-feed 2026-11-12 19:20:35 -08:00
shinyobjectz 6c7889dbf7 Claude plugin: raea's marketplace installs raea-skills' plugin (its skills/ folder: the raea skill and its two hooks) instead of a second raea plugin of its own, whose manifest said 0.1.0 and carried no hooks. The README says how to install it 2026-11-12 19:03:08 -08:00
shinyobjectz 620ccb4093 Email plan (docs/email.feature): sign-in by emailed code, invites and review links by email, two-factor, notices, and raea news, the list people opt into and out of (EM10). Status 11-12: raea.io verified in Resend, DNS added, sign-in by email and the list live 2026-11-12 19:01:15 -08:00
shinyobjectz aca025d343 FP14d: the CLI reference describes move's flags (--to, --source, and --project's meaning with move), regenerated from raea help 2026-11-12 18:57:32 -08:00
shinyobjectz e4b607e7f8 FP14d: a note or mark teaches the fingerprint that judged the piece. teach, approve and pair already label the one which picks for the file; read, readings and learn-notes now keep a project's notes in the one that judges the project ([PROJECT] on readings and learn-notes), and learning again remakes only those notes' rows. raea fingerprint move [--fp CHILD] [--to PARENT] --axis/--source/--project takes a child's own matching rows up into a fingerprint it extends and retrains both; rows on an axis the parent lacks or the child overrides stay 2026-11-12 18:53:03 -08:00
shinyobjectz 0226baca9a FP14a: raea/brief's reference page lists the fingerprint types brief.ts exports (Fingerprint, Axis, Applies, Modality and fingerprint()) 2026-11-12 18:43:27 -08:00
shinyobjectz 760fcc9ec8 FP2c: raea-sys-fingerprint is a facility: raea-sys-fingerprint-use scores, compares and picks with its taxonomy, evidence and heads 2026-11-12 18:39:11 -08:00
shinyobjectz 4dcfa760b1 FP2c: Cargo.lock without half in raea-sys-fingerprint and serde_json in raea-sys-fingerprint-use, which neither uses now 2026-11-12 18:35:52 -08:00
shinyobjectz 85b877f06b skills pin: raea-skills fingerprint-ref (c5bfd05), on its main (cb8904f, #51), held off main until 0.1.3 ships: the skill scores a cut with the person's fingerprint before posting it and names raea/fingerprint, and reference/sdk.md lists raea/fingerprint 2026-11-12 18:34:47 -08:00
shinyobjectz 28fd448ea2 FP2c: fingerprint folded into what it copied, as L1's duplicate check asks. The ledger says its rows' labels, counts and projects once for training, inheritance, pairs and the bootstrap; one half-float codec serves the column cache and a fingerprint's words and evidence; a verb's files and a list's lines are read once; raea check's defects and its sound rules share their level in dB and their moments as issues; Encoders::pins is a map; the bootstrap names its own rows and each sense's defects once 2026-11-12 18:33:37 -08:00
shinyobjectz db58ead2c9 FP14a: room for fingerprint in L1's checks. raea/fingerprint gets its SDK reference page under Tools, every field of a fingerprint.ts described; the four crates have their layers; raea-sys-fingerprint-use drops serde_json, which it never used; and raea-cli's hook and check dispatch are one line each, as world, findings and notes are, keeping the crate at its 2000 lines with raea fingerprint in it 2026-11-12 18:21:27 -08:00
shinyobjectz 6f253b3fe5 FP5a, FP6b, FP6c, FP6e, FP8c, FP14c, FP14e: raea fingerprint pair WORSE BETTER records a pick or a hand edit as a pair, fit Bradley-Terry and held out by project, and an axis with pairs and no labels is ranked by them alone; versions makes weak pairs of noted moments the next version changed and nobody noted again; profile takes the ranges work you admire spans (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside, where and which way; read has a fresh session read a project's pinned notes into kinds and axes, readings puts them to you in the app and tallies your answers, and learn-notes trains on them only once you've agreed with 45 kinds and 40 axes in 50; reembed moves evidence to this machine's encoders where its media is found, each row keeping the pin it was embedded on; new --kinds --tags writes where a fingerprint applies; bootstrap leaves gaps and clipping out of windows too quiet for them to change. Scoring, the sheet, which, diff and profiles move to raea-sys-fingerprint-use, keeping raea-sys-fingerprint under its size. The guide (docs/manual/guides/fingerprint.md) and every new flag in the CLI reference 2026-11-12 18:14:51 -08:00
shinyobjectz 64dfd63cd7 FP2e, FP4b, FP6a, FP6d, FP8a, FP8b, FP14b, FP14c: a test that word heads score the spike's noise and clipping from words alone (0.987, 0.975); every mechanical axis carries a cheat (darkened half as much, a white flash, a gap a third as long, clipping a third as hard, beside the de-rez sharpened after, half glow, quiet noise and a zoomed freeze); raea fingerprint approve makes approved work clean on every axis away from its notes; another eye's readings teach a head but never count toward its gate; a project's or workspace's fingerprint keeps its evidence a folder a person and each machine trains its own heads (raea fingerprint share); raea fingerprint diff A B lists the axes two tastes rank the same evidence most differently on; a fingerprint that extends another inherits its axes and evidence, its own labels counted twice and measured against each alone, an override learning from its own only and the parent never from the child; raea fingerprint which PATH and use NAME --in project|workspace pick the one that judges a piece (the project's that applies to its kind, its default, the workspace's, then the person's) 2026-11-12 18:14:51 -08:00
shinyobjectz fb11b58f6f FP1-FP4, FP14a: raea fingerprint. raea-sys-columns turns a video into one-second windows read by encoders that run on this Mac (SigLIP 2 for pictures, CLAP for sound, YAMNet for sound events, on ort; SigLIP never on Core ML's GPU), cached by content hash. raea-sys-fingerprint holds the taxonomy (each axis with its words, a fingerprint saying what it's for and what it builds on), the evidence ledger, small heads trained held out by source, scoring and the contact sheet. apps/fingerprint is the verb: new, bootstrap (known defects put into windows of real work), teach, score (--json, --sheet, --timeline), report, and a service that keeps the encoders loaded. raea check finds clipping, dropouts and flash frames as its own findings. sdk/raea types a fingerprint. 2026-11-12 18:14:51 -08:00
shinyobjectz f89873c1df FP14a: raea fingerprint in the CLI reference: its page under Check, each flag described, and the pages after it renumbered 2026-11-12 18:14:51 -08:00
shinyobjectz 853b6ab3dc FP0: Fingerprint, the plan and its spec: a taxonomy of axes with small heads over frozen on-device encoders (SigLIP 2, CLAP, YAMNet on ort; SigLIP on MLX once MX5 lands), trained from notes, marks, approvals and reference profiles, shared as evidence. FP0a-g hold the 11-12 measurements; FP1-FP13 are the build, with earshot (MIT) as the reference design 2026-11-12 18:14:51 -08:00
shaneandshinyobjectz a983349265 Release: ship only raea-skills' skill folders into share/raea/skills (#123)
raea-skills' skills/ is becoming its Claude plugin too (skills/.claude-plugin/plugin.json, hooks/, README.md,
icon.png), and release.sh copied that folder whole, so the installer, which copies every entry of
share/raea/skills into ~/.claude/skills, would have put the plugin's README, icon and hooks folder there beside the
skill. Now only folders holding a SKILL.md are staged, and _-prefixed ones (raea-skills' _template) stay out as
before. Tested on a mock skills/ with the plugin's files: raea/ alone is staged.

Co-authored-by: shinyobjectz <[email protected]>
2026-11-12 21:11:42 -05:00
Luke, I am your fatherandshinyobjectz ea741f6bef Page: give Blitz its viewport in device pixels (a Retina window's interface sits in a quarter of it) (#120)
* Page: Blitz's viewport is in device pixels, so a page at scale 2 fills its image (#119)

a78fb95 gives the app window's page the display's scale. With a scale other than 1, raea-sys-page still gave
Blitz a viewport whose window_size was the page's size in points. Blitz's window_size is in device pixels (it
divides by hidpi_scale for the CSS viewport), as the page's image and paint_scene already are, so on a Retina
display the interface was sharp but laid out in the top-left quarter of the window.

Page::px is the page's size in device pixels, used for the image, the paint and the viewport.

Nothing changes at scale 1.

* Page: the page's JS and its element list read the viewport in CSS px, and devicePixelRatio is the page's scale

With Blitz's viewport in device pixels, two readers of window_size in runtime/dom still took it for CSS px.
snapshot sent it as vw and vh with dpr 1, so at scale 2 innerWidth and matchMedia answered twice the width the
page is laid out at; elements tested boxes against a window twice the size, so elements up to a window's width
off screen were listed as visible. Both read the viewport's logical size now, and dpr is its scale.

tests/viewport.rs: a page at scale 2 lays a 100vw x 100vh element out at its size in CSS px; scale 1 is as it
was; a fractional scale rounds the image up.

Rebased onto main at 6da2995: main's LR1 (7fb2194) moved the layout snapshot into raea-sys-page (systems/page/src/snapshot.rs, snapshot_by, which a composition's page.layout answers too), so the vw, vh and dpr change is made there, and elements.rs re-exports it.

* Page tests: q and attr live in tests/common, which vars.rs and viewport.rs both use, not one copy each (dupes back to 293)

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-11-12 19:48:36 -05:00
shinyobjectz 5d181dae28 Skills: raea-skills 803dd07, files.md says the default workspace folder as raea picks it (~/Studio where workspaces already are, else ~/Documents/raea, or ~/raea when iCloud keeps Documents), as SKILL.md does (raea-skills #29) 2026-11-12 16:40:16 -08:00
shinyobjectz bb7e6716b4 raea's own commits name their author when git has no user.name: a Linux account with no full name (CI's runner, a container) failed every one with "empty ident name ... not allowed", so a new workspace was never made there (main's CI: workspace tests' a_new_workspace_and_project_have_the_layout on ubuntu-24.04). As git_cmd gives a fresh Mac an EMAIL, it names the author and committer for the account, only when no user.name is set 2026-11-12 16:35:10 -08:00
shinyobjectz 6cb250a531 Tutorials: Libraries and Share work for review name their tutorial in their front matter, as the other eight tutorials do, so raea.io's docs show each one's walkthrough player (its voiced script is already made) and step to it in the tutorials' order 2026-11-12 16:32:02 -08:00
shinyobjectz 99e3fe0751 Tutorials: Publish and the tour name YouTube, LinkedIn or Bluesky, the networks anyone can connect today
Shane, 11-11: "sync all publishing to the current status state". TikTok and Instagram wait on their app reviews
(raea-api's CONNECTIONS_LIVE), so the pages name live ones; the narration was re-voiced to match in the private repo,
and raea.io's v0.1.1 build lays these two pages over the release's docs until main carries them.
2026-11-12 16:32:02 -08:00
shinyobjectz ebff73dbc6 LR6, LR7: the canvas's text natives (measure, advances, svgText) are each a function of the fonts (raea_sys_canvas::TextNative), registered from one table and given the page's fonts by with_page_fonts, instead of three wrappers that did it alike; canvas.read's rectangle and svgText's tracking read without closures that copied raea-runtime-sound's (dupes back to 293/59)
Skills: SKILL.md's 7. Deliver (sources: runtime/export/src) checked, still true: the export's change only passes page.layout's request through.
2026-11-12 16:26:53 -08:00
shinyobjectz 734b172d34 LR8: done, 11-12: ResizeObserver from the page's layout, the silent observers, holds in passes that draw nothing, and the harness's Chrome that renders 2026-11-12 16:16:09 -08:00
shinyobjectz b30eb6aa88 LR7: done, 11-12: document, createElement, ranges, svg text measures and URL faces, as built and measured 2026-11-12 16:16:09 -08:00
shinyobjectz fb4572f284 LR6: done, 11-12: measureText and getImageData from the page's fonts and pixels, as built and measured 2026-11-12 16:16:09 -08:00
shinyobjectz eb8d3ad795 LR5: done, 11-12: el.style's writes and getComputedStyle's page values, as built 2026-11-12 16:16:09 -08:00
shinyobjectz 203c26621c LR10: the harness: the runs both sides make, and a Chrome that renders. An inline <svg>'s words are runs of their own, one per <text>, in the render manifest (from the svg's usvg tree, mapped onto the page) and in boxes.ts, where they had fallen into the nearest html box: drop-line's 'then ships the film t h e n t h e n'. Words hidden by visibility, a measuring copy, are skipped on Chrome's side as the manifest skips them. Chrome renders each frame in real time through Playwright (bench/layout-reads/chrome.ts, the same pinned Chrome for Testing): a headless --dump-dom under --virtual-time-budget runs no rendering step, so a component's requestAnimationFrame and ResizeObserver never ran on Chrome's side. probes/document.tsx (getComputedStyle, svg text, a Range, a node made and measured, word- and letter-spacing) and probes/observe.tsx (ResizeObserver) are new 2026-11-12 16:16:09 -08:00
shinyobjectz a5d89e95c1 LR7: a composition's document, with LR5's style and LR8's observers. LR5: el.style reads and writes the element's style (writes send an update op; React's next commit to the property wins), and getComputedStyle answers from the page's computed style: page.layout takes { styles: [ids] } and the snapshot carries s: {id: {property: value}} for them, as stylo serializes it (engine/page read.rs computed_style), kept until the next commit (page-layout.ts computedOf). LR7: document has body (the composition's surface, the element the page draws from), documentElement, getElementById, querySelector(All), createElement (appended into the composition it's laid out and measurable, removed it's gone; a canvas is an OffscreenCanvas), createTextNode and createRange: a Range over a text node is its characters laid out in the parent's computed font, placed where the parent's line starts. An svg <text> has getComputedTextLength, getNumberOfChars, getStartPositionOfChar, getEndPositionOfChar and getSubStringLength, laid out by usvg in the element's computed font (canvas.svgText: family, size, weight, letter- and word-spacing, font-variation-settings). document.fonts loads a family the composition asked for (fonts.load), and a FontFace given by URL is fetched through raea's cache into the faces an svg's and a canvas's text are set in (fonts.face). window is globalThis with innerWidth, innerHeight, devicePixelRatio and getComputedStyle. LR8: ResizeObserver calls back after a commit whose layout changed an observed element's size, and once on observe, with contentRect, borderBoxSize and contentBoxSize; while a delayRender hold is open it checks every 16 ms, as a browser renders while a page waits. MutationObserver and IntersectionObserver exist and never call back. A pass that draws no page (the sound pass, the 3D rows' pre-pass) answers reads with a 0 x 0 page, and its holds are released (page-layout.ts noPage): a hold waiting on a measure could never end there. probes/document.tsx and probes/observe.tsx match Chrome within 1 px 2026-11-12 16:16:09 -08:00
shinyobjectz 37fc50782d LR9: holds released as Chrome releases them. A composition holding its frame until an <img>'s onLoad is released: the load is told on the turn after the img is made or its src changes (sdk/raea dom-load.ts), through the host's events, as Chrome fires it once the picture is in (the page holds the frame for the picture itself). A hold released from requestAnimationFrame (two rAFs after a ref lands) is released: while a delayRender hold is open, rAF's callbacks run every 16 ms with the held frame's time (frame-globals.ts), as a browser keeps rendering while a page waits; <R3F>'s own hold doesn't pump. channel-thread, logo-collapse and pulsing-border, which LR9's real holds had stopped, pass again. settle.rs's held flag is set once per turn (no dead initial value) 2026-11-12 16:03:05 -08:00
shinyobjectz 34629d33b8 LR6: a composition's 2D context measures and reads back. measureText is the text shaped by usvg as the canvas draws it, in the page's fonts (canvas.measure: width, actualBoundingBox*, fontBoundingBox*, from the alignment point), and getImageData reads back what was drawn (canvas.read); raea-runtime-canvas serves both as natives, which @raea/ui's wire reaches through the composition's __ui_sync (sdk/raea canvas2d.ts). putImageData writes its pixels as they are (a put op). OffscreenCanvas is a canvas no page shows. raea's bundled faces (Inter and the rest) now reach usvg's font database too, so a canvas measures and draws them, not a fallback. probes/measure.tsx matches Chrome: width exact, ink and font box within 0.8 px, pixels read back equal 2026-11-12 16:02:32 -08:00
shinyobjectz 6da2995575 Layout L1: lint.rs's outside-import hint formats the shared path where it says it, so no closure copies direction/world.rs's (dupes back to 293/59) 2026-11-12 15:31:36 -08:00
shinyobjectz c7e857b243 Layout L1: the CLI crate back to 2000 lines (component and part's checks in one), workspace_of is shared_of (the loader only wanted shared/, and it duplicated godot_run's nearest_project), and the manual's raea component page (Projects group, --shared and --force described) 2026-11-12 15:19:50 -08:00
shinyobjectz 657664d7d9 Skills: raea-skills 8c6225c, the reference and SKILL.md for LY1-LY4 (project new's folders, @shared/); also brings in #46 (findings) and #47 (hold) already on raea-skills main 2026-11-12 15:13:33 -08:00
shinyobjectz cb87e0cd59 Layout LY1-LY4: a project's compositions/, components/, controllers/, assets/ and artifacts/, and the workspace's shared/ (docs/layout.feature)
Shane 11-12: reorganize the default project around compositions, components, controllers, assets and artifacts, with a workspace library any project can call on. It's named shared/ and @shared/ so it isn't confused with raea's media libraries.
- LY1: raea project new makes the five folders (each with a .gitkeep), out/, brief.ts, AGENTS.md and a tsconfig mapping @shared/* to the workspace's shared/. raea workspace init makes shared/ with the same five, and .gitattributes keeps assets/** and out/** in LFS.
- LY2: the engine's loader resolves @shared/<kind>/<name> by walking up to .raea/workspace, with a relative import's extensions and index files; outside a workspace it's refused with what to do. PJ8's lint takes @shared/ imports and names @shared/ as the fix for a climb into shared/.
- LY3: the scan reads compositions from compositions/ and components from components/ (and from shared/), lints a composition elsewhere as misplaced, says once that a project is in the old layout, and reads controllers as the project's over shared/controllers/ by id.
- LY4: raea component list/add [--shared] replaces raea part, which still answers this release.
2026-11-12 15:07:16 -08:00
shinyobjectz b3fe2699d0 LR9: "raea" exports delayRender(label?, { timeoutInMilliseconds }), continueRender(handle) and cancelRender(error) on the frame hold <R3F> already uses: the frame isn't marked done while a hold is open, and the last release draws it, so a composition that measures after a font, a fetch or a timer has that frame taken, not the one before. A hold not continued within its timeout (30 s) fails the render naming its label; cancelRender fails it at once, as a throw does. Settle lets a held frame wait up to HOLD_SECS (120 s) instead of failing it at its 20 s stall guard, so the hold's own named failure comes first. probes/hold.tsx sets its words after a timer under a hold and matches Chrome; a never-continued hold fails in 2.6 s naming it. The manual has its page (reference/sdk/hold.md) 2026-11-12 14:45:00 -08:00
shinyobjectz 8a2f9c78ab LR4: a composition's refs have the tree a web component walks and queries: children and childNodes, the first, last and sibling nodes, parentElement, tagName, nodeName and nodeType, id, className, classList, dataset, getAttribute, textContent, contains, matches, closest, querySelector and querySelectorAll, answered in JS from bevy-react's committed instances (sdk/raea's dom-tree, installed from the entry with dom-reads). Selectors cover tag, *, #id, .class, attributes, descendant and child, comma lists, :first-child, :last-child, :only-child, :nth-child and :not; anything else throws a SyntaxError, as Chrome's does. el.id is the id attribute as on the web: the bevy-react patch renames its reconciler id to nodeId, and canvas2d, dom-reads and useEntity read that. probes/tree.tsx prints every answer and matches Chrome's words 2026-11-12 14:26:20 -08:00
shinyobjectz 2d869d719b LR3: a composition's refs have the geometry a web component reads, from the page that draws the frame: getBoundingClientRect (a DOMRect, transforms included), getClientRects, offset* and offsetParent (untransformed, whole px, from the positioned ancestor's padding edge), client* and scroll*, each as Chrome answers it. bevy-react 0.8.1 gets a patch (sdk/react/js/patches, applied by bun install) that makes its instances a tree, BevyElement and BevyTextNode with their parent, children and committed props; sdk/raea's dom-reads puts the reads on BevyElement from the entry. #54's repro now puts "here" where Chrome does (x 342, was 0), and probes/geometry.tsx prints every read and matches Chrome's words. The bundle crate's stylesheet url() rewriter moves to raea-runtime-cssurls to leave it under 2000 lines 2026-11-12 14:18:19 -08:00
shinyobjectz 272b94e765 LR1: a pass with no page answers through layout::nothing_drawn() (one closure, not one per caller), and the two new crates have their layer (runtime) 2026-11-12 14:13:01 -08:00
shinyobjectz ee171c4f85 LR1: room for the layout reads in crates at their 2000-line limit. Matchmove (raea track, matchmove.solve) moves out of raea-runtime-react into raea-runtime-track, which react re-exports as scene::track; the frame pages' asset writer (store_page, store_clear, the writer pool) moves out of raea-runtime-export into raea-runtime-pagestore. page-layout installs itself on import, so the entry adds one line. A pass with no page answers NOTHING_DRAWN, and wait_flush takes the runtime's ask. page-layout and dom-reads are installed by the entry, so the manual's and the skill's references skip them as they skip canvas2d 2026-11-12 14:09:19 -08:00
shinyobjectz 7fb2194503 LR1: A composition reads its layout synchronously from the page that draws its frame (#54). Its JS asks page.layout and blocks; settle wakes on the ask as on a flush, applies the commits already sent, and the host lays its page out at the frame's time and answers every element's boxes at once, keyed by React id: raea-sys-page's snapshot (now runtime/dom's too), with offsets from blitz-dom's offset_rect and offsetParent. settle_with takes the host's answer; plain settle says the host lays no page out. Each runtime has its own ask (a render's 3D pre-pass and a bake's workers run beside it). The still, 3D and fed renders answer from their page; the sound pass and the 3D rows' pre-pass answer no boxes. sdk/raea's page-layout keeps the answer until the next commit or frame, so a composition that never reads makes no snapshot 2026-11-12 13:54:53 -08:00
shinyobjectz fc7bfa3a0c LR0: bench/layout-reads, compositions that measure their text and layout against headless Chrome: check.sh runs a corpus (modules exporting Comp, conf and props) at its first, middle and last frames in raea and in Chrome (React DOM in raea's Clock, mounted once its fonts are in), and compare.jq pairs their text runs by words (raea's manifest against boxes.ts, made the same way), box and ink within 1 px. probes/ is raea's own corpus, #54's repro first ("here" at x 0 where Chrome puts it at 342); snapcn's 33 run through the private tree's adapter. The baseline, recorded in docs/layout-reads.feature: 3 of snapcn's 33 pass (all hold-only); 13 of the 27 that measure throw and the rest drift up to 87 px 2026-11-12 13:42:42 -08:00
shinyobjectz 593ebb5226 LR0: Layout reads, the plan (docs/layout-reads.feature): compositions measure text and layout as Chrome does (#54), answered synchronously from the Blitz page that draws the frame; LR0 the snapcn harness against headless Chrome, LR1-LR2 the layout call and every host, LR3-LR8 the DOM on refs and document, LR9 delayRender, LR10-LR11 the bar, docs and the issues 2026-11-12 13:42:42 -08:00
shinyobjectz 97e03e7447 The black-frame warning reads only elements' boxes: asking a text node for its bounding rect panicked in blitz-dom (transform on a text node), so a render whose frame drew black twice crashed whenever near-black words came before anything with a colour of its own (snapcn's text-build and text-swell, 11-12). bench/black-frame gains RAEA_BLACK_FAULT=3 (every draw black, the canary healthy: the render warns, naming what the page shows) and a text-first case that panicked before this; regression from 559d8274e (#96), which isn't in 0.1.2's rc3 2026-11-12 13:21:04 -08:00
shinyobjectz 559d8274e0 A frame that comes out all black though its page shows something is a warning, said once over its run of frames (#96)
A frame black on two draws whose GPU passes its canary was kept as the scene's black with one stderr line, and every
later black frame was let through silently: #96's 4K handover lost frames 22-29 that way, the render reporting
success. Now, when such a frame's page shows something that isn't black, the render warns "black-frame" naming it
and where it's written ("frames 22-29: drew all black on two draws, though the page shows a rgb(34, 34, 34)
background (handover.tsx:31:3)"), in the run's findings: stderr, the manifest, the summary's count and raea check's.
A page that is black (a black background, nothing on it) says nothing, as before.

raea-page's visible_paint finds it: the first element shown on screen, not a video's holder, whose background or own
words' colour isn't black, with its source stamp; it shares the manifest's opacity and stamp walks, now functions of
their own. raea-core-facts' said_frame joins a frame's finding to the same one running on the frames just before it,
so a run prints one line and counts once. Both black checks of the page path call it (bevy_frame.rs's still and video
frames, render.rs's page over 3D). Left out, as on the issue: a fed MP4's frames, which never come back to the CPU.

RAEA_BLACK_FAULT=3 draws every frame black with the canary passing (a draw dropped whole, as #96's was), to test it.
Checked: a #222 page under that fault warns once over frames 0-5, the manifest holding one finding with frames [0, 6];
a black page under it says nothing. Test: said_frame merges a run and starts another after a gap (the two tests that
say and take findings hold one lock).

Skills (SK4): SKILL.md's "7. Deliver" names runtime/export/src and says nothing of black frames: checked, still true.
2026-11-12 12:49:42 -08:00
shinyobjectz 645b0853cc Compositions get the web's canvas 2D context, requestAnimationFrame and Image (#55, #56)
A <canvas> ref's getContext("2d") in a composition was bevy-react's recording context, whose API isn't the web's
(no fillRect, setTransform or createImageData) and whose draws nothing in raea reads: snapcn's dot-bloom and
orb-swarm threw, and a canvas drew nothing. sdk/raea's canvas2d.ts gives it @raea/ui's CanvasRenderingContext2D, the one
an app page has, whose display list goes to the element as its __canvas2d prop, which the page already draws into
the canvas's bitmap (systems/canvas). The context sends through the host's own _send when it has one (sdk/ui
paths.ts, context.ts). bevy-react's handle keeps no props, so a canvas's width and height (300 x 150 unset) are read
from the batches the bridge sends through the host's op_flush; set on the ref, they go to the element and clear the
bitmap, as in a browser. getImageData reads zeros in a composition (no host to read back from).

frame-globals.ts installs requestAnimationFrame, cancelAnimationFrame and Image where they're missing (#56). A callback
runs once, at the frame after it was asked for, given that frame's time (f * 1000 / fps), so a frame drawn again gets
the same calls: from the React entry's frame step and the live entry's draw. Image's load fires on the next microtask
once its src is set, so a preload resolves; it reports no pixel size.

The bundle pointed @raea/<package> imports only at packages listed whole; a module listed alone (@raea/ui/canvas, as
@raea/ui/plugin is) now resolves too (rewrite.rs point_sdks).

Checked: a composition drawing red, then lime under setTransform(1,0,0,1,50,50), draws both where Chrome would;
canvas.width reads its width prop (200), createImageData(2,2) is 2x2, rAF's time at frame 5 is 166.67 ms and an
Image's onload fires, across a 10-frame MP4. Tests: conformance/frame-globals.test.ts; point_sdks with @raea/ui/canvas.
2026-11-12 12:37:09 -08:00
shinyobjectz e165d0c4a8 Video with alpha (#113): a VP9 WebM's transparency and a ProRes 4444's are drawn, not refused or made opaque
A <Video> on the page was opened by the platform's decoder alone (Apple's on a Mac), which reads no WebM: a VP9 WebM
with alpha was refused, "no video track". The page now asks the backends in raea-io-media's order (RAEA_MEDIA's, the
platform's, the portable one, the ffmpeg CLI), as the other readers of video do, and says what each answered when
none opens it.

The ffmpeg CLI decoder read nothing under FFmpeg 8 and later, which took out -vsync: raea-io-ffmpeg's passthrough()
gives -fps_mode from 5.1 on (apps/check's flash test had that rule; it calls this one now). A VP8 or VP9 stream tagged
alpha_mode=1 is decoded with libvpx, named before the input (FFmpeg's own VP9 decoder drops the alpha WebM keeps beside
the picture), where this FFmpeg has it. ffmpeg's stderr is kept for a read that fails and out of the run's output.

Apple's decoder made every pixel's alpha 255. A track whose format description says it carries alpha (ProRes 4444 at
depth 32, HEVC with alpha) keeps VideoToolbox's: straight, as checked on a ramp from 0 to 255 over blue (63/192,
127/128, 190/65 at a quarter, half and three quarters).

Checked on the issue's files, a red circle on nothing over a blue page: WebM and ProRes give a blue corner and a red
centre (were refused and red); a 30-frame MP4 from the WebM holds that on every frame read; a plain H.264 is unchanged.
Test: raea-io-ffmpeg's vp9_webm_keeps_its_alpha (skips without ffmpeg and libvpx), now in CI's list.
2026-11-12 12:14:24 -08:00
shinyobjectz d1e61bee2b render --alpha: a frame with 3D is transparent where nothing is drawn, as a 2D page is (#114)
The 3D camera already cleared to #00000000 under --alpha (program.rs), but bevy_over_3d, which lays the page over the
3D for PNGs and transparent movies, set every pixel's alpha to 255 (the 3D taken as over black), so an <R3F> or a
native 3D scene came out opaque black around it and setClearColor(x, 0) had nothing to reach. Under --alpha the 3D's
own alpha is now laid under the page's by the same SrcOver as its colour and the premultiplied result made straight
(scene_straight); the page alone, a 3D slot and a camera in a page element keep their alpha too. program.rs's note
that frames with 3D come out opaque is gone. Checked on the binary at 320x320: the report's <R3F> box with
setClearColor('#000', 0), a native Camera3d box and a camera inside a positioned element all write alpha 0 in empty
corners and 255 on the box, a transparent .mov likewise, and a render without --alpha is unchanged (Bevy's 43, 44, 47
clear, opaque).

Skills (SK4): SKILL.md's "7. Deliver" names runtime/export/src; neither it nor the 3D pages say 3D is opaque under
--alpha: checked, still true.
2026-11-12 11:58:27 -08:00
Ragul Sundaram 875006089f r3f: three peer range >= 0.180.0 (HDRLoader first ships in 0.180) (#118)
src/three/scene.ts imports three/examples/jsm/loaders/HDRLoader.js, added in three 0.180; with three 0.170-0.179,
inside the old range, every <R3F> scene fails to bundle.
2026-11-12 14:45:59 -05:00
Ragul Sundaram 163f0b9e00 R3F: an opacity outside [0, 1] is clamped, as three draws it, instead of throwing (#117)
An easing that overshoots (bezier(0.34, 1.4, 0.64, 1)) gives a material opacity of 1.03; three clamps it when it
draws, but the bridge handed it straight to raea's MeshBasicMaterial, whose check threw RangeError. The bridge now
clamps opacity before converting.
2026-11-12 14:45:55 -05:00
shinyobjectz 76a4ef7885 A still no longer prints 54 CommandQueue warnings: the last frame's extract commands are applied before the engine goes (#89 item 7)
Bevy applies the extract schedule's commands in the next frame's render schedule. A still draws one frame and drops
the Engine, so each extract system went with its queue unapplied and bevy_ecs warned "CommandQueue has un-applied
commands being dropped" 54 times (lldb on the warning: the extract systems' FunctionSystemState, dropped with the
render sub-app's schedules from render_with). Engine's Drop now runs the extract schedule's apply_deferred on the
render world, as Bevy's apply_extract_commands does each frame. Checked on the binary: a still of the starter edit
prints no CommandQueue line, and a video renders with 0 findings. forward_render_diagnostics is written shorter to
keep raea-render within 2,000 lines.
2026-11-12 11:40:06 -08:00
shinyobjectz a185361869 A fresh raea init renders again: an <Audio> behind a condition isn't one the render must hear
The starter edit plays a sound-only cut with <Audio> (09ee78513, #89 item 2) on a branch that runs only when there is
one (`c.kind === "audio" ? <Audio /> : <Video />`). The render's silence check refused any edit whose bundle has an
<Audio> call and no sound, so `raea init` then `raea render edit.tsx` was refused before the edit had any cuts. The
check (raea_runtime_sound::always_plays_audio, its own file with a test) now counts only an <Audio> that always plays:
one behind `?` or `&&` is silent when its condition is false, as meant, while one in a wrapper's children
(`children: jsx(Audio, …)`, the <Mix> that dropped them on 10-18) is still refused. Checked on the binary: the starter
edit renders 90 frames with 0 findings, and an <Audio> inside a component that returns null is still refused.

Skills (SK4): SKILL.md's "7. Deliver" names runtime/export/src and says nothing of the silence check: checked, still true.
2026-11-12 11:32:27 -08:00
e90d70f0dc check: a card that shares one word with a line isn't held to it as a caption (#102, #89 item 3)
The cue rule anchored on any one word of weight within 2 s, so a card
sharing a single word with another line ("Wirestock x OpenAI Sora" against
"At Wirestock, I worked on...") was held to that word's time. A text now
counts as a caption only when at least half its words match the spoken run
in order, and a one-word card only within 0.75 s of its word. Words are
compared by the shared word_key, as the rest of the rule does. A caption is
still timed from its first word, so a card whose first word was said earlier
is still flagged, by design.

Part of #89

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: shinyobjectz <[email protected]>
2026-11-12 14:26:07 -05:00
shinyobjectz 6d8623ca9b Node's import.meta.url is written into each module, as import.meta.main is: macOS 15's JavaScriptCore left it undefined
createRequire(import.meta.url) then resolved packages from ".", so a tool requiring a package that way failed on
macOS 15 with "Cannot find package" (a newer JavaScriptCore gives the module's key, which is why it passed here).
raea-native's node test found it as soon as CI's unit tests ran it: the crates #90 added switch on raea-native's
modules feature, and before that the test compiled to nothing in CI. Each module's text now has import.meta.url as
its file's own file:// URL, the way node.rs already writes import.meta.main in.
2026-11-12 10:59:23 -08:00
shinyobjectz 2b8b43a420 raea check's flashing screen is a crate of its own, raea-app-check-flash, so the check has room for #89's fixes
apps/check was at its 2,000-line limit (tools/size.sh) with three of #89's items still to come. The screen itself
(Px, Swings, FlashScreen: WCAG 2.3.1's opposing swings in a frame's windows, from decoded RGB) is pure pixel maths
with nothing of the check's, so it moves to apps/check/flash with its six tests, unchanged; the FFmpeg side (the
decode, showinfo's exact times, the log's severities, the findings) stays in flash.rs. apps/check goes to 1,680
lines. CI's unit tests take the new crate too. And raea-render's log-filter comment is folded a line shorter: the
merge of #104 left the crate at 2,001.
2026-11-12 10:55:50 -08:00
Mattias HjemgaardandClaude Opus 5.5 ab0babcce7 log: the 3D camera is the shadow LOD origin, and bevy_time's warning is filtered (#104, #89 item 7)
* fix(log): a 3D camera that is the shadow LOD origin, and bevy_time's warning filtered

Every 3D run with a point or spot light warned that no entity has
ShadowLodOrigin (the scene camera draws into an image, so Bevy picked one
arbitrarily): the scene camera now carries the marker. bevy_time's "did not
receive the time from the render world" (raea drives Time by frame, with the
render world in step) is filtered out of stderr, in Bevy's log filter and in
raea_io_trace's logger; the event log keeps every record.

Measured on main 5b2c7731: a 3D still with a point light printed the
ShadowLodOrigin warning, now nothing; a 2D still printed bevy_time's line,
now not. The 54 dropped bevy_ecs CommandQueue lines on a 2D still are left as
they are: their source still needs finding.

Part of #89

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* check: keep raea-render under the size cap

The two new comments said in five lines what fits in three; raea-render
was 2 lines over tools/size.sh's 2,000-line crate limit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-12 13:43:33 -05:00
shinyobjectz 09ee785138 raea cut takes a sound-only take (#89, item 2)
A take under media/ with sound alone (wav, mp3, m4a, aac, flac, aif, aiff, ogg, opus) was no take at all: `raea cut
take.wav --at 0-1` refused it, and a video's shot detection would have opened it as a picture. Such a take is listed
with the videos, cut on its words or spans as a video is, with no jump cuts to keep off and the edit's 30 fps grid; its
clips carry kind "audio" in cuts.ts (and no face is looked for in perception.json), and the project template plays
them as <Audio> under whatever the edit puts in their place. Found and shaped by SirSicard's report; items 3, 5, 6
and 7 stay open.
2026-11-12 10:32:22 -08:00
shinyobjectz 6f88437dc1 raea check: the safe-area rule tests a text's letters, not its box, and a missing taste file is a note (#89, items 1 and 4)
A centred line in a left: 0; right: 0 box was flagged in the left zone, since the rule tested the layout box, which
starts at x = 0. The render's manifest now records each text's ink (the lines' own extent, each laid by its alignment,
as a box beside the element's), and a run's per-frame boxes are its ink where that's recorded, its box on an older
manifest, so the clipped, safe-area and face rules measure the letters; the safe-area finding names the edge crossed
and prints what it measured. And --taste naming a file under the person's taste folder (RAEA_TASTE, else
~/.raea/taste) that isn't there yet prints a note and checks without it, as the skill's standing
`--taste ~/.raea/taste/taste.ts` does on a machine with no taste file; any other missing path still refuses.
findings_of and Probe::of are written shorter to keep the crate within 2,000 lines. Item 2 is the next commit; 3, 5
and 7 stay open (6 is in the docs already). Diagnosis and shape from SirSicard's report.
2026-11-12 10:32:22 -08:00
shinyobjectz 6e79971b12 CI runs the tests of the crates that need no GPU or media device, and two of their tests hold on any build (#90)
ci.yml's unit-test step tested three crates; the brief, K, bundle, check, workspace, tools and targets crates join it,
with debug info off for the test binaries (with it they filled 27 GB of a runner's disk). Two tests only passed by
accident of the build: the bundle test's fake SDK sat where the resolver no longer looks (it reads sdk/tsconfig.base
.json's paths since S1d), so it's laid out as the real one with that file; and the workspace's literal test depended
on serde_json's key order, which a crate built alongside (raea-cli) turns into insertion order through preserve_order,
so its lines are held as a set. Found and shaped by SirSicard's report.

Skills (SK4): SKILL.md's "2. The workspace and its projects" and "3. Read before you make" name apps/workspace/src,
where only its tests changed: checked, still true.
2026-11-12 10:32:04 -08:00
shinyobjectz 11dab02b51 Page: getBoundingClientRect stops at a freed containing-block link and answers a zero rect under display: none (#108)
A containing-block link is what the last construction and layout left, and freeing a node doesn't clear links to it:
after a display: none clip's anonymous blocks were freed, measuring one of its descendants panicked on the stale key
(invalid SlotMap key), which an HTML composition hit through its script's getBoundingClientRect. The two geometry
walks and inline_root_ancestor now stop at a missing node, as the paint tree's walk does, and an element in a display:
none subtree answers Chrome's zero rect rather than a rect measured up to the stale link. Cause read by Razepriv in
#108; the same family as #24.
2026-11-12 09:55:56 -08:00
shinyobjectz 6177e27d51 Encode: the RGB to NV12 step dithers through a 4x4 Bayer threshold, so dark gradients stop banding in 8-bit H.264 (#87)
nv12.k and nv12buf.k rounded half up into limited range (220 levels of 256), so a slow dark gradient merged into
bands and blotches that raea check flagged on every sampled frame of a 1080p60 fog shot. Each sample now rounds
through the Bayer threshold of its pixel (a chroma pair's, of its block's top-left), fixed by position, so play and
render agree and nv12_cpu (the CPU render) stays bit-equal: core/k/tests/nv12_dither.rs runs both kernels through the
interpreter against it, and holds a flat dark grey's mean. Samples are clamped to the nominal range (luma 16..235,
chroma 16..240), since 220/256 overshoots 219/255 and the dither would have put some white on 236. The report's
dark-gradient repro goes from a blotching error on 2 of 2 frames to clean, at 2.98 MB instead of 0.64 MB for its
4 s: the encoder keeps the gradient it used to flatten. Diagnosis and shape from SirSicard's report.
2026-11-12 09:55:54 -08:00
shinyobjectz a78fb95e75 raea's window: the page is painted at the display's scale, so a Retina window is sharp
v0.1.1 laid the window's page out at scale 1 and stretched its image over the window: on a Retina display every
glyph and hairline was drawn at half the pixels (a bug report of 11-12: "UI renders at 1x on Retina", the blur and
pixelation people noticed). page.rs size() now gives the page the window's scale factor along with its size in
points, read each frame so a window moved to another display follows; headless, the image target's scale stands.
RAEA_WINDOW_SCALE=2 opens the window at that scale on any display, to check it on a 1x Mac. tests/retina.rs covers
the scaled window and the headless case.
2026-11-12 09:47:09 -08:00
shinyobjectz be220a6064 Page paint: a filter of opacity() functions alone is drawn as the layer's alpha, not as an atlas image (#96)
Every filtered element is an image the size of its box in Vello's atlas (8192 px a side). Two overlapping scenes that
each stacked six full-frame <Freeze> layers under filter: opacity() (a motion blur) at 2160x3840 asked for twelve such
images, more than the atlas holds, so the frame was drawn without them: on 0.1.0 silently, on main as a refusal. An
opacity() filter scales the group's alpha exactly as the opacity property does, so it now folds into the layer's
alpha and needs no image. The report's composition draws its frame 26 at 4K; the filter-functions, opacity and
backdrop-filters parity cases match Chrome as before.
2026-11-12 09:07:31 -08:00
shinyobjectz 7fb6251bf9 Page layout: an inline box is laid out in full while its line is only measured, so a relayout keeps its baseline (#109)
Taffy's measure cache keeps a box's size without its baseline. On a fresh layout every inline-block missed the cache
and its baseline came along; once one span's transform changed, the title's other spans came back from the cache
baseline-less during the measure pass, sat on the line by their bottom margin edge, and the line measured taller by
the font's descent: a per-character spring title jumped 24 px and the block under it 25 px on the frames one span's
value left zero. Blitz already asked for a full layout of inline flex and grid boxes for the same reason; now every
inline box gets one. Checked with the report's composition: the accent line stays at the same row on every frame,
in either render order. The parity case p12-css/inline-block-transform-relayout toggles one span's transform and
holds the block under the title against Chrome.
2026-11-12 09:07:30 -08:00
shinyobjectz 5d320bc96e Live 3D: a mesh's emissive colour is sent the frame it changes, with its strength (#106)
A video draws its 3D live, and a mesh's row keyed only the emissive strength, and only where the first frame glowed:
a part dark on its first frame stayed black for the whole video, and a change of hue was ignored (stills were
right, since their first frame is the frame). The full path now sends the colour whenever it differs from what was
sent (none is black), with the strength (0 once black); the fast path hands such a frame to the full one, and its
strength rule reads the sent colour, not the first frame's. runtime/live/tests/live_emissive.rs steps a ball from
dark to blue to orange to dark, under RAEA_LIVE3D_CHECK.
2026-11-12 09:07:30 -08:00
shinyobjectz 3de2c63bab 3D: a Cone's picking bounds span its height, not twice it (#98)
boundsOf passed the cone's full height to box(), which takes half extents; the cone is drawn centred on its origin.
Found and diagnosed in #98. events3d.test.tsx checks a radius 0.5, height 2 cone's bounds.
2026-11-12 08:32:11 -08:00
shinyobjectz c89de2a778 canvas: arcTo draws the corner's short arc, as a browser does (#97)
Its ccw flag was inverted, so a right-angle corner drew three quarters of the circle through the far side. Found and
diagnosed in #97. sdk/ui/test/canvas-arcto.test.ts checks both turning directions and a four-corner rounded rectangle.
2026-11-12 08:32:06 -08:00
shinyobjectz d70c8e6604 Windows: every executable links with an 8 MB main-thread stack, not raea.exe alone (#112)
The desktop app's raea-page-host.exe kept Windows' 1 MB default and overflowed it inside a window callback
(0xc000041d) right after opening an MP4. .cargo/config.toml now passes /STACK:8388608 for both Windows MSVC targets,
so raea-page-host, raea-rune-host and raea-perceive match raea.exe.
2026-11-12 08:30:03 -08:00
shinyobjectz dfca0bcf12 Docs: raea's own servers index nothing for customers (docs/libraries.feature LB6b), so storage-and-search says indexing runs on your own computers again, and the API guide says a cloud upload is indexed by one of your linked computers 2026-11-11 19:46:40 -08:00
shinyobjectz 14870df064 Docs: sharing for review, libraries and the storage API. Two tutorials (share-for-review: a link anyone can watch and comment on, notes back to the agent, the next version on the same link, Review links, several files on one link, agents sharing; libraries: this Mac or the cloud, making one, search by what's in a shot, statuses, sharing from a cloud library, projects beside their code) and a guide to the API (who may call it: anyone on Pro or Team; agent keys and their scopes; libraries, search by meaning or by words, files, uploads, the trash, review links). storage-and-search says libraries stay on the Mac unless made in the cloud, and where indexing runs 2026-11-11 19:18:57 -08:00
shinyobjectz 6ba881cf0f R6e, R6f, R6g, R6h: the Library's review work is built. R6h: the projects saved to raea are listed under Projects in the Library's column, each its own cloud library over the project's folder (search, statuses, review links), with where its code stands above it (its GitHub repo and Pushed, or commits to push and to pull and changes in its folder) and one press to make the library; R6e to R6g take their @done tags 2026-11-11 19:01:47 -08:00
shinyobjectz de994972cd R6g: several files on one review link is built (a cloud library's picked tiles shared from a bar at the grid's foot; the set's page lists each item's own link; Review links lists the sets with Copy link and Stop sharing); R6h keeps what isn't: a library of a workspace's projects' cloud copies and synced code 2026-11-11 18:46:17 -08:00
shinyobjectz 13daeb9976 R6e, R6f: a file's own status and sharing a cloud library's file are built in the feed (statuses as reserved tags with the grid filtered by them; Share for review in a cloud library file's panel, Mac-only libraries never sharing); R6g keeps what isn't: links of several items and a library of projects' cloud copies and synced code 2026-11-11 18:33:34 -08:00
shinyobjectz b7b777fc8a README for v0.1.1: the first full release, the desktop app on the Mac, Windows and Linux from raea.io (it tells you when a new version is out; the Mac's updates itself), and a release badge in place of canary 2026-11-11 17:25:41 -08:00
shinyobjectz b903c74e5c skills pin: raea-skills ae8002c, SKILL.md teaches raea findings (what every render and check found, read back from the project's record; --open for what still stands, --despite for what the person accepts) 2026-11-11 17:24:38 -08:00
shinyobjectz ab904156c6 Release promote: a release may carry newer skills and docs than its candidate (Shane, 11-11: "promote skills to the latest possible"). No build of the shipped binaries reads skills/ (the raea-skills pin) or docs/: release.sh packs the skills the release's commit pins, and its skills-passed line and check-cli hold them to the candidate's binaries. So v0.1.1 can go from rc5's binaries with the skills that teach the feed's sharing tools 2026-11-11 17:11:34 -08:00
shinyobjectz 1ac6f0b88f R4d: a side-by-side compare of two versions on a review link's page is built 2026-11-11 16:49:51 -08:00
shinyobjectz 550b2b836d R6c: a file out for review says so in a library's tiles and search hits, and its panel opens the link in Review links; R6e keeps a status the person sets on any file as not built 2026-11-11 16:44:36 -08:00
shinyobjectz 27e54e954f R6: the Library in the review spec. Review links leave Settings for the Library's own board (R4a, R6c); guests' comments sync to the item as edits and the reviewer sees Done in vN (R4c); invites and shared projects live in the Library's Shared with you (R5b, R6d); Open in raea clones a shared project into the sidebar (R5d); R6 the Library: one column with Search by meaning across every library, Review links by state, Shared with you and the libraries, and what isn't built yet 2026-11-11 16:38:18 -08:00
shinyobjectz a3241af2b5 skills pin: raea-skills 68aca5a (PR 45), which teaches the feed's sharing tools and regenerates reference/feed.md 2026-11-11 16:04:01 -08:00
shinyobjectz c9e5a20c6b R4, R5: review links are Pro's and Team's and built (the Share button, Settings → Sharing, the agents' share tools behind Let agents share); R5 is collaborators on Team: invite by GitHub username or email, accept in your own raea, GitHub's invite too, remove; what isn't built yet is said in each scenario 2026-11-11 16:00:16 -08:00
shinyobjectz 8d111c6f5b Release promote: a release can go as soon as the Mac's candidate archive is out (Shane, 11-11: "once mac is ready we can go live too"). tools/release/promoted-bins.sh waits for a platform's candidate archive (and its .sha256) while the candidate's own release run is still building it, every two minutes, and fails at once when that run has ended without one; so v0.1.1's Windows job promotes rc5's zip as soon as rc5's windows-verify attaches it. Tested: rc5's Mac archive, still building, is waited for; rc4's Mac archive, built by the release-disk branch's dispatch, is refused by the attestation check (source ref refs/heads/release-disk, not the tag) 2026-11-11 15:10:21 -08:00
shinyobjectz f96fdda16a Release: promote a candidate instead of compiling again. A release whose code is an rc's (only the README, the workflows and the release tools may differ) is that rc's attested binaries packed again as the release: raea's version isn't compiled in (release.sh writes share/raea/VERSION; rc3's five binaries hold no "0.1.1-rc3"), so what ships is what the rc's checks ran, in minutes instead of a three-hour cold build. release.yml reads the tag's "promoted-from: <rc>" line (or the promote_from input; none builds from source) through tools/release/promoted-from.sh, which refuses, naming the files, when any code differs; each job then takes the rc's archive for its platform through tools/release/promoted-bins.sh (sha256, and gh attestation verify against release.yml and the rc's tag), its symbols from the rc's run, and packs, checks, attests and attaches as before. release.sh keeps a promoted Linux binary's carried symbols instead of stripping it twice. dry_run (by hand) packs and checks without attesting or attaching. Tested: rc5 against main passes the code check and rc4 is refused with its files; rc3's Mac archive downloads, verifies and unpacks 2026-11-11 14:55:54 -08:00
shinyobjectz 619816627e The manual's SDK reference from the SDK as this stack leaves it (bun tools/manual-ref/sdk.ts gen): an inline FramePass's uniforms are each frame's own (3d, post_process), a controller is a standing decision (brief), and Nudge places by scale, rotate and opacity too (raea) 2026-11-11 13:50:13 -08:00
shinyobjectz 0295020a39 skills pin: raea-skills d63c30a (PR 44), 3d/solari.md and 3d/water.md copied from the guides this stack adds 2026-11-11 13:34:02 -08:00
shinyobjectz 1e8b2e63dc CL10b: raea cloud on Cloudflare Containers (sdk/cloud/deploy/cloudflare): a Worker in front of one container that sleeps when idle and wakes on the next request, its home folder kept in R2 through RAEA_CLOUD_STATE 2026-11-11 13:34:02 -08:00
shinyobjectz 67d2b3e3ea sdk/plugins bevy.gen.tsx regenerated: raea-sys-shader's OwnMaterial and OwnArrayMaterial are in the registry (3D, 2D and the sprite extension), 389 components 2026-11-11 13:34:02 -08:00
shinyobjectz 1be0cc4a5b Craft guides bevy/solari (ray-traced light: what it lights and traces, glowing lamps, rooms that do not leak, cuts, metering) and bevy/water (seas, lakes and pools: waves, reflection, refraction, absorption, caustics, foam), routed from bevy.md, their sources cited in NOTICE 2026-11-11 13:34:02 -08:00
shinyobjectz b861af80be A controller's doc comment (sdk/raea brief.ts) says what one is: a standing decision ("every ad is 9:16"), not one piece of work; the raea app shows a new one in the project's feed, and an agent brings one to the person with controller_post 2026-11-11 13:34:02 -08:00
shinyobjectz 4855d4da0f Nudge places a part by scale, rotate and opacity too, not only x and y (sdk/video nudge.tsx), with docs/editing.feature: the editor as live changes to the composition's code (E1-E5, from Shane's 11-07 notes; E1c, the Properties panel's scale and opacity, were dropped on save before) 2026-11-11 13:34:02 -08:00
shinyobjectz eb56911dd6 R3F (sdk/r3f) draws more of raea as three.js does: a <ThreeShaderMaterial glsl> is three's own ShaderMaterial, its uniforms and samplers set each frame (three/shader.ts), and a <BufferMesh> carries its own attributes for it; <Look mode="paint"> and cartoon paint in the surfaces (three/paint.ts, colours written through the inverse of three's ACES) and the frame pass only draws the cells; Grass is clumps of tapered blades by the engine's detail steps, made once per field; an HDR or EXR panorama lights the scene only once it has loaded (one still loading compiled every lit material's shader wrong, so nothing drew) and wakes every page that asked for it; a light inside a moved Entity moves with it; a Grade's top-level value is each section's unless the section sets its own; emissive_nits sets emissiveIntensity; meshopt-compressed glTFs decode; the composition's size is in whole pixels. kinds.ts gets rows for Skybox and Lightmap (engine: their .ktx2 files are ones three's KTX2Loader does not read) 2026-11-11 13:34:02 -08:00
shinyobjectz ddf9a6adef Skin up close: the micro tile's grain shades the colour too, a crease or pore darker with green and blue more than red (the blood under them shows; a grey darkening read as dust), as a photo's colour is a blur that close. The tile keeps its size on the skin by the mask's scale channel (skin_mask.png green, 0 on older bodies is 1). The wrap per channel no longer widens with curvature (sdk/character skin.ts) 2026-11-11 13:34:02 -08:00
shinyobjectz 4fe5eb115b A material re-covering a glb takes real transmission, ior and thickness (systems/material surface.rs): a glass or frosted-veil <StandardMaterial> over a glTF part drew opaque, since over() copied every given field but those three. Test: transmission_ior_and_thickness_re_cover_a_glb_material 2026-11-11 13:34:02 -08:00
shinyobjectz d730ef1cdd raea render -o out/a.mp4 (and --audio out/a.wav) makes out/ first when it isn't there (a project made by hand has none): the render ran to the end and then failed writing with "No such file or directory". apps/sound out_folders, at the top of raea_app_sound::render, which every render passes through first (raea render, and raea export capcut's parts); it replaces the sound render's own folder making. Test: a_render_makes_the_folders_its_files_go_in 2026-11-11 13:34:02 -08:00
shinyobjectz 52b9bb7f65 docs/review.feature R4: review links, proposed and Team only (decided 11-11). The person or their agent shares an item as a raea.io link; anyone with it watches and comments on the picture without an account; comments come back to the item and its agent as R1 comments and R3 edits; new versions replace the cut on the same link; a link is the reviewer's only right. On Free and Pro, Share says links come with Team. Not built, not in v0.1.1, with two open questions 2026-11-11 13:24:34 -08:00
shinyobjectz 7116d23eeb Tutorial: storage and search says what Pro is now, one computer whose libraries are searched on raea.io too, with Team's teammates searching the same media 2026-11-11 13:24:34 -08:00
shinyobjectz c5269af648 A UiTexture's image is the texture of any material map, not only the base colour (systems/material maps.rs): as the emissive map a panel glows and shows under Solari, which draws no unlit surface; before, emissive_texture={targetImage(...)} was refused as a missing file. Test: a_screen_image_is_the_texture_of_any_map 2026-11-11 13:24:33 -08:00
shinyobjectz a81a8a1e1e Solari leaves additive and multiplying surfaces out of its traced scene (engine/render/raytrace solari.rs): traced, an Add sprite was an opaque card, and a wind's dust and air streaks cut a sunlit wall's light by a quarter. They still draw, forward. A mesh whose material isn't made yet is decided on a later frame. Test: an_additive_or_multiplying_surface_is_not_traced 2026-11-11 13:24:33 -08:00
shinyobjectz 5aa10b955c An inline FramePass's uniforms follow the frame (systems/framepass, runtime/scene3d shaded.rs, sdk/render framepass.tsx): the SDK sends them as a keyed prop, as a pass as written's are, and follow() puts each frame's values in the pass's slots. Before, an inline pass kept its first frame's uniforms for a whole render, so a camera or a time handed to a raymarch stood still. A uniform keeps its first frame's type; textures stay the first frame's (a texture array's layer picked by a uniform changes what's read). Test: an_inline_pass_follows_its_uniforms_frame_by_frame 2026-11-11 10:14:34 -08:00
shinyobjectz cd6bb40834 BL37, GD9, GD12: the manual's CLI reference from the help as landed (tools/manual-ref/cli.ts gen): scene export with its --at and -o described, godot run's --scene and --frames, and setup godot trying raea's own build first 2026-11-11 10:13:46 -08:00
shinyobjectz a331bffd13 BL29, GD8, GD9: Windows and Linux on raea's own v0.1.1-rc4 builds, and setup blender finishes on Windows with uv. Linux (debian:trixie-slim): Blender and GodotJS's Godot installed and both smokes passed. Windows 11 from the release zip in an empty home: Blender's smoke passed, GodotJS's Godot installed and its smoke passed, and raea's own Windows Godot (sha256 as pinned, 4.6.1.stable.raea) passed it too, its typings the same text as GodotJS's (4 of 18 files CRLF there, LF in raea's). With uv on PATH, setup blender exited 1 there: the MCP add-on's installer prints an arrow Python can't encode for the cp1252 console; it now runs with PYTHONIOENCODING=utf-8 and PYTHONUTF8=1 (apps/tools blender.rs), and so run on that machine it installed the add-on and exited 0 2026-11-11 10:09:23 -08:00
shinyobjectz 0eda5dc0f5 BL36, GD11: register_natives in 6 lines, not 11 (the calls crate's own registration in the one list), so raea-runtime-react is 2,000 lines, within the crate limit 2026-11-11 10:03:01 -08:00
shinyobjectz ad4fbf6b35 skills pin: raea-skills 9832e02 (#43), the lane's guides (3d/blender.md, 3d/godot.md, sources, blend-files, godot-projects) and reference/cli.md with its verbs 2026-11-11 09:58:28 -08:00
shinyobjectz 848ff9471d BL36, BL37, BL38, BL39, BL40, GD9, GD11, GD12, GD13, GD14: status 11-11 with the evidence. Each command passed on a test scene (a crate, a metal ball, a pole, a floor, a sun, a point light and a moving camera): scene export 6 parts on 30 frames; blender open built the .blend in 5 s; blender back said each change at its TSX line and wrote the new box as a model; godot export 3 tracks over 30 frames; godot back the same; the shots 30 frames in their Sequence, a second render 2 s from the store; take.py and the scene-glb guide script on real files (Godot's 3d/platformer: 2,923 meshes). GD9: the three editors report 4.6.1.stable.raea, the Mac's notarized and stapled, Mac and Linux pass the smoke and the typings check; the zips' sizes and sha256 are godot.rs's pins, uploaded with the release's files 2026-11-11 09:57:46 -08:00
shinyobjectz dfb13e6ec9 BL37, BL39, GD9, GD12: eleven new duplicate groups folded or written plainly (tools/dupes.sh: L1 counted 300 exact and 64 near against main's 294 and 59). Godot's pins are six consts, not two closures building them; a material's numbers read one table of defaults; scene export counts instances in the loop that lists what doesn't cross; a track no longer returns early when every channel holds still (each channel is skipped then anyway); an edit pushes itself onto the list; a shot's flags are a map and --transparent a field. Tests: apps/engines (15), apps/interchange (9) 2026-11-11 09:50:25 -08:00
shinyobjectz 9ab4e05f86 BL36, GD11: <BlenderShot> and <GodotShot>'s native calls move to a crate of their own, raea-runtime-shots (runtime/shots), which raea-runtime-react registers: in runtime/react they took that crate to 2,202 lines, over the 2,000 limit. No change in what they do; the size and length a shot is asked for are whole numbers of 1 or more and its fps a number over 0, each said by name when it isn't. Tests: a_shot_is_keyed_by_what_it_is_made_from and the command's 2026-11-11 09:50:19 -08:00
shinyobjectz d4e23b602a BL40, GD14: open .blend files and Godot projects come into raea by the guide, and the Blender and Godot guides teach the round trips and shots. bevy/blend-files: contents.py lists a .blend's meshes, collections, node groups and materials; take.py writes named objects and collections as one .glb with modifiers applied and a licence sidecar, now linking each taken object's parents into its scene (glTF's export walks down from the top objects, so a parented object came out as an empty 132-byte .glb). bevy/godot-projects: godot/scene-glb.ts writes a Godot scene's meshes, materials, skins and clips as one .glb, its cameras and lights left behind and the tracks that moved them dropped (glTF's export reported them as an error); type-checked as sdk/godot/test/guide-scene-glb.ts and run on Godot's 3d/platformer demo (2,923 meshes). bevy/sources: the open libraries and their licences, routed from bevy/assets. bevy/blender: raea blender open and back for the person's hands, and <BlenderShot>. bevy/godot: --scene and --frames, <GodotShot>, raea godot export and back. convert.py: a packed image isn't a missing texture 2026-11-11 09:35:28 -08:00
shinyobjectz b85ce4f97d BL36, BL37, BL38, BL39, GD11, GD12, GD13: Blender and Godot in a raea project: shots drawn by them, the scene sent to them and its changes read back. raea scene export EDIT.tsx -o DIR [--frame N | --at A-B] writes the composition's 3D as scene.json (each part's id, kind, name, TSX line from the bundle's source stamps, placement, material, primitive sizes; other meshes as .glb, models copied with their sidecars; lights, camera, ambient, background; what doesn't cross listed in left) (new crate apps/interchange). raea blender open builds it in Blender through raea/blender (sdk/blender scene.ts: Blender's own meshes, Principled BSDFs, lights and camera keyed on --at, raea_id on each object) and opens the .blend; raea blender back and raea godot back read the file back and say each move, colour, light, camera and deletion as an edit at its TSX line, and write objects made there as media/NAME.glb. raea godot export writes a Godot project that runs (native meshes, StandardMaterial3D, an AnimationPlayer for --at, still channels left out, nodes named for their parts); raea godot run takes --scene with no script (host/none.ts). <BlenderShot> and <GodotShot> (raea/blender/shot, raea/godot/shot) render their frames once per bundle, file, props, size, fps and length, sized from their Sequence's end, kept in the asset store (native calls blender.shot, godot.shot; raea blender shot, raea godot shot). register_natives() gathers every native call a composition's thread answers, so raea types lists them all. Tests: apps/interchange (9), apps/engines 2026-11-11 09:35:16 -08:00
shinyobjectz a4a213e05e GD9: raea's own Godot 4.6.1 + GodotJS editors, and raea setup godot downloads them first (apps/engines godot.rs, sdk/godot/build). Pins move to raea's v0.1.1 release (godot-4.6.1-raea-macos-arm64, -linux-x86_64, -windows-x86_64 .zip, each pinned by size and sha256); GodotJS's own pinned build is the fallback, so a release whose zips aren't up yet still installs, and setup says which build it installed and why not raea's. RAEA_GODOT_FROM=URL (file:// too) installs from elsewhere. windows.py cross-builds the Windows editor with MinGW-w64; macos.sh makes Godot.app from Godot's macos_tools.app; package.sh signs it with the Developer ID and Godot's editor entitlements, notarizes and staples it, and zips all three; verify.sh fails unless the smoke prints its PASS line. godot run's usage gains --scene and --frames. Tests: every_pin_has_a_full_digest, raeas_build_is_tried_first_and_godotjss_after, setup_says_whose_build_and_why_not_the_one_before 2026-11-11 09:34:49 -08:00
shinyobjectz fddaf29fb1 CC2a: raea export capcut finds a composition's footage where the render did: a staticFile path (/media/x) in the edit's media/, then the project's media/ and assets/ (raea-core-scene's media_path, the renderer's own lookup). It read /media/x as a file at the disk's root, so every project that names its footage with staticFile was refused (found making the release post's draft). The summary line says 1 clip and 1 sound, not 1 clips 2026-11-11 07:38:11 -08:00
shinyobjectz 91157b6610 CC4: the raea skill teaches handing a cut to an editor in layers: sdk/guides/craft/motion/delivery.md says when to raea export capcut (a CapCut draft, footage as clips of their own files, raea's drawing as transparent clips over them; Export to, then CapCut in the app), that graphics for someone else's edit go out as a transparent .mov with --alpha and nothing behind them, and the two mistakes (a background in a transparent movie or --alpha with an .mp4; exporting while CapCut is open). Its copy in raea-skills is PR 42; the pin moves with this 2026-11-11 07:27:30 -08:00
shinyobjectz e9174676c7 CC4: skills pin: raea-skills 8fa672e (PR #42), whose motion/delivery.md teaches handing a cut to CapCut in layers and transparent movies for graphics, and whose reference/cli.md has raea export and render --alpha-codec from main's help, so the release's strict skills gate passes on main 2026-11-11 07:27:19 -08:00
shinyobjectz 87ccba76c1 AP10: the app's icon counts what's waiting in the Inbox on Windows too: raea-page-window's dock.badge sets an overlay icon on the window's taskbar button (ITaskbarList3::SetOverlayIcon, win.rs), as the Dock's badge does on the Mac. badge.rs draws it, pure and tested everywhere: a red circle or pill with the count in a 3x5 pixel font at the small-icon size the taskbar asks for, 9+ above nine, cleared at nothing. win.rs type-checks for x86_64-pc-windows-msvc (windows 0.62, already in the lock); notify's nested if is collapsed for clippy 2026-11-11 07:20:52 -08:00
shinyobjectz 45aa5ca212 CC2d: raea export capcut keeps the copy of CapCut's project list in the person's own folder, ~/.raea/capcut/backups (%LOCALAPPDATA%\raea\capcut\backups on Windows, RAEA_CAPCUT_BACKUPS to choose), as docs/capcut.feature says. It went to raea's home, which from a checkout is the source tree, so an export run from one left the backup in the repository 2026-11-11 07:12:24 -08:00
shinyobjectz 7fd6282cb2 GD9: raea builds GodotJS's editors itself: sdk/godot/build holds the macOS (arm64, JavaScriptCore) and Linux (x86_64, QuickJS-ng, on Modal) builds from source, as GodotJS's CI builds its release (Godot 4.6.1-stable 14d1969, GodotJS a8e2567 at v1.1.0.beta1-4.6.1, AccessKit-c 0.18.0), and verify.sh, which runs raea's smoke script on a build and compares the typings it generates with those from GodotJS's own build
On 11-10 the Mac build took 370 s at -j6 (133,184,648 bytes, reporting 4.6.1.stable.raea.14d19694e): smoke PASS, and its 17 typing files are byte-identical to GodotJS's build's. The Linux build took 511 s on 16 cores (161,938,768 bytes); it ran before the BUILD_NAME=raea line, so it reports custom_build, and it hasn't run raea's smoke yet. `raea setup godot` keeps GodotJS's pinned builds for 0.1.1; the pins move to raea's own in 0.1.2, once the Windows editor is built too, the Mac one is signed and each passes the clean-machine smoke. Nothing is uploaded before then.
2026-11-11 06:48:22 -08:00
shinyobjectz 07cd85e663 CC1, CC2: raea render -o OUT.mov --alpha writes a transparent movie natively, and raea export capcut EDIT.tsx writes the composition as a CapCut draft ready in its timeline (docs/capcut.feature)
raea-io-alpha encodes --alpha PNG frames (straight alpha) as a QuickTime movie: ProRes 4444 or HEVC with alpha through AVAssetWriter on the Mac, and QuickTime Animation (32-bit ARGB run-length, FFmpeg's qtrle layout) or PNG frames on every platform. `--alpha-codec prores|hevc|rle|png` picks one; prores is the Mac's default, rle elsewhere. CC1a, on a 3 s 1080x1920 graphic: 12.3 MB, 0.34 MB, 0.84 MB and 7.4 MB; rle and png decode identical to the PNGs, prores and hevc alpha within 61 dB, and a frame that draws nothing decodes fully transparent in all four.

raea-io-capcut writes CapCut 8.5.0's draft as CapCut writes it (an empty project and one with a clip placed by hand give its skeleton and a video segment's companion materials): one material per segment, times on the frame grid, media copied into its assets/, version markers from the newest draft CapCut made, and the entry in root_meta_info.json (backed up first, refused while CapCut runs). raea-app-capcut renders the composition three times: as it is with --manifest (footage runs, sound clips); with its footage and the backgrounds holding it hidden (RAEA_HIDE_MEDIA=1, the overlay); and with only those backgrounds (RAEA_HIDE_MEDIA=under, kept unless black). Footage becomes clips of the original files at their trims and rates, placed by object-fit (cover, contain, a cover crop), keeping their own sound at the composition's gain; sounds become audio clips with gains and fades; the overlay becomes clips cut where it draws. The manifest gains each video's object-fit and each sound's rate and fades, and the export cache is skipped under RAEA_HIDE_*. Checked on two fixtures: the draft's layers composited in ffmpeg match raea's render (31-33 dB against its H.264). Not yet checked: the draft opened in CapCut itself (CC3a). The CLI reference gains export (in Make) and --alpha-codec.
2026-11-11 06:43:39 -08:00
shinyobjectz ce920a5530 release.yml: room for the macOS build. rc4's macOS job ran out of disk linking raea-page-host (ld: write() failed, errno=28): rc3's build had left 576 MB of macos-15's 320 GB free, and rc4's dSYMs (#88) took the rest. Before the build, the Mac job removes the image's Xcodes other than the selected one, and the Android and .NET SDKs, in parallel, printing the free space before and after 2026-11-11 07:04:04 -05:00
shinyobjectz 0ea4eabe4a BL29, GD8: Windows 11 runs raea/blender's smoke on Blender 5.2.4 and starts GodotJS's editor
- BL29: Blender 5.2.4's Windows zip (406 MB, sha256 as blender.org lists it, 901 MB installed) needs nothing more;
  sdk/blender/test/smoke.ts run under Bun 1.4.2 through raea/blender printed its PASS line (3 cubes, the last 4.000 m
  out, a bmesh volume of 1.000).
- GD8: GodotJS's QuickJS-ng Windows editor (83,915,786 bytes, raea's pinned sha256, 178 MB installed) reports
  4.6.1.stable and starts and quits headless with exit 0.
- Still to run on each: raea's own Windows and Linux builds (raea setup, then raea blender run / raea godot run), which
  come with v0.1.1's release builds.

Proven: a probe on a Windows 11 PC (x86_64) in a scratch folder, removed after.
2026-11-10 22:04:00 -08:00
shinyobjectz 0c72d3942a skills pin: raea-skills 26c0cfe (PR #41), whose reference/cli.md has the Blender and Godot verbs (setup godot, blender run, godot run/types/open), so the release's strict skills gate passes on main 2026-11-10 21:57:36 -08:00
shinyobjectz 65074df06e BL22: 155 any declarations down to 79: Python returns read from their own source, sequence items from Blender's C
- tools/returns.py reads what a function written in Python returns from its source, where its docstring has no
  :rtype: (or a Python property's getter, no :type:): the type every `return` gives when each shows one (a literal, a
  comparison, a builtin's result, a str method on a string, os.path's, a local only ever bound to such), "T | None"
  when a path falls off the end; anything else leaves it any. dump.py gives it as `ret`, gen uses it for functions and
  Python properties alike: CyclesPreferences.has_active_device() boolean, Mesh.edge_keys an array,
  BoneCollection.bones_recursive a set (33 members).
- pymod.ts types the items of sequences whose name doesn't give them, from the C (bmesh_py_types*.cc,
  idprop_py_api.cc): bm.select_history[i] a vertex, edge or face; a BMElemSeq's any element; a layer collection's
  BMLayerItems; a deform vertex's [group] a weight; an IDPropertyArray's numbers or booleans. BMVert/BMEdge/BMFace/
  BMLoop[layer] and an ID property group (keyed by name) no longer claim a number index.
- dump.py leaves out Python's own names a Blender module imports (anim_utils' Mapping, Sequence, Iterable, typing
  aliases, dataclass), and keeps a private class the module's functions name as their :rtype: (bpy.props'
  _PropertyDeferred, so FloatProperty() and the rest return it).
- cret.ts reads `(PyCFunction)(void *)(name)` entries (GPUShaderCreateInfo's depth_write, fragment_out,
  push_constant, uniform_buf: None) and a returned local by its every assignment (libraries.write None,
  bpy.utils.units.to_value float, bpy.app.help_text str): cret.json 284 method and 123 property names.
- Declarations typed any: bpy.types 51 -> 32 of 16 684; modules outside RNA 104 -> 47 of 1 440.

Proven: tools/gen.sh from Blender 5.2.1 (tools/cret.sh 5.2.1 first); sdk/blender's tsc and its 16 bun tests pass,
with test/returns.test.ts: the reader's 18 cases, and every member it types on live meshes, bone collections and
Cycles' preferences reads as that type in Blender.
2026-11-10 21:54:55 -08:00
shinyobjectz 3725537f35 sdk/cloud: renders on a GPU or a CPU from one image, render jobs, and a CPU box that hands its renders to a GPU worker (docs/cloud.feature CL13-CL15)
- The image is Node 24 on Debian trixie with glvnd and X11's libraries (libxext6 libx11-6 libgl1 libegl1), without
  which NVIDIA's Vulkan driver (mounted by the container runtime) doesn't load or gives no vkCreateInstance (driver
  610.57 on Modal's T4, A10G and A10). The entrypoint opens NVIDIA's driver when the host passed a GPU in, else Mesa's;
  WGPU_BACKEND=vulkan, and on the CPU EGL's vendors are hidden, since NVIDIA's EGL would hand wgpu an OpenGL adapter
  over llvmpipe. RAEA_CLOUD_DEVICE=gpu fails at start on no GPU; /v1/health says the device.
- /v1/jobs takes a project as a tar and gives back what the render made (CL14); deploy/modal/raea_cloud.py runs it on
  a Modal GPU list (L4, else A10G, else T4), one container that sleeps after five idle minutes.
- RAEA_CLOUD_GPU_URL on a CPU box sends raea render to the worker and lands its files back (CL15, image/raea.sh and
  server/offload.ts); deploy/k8s.gpu.yaml is such a worker.
- test/smoke.sh: worker and box, ten checks, all pass on 0.1.1-rc3. On Modal, test/gpu/edit.tsx (576 lit blocks,
  1080p, 90 frames): T4 156 s against llvmpipe on the same machine's 8 cores 203 s; a box on a Mac handed it to an A10
  (119 s) and the MP4 came back.
2026-11-10 21:52:21 -08:00
shinyobjectz 98e215b4c9 sdk/cloud: raea and an ACP agent on a developer's own server (docs/cloud.feature CL1-CL12). One image (image/Dockerfile): Node 24 on Debian trixie, raea's Linux release checked against its .sha256, any agent the ACP registry lists installed from its entry at build time (AGENTS=kimi-code claude-acp ...; npm at the registry's version, or a linux archive checked by sha256), and a server on :8080 behind one token: /v1/health, /v1/files (paths confined to the workspace, symlinks out refused), /v1/run (raea ARGS streamed as NDJSON), /v1/login (an agent's terminal sign-in found from its ACP authMethods, under script(1), handing back the device link and code) and /v1/acp (one agent process per WebSocket). The agent and raea never see the token. raea's skills are installed for each agent on every start; RAEA_CLOUD_STATE keeps the home folder in an S3-compatible object where the disk doesn't outlive the container. A TypeScript client (src/, fetch and WebSocket only), and deploy files for Compose (CPU, or an NVIDIA GPU with the graphics capability for Vulkan), Fly Machines and Kubernetes. test/smoke.sh on 0.1.1-rc3's Linux release with a stand-in agent: 8 of 8 (the token refused, four path escapes refused, a frame rendered through /v1/run in 19.5 s under amd64 emulation, an ACP turn with the permission answered); Kimi Code 2.5.3's device sign-in started through /v1/login. The Fly, Kubernetes and GPU files are written, not yet deployed 2026-11-10 21:52:21 -08:00
shinyobjectz beb69f40bc tools/release/rl3-mac.sh: the play step runs with RAEA_AUDIO_MUTE=1, so a clean-machine check makes no sound on the Mac's speakers while someone works at it 2026-11-10 21:51:20 -08:00
shinyobjectz fe44ef6e42 skills pin: raea-skills a5b8700 (PR #40, merged on #39 and #38): 3d/blender.md says a Blender step can be written in TypeScript (raea/blender, typed) and the new 3d/godot.md is raea guide bevy/godot's copy, routed from 3d.md, games.md and SKILL.md (BL35, GD10); with 3d/characters.md's game_engine joints (#38, 07166db, rc4-issues) and motion/match-cuts.md with craft/match-cuts (#39, d0e5e8d, match-cuts) beneath it in this stack 2026-11-10 21:43:27 -08:00
shinyobjectz 33d5548254 BL29, GD8, GD2: setup on a clean machine needs no uv, git or shasum; smoke scripts; a clean Linux's libraries recorded
- raea setup blender finishes on a machine without uv (the MCP add-on becomes a note) or git (raea.blender is
  remembered only where git is; find() takes raea's download anyway).
- Downloads are checked with coreutils' sha256sum where perl's shasum is missing (debian:trixie-slim has none), for
  Blender's setup and Godot's.
- A Linux Blender that can't load its libraries names the Debian packages it needs, found in debian:trixie-slim:
  libx11-6 libxi6 libxext6 libxfixes3 libxrender1 libxkbcommon0 libsm6 libice6 libgl1 libopengl0.
- sdk/blender/test/smoke.ts: raea blender run's smoke (cubes made, a bmesh volume, mathutils against Blender's, one
  PASS line).
- GD2: pin_for(os, arch), and a test that Linux and Windows on arm64 and other systems are told to build GodotJS and
  set raea.godot.
- docs: BL29 and GD8 record the clean Mac runs and the clean Linux probe; GD2 is done.

Proven: cargo test -p raea-app-tools -p raea-app-engines. macOS with an empty HOME and the system's PATH: raea setup
blender --download, then raea blender run smoke.ts, PASS (Blender 5.2.4 LTS); raea setup godot, then raea godot run
smoke.ts, PASS. debian:trixie-slim on Modal: Blender 5.2.4 runs with the packages above, smoke.ts under Bun through
raea/blender PASS, and GodotJS's Linux editor starts headless.
2026-11-10 21:42:49 -08:00
shinyobjectz 8a9236fffa BL28: raea setup blender installs raea's add-on, and a script drives the person's own Blender live
- raea setup blender copies sdk/blender/python/raea_blender into that Blender's add-ons folder (replacing an older
  copy) and enables it, beside the MCP add-on; --check says whether it is current and on. Started with its window,
  that Blender serves raea/blender on 127.0.0.1 behind a token (~/.raea/blender/live.json).
- The add-on serves only a Blender with a window: a background one (a command-line render, setup's own checks) would
  hide the person's open Blender behind its own live.json.
- Fixed: Blender 5.2 gives a timer the window but no area, so the bridge's ui_context left view3d operators with no 3D
  view; it now fills in the area whenever there is none.
- Fixed, headless too: a slot freed by garbage collection was freed at the head of the next batch, before the read an
  await had queued for it ("reference N was released or never set"). Frees now go last, and are sent again after a
  batch that fails before them. test/bridge.test.ts forces the race: it failed before the fix and passes after.
- test/live.ts, run by hand (it opens a window): setup in a scratch BLENDER_USER_RESOURCES, Blender started with its
  window, a cube made, moved and put in edit mode and view3d.snap_cursor_to_center run, on the main thread in the 3D
  view; once Blender quits, connect({ live: true }) refuses its live.json.
- The CLI reference (docs/manual/reference/cli: setup, blender, index) follows the help.

Proven: cargo test -p raea-app-tools; sdk/blender's tsc and its 14 bun tests against Blender 5.2.1; test/live.ts 5 of 5
runs; the race test 5 of 5; bun tools/manual-ref/cli.ts check.
2026-11-10 21:42:49 -08:00
shinyobjectz 95cccb4af5 BL22: C methods and properties typed from the bindings' own C source (tools/cret.sh)
- tools/cret.sh fetches Blender 5.2.1's Python bindings (a sparse clone of its tag) and tools/gen/cret.ts reads, for
  every method and getset entry, the one Python type all its C function's returns give: None, bool, int, float, str,
  or a tuple a Py_BuildValue format makes. An error's nullptr gives nothing back; any other return leaves it unknown.
  A name is typed for a family of bindings (bmesh, gpu, mathutils, generic, bpy, aud) only when every C function bound
  to it there agrees: tools/cret.json, 274 method and 122 property names.
- dump.py marks functions written in Python (`py`), which keep what their own source says. gen applies cret.json where
  a docstring has no :rtype: or :type:, and a C property's setter takes what its getter gives.
- Declarations typed any: bpy.types 68 -> 51 of 16 684; modules outside RNA 423 -> 104 of 1 461 (gpu.state,
  gpu.matrix, aud's properties, bmesh's and gpu.types' methods).
- test/cret.test.ts reads every property so typed on live bmesh, aud, imbuf and mathutils objects in Blender: each is
  that Python type.

Proven: tools/gen.sh twice gives identical src/gen; sdk/blender's tsc and its 13 bun tests against Blender 5.2.1 pass.
2026-11-10 21:42:49 -08:00
shinyobjectz 07b6e3c7ec BL34: the bevy/blender guide drops the fill_mode cast: an enum Blender works out at the time takes any string 2026-11-10 21:42:49 -08:00
shinyobjectz 87fa310c80 BL34: an enum Blender works out at the time takes its static items or any string; Python methods that return None are typed so (BL22)
- BL34: tools/itemf.sh reads Blender 5.2.1's own makesrna (a sparse clone of its tag) for RNA_def_property_enum_funcs
  calls with an item function, into tools/itemf.json (tools/gen/itemf.ts): 147 properties and RNA function parameters,
  a helper's placed on the struct its caller defines. gen types them `static items | (string & {})`: 222 declarations,
  Curve.fill_mode among them, so `fill_mode = "BOTH"` on a 2D curve type-checks without a cast. Python can't tell
  these enums apart (with no context Blender never calls an item function). 8 helpers whose struct is named at run
  time stay unresolved; their enums have one item or none, typed string already.
- BL22: dump.py marks a function written in Python whose source returns no value anywhere (returns_none, by its
  AST), and gen types it as returning nothing where its docstring has no :rtype: (register, draw, shade_smooth,
  keyframe helpers...). bpy.types declarations typed any: 127 -> 68 of 16 684; Python modules 470 -> 423 of 1 461.
- Two dumps of one Blender now write the same src/gen: a data member's repr sorts a set's items and drops memory
  addresses.
- The guide (bevy/blender), README and docs/blender.feature drop the BL34 cast.

Proven: sdk/blender's tsc and its 12 bun tests against Blender 5.2.1 (bridge, rna, mathutils); test/typing.ts sets a
2D curve's fill_mode to "BOTH" and still refuses rotation_mode "XYZW"; run by `raea blender run`, the same script
prints fill_mode BOTH; tools/gen.sh twice gives identical src/gen.
2026-11-10 21:42:49 -08:00
shinyobjectz 32fdfe0863 blender-godot: L1's repo-wide checks (licences, dupes, taxonomy, the CLI reference)
- Licences: Godot's setup unpacks its zip with the zip crate, which brings zeroize_derive into a plain raea build, so it
  leaves the plugin catalog's list (tools/licenses.sh: NOTICE's line and LICENSES/zeroize_derive-1.5.0).
- Dupes, back to 294 exact and 56 near: Blender and Godot share apps/tools' own_dir(name) (~/.raea/tools/NAME);
  godot_run's project_size reads `key=value` with split_once, and godot types counts its .d.ts files in a loop.
- Taxonomy: the backend-name scan leaves out sdk/blender/src/gen, Blender's own API as its RNA names it
  (bpy.ops.render.opengl), as it leaves out the generated .gen.tsx.
- The manual's CLI reference (tools/manual-ref/cli.ts gen): `godot` joins Generate and 3D tools with a page of its own
  (docs/manual/reference/cli/godot.md, with its prose: run, the window that --window and --movie open, types, open);
  blender.md says what a .ts script does; setup.md and the index follow the help.

Proven in an export of origin/main + this lane: tools/dupes.sh (294, 56), tools/taxonomy.sh, tools/licenses.sh --check,
and bun tools/manual-ref/cli.ts check (48 verbs, 214 flags, every flag described) pass; cargo test -p raea-app-engines
-p raea-app-tools passes.
2026-11-10 21:42:49 -08:00
shinyobjectz 4dc3083c6e apps/engines: Blender's TypeScript runner and Godot in a crate of their own, so apps/tools and engine/cli stay under the 2,000-line crate limit (tools/size.sh)
The lane's first commit put apps/tools at 2,192 lines and engine/cli at 2,041, and L1 refused it. raea-app-engines
(apps/engines, layer apps) now holds godot.rs, godot_run.rs and blender_bridge.rs unchanged, and `raea blender run
SCRIPT.ts` (blender_ts.rs, moved out of engine/cli's cli.rs). Its cli(args) answers `setup blender|godot`, `blender ...`
and `godot ...`, so cli.rs calls it once where it had five branches. Finding and setting up Blender stays in
apps/tools/src/blender.rs, whose run and sha256 are now pub for Godot's setup; zip and dunce moved with Godot.
Sizes now: apps/tools 1,496, apps/engines 777, engine/cli 1,996 (main has 1,999).

tools/layers.toml gives the crate its layer; tools/skills.sh's stale-help check also watches apps/engines/src, where
Godot's usage now lives; docs/godot.feature, sdk/godot/README.md, sdk/godot/tools/gen.sh and runtime/calls/src/blender.rs
name the new paths.

Proven: cargo test -p raea-app-engines -p raea-app-tools (10 and 12 pass, among them a new test that cli() takes only its
own verbs and leaves the rest to the CLI); raea built with it runs `raea godot`, `raea setup godot --check` and
`raea blender run` on a .ts script as before.
2026-11-10 21:42:49 -08:00
shinyobjectz b2631ff5b6 raea/blender and raea/godot: Blender's and Godot's whole APIs from TypeScript (docs/blender.feature BL22-BL35, docs/godot.feature GD1-GD10)
Shane, 11-10: "include natively a blender api package in raea/blender using samchon/blendia as good starting place and
get us to a solid scripting parity to the official blender python api. we will own this ourselves", and "make sure to
add GodotJS which should add a more complete integration and bindings for godot integration".

raea/blender (sdk/blender, started from samchon/blendia, MIT, and rewritten): bpy, bmesh, mathutils, bpy_extras and
gpu typed from Blender 5.2.1's own RNA and docstrings (tools/gen.sh: 1809 structs, 2498 operators, 41 modules outside
RNA; 102 of about 12 900 members any), run against a real Blender. Paths are lazy as Python's attribute access is
(writes and calls sent in order, reads awaited, py.pin for a stable handle), errors are Python's (BlenderError),
mathutils is computed in TypeScript with Blender's maths (1450 values within 1e-5 of Blender's), float arrays are
the value Blender gives (Vector, Matrix, Euler, Quaternion, Color), a call that makes a thing by its type returns
that class (tools/refine.py), node sockets are typed by name, and every argument can be given by keyword.
`raea blender run SCRIPT.ts [FILE.blend] [ARGS...]` runs a script on raea's engine against a headless Blender
(apps/tools blender_bridge.rs, runtime/calls blender.post); under Bun or Node it starts its own, or joins the person's
Blender through raea's add-on (python/raea_blender).

raea/godot (sdk/godot) on GodotJS (MIT): Godot 4.6.1's every class, singleton, enum and builtin typed from GodotJS's
codegen, JavaScriptCore on the Mac and QuickJS-ng on Windows and Linux (no V8). `raea setup godot` downloads GodotJS's
editor build pinned by size and sha256 (apps/tools godot.rs); `raea godot run SCRIPT.ts` bundles the script and runs
its default export (a function given the SceneTree and ARGS, or a SceneTree subclass as the main loop) headless or
with --window, --movie recording with Godot's Movie Maker (the window kept on top, the frame size from the project),
a callback that throws stopping the run, RAEA_CWD with cwd() and resolve() for paths; `raea godot types` and
`raea godot open` (godot_run.rs).

The guides: raea guide bevy/blender gains "A step in TypeScript" and bevy/godot is new, each example type-checked
with its SDK's tests (sdk/blender/test/guide.ts, sdk/godot/test/guide.ts) and run as shown; raea guide bevy routes to
bevy/godot. Their raea-skills copies are 7497067 (branch blender-godot-ts, not pushed). sdk/tsconfig.base.json maps
raea/blender and raea/godot; tools/release.sh ships @raea/blender's python/.

Proven: sdk/blender's tsc and bun tests against Blender 5.2.1; sdk/godot's tsc and its 7 bun tests against the
installed GodotJS; apps/tools godot_run's unit tests; post 07b's film (releases/0.1.1/src/engines), its left half
built and keyed by raea/blender and its right half recorded by raea/godot.
2026-11-10 21:42:49 -08:00
shinyobjectz 3763a778de skills pin: raea-skills d0e5e8d (PR #39, stacked on #38): motion/match-cuts.md and craft/match-cuts, the match-cut guide and its kit, copied from sdk/guides/craft (MC1-MC4), on top of 3d/characters.md's game_engine joints (07166db, PR #38) 2026-11-10 19:23:47 -08:00
shinyobjectz 20391a0649 MC5: the match-cut guide shown to change how a fresh agent plans. One-shot agent sessions planned the same 24-second loop (16:9, 30 fps, a 120 bpm grid) as a storyboard and its chain, four with the guide and two with raea's home on main's guides, which have none. All six chains pass all eleven plan checks, since each found plan.ts in its kit, so the change is in the craft: one hard cut on a downbeat in every guided plan and none in the controls, 7-9 thirds places used against 6-7, and storyboard cut fields that name where the eye lands 85-100% of the time against 46-67%. A fifth session built a 13-shot graybox of one guided chain from the guide's steps; the render check found nothing on it and failed all 22 hooks and both bridges when the hooks were moved. The render passed the cut check, and its floor was clean once three contacts were fixed. The sessions' findings went into the guide (MC1) and plan.ts (MC2) 2026-11-10 19:23:32 -08:00
shinyobjectz 76f383300c MC4: a chain's board for any project (sdk/guides/craft/match-cuts/board.tsx): Board({ chain, places, title, intro }) draws the eye's way through the whole piece with how often it rests at each place, the eleven plan checks' results, each shot's frame with its in hook, its out hook and the eye's way between them (its join, what it lands on, its bridge, montage, hooks in words, carry), and the library of places with their hooks, props and picks; the person's picks (added to and dropped from the chain) and notes come back with app.result. The frame takes the chain's aspect (16:9 when unset). A project's board.tsx is three lines (bench/direction/match-cuts/board.tsx, places.ts) and goes to the person with raea show board.tsx. match-cuts.sh now mounts it headless (raea app check --target web, @raea/app replaced by a stand-in with its two calls), and a board that throws fails it 2026-11-10 19:23:32 -08:00
shinyobjectz c49cc6b267 MC1: raea guide match-cuts, how a planner writes a piece's cuts as a chain of hooks on the thirds while it writes the storyboard (sdk/guides/craft/motion/match-cuts.md). It covers the kit a project copies (craft/match-cuts: chain.ts, plan.ts, thirds.ts, board.tsx) and NAME.chain.ts beside the storyboard; the frame's places; choosing hooks by shape, motion direction, colour, light or sound, and naming the part the render check measures; the action that carries the eye from each shot's in to its out, and where the eye travels over the whole piece; the six joins (graphic, motion, eye on a beat, a FULL wipe, a sound bridge, hard) in a table with what the plan checks and the render check hold for each; a montage's hand-off, J and L bridges and a loop; when a hard cut beats a match; what a chain does in story, pitch (the proof lands where the problem was) and explain (the cursor is the hook); seven planning steps with an example chain, its check file and its rule; what the render check can't see; and the common mistakes. The router's plan step, the story, pitch and explain modes and motion.md's index route to it. tools/skills.sh copies craft/match-cuts into the skill beside craft/checks 2026-11-10 19:23:32 -08:00
shinyobjectz b4aaa8204f MC3: the match cuts checked in the render: at each cut of a chain, the hooked part sits at its thirds place on the frame before the cut and on the frame after it (sdk/guides/craft/match-cuts/thirds.ts). landsOnThirds(chain) is a raea/check system on the chain's cut frames only, reading raea world's facts with no render: a part (named() as raea/check matches names) by its world box projected through the frame's camera, its corners clipped at the near plane; a text by its laid-out box, named by its words; where several share a name, the one nearest its place. A point holds within a tolerance of the frame (0.06 when the rule's values don't say), a line on its axis, FULL to a share of the frame (0.9). Each cut of the chain must be a cut of the composition, a Sequence starting on the chain's frame with the shot's name; a J bridge's sound is placed its seconds before the cut and playing on the frame before; an L bridge's still playing on the cut's frame and its last; the plan checks run once after the frames, so one rule holds both. A project makes it from its chain in a three-line file of its own and names that in a rule or an ask. bench/direction/match-cuts/graybox.tsx builds the chain as a project would (each shot a Sequence from sequences(), each hook placed with onFrame and carried over its shot), and match-cuts.sh checks it: nothing found on it, and each of nine cheats found: a hook off its place, one gone from its place by the cut, the part renamed, a cut ten frames late, a FULL covering half the frame, a part behind the camera, a hook naming no part, the J sound starting at the cut, the L sound stopping at it. The whole bench runs in 7 s. What it can't see: a part hidden behind another, a camera rolled about its view, the eye's way inside a shot, and a 2D graphic that isn't text 2026-11-10 19:23:32 -08:00
shinyobjectz 85c13e6daa MC2: a piece's cuts planned as a chain of hooks on the frame's thirds, and checked by name before anything renders (docs/match-cuts.feature). sdk/guides/craft/match-cuts/chain.ts holds the thirds (nine points, four lines, FULL), the glyphs and which read as the same thing, hooks (what the eye is on, where, and optionally the part that draws it, the way it moves, its colour and light), shots with the join they are cut into by (graphic, motion, eye, full, sound, hard) and chain(), which places each shot on the piece's frames; toFrame and onFrame put a point in the world on the frame and back (Y up, vertical field of view, as Bevy draws it: a ball placed by them lands within 0.0004 of the frame of where the render draws it). Its eleven plan checks: hooks, length (to a frame), lands (every match cut lands the eye where the last shot left it; a point on a thirds line lands on that line; FULL only on FULL), glyph (graphic cuts and montages), motion (the direction kept), carry (a shot that moves the eye says what moves it), hard (says what it lands on), beats (cut to music, every picture cut on a beat; an eye-trace cut always), bridge (J and L sounds that fit their shots), montage (three or more shots handing one hook on) and loop. It imports nothing, so bun and raea check's bundle both run it; plan.ts runs the checks on a NAME.chain.ts by name (--only lands,glyph). A chain is NAME.chain.ts, since cuts.ts is a project's footage edit. bench/direction/match-cuts: a twelve-second chain using every join passes all eleven, and each of fourteen cheats made from it by one change fails the check it names and no other. On the chain of the film this was taken from, lands, glyph and length pass as its own checks do, and beats finds its montage's cuts drifting 44-51 ms off the song's beats 2026-11-10 19:23:32 -08:00
shinyobjectz 19102fac4c skills pin: raea-skills 07166db (PR #38), 3d/characters.md names the game_engine joints (#68) 2026-11-10 17:40:01 -08:00
shinyobjectz 766eab881d sdk/raea/tools/anny/character.py writes a body on MakeHuman's game_engine rig, so it renders (#68). It still wrote Anny's cmu_mb rig, CMU's 31 joint names with 30 finger joints after them in skeleton.json and a skin of 68 of Anny's own bones in body.glb, which raea's character SDK stopped reading when it moved to game_engine (docs/skeleton.feature): the engine refused body.glb, its skeleton's joints (RightHandPinky3, ...) being no nodes there. Now it builds Anny on her game_engine rig (MPFB2's, shipped with her) in her own A-pose and writes what projects/psx/export.py writes for a psx person: the 52 joints in bones.ts's order with parents, heads and tails (a finger's thickness too), Root's weights on the pelvis, each vertex's four heaviest, body.glb's bones nodes of those names, landmarks (eyes from her default rig, which has eye bones) and the surface samples; no skin, bind or follow. The graph paper, the hull, joint.glb and the presets are as they were. The issue's steps on the adult preset: 1.626 m, 52 joints, 1,588 surface samples; the render of held(adult, { upperarm_r: [-0.45, 0.25, 0.9] }) at frame 30 draws the arm raised with the skin bending cleanly, and the rest pose stands in the A-pose. The characters guide's held example and its Why name the game_engine joints, and character.tsx's header the rig 2026-11-10 17:38:21 -08:00
shinyobjectzandSirSicard 6f7a3f4478 raea check --quick looks at a quarter in, the middle and the end of the composition's real length, and says which frames (#86). It read the length from the source's first durationInFrames={N} and took 90 for anything else, so a durationInFrames={DUR} of 300 frames was sampled at 22, 45 and 89, and text only in its second half went unseen (all 0 texts, exit 0) by the after-save hook too. Now render.json carries the composition's length (length, written by every render whatever frames it drew), the quick check renders frame 0 first to read it, then the three stills, and its report says ok looked at frames 75, 150 and 299 of 300. The reporter's one-text file with DUR: main, all 0 texts; now all 1 texts and its safe-area error, as with a literal 300. The extra render of frame 0 costs about half a second (the literal file 0.85 s to 1.40 s). frames_come_from_the_render replaces the source-reading test; the manual's check and render references say both
Co-authored-by: SirSicard <[email protected]>
2026-11-10 17:34:46 -08:00
shinyobjectzandSirSicard 7f438bf130 H.264 above 4096x2304 on the Mac finishes instead of hanging (#83). VideoToolbox gives such a session its software H.264 encoder (VTCompressionSessionCreate still succeeds), which emits nothing until it holds 13 frames; raea keeps 3 in flight and waited on the oldest with no timeout, so the render stopped at frame 0 and the watchdog blamed the GPU. Now a full queue with nothing out for 300 ms has its frames completed (what RAEA_VT_FLUSH does), unlocked since the output callback takes the lock, with one note on stderr naming the size and --10bit, and every full queue after that completes them at once; nothing out for 60 s fails the render with that reason, and finish() waits the same 60 s. A dropped VtEncoder invalidates its session, so a callback can't reach freed state after such an error. The reporter's 4608x2592 60 fps page: main stalls at frame 0 (killed after 20 s, no file); now 60 of 60 frames at 31.0 ms a frame. 640x360 2.2 ms a frame (main 2.4), 1080p 5.0 (5.1). The 60 s deadline itself isn't exercised here (no encoder stays quiet that long)
Co-authored-by: SirSicard <[email protected]>
2026-11-10 17:34:40 -08:00
shinyobjectzandSirSicard 2c2e3ad3b8 What ships is stripped, its symbols kept beside it (#88). Release builds were never stripped: .cargo/config.toml keeps rustc's strip off (it re-signs without the JIT entitlement) and tools/link-jit.sh signed without stripping, so 0.1.1-rc2's macOS raea was 707 MB and its Linux raea 2.67 GB, nearly all symbols and debug info. Now link-jit.sh runs dsymutil on a dist-profile executable (into target/dist/symbols), then strip -x, then signs it with the entitlement; RAEA_KEEP_SYMBOLS=1 keeps them. The release profile the agents build isn't stripped (dsymutil takes 5 minutes a link there, and a stripped binary's panics name no functions). On Linux, release.sh splits each binary's debug info into dist/NAME-symbols/FILE.debug (named by a gnu-debuglink) and strips the copy it packs; on the Mac it copies the dSYMs there and warns of an unstripped binary. release.yml keeps those as a 90-day workflow artifact, never published. Measured on rc2's binaries: macOS raea 707 to 394 MB, raea-page-host 370 to 217; Linux raea 2,665 to 491 MB, raea-page-host 1,541 to 259; the archives 318 to 264 MB (macOS) and 1,008 to 300 MB (Linux). The stripped, re-signed Mac raea keeps com.apple.security.cs.allow-jit (codesign -d --entitlements -) and renders; a test link of a dist executable gets a dSYM whose UUID matches it
Co-authored-by: SirSicard <[email protected]>
2026-11-10 17:27:29 -08:00
shinyobjectz 7099bb9226 skills pin: raea-skills 9c4e65c, 3d/meshes.md says an <Instances>' list that changes moves the copies and each distinct list is kept (#84, #85) 2026-11-10 16:46:23 -08:00
shinyobjectz 9a2187a6b9 raea render says NOT APPLIED for a --w, --h, --fps or --frames the composition's own size or length overrides (the #84 reporter's --frames 3 on a 1,350-frame composition rendered all 1,350, unsaid). They only size a file with no <Composition> or config, as the reference says; the entry now names each one it passes over and the value the composition holds instead. Checked: mem-static.tsx --frames 3 --fps 24 says both and renders its 120 frames at 30 fps 2026-11-10 16:46:23 -08:00
shinyobjectz d7f2aaf076 An <Instances> keeps one copy of its placements across a render's frames, not one a frame (#84). The SDK sent them inside data-props, so a set whose other props changed each frame (a spin) was parsed whole into each frame's props and every frame's scene was kept (the fed render's frames, the clipping check): 20,000 spheres turning cost 2.1 GB at 120 frames and the issue's 60,000 at 4K 7 GB at 60 and 14 GB at 240. Now the SDK sends them as data-at; raea-runtime-react keeps each part's text as one Arc<str> (AT3D) while it's the same, and Node3 and Item carry it as at; the look compares frames' texts before parsing one (instances_column), and the fast live path compares the Arc (panel_srcs, now shared text). <Entities>' expansion moves to raea-core-scene (entities_nodes) to keep raea-runtime-react under 2000 lines. Measured: the 20,000 spinning, 621 MB and 18.6 ms a frame at 120 frames (was 2,117 MB, 69.7 ms), 645 MB at 480; 60,000 at 4K60, 1.04 GB at 60 frames and 1.22 GB at 240. About 1 MB a frame still grows. A binary from before this, run on this SDK, draws an <Instances> as its one mesh 2026-11-10 16:46:23 -08:00
shinyobjectz 8796ceb67c <Instances> whose placements change over the shot move in a video, as they do in a still (#85). A render drew the first frame's list on every frame of a video or an --at list (the row's inst column held one list and said so only in a warning), while a still of a later frame showed it moved. Now the row keeps every distinct list it shows (inst_all, '|' between lists, each frame's list compared with the frame before's) and keys which one each frame shows (inst_k), as a panel's pictures are; a live frame sends its inst, and the fast live path drops to the full one when an Instances' list isn't the one it sent. raea-runtime-scene3d's sync_instances moves the copies (a mesh's, or each of a model's meshes at its place in the model) when the frame's list is another; a list with another count than the copies is the frame's error, and the rows hold the list before it with a warning. The SDK's at, the guide's meshes.md and the manual's rows say a list that changes moves the copies and costs a list a frame. The issue's 20 sliding spheres at 640x360: x-centroid 141.2 at frame 0 and 326.7 at frame 59 in the video (the fed live path, RAEA_LIVE3D_FAST=0 and RAEA_3D=program alike), 327.0 in a --frame 59 still; was 141.1 at 59. The same with a glTF (knot.glb): 142.9 and 326.8, still 327.1. raea-runtime-look tests: lists keyed frame by frame, still ones one column 2026-11-10 16:46:23 -08:00
shinyobjectz 9ebedb3f6f A render's timings (the JSON line on stderr after a video) print only with RAEA_RENDER_STATS=1. The fed, CPU, direct and engine paths each printed it after every render, so a person's terminal and the app's render log showed a line of numbers beside raea's own APPLIED line. The benches that read it ask for it: bench/rerender's bench.sh, bench.ps1 and the iOS app's entry, and bench/lightspeed/export.sh; nothing else read it (tools, apps, docs, tests). RAEA_TIMES' lines are unchanged. On bench/rerender/pages.tsx: without the variable stderr holds the APPLIED and summary lines only; with it, the fed path's line as before 2026-11-10 16:26:20 -08:00
shinyobjectz 75b1c69e71 A page's <video> and <audio> play at their element's volume in raea's window (Shane 11-10: 'a loudness lever not just on and off'). sdk/ui's element takes volume as a browser's does (0..1, RangeError outside it, volumechange) and tells the host __volume, again with each play; runtime/dom/media asks the decoder Cmd::Volume when it changes; raea-runtime-js keeps it per player and plays the sound at that gain while it isn't muted (an AtomicU32 beside muted, read in the audio callback), set again when a sound opens. Before this the window had only muted, so the app's volume slider changed nothing. sdk/ui test: the element's volume reaches the host as __volume, fires volumechange once and is told again with a play. The live composition stage has no volume call yet 2026-11-10 16:16:08 -08:00
shinyobjectz f822be2c05 The Linux release's README names ALSA and fontconfig: raea and raea-page-host link libasound.so.2 and libfontconfig.so.1, which a bare Ubuntu 24.04 lacks, so the first raea failed with a loader error (0.1.1-rc2's tarball in an ubuntu:24.04 container, 11-10). apt install libasound2t64 libfontconfig1 (libasound2 before 24.04); raea.io/install now says the same when ldd finds them missing 2026-11-10 16:15:04 -08:00
shinyobjectz d0d71e67d5 An <Audio> or <Video> fadeOut fades inside its clip, silent by its end, not after it (#89 bug 5). The fade began when the element left the timeline, so a clip played at full volume to its last frame and faded past the cut. A Sequence or Loop pass gives its end through MediaEndContext, the nearest of nested ends, and with endAt's: each frame's volume is turned down into it ((end - f) / (fadeOut * fps), the mixer ramping each frame's gain over the frame after it), and data-fade-out is 0 there, so the stop at the end is the mixer's 5 ms edge. Its last frame isn't 0: a silent sound isn't played, which dropped it a frame early and faded the frame before's gain over the whole fadeOut. Without an end, the fade after it's gone is as before. A 440 Hz tone in a 1 s Sequence, fadeOut 0.5 at 60 fps: -5.6 dB at 0.75 s, -12.9 dB at 0.9 s, silent from 1.01 s (was no fade in the clip and a tail to 1.6 s). sdk/raea conformance media.test.tsx: a Sequence's end, endAt's, a Loop pass's, nested ends, and none 2026-11-10 15:58:28 -08:00
shinyobjectz c4f9a84988 startFrom, endAt, trimBefore and trimAfter say they count the composition's frames, not the media's own (#89 bug 6): a 24 fps clip in a 60 fps film starts at its 4 s with startFrom={240}. The doc comments and the manual's SDK reference said the media's own frame 2026-11-10 15:58:28 -08:00
shinyobjectz 7d66dfc59c RR2: the camera changes per frame. <Camera3d is_active> (Bevy's Camera field) says which camera draws: each frame's first active camera in the tree is the piece's, the others are dropped from that frame with their depth of field and ambient, and the camera row's shot column steps where another camera takes over (raea-runtime-look active.rs). A frame where it steps is a cut (raea-sys-frame Shots), drawn as a shot rendered alone draws its first frame: motion blur's step before it draws the frame itself rather than the other camera's, with a plugin too, and Solari's and the path tracer's history reset. Play sends the shot on its live camera row (0 again when the first camera is back), and a live engine takes a changed shot as a cut (Moved). The step to f - 1 that motion blur needs never ran on any engine, because the Engine's reads count as a Bevy plugin; renders were right anyway (export draws f - 1 before f), and play blurred cuts from the other camera's frame. bench/rerender/rr2.sh on cams.tsx (cameras A, B, A with parts moving): without motion blur the piece equals its three shot compositions 120/120; with it the frames before the first cut and both cut frames are identical and the rest differ by the blur's grain alone (seeded by the frame number, SSIM >= 0.999439; one camera moved instead: 0.810 and 0.785 at the cuts); each shot of the piece rendered alone with --at is identical 120/120; play's 7 held seeks onto and across the cuts equal the render. The craft guide's rule 6 and limits.md say how to cut between cameras 2026-11-10 15:40:43 -08:00
shinyobjectz 5b2c7731e2 skills -> 551722c: 3d.md's rule 6 says how to cut between cameras (each shot its own <Camera3d>, switched with is_active; a cut is one render, its first frame drawn as a shot alone starts) and 3d/limits.md is regenerated from raea's guide (raea-skills #35, for RR2) 2026-11-10 15:40:28 -08:00
shinyobjectz d412678357 DR6: done. Each ask of a note is held by a check that must fail on the work as it stands before the work changes, or by a clip the person signs. An ask names its check (raea's by name or a .ts check by its path), its values, its composition (Ask.of; Rule.of runs a rule only there) and, where it can't be measured, proof { shot | frames, sign }. raea notes check runs the asks through raea check's run (apps/direction, lent by the CLI): a first run that passes is refused (exit 1), a failure is kept with its check and values in .raea/notes-checks.json, a check changed after it failed is to check again, and each finding's by is its ask, so two asks on one check are counted apart; raea check runs the notes' checks beside the rules. Each clip is cut with ffmpeg from the composition's newest render, never from one the composition changed after; the person's sign comes back from the app with the render's sha256 and is kept by raea notes take. An ask reads to check, failing, to sign, passing or signed (the agent's move until there is a clip of the work as it stands), the note its worst; raea notes ls says each and raea notes post sends the badge, each ask's state and each clip (raea show --status --states, --sign --clip --render). raea/check gains a per-rule memo, after, named, turned and inside; six worked checks ship in sdk/guides/craft/checks and in the skill as craft/checks (rides, flat-type, faces, stands-on, shot-length, no-part), with their pieces and cheats in bench/direction/asks (asks.sh: 35 cases as expected). A plain element that covers another is named by the component that drew it (runtime/world). Proved end to end in a copy of the raea app (1109.87): a note sent, taken, restated, failing, the work changed and passing, the clip signed in the page, --done refused, and the sign reopened by a changed composition. Tests: raea-core-facts 16, raea-app-notes 10, raea-app-direction 16, raea-runtime-world 15, engine/cli show.test.ts 5. The craft router says the order, and the manual's notes, show and raea/check pages say what's new. The worked checks' table moves "low poly" to DR14 and "the light at the cut" to DR19, each with why. 2026-11-10 15:34:46 -08:00
shinyobjectz 96191842c4 skills -> 9addeb6: craft/checks, the six worked checks a note's ask copies into its project (rides, flat-type, faces, stands-on, shot-length, no-part); craft/ROUTER.md's notes steps 5 and 6 (give each ask a check or a clip, raea notes check until each fails first and then passes); cli.md's raea notes check and raea show --status, --states, --sign, --clip, --render; sdk.md's raea/check named, turned and inside (raea-skills #36, for DR6) 2026-11-10 15:22:52 -08:00
shane 4eb42e3476 Merge public PR #81 from Ragulsundaram: HTML: frame 0 applies the GSAP timeline's time-0 sets (#79)
A paused timeline's playhead starts at 0, so seeking it to 0 changed nothing and frame 0 showed the page's raw CSS; at t=0 the seek forces the render. sdk/ui test html-frame-zero pins it.
2026-11-10 18:22:11 -05:00
shane db9973375f Merge public PR #94 from JimGHTB12: a page of many layers the size of the frame draws them all, and one of more than Vello's image atlas holds fails its render
vello_encoding lets go of what the resolve hasn't used (the longest unused first) and packs the atlas again with the resolve's own images once, before an image is left out; what is still left out is counted, raea-page refuses the frame naming it, and the fed render now reads refusals, so a video fails as a still does. bench/layer-atlas: 18 frame-sized layers drawn in all 48 frames (32 short on main).
2026-11-10 18:17:18 -05:00
shane d407fde7ee Merge public PR #93 from JimGHTB12: a filter takes in what its element draws outside its box, as Chrome filters it
blitz-paint sizes a filtered element's layer from the boxes it and its descendants draw (drawn_bounds: up to the clips in their way, a descendant's own filter reach included, and the out-of-flow boxes its stacking context paints past its clip), then grows it by the filter's reach as before. bench/filter-overflow checks twelve pixels against Chrome 157 and 120 clipped filtered boxes.
2026-11-10 18:17:07 -05:00
shane ff3515eda4 Merge public PR #92 from JimGHTB12: an inline SVG's CSS transform: a style of transforms alone turns its shape, and view-box origins are at user 0 0
blitz-dom's SVG serializer no longer writes a leading ; before the computed transform when the element's own declarations were transforms alone (simplecss dropped the whole style), and transform-box: view-box's reference box sits at user space's origin, as css-transforms-1 puts it. bench/svg-css-transform gains viewbox.tsx and probes measured against Chrome.
2026-11-10 18:16:00 -05:00
shane 38684c9246 Merge public PR #91 from JimGHTB12: stills of a 2D composition render into a folder that doesn't exist yet, as before DR2
write_manifest makes the manifest's folder before it writes: DR2 wrote it before the 2D stills path made the output folder, so --at into a new folder was refused (bench/at-0 and bench/svg-css-transform failed on main).
2026-11-10 18:15:38 -05:00
shinyobjectz 71750e0542 DR5: done. The craft guide's notes section says the order: raea notes take, restate each note as its asks (one per thing asked, the medium its words name, what it's about, what it doesn't ask for), raea notes ls until it owes nothing, then raea notes post, and a correction from the app is restated again; each ask is one move, so a note with three asks is three moves. The scenario's status says what was built, the end-to-end run in a copy of the raea app (a comment sent, taken, restated, posted, corrected in the page and restated again), the tests, and what wasn't seen. 2026-11-10 14:18:19 -08:00
shinyobjectz 0fbfcb1d48 skills -> df2d233: craft/ROUTER.md's notes section says the order of work: raea notes take, restate each note as its asks, raea notes ls until it owes nothing, raea notes post, a correction restated again (raea-skills #34, for DR5) 2026-11-10 14:18:10 -08:00
James DimachkieandClaude 4c773e5fcf A filter's layer stops at paint containment and at its own clip over the boxes its stacking context paints
Two more ways the layer grew over content nobody sees, both from the Codex review of the first commit:
- the stacking context's boxes were all added whole, where hoisted_content_bbox places them. Only the ones painted
  past the clip need that (the out-of-flow boxes from containing blocks above, #39's from_above, which the walk
  doesn't meet). The others are met by the walk, under the clips they are painted under, so a filtered
  `overflow: hidden` box with a frame-covering `z-index` child keeps a layer its own size;
- drawn_bounds stops at a `contain: paint` box as at an overflow clip (render_element's contain_paint).

bench/filter-overflow/clipped.tsx is now 120 boxes cut four ways, 30 each. The first commit drew 60 of its 120
tiles: each of the two new kinds made 30 layers the size of the frame, more than Vello's image atlas holds.

Co-Authored-By: Claude <[email protected]>
2026-11-10 14:13:17 -08:00
James DimachkieandClaude b6675ced26 The manifest's folder is made in a statement of its own
The first form chained the write after the folder with `.and_then(|()| std::fs::write(&path, m))`, which
tools/dupes.sh reads as a copy of apps/check's hook.rs:105 (57 near-duplicate groups against the 56 allowed).
The folder is now made first, in its own statement, and the write is as it was. The crate is still at its
2,000 lines: the manifest's JSON is written where it is built.

Co-Authored-By: Claude <[email protected]>
2026-11-10 14:06:22 -08:00
shinyobjectz a4fd51bebe DR5: a person's notes become files the work is held to, restated as asks before anything changes. raea notes take writes each note sent from the raea app (each edit comment, with its pin) or said in a session (--said) to notes/ROUND/nN.ts, the words verbatim and no asks; a note already taken isn't taken again. raea notes ls says where each stands (to restate, to check) and what its restatement still owes: a second reading where one ask came from several sentences, each medium its words name (2D, 3D, flat, extruded, real, modelled, voxel) that no ask asks for or turns down, and what a redesign keeps. raea notes post shows a restated note's asks on its comment in the app (raea show --on ITEM --working ID --ask TEXT...), once per restatement, and none that still owes something; the person's correction comes back with the next take as a new line of the note, kept, with its ask in corrected until restated. Note, Ask, Pin and Proof are world facts (core/facts note.rs) with their TS types, and sdk/raea/src/note.ts gives note({...}). The notes are a crate of their own (apps/notes), not apps/direction, which is near its size; the feature file says why. 2026-11-10 14:03:56 -08:00
shinyobjectz 105d285691 RR1: the guides and the SDK's doc comments say the effects are each frame's own. raea guide bevy's rule 6, bevy/limits.md, bevy/post.md and bevy/lights.md: the sky, Bloom, Fog, Grade, ToneMapping, Shadows and the rest, and each light's colour, shadows and shafts, take each frame's values, so shots with different looks are one composition and one render (a cut that brings or takes a mode warms up about 0.3 s); the Grade's worked example is bench/rerender/film.tsx and shots.tsx (content/rome isn't in a checkout), and post.md's mistake is now a render a shot joined with ffmpeg. AmbientOcclusion, AntiAliasing and Shadows' doc comments, and the manual's SDK pages from them (3d, pbr, post_process, light), say each frame's is its own. The skill's copies are raea-skills #32. 2026-11-10 14:03:56 -08:00
shinyobjectz 2e5f9d7755 RR1: every look changes per frame. Each frame's post-processing is its own (runtime/look post.rs), and a set that changes goes in a per-frame table (frame_sets) laid onto the camera's row frame by frame; the camera takes a group off and puts it on again when its columns change (raea-sys-post camera.rs, moved out of raea-runtime-scene3d; volumetric fog's group is raea-sys-fog-half's, which raea-runtime-scene3d hands to it, as a system can't use another sideways). Each light's colour, shadows and shafts change the same way. A draw across a cut (a sky, AO, anti-aliasing, a tonemapper, shadows or volumetric fog coming or going) warms up 8 updates as a load does, so the sky's light is there on a cut's first frame; a ramp is no cut. Play builds its rows the same way: a row with a table is never still (a play's first frame has its sky), depth of field comes and goes with the frames that have one, the page background is keyed, and a seek back that makes a new engine sets play's rows on it again. bench/rerender/rr1.sh: the film as one composition equals its six shot renders 900/900; a 60-frame grade, bloom and fog ramp equals 60 stills 60/60 at SSIM 1.000000; play draws the looks as the render does at 12 seeks and 2 seeks back (the HTML caption over the 3D still differs by up to 2 levels at its edges, as before RR1). The supersample downsample moves to raea-runtime-gpuframe, and light_sig and pass_column to raea-runtime-look, keeping raea-render and raea-runtime-scene under 2,000 lines. 2026-11-10 14:03:56 -08:00
shinyobjectz 45d41783a2 RR0: the iPhone bench stops at a locked phone: devicectl launches nothing on one, so every render after it failed the same way with no log. bench.sh exits 3 saying to unlock it, and clears a render's old logs before copying the new ones back (a stale log read as a fresh result). 2026-11-10 14:03:56 -08:00
shinyobjectz afa0f61ece skills -> dc4d05b: 3d.md, 3d/limits.md, 3d/post.md and 3d/lights.md say the effects and light colours are each frame's own (raea-skills #32, for RR1), and cli.md and sdk.md have raea notes, show's --ask with --working and raea/note (raea-skills #33, for DR5) 2026-11-10 14:03:41 -08:00
James DimachkieandClaude 43e8892ce2 A filter takes in what its element draws outside its box, as Chrome filters it
blitz-paint made a filtered element's layer from its border box grown by the filter's reach, and raea-sys-filters
sizes the layer's texture from that clip. So whatever the element's descendants drew outside its box was cut off
before the filter ran: a wrapper of no size with `filter: blur(4px)` around absolutely positioned children drew a few
px of blur and nothing else, and a 60 px box with `grayscale(1)` showed 60 px of a 200x100 child. The same wrappers
with `opacity` drew whole, since an opacity group already reaches over the element's overflow.

A filtered element's layer now reaches over the boxes it and its descendants draw (drawn_bounds), and the same of
each box its stacking context paints, then grows by the filter's reach as before. drawn_bounds is
scrollable_overflow's walk (blitz-dom's resolve_transforms: each child's box through its transform) with two
differences. It is cut, on each axis an element clips, to that element's box grown by its overflow-clip-margin
(the root element clips nothing, as in should_clip). The overflow itself reaches through every clip, and a texture
made from it is as large as content nobody sees: small filtered boxes, each around a clipping box with a child
covering the frame, became layers the size of the frame, more than Vello's image atlas holds, and tiles went
missing. And a descendant with a filter of its own counts with that filter's reach (its drop shadow).
raea-sys-filters still cuts a layer to the page grown by the reach.

bench/filter-overflow/check.sh: page.tsx draws the blurred wrapper, a grayscale box around a square with its own
drop shadow, and the grayscale box three ways (as it is, clipping its overflow, clipping x alone), probed at twelve
pixels for Chrome 157's values, read from a screenshot of the same markup; clipped.tsx is 60 small filtered boxes
around clipping boxes with frame-covering content, half of them painted by the stacking context, its tiles counted.
The raea before this fails five probes; with it all pass and all 60 tiles are drawn.

Not covered: a box-shadow or an outline of a descendant, and a descendant's url() filter, still end at the boxes'
bounds; a box the stacking context paints that a clip between the two cuts is counted whole (a larger layer, never
a smaller one); and a filtered element inside an element with a perspective transform is still cut to the page's
rectangle in that element's own space (raea-sys-filters' region).

Co-Authored-By: Claude <[email protected]>
2026-11-10 13:22:09 -08:00
James DimachkieandClaude c6f4c9132d An SVG element's transform under a viewBox that doesn't start at 0 0 lands where Chrome puts it
transform-box: view-box, an SVG element's default, takes the nearest viewport as its reference box, and
css-transforms-1 puts that box at the origin of the user space the viewBox sets up, with the viewBox's width and
height. blitz-dom's svg_view_box returned the viewBox's own rectangle, x and y included, and svg_css_transform moves
the origin by the box's corner. So under `viewBox="100 50 400 300"` a `transform-origin` of 0 0 became 100 50:
`<g transform="scale(2)">` drew its content 100 px left of and 50 px above where a browser draws it, and a rotation
turned about the wrong point. A viewBox starting at 0 0, a translate, and a fill-box or stroke-box origin weren't
affected.

svg_view_box now returns the viewBox's size at 0 0. A viewport without a viewBox was at 0 0 already.

bench/svg-css-transform/check.sh gains viewbox.tsx: a square scaled by 2, one turned 180deg about 50% 50%, and one
scaled inside a nested svg with a viewBox of its own, each probed where Chrome 157 draws it (their client rects read
from the same markup in Chrome). The raea before this fails all four probes; with it they pass, and the bench's two
earlier cases are unchanged.

Co-Authored-By: Claude <[email protected]>
2026-11-10 13:16:55 -08:00
James DimachkieandClaude eb3c8ea6bf An SVG shape whose style attribute holds transforms alone is turned by them
Since de1a6830 an SVG element's computed transform goes to usvg in its style attribute: the element's own
transform declarations are taken out and `;transform:matrix(...);transform-origin:0 0` is written after what is
left. When the style held nothing else, nothing was left, and the attribute began with `;`. usvg reads a style
attribute with simplecss, whose declaration parser stops at a `;` before the first declaration, so every
declaration in it was dropped: `<rect style={{ transform: "rotate(30deg)" }}>` drew unturned, and so did one with
only transform-box, transform-origin and transform. A style that also set a fill or a stroke was read.

The element's own declarations are now written from the first of them on (without the separators, spaces and
comments CSS allows before it, which stop simplecss the same way), and the separator only after them when there are
any.

bench/svg-css-transform/check.sh compared mixed.tsx's two squares with each other. Both are of this kind, both drew
unturned, and the comparison passed at 0 px. The check now also probes each square on its turned top edge and where
its unturned edge would be. The raea before this fails those four probes; with it they pass, and the two comparisons
read 75 and 0 px as before.

Co-Authored-By: Claude <[email protected]>
2026-11-10 13:16:55 -08:00
shinyobjectz 6668da3253 A sound render (raea render X.tsx -o OUT.wav) finds its staticFile assets in the edit's folder (from the orientation showcase's gaps): sound_only stepped React without setting the edit's folder (edit_dir, as every picture render does), so a <FramePass file={staticFile(...)}> loaded /media/shaders/... from the filesystem's root and the render was refused at frame 0. Live play's master bounce goes through it too. Checked: a Canvas3D with a file FramePass and an <Audio> renders to WAV (it was refused). The manual's --at example says what the files are named: in order, frame-00000.png the first frame asked for. 2026-11-10 13:09:41 -08:00
shinyobjectz 060380ead5 DR28: text-read, raea's reading check. A render now gives each text an Ocr (what Apple Vision reads in its box on that frame, and the share of its words), from frames decoded once in order (runtime/world pixels.rs), which also measure each text's contrast without an ffmpeg call a text a frame. OCR reads a box fast first, then the text's line across the frame and the box accurately where fast misses a word (a lone short word reads as well upside down), and a crop that holds still but for a video's coding noise isn't read again: the manual's title example checks in 2.5 s from no record. text-read gives each text on, visible (in the frame, at an opacity, size and contrast that read, covered by no layer past a share) and read; holds its reading time (0.3 s a word, at least a second, none for a caption said as it shows) to visible, saying which frames were lost and why; and calls text that can be read where OCR doesn't read it broken (an error past 3 frames; read on under half: a warn). raea check runs it on every composition's newest render as raea's own rule, where it holds the floor's reading rule; what it couldn't measure (OCR off the Mac, covers without --layers) is a note. A word is matched by one key everywhere (core/facts word_key: letters and digits, lower case), which the floor's caption-against-voice rule now shares. bench/direction/read: a caption and five cheats, all as expected. The scenario's plan now gives pixels.rs 240 lines and read.rs 270 (planned 170 and 230): the fast and accurate reads, the still-frame reuse and saying lost frames in groups took more than planned. 2026-11-10 13:08:52 -08:00
James DimachkieandClaude 0198736cd4 A page of many layers the size of the frame draws them all, and one of more than Vello's image atlas holds fails its render
An element with a perspective transform or a filter is drawn apart and placed in the page as an image the size of
its box (raea-sys-filters' placeholder), new in every frame, and Vello copies each into its image atlas. The atlas
stops at 8192 px a side, room for 28 images the size of a 1080p frame, and lets go only of what the last two
resolves didn't use, in one sweep a resolve. So a page of ten such layers or more filled it with the last frames'
images, the frame's last layers (the nearest ones) found no room, and Vello drew them at no size without an error.
A film staged on about twenty frame-sized planes lost a cursor or a mark from single frames, different ones on each
run, with "0 errors, 0 warns".

vendor/vello_encoding, when an image finds no room at the atlas's largest size:
- what the resolve hasn't used is let go, the longest unused first (ImageCache::evict_unused), so last frame's
  placeholders go before a picture this frame's layers drew;
- if an image is still left out, the atlas is packed again with the resolve's images alone, the tallest first
  (repack_with, once a resolve). Images met in paint order cut a guillotine atlas up: 18 a few px apart in size
  didn't all find a place in room for 28;
- the images left out after that are counted (take_images_left_out).
An empty image is no longer looked for a place (the allocator has none for it, and the atlas grew to its largest
looking), and isn't one left out.

raea-sys-page reads the count after each Vello draw (skipped.rs) and refuses the frame, and the fed render now reads
refusals (raea_gpu_device::check::fed_checked): it had no one to read them, so a refused page went into a video as
it came. A still's render read them already.

Tests: vello_encoding's resolver places all 18 frame-sized images of each of 40 frames (unpatched: 10 of 18 from
the second frame) and counts the ones left out of a frame of 40; the cache's two new steps; fed_checked fails a
refused frame by its number.

bench/layer-atlas/check.sh, 18 layers the size of the frame, each with one white tile, on Windows 11 with an RTX 4070
Laptop (Vulkan). Before: 32 of the video's 48 frames short of 18 tiles, stills 1, 3 and 5 of six drew 10, and 40
layers rendered with every frame short. After: 18 tiles in every frame of the video and in each still, and the
40-layer render fails with "frame 0: a page (1920x1080) was drawn without N of its images".

Not changed: the atlas's size. A page still can't draw more images in one frame than 8192 px a side holds (28 the
size of a 1080p frame at best, 6 at 4K); it now fails instead of drawing without them. An image wider or taller
than 8192 px, which Vello also left out silently, fails its render too.

Co-Authored-By: Claude <[email protected]>
2026-11-10 13:06:42 -08:00
shinyobjectz 0b96b5ebd8 skills -> 468ee89: craft/floor.md's reading time is counted while the text can be read, and raea check says which frames were lost (raea-skills #31; for DR28's text-read) 2026-11-10 13:00:51 -08:00
James DimachkieandClaude 22cac9cf13 Stills of a 2D composition render into a folder that doesn't exist yet, as before DR2
Since bb0a1768 every render writes its manifest beside its output, DIR/NAME.render.json for a folder of frames. A 2D
composition's stills write the manifest before raea-render makes the folder and its frames, so with a DIR that
didn't exist the render stopped before drawing anything:

    raea render edit.tsx --at 0 -o new-folder
    REFUSED  new-folder/edit.render.json: The system cannot find the path specified. (os error 3)

It worked into a folder that was already there, and for a composition with 3D, whose path makes the folder first.
write_manifest now makes the manifest's folder before it writes.

bench/at-0/check.sh and bench/svg-css-transform/check.sh render stills into a fresh temporary folder: both fail on
main with the message above, and both pass with this (Windows 11).

Co-Authored-By: Claude <[email protected]>
2026-11-10 12:37:09 -08:00
shinyobjectz 089ff35577 DR4: raea/check in the manual and the skill's router: doc comments on every export (and on raea/ecs World's members it re-exports), the module in the SDK reference's Tools group with its page written by hand above the generated block, and craft/ROUTER.md's evidence step says when a line the work keeps every round is a rule: a controller field naming one of raea's checks or a .ts check written with raea/check, run by raea check PROJECT 2026-11-10 12:14:15 -08:00
shinyobjectz 973ee00acc DR4: a check is a system, and raea's own are written the same way. raea check PROJECT|EDIT.tsx runs every rule that applies to each composition: raea's floor on its newest render, the person's taste, and the workspace's and the project's controller rule fields. It reads the frames each check ranges over (all, cuts, lines, once or a list) into worlds once, runs raea's named checks in Rust (apps/direction systems.rs) and a project's .ts checks in the JS host (raea/check: check({ id, text, needs, level, frames }, (world, frame, values) => ...) and found(...), with the components' types generated from core/facts), and keeps the findings in the project's record. A check that needs a render and has none waits, and says what for; a check that throws, or a rule file raea can't read, is a finding. raea check VIDEO.mp4 is the floor as before.
Proved by bench/direction/proof/proof.sh: five checks that import nothing of Bevy's (a lyric layer over footage, a footage cut, a cue in a mix, a caption in a vertical ad, a rider on a 3D seat), each passing its piece and failing its cheat, and a taste line failing the ad's cheat as the named check of its form.

Fixed on the way: a text's box grows over words drawn past it (the caption cheat passed); a word a cut passes through is in each clip's words (the cut cheat passed); a Part carries its own box before its transform, so a turned part is tested as turned; the help reads `[A|B]` as one argument. Copies folded rather than added: a command's words (apps/check, now also raea workspace's), the printed report and exit code, the person's taste folder, a controller read from JSON (core/brief, now also apps/workspace's), and a path made plain (runtime/bundle's). The spec's lines that the code showed wrong are fixed beside them: --stage moves to DR10, a note's checks to DR6, and the rule field from DR8 to DR4.
2026-11-10 12:14:15 -08:00
shinyobjectz 5ba4688c74 DR4: a rule is a line and the check that holds it (core/facts rule.rs): one of raea's checks by name with its values, or a project's .ts check by its path; taste's six forms are six named checks with the same names and values; a controller gains the field type rule ({ label, check, values?, level? }), each a rule; brief.gen.ts regenerated 2026-11-10 12:14:15 -08:00
shinyobjectz 9444f13df3 skills -> 3f29ca6: cli.md has raea check PROJECT|EDIT.tsx and raea world's --render and --no-render, sdk.md raea/check, files.md the controller field type rule, SKILL.md a rule field and the default raea.root (raea-skills #30; DR4 lands next) 2026-11-10 12:12:07 -08:00
shinyobjectz bb0a1768c5 DR2: every render writes its manifest beside its output (OUT.render.json, or DIR/NAME.render.json); raea world joins the composition's newest render (from the project's record, or --render OUT): each text's Contrast against its pixels, the frame's and each shot's Picture (light and movement), the render's Mix, each cue's Onset in it, and Covers from a render with --layers, measured on the output when asked (raea-sys-measure, which raea check's contrast and loudness now call) and kept in the manifest; a frame or world with no render says what Waits for one 2026-11-10 10:39:13 -08:00
shinyobjectz 43429e6f2a raea render's --layers stamps the source itself (a real-case run of DR2 found it): a layer is a stamped thing, and RAEA_SOURCE_STAMPS was off unless set, so a render with --layers (or RAEA_LAYERS=1) wrote a layers file with no layers outside bench/layers, which sets it. It now sets RAEA_SOURCE_STAMPS=1 before bundling unless the environment says otherwise (RAEA_SOURCE_STAMPS=0 keeps stamps off), as raea world and the stage do. Checked: the conformance composition rendered with --layers and RAEA_SOURCE_STAMPS unset records its layers (19 keys). 2026-11-10 10:26:46 -08:00
shinyobjectz b5de0cbee4 A GPU that stops drawing fails the render (from RR0's A15 bench): the fed and live-3D paths (runtime/export bevy_frame.rs) only said the frame's error and went on, so with Bevy's StopRendering every later frame had no 3D and the render wrote the page alone and exited 0 (bench/rerender shot 1 on an A15: Bevy's atmosphere LUT, Rgba32Float behind a filtering sampler, without FLOAT32_FILTERABLE). raea_sys_frame::gpu::said takes a drawn frame's error: said as before (a model that didn't load: the render goes on), or, once the GPU has stopped, the render's error (exit 1; the frames before it are kept, as for any failed render). runtime/export depends on raea-sys-frame for it. 2026-11-10 10:26:46 -08:00
shinyobjectz 1f4a825714 RT3: a scene with <Grass> under <SolariLighting> renders instead of panicking on frame 0. Solari's mesh copy read each mesh with Bevy's plain accessors, which panic on a mesh whose data went to the GPU alone (RenderAssetUsages::RENDER_WORLD, as raea-sys-grass makes its blades), so all six of RR0's shots refused under Solari; it now reads with the try_ accessors and leaves such a mesh untraced (still drawn, lit by Solari). Tested: a mesh whose GPU data was taken is left untraced; a readable one is copied, its u16 indices widened. Measured on RR0's grass-free shots on the M5 Pro at 1080p: Solari 31.7-64.1 ms a frame against raster's 7.0-32.2 ms 2026-11-10 10:23:38 -08:00
shinyobjectz a3477d0721 RR0: done: today's numbers on the Mac, the Windows PC and an iPhone. Mac: six chunks joined with ffmpeg -c copy 16.3 s quiet (25-27 s loaded), one render 31-38 s, the six start-ups 10.5-16 s; Windows: chunked 71.0 s, 47.3 s of it raea media concat's re-encoding join, React 12 ms a frame on QuickJS (10x the Mac's); the note by hand 3.6 s on the Mac and 64.7 s on Windows, against 29-43 s and 38 s for the whole film again. bench.ps1 runs bench.sh and change.sh on Windows' own PowerShell; the film's shots move to shots.tsx. bench/rerender/ios renders the shots on an iPhone 13 Pro Max (A15: shots 3-5 at 61-265 ms a frame; the atmosphere's Rgba32Float LUTs can't be filtered there, and shot 2 is killed at its first 3D frame); raea-io-os builds for iOS, where its system calls answer as headless (rfd, arboard and opener have no iOS backend) 2026-11-10 10:04:01 -08:00
shinyobjectz 8e15cfccd3 RR0: bench/rerender: a six-shot film made from code (film.tsx), its baseline bench (bench.sh: six chunk renders joined as agents join them, and the film as one render, with each render's start-up and per-frame split) and the one-note case (change.sh) 2026-11-10 09:56:13 -08:00
shinyobjectz fc274e2870 DR3: under the size and copy limits: gen check's fitted-fix wording moves to raea-core-meshcheck (said_fix, tested there), Finding::read replaces four copies of reading a kept finding, the export cache prune is one pass over the folder, and the closures cargo-dupes matched by shape are written another way 2026-11-10 09:54:02 -08:00
shinyobjectz f4c41e9996 skills -> 49d440e: cli.md has raea findings and render's --despite, 3d/rooms.md the room checks' finding shape (raea-skills #28; also a workspace's default folder, landed on main) 2026-11-10 09:20:20 -08:00
shinyobjectz bf7fed1817 DR3: done. raea findings in raea's help and the manual (its page, the reference regenerated); the room checks' guide says their finding shape; the status written in docs/direction.feature 2026-11-10 09:18:27 -08:00
shinyobjectz eab9198a1e DR3: nothing reads as fixed by hiding it: a clip no frame shows is said as a note, a renamed part is renamed, a video from the export cache says what it found, a run is set against the one before of its kind; renders inside another (a review's tiles, a quick check's stills) keep no entry; a review's cameras face where they're put 2026-11-10 09:18:26 -08:00
shinyobjectz c98501a88f DR3: the record and raea findings find the project from a bare file name; a clip's span counts its last frame; gen check says a fitted copy's fix as what to run; raea next's page says what it reads from the record 2026-11-10 08:56:09 -08:00
shinyobjectz aebbdb2d4a DR3: the project's record keeps what each render and check found; raea findings reads it, raea next steps by it
A render, or raea check, of a file in a raea project keeps its findings in .raea/record/, one file apiece named by
when (UTC) and what, with the project's commit ("+" when the file has changes not committed), what --despite let
through, and at most 500 entries. raea findings [PROJECT | EDIT.tsx] [--about NAME] [--check ID] [--open] [--since
RENDER] [--json] compares each thing's latest entry with the one before (or RENDER): what was fixed, what is new and
what is carried, and since which render; a finding is the same across renders by its check and what it is about, not
its frames. raea next reads the record, not out/ and a check.json's time: a render's errors are the next step, then
its video's check and what that found. A render's manifest has all its findings (the exposure's too). The record lives
in core/facts beside Finding, since the render, raea check and raea next all use it (the scenario says why); the
registry's up() moved with it. raea findings is dispatched; its help line follows the lane changing help.
2026-11-10 08:56:09 -08:00
shinyobjectz 8a67680058 DR3: a render's exposure warnings and raea scene light's cuts are Findings
A render's measured exposure (clipping to white, crushing to black, stops off mid grey) is said as its Findings, so
it counts with the clipping check's on the last line. raea scene light says a cut that jumps in exposure or drifts in
white balance as a warn about the shots either side, with the stops or mired it turns on, and counts its findings
last; --json has them. The conversions live in raea-sys-light-meter, beside what they read, and scene light's text is
its report(), which leaves raea-runtime-export 7 lines smaller.
2026-11-10 08:56:09 -08:00
shinyobjectz 44b446302d DR3: raea judge writes what it saw as Findings
The defects present on its sheets become Findings in judge.json (findings, count) and in its text, counted last: a
blocking defect an error, a detail a warn, each a level lower from a judge that only advises (clef before
calibration). A judge sees pictures, not parts, so a finding names its sheet in its words and is about no entity. The
rubric's raw answers stay in defects.
2026-11-10 08:56:09 -08:00
shinyobjectz a0b770709f DR3: raea gen check, raea solid info and raea project scan write Findings
gen check's and solid info's {check, level, says} become Findings about the model, or the part (else the solid's file),
worst first, their count last; their JSON has findings and count in place of found, errors and warnings. A fix's
command, which was in its words, is its fix. project scan's lint is Findings about each file keyed file:line, a note
for what only the render knows, a fix raea doctor --fix applies starting by saying so; its JSON has findings in place
of lint. A file whose registerRoot makes its compositions through a helper is no orphan: the scan says it can't list
them (computed-root, a note).
2026-11-10 08:56:09 -08:00
shinyobjectz 3a705253de RR0: the re-render overhaul planned as docs/rerender.feature (RR0-RR15), with its research: why agents stitch clips with ffmpeg (docs/rerender.md) and the GPU layer on Mac, Windows and Linux (docs/gpu.md) 2026-11-10 08:54:56 -08:00
shinyobjectz 1c49f37e06 Merge branch 'raea-root' 2026-11-10 08:54:56 -08:00
shinyobjectz 4ca98b13a3 Workspaces go in ~/Documents/raea when no raea.root is set
~/Studio didn't say whose folder it was. With no raea.root, default_root: ~/Studio where workspaces are already (the root before 11-10), else ~/Documents/raea, or ~/raea when iCloud keeps the Documents folder (a workspace's git history and footage don't belong in a synced folder). The feed's host says the same (raea-feed host/workspace.ts defaultRoot). raea's usage and the manual's CLI pages name the new default; the skill's files.md follows in raea-skills.
2026-11-10 08:54:10 -08:00
shinyobjectz e98085bb45 render's --quality says what it does on Windows and Linux: OpenH264's bitrate scaled, and no change once a frame fits at its finest quantiser (#82)
The reporter saw --kbps and --quality write byte-identical files. On an RTX 4070 with rc2 the default, --kbps 20000
and --quality master did too (blocks.tsx, 1.0 Mbit/s), while --kbps 1000 gave 0.79: OpenH264's rate control never
goes below QP 12 (encoder_ext.cpp clips iMinQp to GOM_MIN_QP_MODE), so a frame that fits there has nothing left to buy.
2026-11-10 08:28:08 -08:00
shinyobjectz 9b9dd9e780 K's min, max and clamp take their bounds plus a zero the GPU compiler can't prove (#82)
On a Snapdragon X's Adreno X1-85 (Vulkan), a byte from clamp, min or max that was then shifted and or'd into a word
came out with 0xff in its top two bytes: the compiler fused the three into a pack it gets wrong. nv12buf.k packs four
luma bytes that way, so half the luma words of a bright frame were wrong and video striped. The bounds now add kz,
i32(shape.n >> 31u), which is zero but read from the shape uniform, so the compiler can't fuse them. The reporter
found the trigger and this fix on the device (128,319 of 262,144 words wrong before, 0 after); the test runs their
kernels, clamp and min/max each packed with or and shl, against the interpreter on random pixels. 05c978867's
unsigned shl stays (an i32 shift into the sign bit is still left to the compiler) but wasn't the cause.
2026-11-10 08:28:08 -08:00
shinyobjectz ebce4f28ab DR3: the older commands' JSON reads as a Finding (Finding::of_value), and scene lint's findings are read through it
{check, level, says} with what it is about (part, into, on, file) is what scene lint, gen check and solid info write;
of_value reads it as a Finding, a pass ("ok") as none, an object fix as its command. The plan's finding.rs is 240
lines for it.
2026-11-10 08:25:40 -08:00
shinyobjectz 2c111623c7 DR3: raea check's report turns an issue's second into its frame without a closure of its own (tools/dupes.sh) 2026-11-10 08:25:40 -08:00
shinyobjectz 0a895f8752 DR3: the render reference says a render's findings, its count last, exit 1 on an error, and --despite 2026-11-10 08:25:40 -08:00
shinyobjectz 9f3ffa7b1c DR3: raea render's usage names --despite CHECK WHY 2026-11-10 08:25:40 -08:00
shinyobjectz 574a4d228f DR3: raea/room's checkLayout and checkDecor return raea's one Finding
Each is { check, level, about, says, measure, by }: the check by an id a command line can name (work-aisle, walkway,
facing, behind-seat, work-triangle, decor-floats, decor-opening, decor-unit, decor-height, decor-centre, decor-width),
error, warn or note, the things it is about by name, and the distance it turns on with its limit. A clearance that is
met is a note (it was "ok"), so its margin still shows; "warning" is now "warn" and "rule" is "check".
2026-11-10 08:25:40 -08:00
shinyobjectz 898a0068df DR3: raea render counts its findings last and exits 1 on an error not let through
A render's findings (the clipping check's, as it says them) are kept for the end: the last line it prints is their
count, and an error not let through makes it exit 1 once its output is written. RAEA_DESPITE="CHECK: why" (a check's
name, or all) lets a check's errors through and writes the reason into the manifest, for a harness that renders many
pieces and compares pixels: P26's compare and recapture set it; a raea before this ignores it. The --despite CHECK WHY
flag is read the same way; its line in render's usage follows once the lane changing that line lands. raea check
--quick judges its stills' render by the manifest it wrote, not its exit, and reads their findings.
2026-11-10 08:17:29 -08:00
shinyobjectz 05abcdfc82 DR3: one Finding; the clipping check, raea scene lint and raea check write it
core/facts gains Finding { check, level, about, frames, says, measure, fix, by }, its one-line text, ranked (worst
first) and count, with its TypeScript declaration; raea check's P0 and P1 are errors, P2 a warn, P3 a note, and lint's
"warning" a warn. systems/contact's found.rs makes the lint's faults and the clipping check's overlaps Findings about
the parts by name, with the number each turns on and its fix. A render's manifest carries "findings" (it carried
"clipping", which nothing read) and says each on stderr; raea scene lint prints them worst first, notes included,
with the count last. raea check -o writes {file, fps, findings, passed} and prints the count last; --quick takes in
what its stills' render found and says a render that fails as an error. raea next reads the errors from findings.
The plan's apps/direction issue.rs is six lines in apps/check's report (the scenario says why).
2026-11-10 08:17:29 -08:00
shinyobjectz b8e55e9d5f skills -> 9e0adfd: cli.md names raea render -o OUT.wav and --audio OUT.wav (raea-skills #27; also raea world, landed on main) 2026-11-10 08:01:17 -08:00
shinyobjectz 1b55218328 raea render -o OUT.wav renders the sound alone, and --audio OUT.wav writes a video's sound beside it from the same pass
Shane 11-10: "we should add an audio-only render and also be able to render video and audio at the same time".

apps/sound (raea-app-sound, new): `raea render EDIT.tsx -o OUT.wav` bundles the composition as a render does (its --composition and flags), steps React through every frame for its sounds with no frame drawn (raea_runtime_export::sound_only, which live play already mixes from), masters it by its <Mix> as the video's sound is mastered, writes a 48 kHz WAV and prints its length, loudness and true peak. `--audio OUT.wav` on a video render sets RAEA_AUDIO_BOUNCE, which every render path already writes from its own bounce (export sound.rs and fed.rs, encode sound.rs), so the WAV is the very sound the video carries before AAC, with nothing rendered twice. engine/cli: the render line names OUT.wav and --audio, and run() hands a render to apps/sound first (one line; raea-cli is at its size limit). runtime/export, at its 2,000-line limit, is unchanged. docs/manual/reference/cli/render.md regenerated, with --audio described.

Checked: the Orientation film's sound alone, 125.8 s in 22.3 s, -14.0 LUFS, true peak -1.7 dBTP; a 2 s test with -o t.mp4 --audio t.wav wrote both, the WAV 2.000 s and the MP4's audio track 1.961 s (AAC).
2026-11-10 08:01:17 -08:00
shinyobjectz 0207451f1b DR28: Shane's note of 11-10 as a scenario: text on screen timed by when it can be read, and visible text OCR doesn't read is an error
His words verbatim, restated as five asks with what they don't ask. Each Text gets on, visible and read times; reading
is measured against visible; visible-but-unread is an error, a run read on under half its visible frames a warn; a
named check on every render, with its cheats. DR26 builds it straight after DR4.
2026-11-10 07:47:50 -08:00
shinyobjectz fcdcd8dbaa DR1: done. Status written; a word set one letter a span reads as its letters
The render's page manifest joined every text node of a run with a space, so a word revealed letter by letter
(content/rome's <Letters>) read "4 9 B C" for 49 BC; a run of single letters now reads as they're set, spaces
included (raea-page run_text, 1 test). A part's kind comes from its shape, never from what its author named or
propped it (the cheat test). raea world's reference page (docs/manual/reference/cli/world.md), the Check group's
order shifted by one. tools/layers.toml places raea-core-facts, raea-runtime-world and raea-app-direction.
raea-runtime-react back to 2,000 lines (scene/holders.rs, behaviour unchanged).
2026-11-10 07:47:50 -08:00
shinyobjectz ca54307223 DR1: raea world reads a frame into one world of facts
runtime/world (raea-runtime-world) steps a composition's React to the asked frames, as raea scene lint steps it,
and reads each into raea-core-facts entities: the 3D layer with its Camera (velocity from the next frame) and
Parts measured from their triangles, Text3D as Text and Part; the page laid out by the render's own Blitz page with
nothing painted (BevyPage::lay_out), so text has its box, size, font and line count; Sequences as Shots (from and
to; Sequence now stamps data-raea-end), footage as Clips with SHA-256 and their take's words, sounds as Cues, the
project transcript's lines and <Speech> lines; each entity's Source from the code stamps. <style>/<script> text is
not read as words.

apps/direction: raea world EDIT.tsx [--frame N | --at A-B|A,B] [--find JSON] [--no-layout] [--json]; --find spans
media (with, without, where Comp.field).

Folds: raea_runtime_react::scene::surface, raea_runtime_bake::runs, raea_core_facts::Word/transcript_words (raea
check's). Stamps name Audio. The time a layout-only page update gets is sent as a drawn update sends it.
2026-11-10 07:47:50 -08:00
shinyobjectz e0067e2f00 DR1: a composition's stepped frames are readable outside raea-runtime-export (scene_frames and a Frame's scene are public; no lines added, the crate is at its limit), and raea scene lint steps the frame it reads and its neighbour, not the whole composition 2026-11-10 07:47:50 -08:00
shinyobjectz 7222289a05 DR1: core/facts, the world's components. A frame of a composition as one world of entities with components by name, in raea/ecs's form (an id, a parent, components), as data Rust reads and a TypeScript world is built from: Source, Layer (its medium: 2d-type, 2d-graphic, 3d, footage, page), Text (words, box, extruded), Part, Camera, Shot, Clip, Cue, Line, and relations by name. Their TypeScript declarations come from the types. 2 tests. 2026-11-10 07:47:50 -08:00
shinyobjectz b46b6468f4 skills -> 1c68723: raea show posts quietly and asks everything as one item with previews (raea-skills #25: SKILL.md §6, cli.md raea show --open, the repeatable --question and --preview; #26: files.md names engine/cli/src/app.ts as app-host.json's reader) 2026-11-10 07:21:15 -08:00
shinyobjectz b30ef6adca raea show posts quietly, and asks everything in one item with previews
Shane 11-10: "any time you make an update to the feed it takes me out of the thing im currently doing", and the questions should be "a single thing that allows me to actually preview things while answering questions and all in one feed item rather than a bunch of them".

show.ts: --question repeats, each starting a question whose --choice's follow; --preview FILE after a --choice is that choice's (a still, a video, a sound, a NAME.script.ts or a .md), after the --question the question's own. Several questions, or any preview, go to the app's host as one item (questions); one question without previews is sent as before. The CLI opens the item's raea:// link (which brings the window up) only with --open or when it just started the app; otherwise the page finds the post (raea-feed f03b4e7, /host/shown) and says so in a notice. An app from before that route never finds an unsent item, so there the link is opened as before.

app.ts: the app-host verbs (show, harness, task, library) and their host lookup move out of native.ts, which was over the 500-line limit (514; now 407). cli.rs: the help line says so. docs/manual/reference/cli/show.md: regenerated, with --open and --preview described and the prose saying posts are quiet.

Checked: the parser on seven argument lists (old one-question stills, three questions with previews and --open, a --preview before any question, two previews on one choice, a stray file beside questions: refused with why); tsc --strict on native.ts, app.ts and show.ts; tools/manual-ref/cli.ts check clean for show.
2026-11-10 07:17:47 -08:00
shinyobjectz 086115c907 DR0: docs/direction.feature, the plan for direction that holds. One world of facts, findings and rules in raea/ecs's form, so a person's notes become checks and a project is built in an order that can't skip modelling, blocking or review. 28 scenarios (DR0 to DR27) with what raea already has and the gap in each, read against the code. DR0's decisions are decided. bench/direction/proto/world.ts proves the form on raea/ecs as it is, under plain bun: a 2D lyric, a 3D rider and seat, a footage cut and a cue in one world, four checks as systems, a three-ask note, six cases and two cheats as expected. 2026-11-10 06:25:45 -08:00
shinyobjectz 20a696e793 A click in a scene reaches the object under an overlay that covers the frame, and a part with no key is followed. A film lays a sheen or a grade over its whole picture as a page element; the pick answers the page's element when it is in front, so with one on top no click reached a 3D part. An element covering seven tenths of the frame or more now gives way to a part under the point and is answered as what is over it. locate boxes a part around its vertices as drawn (a skinned part by its pose, as a pick's own box already was) and finds a part with no LayerKey by its entity (entity:BITS, which a pick now names as entity_key), so the box of a loaded model's own mesh follows it. 2026-11-10 06:08:57 -08:00
shinyobjectz f25c925eec A script's solid is its expression until something needs the solid. /3d's manifold held a built Manifold for every solid a script made, so a set made of cuts was cut twice on every open: once here as the script ran, and again by the renderer, which builds its meshes from the expressions (and now keeps them on disk). A boolean, a move, a rotate and a scale now only write the expression; a query, a mesh, an export or an operation on the solid itself builds it then, from the expression (raea-core-shape's solid_or_empty, so a boolean that left nothing can still be asked whether it is empty). A launch-film set played offscreen at frame 0: 4.6 s to 3.6 s, another 4.4 s to 3.2 s, each frame the same bytes as before; examples/headless/solids-and-worlds.ts passes its 12 checks. 2026-11-10 05:46:47 -08:00
shinyobjectz 07e47b4ee1 What is drawn is measured as it is posed. The scene's bounds (what a free camera frames) were each mesh's own box placed by its own node, which says nothing of a skinned mesh: a rigged model under a scaled armature measured a fraction of what was drawn, and a camera framing it stood inside it. view::bounds now takes the vertices the frame draws (layer.rs drawn, the ones a pick's ray is cast against), so a skinned mesh is measured where its joints put it. Seen in raea.app 0.1.0-dev.1109.42 on a launch-film cat: the whole model in frame, its parts pointable. 2026-11-10 05:20:10 -08:00
shinyobjectz 05c9788672 A video's bright parts come out whole on GPUs whose compilers treat a signed shift into the sign bit as undefined. nv12.k packs four luma bytes (and two chroma pairs) into a word with shl, the top byte by 24, and the WGSL shifted i32: a byte of 128 or more overflows into the sign bit, which WGSL defines but a driver's compiler (a Windows on ARM GPU's, #82) didn't, so every 4 pixels of a bright region came out as two right and two at 255, white stripes over the whole video (the reporter's luma plane: 29,489 of 29,495 words whose second byte is 128+ have both top bytes 255; none below). K's shl now shifts as u32 and bitcasts back, the same bits as the interpreter's wrapping_shl, so nv12.k, nv12buf.k and p010buf.k (whose 22-bit shift overflows the same way) are unchanged. 1 test: the WGSL shifts unsigned, and on the GPU all 256 bytes pack as the interpreter packs them. 2026-11-10 05:14:25 -08:00
shinyobjectz bec8cddcf0 kept.rs names raea's caches folder without the closure another file already has 2026-11-10 04:30:04 -08:00
shinyobjectz ee62b13253 A solid's mesh is kept on disk between runs. An expression's mesh is the same every time a build makes it, and the boolean cuts of a furnished set were a quarter of the seconds its scene took to open, on every open. raea-core-shape's cached() now reads the mesh it made before from raea's caches folder (shapes/, named by the expression and by the running build, written beside and moved into place) and makes it only when it isn't there; RAEA_SHAPE_CACHE=0 turns that off and =DIR moves it. A launch-film set played offscreen at frame 0: 12.2 s with it off, 4.6 s kept, the frame the same bytes. 1 test (a kept mesh reads back bit for bit; one cut short isn't read). 2026-11-10 04:29:00 -08:00
shinyobjectz 281da9cc10 An ImagePlane plays its sprite sheet and swaps its picture in an mp4 render: a video's 3D is drawn live, frame by frame, and a live frame sent a panel only its placement, visibility and screen values, so the cell frame showed, the src it showed and its sheet's grid stayed at frame 0's for the whole film (a folder of PNGs, made from a program, played them). A live frame now sends a panel's sheet_frame, sheet_cols, sheet_rows and src when they change (live.rs's columns, and the fast path, which leaves a panel whose src changed to the full path: it holds the raw src against the one it last made a row from, so an unchanged one costs nothing); the engine swaps a live panel's picture when its row's src names another (scene3d::Pictures' live, found as spawn finds it). A program keys a part's grid as it keys its cell (it was the first frame's), so a src that changes to a sheet of another grid shows that sheet's cells; a card whose height follows its picture takes the new picture's shape. Found making 0.1.1's app showreel, which worked around it by rendering frames. 2 tests: raea-runtime-look's sheet keys, and raea-runtime-live's live_sheet (raea-runtime-scene is at its 2,000-line limit), where RAEA_LIVE3D_CHECK holds the fast path against the full one; a 30-frame repro reads the right cell and grid at frame 20 in the mp4, the program render and the PNGs. 2026-11-10 03:42:36 -08:00
shinyobjectz 0614e4b950 A 3D part asked for again by id answers its own box on the frame. The game inspector re-reads the picked element on every frame (stage.inspect), and for a 3D part that answered the holder element's box, which has none of its own: the outline a click drew on a mesh was gone a frame later, so a 3D object looked unselectable while page elements kept their outline. Live::element now places the part by its key (raea-sys-frame locate) and says it is a part. Seen in raea.app 0.1.0-dev.1109.33: three meshes in a paused game keep their outline as frames step. 2026-11-10 02:16:19 -08:00
shinyobjectz a956d8f8ee The dot-named edit joins the bundle key's file list in place, and its test is in raea-runtime-bake: raea-runtime-bundle is at its 2,000-line limit 2026-11-10 00:24:48 -08:00
shinyobjectz b6aa8b1d1e A preview wrapper rewritten gets its own bundle: a dot-named edit is part of its bundle cache key. The cache names a bundle by every source file under the edit's folder, but its walk passes dot files over, and the app's preview wrappers (.raea-view-NAME.tsx) are dot files rewritten at one path. A wrapper naming a model's new light level was given the bundle that named the old one, so the stage asked for a copy the store had dropped (the 3D didn't open) or drew the model as it was before an edit. Keys of other edits are unchanged. 1 test; docs/preview.feature PV3b has the packaged low-disk run. 2026-11-09 23:57:40 -08:00
shinyobjectz 85f20faaf0 Shadow maps fit a GPU with little memory of its own (#66): on Vulkan raea reads the largest heap the GPU calls its own (device-local) and, when a scene's <Shadows> gives no size, makes the sun's and spots' maps 2048 a side under 2 GB and 1024 under 1 GB instead of 4096, saying so once. An AMD APU's own memory on Vulkan is the carve-out its firmware leaves it (often 512 MB), and wgpu's allocator never puts a GPU-only texture anywhere else, so a sun's four 4096 cascades, 268 MB of depth, are the likeliest cause of #66's OutOfMemory on a Ryzen 7 4700U (not reproduced: there's no such machine here). On an RTX 4070 the blocks example's first frame holds 571 MB of GPU memory with 4096 maps, 370 MB with 2048 and 319 MB with 1024 (Vulkan, wgpu's allocated total, a build of this change with the heap size forced). The heap read gave 12012 MB on the 4070 and 32606 MB on lavapipe, which keep 4096; DX12 and Metal draw in the system's shared memory and keep 4096 too. A <Shadows mapSize> still wins. 2026-11-09 23:56:39 -08:00
shinyobjectz f04b3ae1b4 PV3b: docs/preview.feature has the proxy store's rules as the packaged app showed them 2026-11-09 23:33:51 -08:00
shinyobjectz fa78ed3bc4 raea play no longer hangs at start-up on Windows: pipelines compile on the render thread as each frame queues them, as Bevy always compiles them on macOS. On Bevy's task pool (its asynchronous compilation, Windows and Linux only) the first frame's wait_pipelines waited on pipelines the pool left unstarted with its threads idle. With the v0.1.0 zip on an RTX 4070, 17 of 32 opens stalled 2.8-42.6 s and some never finished; on lavapipe at 4 cores, as the release run checks it, kept-unmount hung past 200 s, the stall that timed out v0.1.0's Windows live-play check and kept Windows out of the release. Compiled on the render thread, the same binary opened 32 of 32 in 0.49-0.70 s on the 4070 and passed 26 of 26 plays on lavapipe, and a build with this change passes all 13 live-play cases on both. RAEA_BEVY_ASYNC_PIPELINES=1 brings the task pool back. Why the pool leaves its tasks queued isn't known yet. 2026-11-09 23:22:38 -08:00
shinyobjectz dad6913856 PV4d: docs/preview.feature says what the packaged app showed and what it fixed 2026-11-09 22:36:37 -08:00
shinyobjectz aa0a416b73 A GPU error is the render's error (#66): raea's engine answers Bevy's render errors itself (gpu_error), putting the first one, with what the GPU said, where a frame's other errors go, so raea render refuses with it. Bevy's own handler asks the app to quit, which an engine that steps its app never reads: the frame came back half drawn and was saved with APPLIED and exit 0 (on DX12 the blocks example drew its floor and one box; on an AMD iGPU's Vulkan, OutOfMemory left the background only). Drawing stops as before; it's said once, since Bevy asks again every update and a live game prints each one. A unit test gives it an FXC error twice 2026-11-09 21:34:45 -08:00
shinyobjectz 85adac1697 Ink outlines compile under FXC, DX12's shader compiler on Windows (#66): the wide line's 16 directions at three radii are one loop of 48, since FXC can't unroll two nested loops with a return inside them (X3511, 172 iterations) and every 3D scene builds this pipeline, so on DX12 its error stopped every 3D render (the blocks example drew its floor and one box). Checked with naga 30's HLSL as wgpu gives FXC (shader model 5.1, loops bounded) and Windows Kits 10.0.22621's fxc on cuda-box: the old shader fails as the issue says, the new one compiles; the filter passes, froxel min/max, traced AO and shadow-only compile too 2026-11-09 21:26:25 -08:00
shinyobjectz 4c990e1b75 PV4d: a 3D part asked by id answers its own props; docs/preview.feature's scenarios are done
stage.inspect {id} on a part's element answered the holder's raw props (data-3d, data-props as a string), so the
feed's game inspector lost a picked part's props on its next refresh; it answers the part's kind and its own props
now, as the pick does. The feature file: what was built after the first landing (the card that changes code, every
kind of file, a level of detail by size on screen, notes to agents), and each scenario's @done.
2026-11-09 21:24:03 -08:00
shinyobjectz 794769e15b raea show --on against a raea app from before it says so (quit and reopen to update), not the old host's bare "not found"; the host's own refusals still pass through 2026-11-09 21:07:12 -08:00
shinyobjectz e1b7a97ebd Video playback without the hitch every 300 frames: the Mac decoder's reader is recycled at a keyframe play has reached (a cursor stepped back to it, nothing decoded), so it no longer decodes a GOP first; frame 299 went from 46 ms (1080p60) and 163 ms (4K30, 250-frame GOPs) to about 20 ms at the next keyframe, open-GOP HEVC too, every frame's time checked (io/apple/tests/play_timing.rs). The page's video picture shares the frame's pixels instead of copying them again (Shane 11-09: playback starts to get weird) 2026-11-09 21:05:42 -08:00
shinyobjectz 29c7d81369 skills -> 5f0118a: cli.md has raea play --pick/--view and raea media lod (raea-skills #24) 2026-11-09 21:04:01 -08:00
shinyobjectz f0e01210c2 PV3c: raea's help names media lod; two copied closures folded (L1 dupes) 2026-11-09 21:03:59 -08:00
shinyobjectz 551b2102bb PV1: the pick and the layer pass walk the drawn meshes through one function; the licence catalog follows meshopt
systems/frame layer.rs drawn(): every shown triangle-list mesh with its posed vertices and corners, which the layer
pass rasters and a pick's ray is cast against (pick.rs had the walk copied). A render's layers are byte-identical
before and after (shapes.tsx frame 10), and the live pick answers the same part. meshopt and float-cmp are in the
plain build now (raea media lod), so tools/licenses.sh takes them out of the catalog-only list in LICENSES/ and
NOTICE.
2026-11-09 21:03:59 -08:00
shinyobjectz 1bed45b774 PV3c: raea media lod, a model at a lower level of detail; the feature file says what is built
raea media lod MODEL.glb [--level N] [--texture PX] -o OUT.glb halves every mesh's triangles a level (meshoptimizer
on the mesh's own vertices: skins, morph targets, UVs and materials untouched, only the index lists replaced), makes
embedded pictures at most PX on their longer side, and drops what nothing uses. Checked: a skinned body, 27,420
triangles to 6,854 at level 2, rendered and looked at. 2 tests. Cargo.lock has raea-runtime-live's raea-sys-frame
edge too (the first PV1 commit left it out). docs/preview.feature: each rule's status and what isn't built.
2026-11-09 21:03:59 -08:00
shinyobjectz e58ed228a4 PV4d: stage.locate says where parts and world points are on the stage now
A selection's box and a note's pin follow what they are on as the camera turns, a prop moves or the frame plays
(systems/frame pick.rs locate: a part's meshes' bounds and each point through the frame's camera). The stage's host
calls move to calls.rs (lib.rs was past 500 lines); the bundle's raea-props lines are two shorter (its crate was at
2002).
2026-11-09 21:03:59 -08:00
shinyobjectz 7198060ab9 PV1: raea play --seek takes --pick X,Y and --view YAW,PITCH,DISTANCE (its help line and manual page) 2026-11-09 21:03:59 -08:00
shinyobjectz afb3eb6dc6 PV1: the live stage picks 3D parts, a free camera, and props set as it plays
stage.pick answers what is under a point of the stage, the page and its 3D as one picture: a 3D part (its layer key,
name, JSX props, box, the point hit and its distance; the nearest mesh along the pointer's ray, skinned meshes as
posed: systems/frame pick.rs) or the page's element, with the part behind it. stage.view draws the 3D from an orbit
until it is given back (systems/frame view.rs, FreeView). stage.props sets a composition's props over its defaults
as it plays (the entry's raea-props). What the stage opens is stamped, so every pick has its place in the code.
stage.seek (written 11-07 for the editor's Live, never committed) lands with it. raea media still takes --width.
Proof: raea play shapes.tsx --offscreen --seek 10 --pick 640,330 answers shape-2 at shapes.tsx:28:11#2 with its
props; --view 1.2,0.9,9 draws it from above. docs/preview.feature is the plan.
2026-11-09 21:03:59 -08:00
Ragul Sundaram b529c4ea00 HTML: frame 0 applies the GSAP timeline's time-0 sets (#79)
A paused timeline's playhead starts at 0, so seeking it to 0 was a no-op and
frame 0 showed the page's raw CSS. At t=0 the seek now forces the render.
2026-11-10 10:31:30 +05:30
shinyobjectz 2293efc121 skills -> 1ccc69b: edit comments are tasks, marked working and done (raea-skills #23: SKILL.md §6, feed.md comment_task and feed_post answers, cli.md raea show --on/--working/--done/--note/--sub) 2026-11-09 20:08:55 -08:00
shinyobjectz cf28bf1ca0 A shell verb's refusal exits 1: js::run_node takes the script's process.exitCode at its end, as Node does (engine/cli's native.ts sets it, so raea show, init, cut, frame, part, brand and library refusals exited 0) 2026-11-09 20:06:50 -08:00
shinyobjectz a7e5b6c1d1 raea show --on ITEM --working ID / --done ID [--note LINE] [--sub NAME]: an outside session marks the person's edit comments as tasks in the raea app (POST /host/task); FILE --replaces ITEM --done ID settles them with that version; docs/review.feature R3; the show page's flags (Shane 11-09) 2026-11-09 20:03:00 -08:00
shinyobjectz eff11d8778 raea hook: the open's arguments read in one loop, the program's name and the patch's headers matched without copying other code's closures (dupes) 2026-11-09 19:41:12 -08:00
shinyobjectz dfa94a073e skills -> 306d618: raea's hook stops a Preview open once for raea show, for any harness (raea-skills #22; cli.md lists raea hook [claude|codex|gemini|kimi], so every lane's L1 skills check needs it with this lane's raea) 2026-11-09 19:35:05 -08:00
shinyobjectz 94a1cc59f7 The manual's hook, skills, skill and index pages for raea hook on every agent (tools/manual-ref/cli.ts gen in an export of origin/main + this lane) 2026-11-09 19:35:04 -08:00
shinyobjectz e9e0fba83e raea hook for every agent: media opened in Preview goes to raea show (a second try goes through), and every harness gets the hooks (Shane 11-09)
Shane 11-09, on a hook that steers an agent's open of a still to raea show: "yes lets do that or at least make it double
confirm then push and confirm. again also make sure all hooks and usages are acp agnostic not just claude".

apps/check/src/hook.rs: raea hook [claude|codex|gemini|kimi] reads any of the four harnesses' hook input (the harness
named, or told apart: Gemini's BeforeTool/AfterTool, Kimi's client_type). Before a shell command (Bash, shell,
shell_command, exec_command, run_shell_command; not Codex's apply_patch), a still, video or sound opened with open,
open -a Preview, xdg-open or qlmanage -p while the raea app is installed is stopped once: exit 2 with the reason on
stderr, which every harness hands its agent, naming the raea show command for those files. The same command in the
same session within ten minutes goes through (~/.raea/hooks/again), so an agent that means it says so twice. open -a
raea, open -R, links and PDFs are never stopped. After a save (file_path, path, or the files an apply_patch adds or
updates), the quick check on a composition, its findings in the shape each harness reads (Kimi's plain stdout,
Gemini's AfterTool context, Claude Code's and Codex's PostToolUse context). quick.rs loses its Claude-only hook.

apps/tools/src/agent_hooks.rs: raea skills install --agent A adds both hooks to that harness's own config:
~/.claude/settings.json, Codex's hooks.json (trusted in its /hooks), ~/.gemini/settings.json (milliseconds, named),
Kimi Code's config.toml [[hooks]] (only the four keys it allows). An event with a raea hook entry is left alone.
agent_mcp.rs loses claude_hook. engine/cli/src/skill.rs: hooks for every agent; a skill folder that's a link (a
raea-skills checkout) is left as it is instead of replaced by a stamped copy.

engine/cli/src/show.ts, native.ts: raea show names its poster from the harness that started it, found up its parent
processes (HARNESSES: Claude Code, Codex, Gemini, Kimi, OpenCode, Goose, Cursor, Amp, Qwen Code, Crush, Aider) when
its shell carries no mark, with an inbox per harness process.

docs/agents.feature A5d, A5e; the manual's hook and skills pages.
2026-11-09 19:33:35 -08:00
shinyobjectz 36c3fe1dd7 skills -> 96e0764: files.md lists ~/.raea/app-host.json and raea show's inbox (raea-skills #21) 2026-11-09 19:13:23 -08:00
shinyobjectz 5512224403 raea show in the manual: docs/manual/reference/cli/show.md
What raea show does for an agent outside the app, the inbox its answers come to, examples, and every flag described
(generated by tools/manual-ref/cli.ts from raea help --json in an export of origin/main + this lane); index.md lists it
under Agents and setup, and skill, skills and setup move down one in order.
2026-11-09 19:13:18 -08:00
shinyobjectz 397d502f67 raea show: in the manual's CLI groups, and raea-cli back to its 2,000 lines
tools/manual-ref/cli.ts: show is in Agents and setup (what an agent reads and shows the person). engine/cli: the show
comments fold into library's, so the crate is 2,000 lines again (rask's crate limit).
2026-11-09 19:11:35 -08:00
shinyobjectz 28b1acb6d2 skills -> 128698f: agents show work in the raea app with raea show, never in Preview (raea-skills #20; the reference's cli.md lists raea show, so every lane's L1 skills check needs it with this lane's raea) 2026-11-09 19:05:38 -08:00
shinyobjectz cbc763ef8d raea show usage: each flag names one value, so the skills reference counts them right
engine/cli/src/cli.rs: the help line reads --ask LINE and --question Q --choice A --choice B [STILL...] instead of
quoted phrases and a parenthesised choice, which tools/skills.sh read as extra values.
2026-11-09 19:05:25 -08:00
shinyobjectz 890e51afc5 raea show: what a session shows the person goes to the raea app as an item they can use, not Preview (Shane 11-09)
Shane 11-09: "my agent working raea keeps making sheets in preview and not in raea how do we make it so when using
raea and raea app is installed new edits new sheets or examples or questions are pulled up in the raea app and not
preview. we should see them as interactive too. the whole point of raea is interactive artifacts and things and
recording them after making an answer."

engine/cli/src/show.ts (a SHELL verb): raea show FILE... [--title --ask --project --replaces --as --role --inbox] and
raea show --question Q (--choice A ... | STILL...). native.ts finds the running app (RAEA_FEED_HOST, else the address
the installed app leaves in ~/.raea/app-host.json, raea-feed host-file.ts), starts it when it's installed and not
running, POSTs /host/show (raea-feed host/show.ts makes the item: stills a look, several a storyboard, a video a
watch, a sound a listen, a script or .md a read, a .tsx an artifact or the project's composition in its editor, a
question an ask), then opens raea://item/<project>/<id> so the window comes up on it. It prints the session's inbox
file, where what the person sends comes back (docs/agents.feature A3b). Without the app, the files open in the Mac's
viewer and it says nothing was posted. raea library finds the app the same way now. The poster's name and inbox come
from the harness (CLAUDE_CODE_SESSION_ID, ...) unless given.

docs/agents.feature: the file (rules A1 to A4 from 11-09) with A5, raea show.
2026-11-09 19:00:23 -08:00
shinyobjectz c6bb61b248 skills -> a5eb821: a plan is shown as previz, a storyboard of stills or its NAME.script.ts (as a screenplay and an A/V table), and a whiteboard maps (raea-skills #18, #19: feed.md's feed_post read and look files from raea-feed 4f526df; every lane's L1 skills check needs it) 2026-11-09 18:12:00 -08:00
shinyobjectz bb1d2bd0d5 Paste into a page's text fields: raea's pages get Blitz's shell provider with the clipboard (Shane 11-09: "make sure i can paste text into any text field")
Blitz's default shell has no clipboard, so Cmd+V in any field of raea.app inserted nothing (and Cmd+C, Cmd+X copied
nothing). systems/page gets PageShell, the shell provider a page's document is made with (config_in, beside PageNet and
the others); raea-page-host inserts one (src/shell.rs) on raea-io-os's clipboard, which is the system's in the window and
the process's own headless, as navigator.clipboard's is. io/os exports clipboard_text and set_clipboard_text for it.
Test: shell.rs pastes into a focused field through Blitz's event driver (with Blitz's default shell the same paste
inserts nothing), then Cmd+A, Cmd+C copies the field's text back.
2026-11-09 16:51:03 -08:00
shinyobjectz 148379c6e4 skills -> 43b2de1: ~/.raea/sessions and ~/.raea/inbox in the raea skill's files reference, and app-prefs.json's writer is host/app-prefs.ts (raea-skills #17; every lane's L1 skills check needs it) 2026-11-09 16:41:48 -08:00
shinyobjectz 3eccbe39e5 raea gen: a TypeScript flow anywhere imports raea/gen (Shane 11-09: the launch film's Source page flagged four flows importing ~/raea/sdk/gen by its absolute path)
Since the public-first split (11-06) the public sdk/tsconfig.base.json leaves raea/gen out (sdk/gen is the private side's), and `raea gen` gave bun only that file, so a flow outside raea's tree couldn't import raea/gen, the name docs/gen.feature GN12 says flows use. Agents wrote the absolute path instead, which the app's lint rightly flags as an import from outside the project.

raea-io-gen-core tsflow.rs (moved out of raea-io-gen cli.rs read_flow, and re-exported there; in gen-core so raea-io-gen stays under its 2000 lines): bun gets the runner's own override, the SDK's tsconfig with the SDK's folder as baseUrl and raea/gen and @raea/gen mapped when sdk/gen is there. A public install without sdk/gen gets the public names only. Tests: the override (with and without sdk/gen, a file that isn't JSON) and a flow in a folder outside the SDK importing raea/gen through bun (skipped without bun). The launch film's four flows now import raea/gen and quote with raea gen plan.
2026-11-09 16:39:45 -08:00
shinyobjectz b85409d738 Layer pass conformance (docs/review.feature R2e): a flat <Screen> and a skinned character (RobotExpressive, CC0, walking) in bench/layers/conformance.tsx, each one layer. A Screen carries its source stamp (engine/bundle stamp.rs PART_NAMES), and an ImagePlane or Screen panel gets its LayerKey and RAEA_HIDE_LAYERS visibility like a mesh (runtime/scene lib.rs bevy_parts; models.rs panels_rows sends its components). A fifth mutant, bind (a skinned mesh drawn in its bind pose, systems/frame layer.rs posed), fails at IoU 0.80, so the oracle checks the pose. All 18 layers IoU >= 0.962; all five mutants fail. 2026-11-09 13:27:32 -08:00
shinyobjectz bf49796080 skills -> 42d53be: ~/.raea/app-prefs.json in the raea skill's files reference (raea-skills #16: the desktop app's Selectable layers setting, RAEA_APP_PREFS; every lane's L1 skills check needs it) 2026-11-09 13:26:31 -08:00
shinyobjectz 70946b84bf Layer pass before landing (L1): LICENSES/ and NOTICE as tools/licenses.sh writes them (vello_cpu, vello_common, glifo and fearless_simd are in the plain build now, through raea-sys-layers, so not the catalog's alone), and page_css joins its parts in one expression (raea-runtime-bundle back under 2000 lines) 2026-11-09 13:09:03 -08:00
shinyobjectz ed0ebd2c01 Layer pass before landing (L1): RAEA_HIDE_LAYERS's page CSS (hidden_css, layer_selector) moved from raea-runtime-bundle, which was over its 2000 lines, to raea-sys-layers (hide.rs); the render manifest's videos and text moved to engine/page motion/manifest.rs (motion.rs was over 500); raea-sys-layers in tools/layers.toml (systems, a facility raea-sys-frame builds on). Copies folded: a part's key from its props is raea_sys_layers::key_from_props (runtime/scene bevy_parts), an env switch set to 1 is raea_io_home::env_on (fresh.rs stamps, apps/game probing), and the ID scene draws a box shadow as its element's layer out to 1.5 deviations past its box (hiding an element hides its shadow) instead of skipping it. 2026-11-09 13:06:19 -08:00
shinyobjectz ea3d7f85ec raea render --layers in the manual's CLI reference (docs/manual/reference/cli/render.md): what NAME.layers holds and where it goes 2026-11-09 12:53:54 -08:00
shinyobjectz d1edca2817 Layer pass: a <Video> is a layer (docs/review.feature R2e; parked with the source stamps): Video and Audio pass their source stamps on to the element they draw (sdk/video media.tsx useMediaAttrs), and the page bridge keeps a video's KEPT data-raea props (runtime/page elements.rs dropped every data- prop of a video, its player's and the stamps alike). bench/layers: a 4 s test-pattern clip in the conformance composition, IoU 1.000 at all three moments; all 16 layers pass and the four mutants still fail. 2026-11-09 12:53:33 -08:00
shinyobjectz e029385319 Layer pass, the 3D's half (docs/review.feature R2b, R2e; work in progress, parked with the source stamps): each Engine::draw records its frame's meshes with --layers (systems/frame layer.rs record: every shown Mesh3d from the lowest-order active Camera3d drawn on the CPU straight at mask size, nearest first, as the layer of the nearest part up with a LayerKey; skinned meshes posed by their joints; no morph targets), and the file's mask is the page's where it painted and the 3D's elsewhere (raster.rs, Recorder::frame_3d). Names: a use's outermost element is named after its component (Badge), an unnamed part after its tag (Mesh3d), else aria-label, class, tag. RAEA_LAYERS=1 turns it on too, until --layers is in the help with its manual entry. bench/layers: a third mesh in front of the moving cube, written before it; mutants.sh breaks the pass four ways (keys swapped, the 3D 2 px right, the farthest triangle winning, the page under the 3D): each fails compare.sh while the pass passes all 15 layers at IoU >= 0.969. 2026-11-09 12:48:31 -08:00
shinyobjectz 7a3e87dddb Layer pass, the page's half (docs/review.feature R2b, R2c, R2e; work in progress, parked with the source stamps): raea render --layers writes NAME.layers v1 (systems/layers, raea-sys-layers: gzip of RAEALAYR, the header's table of layers, each frame's quarter-size mask as runs) and render.json's "layers" names it. The page is painted a second time once the frame's update has laid it out: blitz-paint now names the node each paint call draws for (painting()), and an ID scene on vello_cpu draws that node's layer index as a flat colour with antialiasing off (edges counted above 12/255 coverage, glyphs emboldened as the page draws them). bench/layers/compare.sh scores each layer's mask (its own pixels plus those of the layers inside it) against oracle.sh's: all 12 page layers pass at IoU >= 0.977 at frames 10, 45 and 80. The 2 mesh layers come with the 3D half. key_of moved to raea-sys-layers (systems/frame re-exports it). 2026-11-09 12:45:05 -08:00
shinyobjectz c03edea294 Layer pass oracle (docs/review.feature R2e, work in progress, parked with the source stamps): bench/layers/conformance.tsx (two 3D meshes, a component used twice, a page element, text, an image, a rotated element and a .map() list, overlapping) and oracle.sh (each layer hidden in turn at three moments, the pixels that change as quarter-size masks, sampled as NAME.layers' are); all 14 layers' hides change their pixels. Stamps: raea's page parts (Img, Video, AbsoluteFill) stamped as 3D parts are; the work folder's motion/prelude read as raea; data-raea-idx kept through the page bridge. 2026-11-09 12:45:05 -08:00
shinyobjectz 09a935abd0 Layer keys (docs/review.feature R2a, work in progress, parked with the source stamps): a .map()'s key in the stamps (data-raea-idx, and loc#key in a use chain); raea's 3D parts (Mesh3d, Model, Entity…) stamped and given a LayerKey component (raea_sys_frame::layer) from it in runtime/scene; the work folder's SDK imports (../motion/x) read as raea's, not the edit's own; only components that read their children's types keep them unwrapped; RAEA_HIDE_LAYERS hides a layer by key (page CSS from its stamps, a 3D part's Visibility) for the layer pass's oracle. Not for landing before the layer pass. 2026-11-09 12:45:05 -08:00
shinyobjectz e1914cabca Source stamps (work in progress, parked): engine/bundle's stamp.rs and its lib.rs and test hunks, parked by the orchestrator so #51's fix can land in the same crate; not for landing until its owner finishes it 2026-11-09 12:45:05 -08:00
shinyobjectz 0adc2ed8f2 Source stamps (work in progress, parked): the render manifest carries each element's nearest source stamp (engine/page motion.rs) 2026-11-09 12:45:05 -08:00
shinyobjectz 4ca212f207 Source stamps (work in progress, parked): fresh::stamps() reads RAEA_SOURCE_STAMPS, and the bundle cache keys on it; not for landing until its owner finishes it with engine/bundle's stamp.rs 2026-11-09 12:45:05 -08:00
shinyobjectz ace0f1423f docs/review.feature: R2 status (the player reads NAME.layers v1 and picks by shape; the engine's page half passes the oracle at IoU >= 0.977; the 3D half and --layers come with stamps-wip) 2026-11-09 12:44:24 -08:00
shinyobjectz 3240414eff docs/review.feature: reviewing a video in raea's player, comments on the picture (R1) and every layer selectable the same way for 3D, React and the page (R2), from Shane's ask of 11-09 2026-11-09 12:44:24 -08:00
shinyobjectz 311b7988ee The Rune host answers the synchronous net.storage.get, through raea-io-net-calls as its async net.* calls are (L1 targets suite: rune-motion and rune-signin on native listed it as unanswered once storage.ts read kept values synchronously)
Without BEVY_TSX_STORAGE the answer is an error, which storage.ts takes as nothing kept. The counter test asserts the call is answered, not refused.
2026-11-09 12:42:59 -08:00
shinyobjectz ebd147a076 The desktop app keeps its localStorage across launches, and a page reads it before its code runs (Shane, 11-09: the open workspace and Getting started's Hide were lost on every quit).
raea.app never set BEVY_TSX_STORAGE, so raea-io-net-calls refused net.storage.* and storage stayed in the window's memory (the launcher half is in raea-platform). With it set, a page still read its settings before the kept values came back, as net.storage.get was only asynchronous, and an app saving its settings on load (apps/app settings/store.tsx) would write its defaults over them. net.storage.get is now a synchronous host call too (raea_io_net_calls::storage_get, registered by raea-runtime-js net.rs install), and sdk/ui's storage.ts fills localStorage from it at load, falling back to the asynchronous answer on a host without it. Test: raea-runtime-js net::tests::kept_storage_answers_synchronously.
2026-11-09 12:42:59 -08:00
shinyobjectz d3e2922058 Page media in its own crate, raea-runtime-dom-media (runtime/dom/media), so raea-runtime-dom stays under the crate limit (L1 size: 2049 lines); its copies folded
The video and audio elements' sync moves out of raea-runtime-dom as it was, and raea-runtime-dom re-exports it as media. raea-sys-image and vello were only media's and go with it. Stream's four one-line senders are now one ask(Cmd), with Cmd public (L1 dupes: seek and muted were one shape). A seek that has landed is Media::landed, which is checked from two places. Tests: raea-runtime-js, raea-runtime-dom and the new crate pass; raea-cli checks.
2026-11-09 12:39:13 -08:00
shinyobjectz ada5e5b5a3 Page media: React's muted reaches the host's player, so an unmuted video plays its sound
The app's watch player stayed silent when unmuted (Shane, 11-09): React DOM's muted is a property, but the page runtime took it as a prop on the wire, which runtime/dom's media.rs never reads (it reads __muted), so play()'s muted start held. sdk/ui dom/host.ts applyProps now sends a media element's muted through its setter on change, and at creation sets __muted in _extra, which hostElement sends with the create. Test: dom.test.tsx React muted case (52 pass).
2026-11-09 12:31:56 -08:00
shinyobjectz f8844bb385 Page media plays: video and audio elements' play(), pause() and load() drive the host's player, on the sound's clock
The desktop app's watch player threw on play() (the page runtime's <video> had none: the host played nothing), and
going back from an item crashed the app (its preload cleanup called load()). Now raea-runtime-js media_play.rs plays a
source on its decoder's thread: frames asked for at the clock's time (a slow decode skips frames, never lags), the
clock the sound's, out of the default device through cpal (media_sound.rs; muted plays silence on it), so picture and
sound can't drift; the wall's with no device or RAEA_AUDIO_MUTE=1. runtime/dom media.rs passes __play, __muted and
__load and tells playing, time (each frame), timeupdate (4 a second) and ended. sdk/ui dom/media.ts: play() (a
Promise), pause(), load(), paused, ended, loop, autoplay, canPlayType, preload, readyState per source, a new src
pausing as a browser's does; dom/host.ts gives React's onPlay, onPause, onPlaying, onTimeUpdate, onEnded, onCanPlay,
onVolumeChange and onEmptied their events. Tests: media_play::tests (wall clock: order, end on time, exact seek,
loop, pause), sdk/ui dom.test.tsx's media case (51 pass).
2026-11-09 12:31:56 -08:00
shinyobjectz 804f57664f raea-app-registry in the apps layer (tools/layers.toml); the dupes ratchet down to 294 exact, from folding the registry's line counting into its caller 2026-11-09 12:30:45 -08:00
shinyobjectz 151de4ba63 Project registry in its own crate, raea-app-registry (apps/workspace/registry), so raea-app-workspace stays under the crate limit (L1 size: 2060 lines)
The registry depends on nothing of the workspace crate. It now owns up() and slug(), which the workspace crate re-exports, and takes the controller ids named by the project's overrides as an argument. raea-app-workspace's registry module wraps scan() with them, read from .raea/project. raea context takes both the workspace's sections (controllers, project files) from one call, raea_app_workspace::context(), which keeps raea-cli at 1997 lines. Folded the copies L1 counted: Registry::warnings() and composition_files() replace the filters and sort in doctor and next, resolve() builds its candidates in a loop, and a line number is counted from the newlines before it (stamp.rs had the same line_starts). New test: an override naming a missing controller is linted once. raea-app-registry has 6 tests and raea-app-workspace 6.
2026-11-09 12:28:18 -08:00
shinyobjectz 0f6c275bdb Project registry lint: a path outside the project is written from ~ (~/.cache/raea-mocap/...), as a person reads it 2026-11-09 12:14:40 -08:00
shinyobjectz 9aaf3f21e6 Project registry (docs/projects.feature PJ8): one static reading of a project's compositions, components and controllers, and lint for what isn't connected
apps/workspace src/registry: each .tsx and .ts is parsed with oxc (the version engine/bundle uses), without running it. A composition is each <Composition> that a registerRoot registers, with its id, component, size, fps and length read from the source. A prop written as a top-level constant, or simple arithmetic on constants (const FPS = 30; 15 * FPS; edit.w; Math.round), is read as its value; anything else is kept as the expression. A .tsx whose default export no other file imports is registered under its file's name, sized from its newest render manifest. A component is a .tsx that a composition imports, directly or through another file. A controller is a module whose default export is controller({...}) from raea/brief.

Lint (each finding has a file:line and its fix): not-a-project, broken, orphan, unresolved, outside, duplicate-id, computed (info), unregistered (info; fixable when a manifest gives the size), controller-home (fixable: moved to controllers/<id>.ts), controller-duplicate, override-missing.

CLI: raea project scan [DIR] [--json]. raea doctor lists the warnings, and --fix registers a default export and moves a stray controller, committing only the files it touched. raea next reads compositions from the scan (no more grepping for registerRoot) and puts unconnected files first. raea context gains a PROJECT FILES section. Tests: 11 pass.
2026-11-09 12:03:32 -08:00
shinyobjectz 4b8157f98c A still of a 3D composition no plugin carries state for draws only its own frame, not every frame before it (#77). Every engine installs the plugin clock (some plugin is always registered), so catch_up rendered each frame before a still in full: render graph, shadow views and submit, about 90 ms a frame in a film, and --at 2448 took 226 s. The engine now steps through those frames only when the rows hold something a plugin carries from frame to frame (raea_runtime_plugins::steps): a component or resource of a type from outside Bevy's own scene and render crates and raea's (a rigid body, a particle effect, Bevy's animation, time or states; a short type name, which could be anyone's), a driven mesh, or a row kind not known to be frame-pure. Keyed component rows land on their frame however it is reached. The film's --at 2448: 226 s -> 20 s, pixel-identical; a physics still at frame 100 (avian) still steps all 100 frames. bench/at-cost checks that a frame-pure still steps none. 2026-11-09 11:18:41 -08:00
shinyobjectz d4a00c6044 Stills late in a long 3D composition no longer cost memory and time with the frame index (closes #77). A still at --at F stepped React only near F, but held every frame before it as copies; each changing column was keyed on every one of those frames, and the timeline evaluated and kept every frame (a film's --at 2448: 234 s and 7.1 GB, against 9 s and 3.1 GB at --at 30). The timeline (core/program) now evaluates only the frames where some key's value can change from the frame before, and a frame no key changes shares the frame before's columns. A column keyed one value a frame keeps only the keys where its value differs from a neighbour's (raea_runtime_look::linear_keys, also used by the scene's per-frame colours), which is exact under linear interpolation. 200 turning cubes at --at 2448: peak 829 MB -> 504 MB (1.32x the --at 30 peak, was 2.14x), engine open 700 ms -> 280 ms, and the frame is pixel-exact. bench/at-cost checks the ratio and the pixels. 2026-11-09 10:23:46 -08:00
shinyobjectzandJameschuthink 97d93d244f Direct render: the 2D image rows' Blitz page (a Bevy App) is made on its first draw, not with the view, so a render that never draws an image row makes none (closes #70)
rows2d::Rows keeps an Option<Page> built by page() on first use with the same arguments; draw returns R<bool>
since building can fail there now, and the engine's overlay (runtime/gpuframe overlay.rs) logs and skips that frame's
rows on an error, as it already does for rgba(). texture() is None before the first draw.

Checked on an M-series Mac, release build, RAEA_EXPORT_CACHE=0, a 30-frame 800x1000 TSX with a moving text box
(and the same with an <Img> on frames 10-19; a TSX page arrives on the GPU, so neither draws an image row): one
warm-up, then 5 runs each, two rounds in swapped order. Median 0.395 s -> 0.312 s (about 83 ms a render). Frames
identical by framemd5 on both, the <Img> red on exactly frames 10-19 in both builds.

Co-authored-by: Jameschuthink <[email protected]>
2026-11-09 08:46:40 -08:00
shinyobjectzandJameschuthink b800a1c5e1 raea-perceive: portable OCR fetches ocrs's .onnx models (the .rten copies answer 403), and the tool's vision-portable feature turns on its own ocr-portable and face-portable, so a vision-portable build has read-lines and the face commands (closes #69)
Checked on this Mac with an empty model cache: cargo build --release -p raea-perceive --features vision-portable,
then read-lines --backend ocrs and see-layout --backend portable on a HELLO WORLD picture both read the line (rc 0),
and the cache holds the two .onnx files.

Co-authored-by: Jameschuthink <[email protected]>
2026-11-09 08:46:17 -08:00
shinyobjectz 85f4f08e14 docs/manual/tutorials: Build and install plugins (install from npm, Git or a folder, read and approve, use in the feed, build one with reload on save, share it); narration to come 2026-11-09 08:45:34 -08:00
shinyobjectz d854f1a7af docs/manual/tutorials: Work as a team leaves out rendering across teammates' computers until that is built and tested 2026-11-09 08:25:31 -08:00
shinyobjectz 19acea76e4 docs/manual/tutorials: ten narrated tutorials, from getting started to storage and search
The scripts the docs' tutorial player narrates (Fish, through raea-api's speech) over the app's own screens on a made-up
workspace, Sunmelt: get started, connect your agent, a tour, review and notes, inspect, controllers, publish, extend
with the SDK, teams, and how storage (Git with LFS pointers, media by hash) and search (vectors in turbopuffer) work.
Each page carries its full narration as text; its front matter names the tutorial the page plays.
2026-11-09 08:25:31 -08:00
shinyobjectz ca69ed1094 docs/manual/guides: Build and share plugins (the manifest, where contributions show, @raea/app and its permissions, the sandbox and network, building with a folder install and hot reload, components for compositions, sharing on npm or Git, what isn't built) 2026-11-09 08:24:34 -08:00
shinyobjectz 41d22acc0c skills -> 0ae1e8e: plugins in the raea skill's references (raea-skills #15: feed_post's plugin type, ~/.raea/plugins) 2026-11-09 08:23:48 -08:00
shinyobjectz 8b94190778 Plugins a person installs: compositions import them after the project's own packages (engine/bundle edit.rs: RAEA_PLUGINS, else ~/.raea/plugins), and docs/ecosystem.feature records phase 2's start (the manifest, per-person installs, approval, permissions, a network allowlist; tools, panels and item types) and the two answered questions 2026-11-09 08:21:24 -08:00
shinyobjectz 4c9ddb3d42 skills -> 22dd7fc: artifacts in the raea skill (raea-skills #14: SKILL.md §5, feed.md's artifact type) 2026-11-09 07:49:03 -08:00
shinyobjectz 494711189a docs/ecosystem.feature: phase 1 narrowed to artifacts as agents' own code, and done (raea-feed cc4fe7d, 9f0ef35; raea-platform 90a6a03; raea-skills #14) 2026-11-09 07:47:40 -08:00
shinyobjectz b4b2f7f03c docs/ecosystem.feature: a plan for raea's plugin ecosystem, the engine and the app (Shane 11-09)
What exists, the two answers it rests on (the engine's extension surface is the SDK with native Bevy plugins under it;
the app is the side that needs a runtime: a loader, a sandbox, a bridge and hot reload, whose dev reload already
exists in blitz/dev.mjs), one package format for both, the engine's three tiers by how they load, the app's extension
host and its contribution points, sharing through npm with an index in raea-api, the phases, and four open questions.
2026-11-09 07:09:21 -08:00
shinyobjectz d6f41c605a release.yml: a plain version tag is a full release
Shane 11-09: the release after canary.3 is v0.1.0, not canary.4. A tag with a suffix (v0.1.0-rc1, canary) stays a
pre-release; a plain version (v0.1.0) is now a full release, GitHub's latest, instead of every release being made a
pre-release.
2026-11-09 06:55:57 -08:00
shinyobjectz 65eb89e635 Windows Live play runs the zip's raea, unpacked, with RAEA_NO_TREE=1 and the cases copied out of the checkout. target/dist's raea has no share/raea beside it, so its home was the checkout with the build's target/ in it, and there every 3D case ran past 300 s (v0.1.0-rc1: 10 of 13 open), where fresh-runner probes of the same zip opened them in 19 to 67 s, after release-check too. A failing case whose log is empty no longer ends the step's log loop (grep -v exits 1 on it under pipefail) 2026-11-09 06:54:59 -08:00
shaneandshinyobjectz 8b5f153ec5 surface: a guide's raea export-game is the command it names, not raea export (#76)
The check that every `raea <command>` in the agent's context exists matched \w+, which stops at a hyphen, so the
delivery and games guides' raea export-game read as raea export and failed every lane's L1 since #73. It matches commands
as the help list is read ([a-z][\w-]*); export-game and setup-audio are the hyphenated ones the guides name, both real.

Co-authored-by: shinyobjectz <[email protected]>
2026-11-09 09:54:55 -05:00
shaneandshinyobjectz 39aade79f7 App steps: { frames: 30 } and { dialog: 1 } play again; a count from JS arrives as 30.0, which u32 and usize refused (#75)
raea app check reads export const steps through the JS engine, whose JSON writes every number as a double, so the
documented { frames: 30 } failed with '{"frames":30.0} is none of press, ...'. Frames and Dialog take a whole double as
the count it is and refuse 2.5, -1 and anything past the type. Tests for both, checked against the unfixed enum.

Co-authored-by: shinyobjectz <[email protected]>
2026-11-09 09:20:09 -05:00
shaneandshinyobjectz c5a6d4f846 Modes and verbs, past a recipe: each mode's decisions and how it fails, each verb's Decide and When it goes wrong; skills at raea-skills c507860 (#74)
The five modes each name the choices that make or break the piece, with the default that comes easily and why to
question it, and a table of how it fails (what you see, why, what to change). The nineteen verbs each say what to
decide before changing anything and what a wrong pass looks like.

Co-authored-by: shinyobjectz <[email protected]>
2026-11-09 09:18:41 -05:00
shaneandshinyobjectz 9ce80fc134 Delivery and apps guides (motion/delivery, motion/interface), reference/platforms.md from the app's publishing guidelines; skills at raea-skills 261e854 (#73)
motion/delivery.md: from the brief and the delivery controller to one composition per shape, cutdowns as their own
edits, UI zones checked with raea check --shape --platform, captions and loudness, file names and versions, export tags,
and publishing as the person's (the app's Publish view). Its example renders in 9:16, 1:1 and 16:9.
motion/interface.md: an app built state by state for modes/tool, roles and labels, steps that walk every state, the
check read PNG by PNG. Its example passes raea app check on web (7 steps).
tools/skills.sh gen writes reference/platforms.md from apps/app src/publish/specs.ts at the recorded commit, and check
holds it current like the other references. motion.md routes to both guides.

Co-authored-by: shinyobjectz <[email protected]>
2026-11-09 09:13:58 -05:00
shaneandshinyobjectz b7fc9e964f skills: the craft guides travel with the raea skill (raea-skills 4db36f6), and tools/skills.sh coverage says what nothing teaches (#72)
tools/skills.sh gen copies sdk/guides/craft into the skill by one list (copies()): bevy/ as 3d/ as before, and now
motion.md and motion/, and the router, floor, rubric, modes/ and verbs/ under craft/, each folder with its NOTICE. check
fails on a copy that differs from its guide and on a copy whose guide is gone, in any of those folders (3d/plugins.md
and 3d/rows.md are the skill's own).

tools/skills.sh coverage lists every verb in raea's help, every SDK entry (sdk/raea/src) and every feed tool with whether
a guide or the skill teaches it outside reference/; check warns on each untaught one, so new engine surface shows in
L1. COVERAGE_SKIP holds what an agent never runs (hook, traces, raea/dev_tools, raea/test), each with why. On this main
with raea-skills 4db36f6: 43 of 43 verbs, 28 of 28 SDK entries, 19 of 19 feed tools. Mutants checked:
an edited copy and an orphaned copy fail, an untaught verb warns.

Co-authored-by: shinyobjectz <[email protected]>
2026-11-09 09:07:00 -05:00
shaneandshinyobjectz 1faf24f9ac skills: raea-skills bc52595 (feed.md's four new feed tools, files.md's new ~/.raea paths, the skill tested against 0.1.0-rc1, a controller is not a feed item) (#71)
raea-skills #10 regenerates reference/feed.md (controller_post, editor_selection, editor_edit, item_tags; feed_post's
changed, export, tags, uses) and files.md (~/.raea/feed, media, plugins.json, usage-queue.json) from origin/main with the
feed app at raea-feed 1b3b9fe, and stamps the skill raea-tested-against 0.1.0-rc1 with rc1's upstream snapshot; #3 adds
SKILL.md's paragraph on controllers against notes and the feed's controller_post. tools/skills.sh check passes on that
export.

Co-authored-by: shinyobjectz <[email protected]>
2026-11-09 08:56:04 -05:00
shinyobjectz bc052693ac Ray tracing: a chrome ball under Solari reflects a panorama's sun
Solari gated light sampling on a glossy metal by its roughness (6% of paths at 0.06), too rarely for a small sun to
show; a metal short of a perfect mirror now samples lights on at least a quarter of its paths, which stays unbiased as
the weights divide by the gate. Off a mirror's specular lobe, which light sampling can't reach, rays see the
panorama's own sun, in Solari and the path tracer alike.
2026-11-08 22:03:28 -08:00
shinyobjectz b301c65570 Ray tracing: see-through materials, uv_transform and a panorama's sun under Solari and the path tracer
bevy_solari 0.20 is vendored (vendor/bevy_solari, changes marked "raea:"). Each TLAS instance now carries a mask, so a
ray finds the nearest opaque hit and then walks the see-through instances up to it: Mask materials stop it by their
cutoff, Blend by the chance of their alpha, Premultiplied by that plus their clear coat's Fresnel share (the path
tracer shades the coat alone, weighted back), and Add never. Before, every traced mesh was opaque, so a transparent
skin turned what it covered black. StandardMaterial's uv_transform now applies to traced texture reads.

<Environment> finds a panorama's sun when it loads (systems/environment sun.rs), using the panorama's own floats, and
Solari samples that sun as a directional light. Inside the sun's disk the environment map shows the sky around it, so
its light isn't counted twice; camera rays and mirror bounces still see the panorama's sun. The path tracer bends a
normal-mapped normal that faces away from a grazing ray, which removes the black streaks toward the horizon of a bumpy
plane.
2026-11-08 21:26:44 -08:00
shinyobjectz 19b72d3dee Ray tracing and shaders: a ShaderExtension that doesn't compile refuses the render, and <Pathtracer /> no longer panics on its first frame
- raea-sys-shader (failed.rs): a shader raea registers for a scene (a ShaderExtension's surface and lit hooks, an own
  material's, a UI material's) that doesn't compile left its pipeline out, the frame drew without it (black) and the
  render said APPLIED. The render world now finds those pipelines in Bevy's cache and refuses the render with the
  compiler's error, through raea-gpu-device's refuse, which the frame's read back checks. Repro: `patch` (a WGSL
  reserved word) as a variable in a surface() hook.
- engine/render/raytrace: SolariPlugins makes every StandardMaterial deferred, but Bevy's Pathtracer requires only Hdr,
  so a <Pathtracer /> camera had no deferred prepass and Bevy's prepass queue panicked unwrapping its deferred phase.
  A Pathtracer camera now gets DepthPrepass and DeferredPrepass.
2026-11-08 20:46:49 -08:00
shinyobjectz f63bbca23b Live play: each bevy-ts case's run is bounded (RAEA_CASE_SECONDS, default 180, by coreutils' timeout where there is one), so a run that hangs is that case open, with its reason, rather than the whole check stuck; rc3's Windows Live play ran 24 minutes with no output until the run was cancelled. release.yml's step streams each case's line as it finishes, bounds each case at 300s (a fresh Windows runner's first play opens in about 100s, the next in seconds) and the step at 75 minutes 2026-11-08 20:32:21 -08:00
shinyobjectz 668ae2eb08 Docs: every SDK prop, field and member described on raea.io/docs, and the reference check fails on a missing one
The SDK reference's tables had 1,476 empty cells. Each prop, field and class member the pages table now has a doc
comment in its source, or Bevy's own field doc where the SDK mirrors a Bevy type:

- doc comments on 773 declarations across 84 SDK files (song maps, goo and rigid bodies, matchmove, the clock and
  timeline, state machines, materials and their extensions, the 2D shapes, bevy_ui and feathers wrappers, colours)
- inline prop types pulled out as named, documented interfaces (EchoesProps, DaylightProps, UiScaleProps, ...), so
  each prop can carry its own doc
- types raea-bevy-sdk generates from raea's crates (/** raea_core_animate::spec::AnimKey */) take their field docs
  from the Rust source, shown as raea's ("Rust: ..."), not Bevy's; core/animate's spec.rs gains the missing ///
- a props type (StandardMaterialProps) takes its component's @bevy fields; the colour classes gain their @bevy tags
- tools/manual-ref/sdk.ts check now fails on any prop, field or member without a description, as cli.ts does for
  flags; tools/manual-ref.sh links an export's node_modules (RAEA_MODULES) so it can run in L1's lane export
2026-11-08 20:18:08 -08:00
shinyobjectz 2881f190bb Docs: a page for every CLI verb and every SDK import path on raea.io/docs
The CLI reference is now 43 pages, one a verb, each with its forms, where it runs and what each of its 164 flags does,
under docs/manual/reference/cli. The forms and flags are generated from `raea help --json`; the prose and the flag
descriptions are written by hand, kept by the generator, and checked: a new flag without a description fails.

The SDK reference is 28 pages, one an import path, under docs/manual/reference/sdk: every export with its doc, its
signature, a component's props, a class's members, its Bevy type and the parity ports and examples that use it,
generated by the TypeScript compiler, with a hand-written introduction and a type-checked example on each page.
Where the SDK mirrors a Bevy type without a comment of its own, Bevy's own doc is shown, marked as Bevy's
(tools/manual-ref/bevy-docs.json). Doc comments added to the SDK exports that had none.

tools/manual-ref.sh gen|check runs both generators.
2026-11-08 19:43:15 -08:00
shinyobjectz e19e07b12f Bevy's own Text2d inside a Canvas3D and TextureAtlasBuilder; Bevy parity for 2d/text2d (exact), 2d/texture_atlas and 2d/rotation
A <Text2d> inside a <Canvas3D> is now Bevy's Text2d (raea-sys-sprite text2d.rs, sent as a Shape2D row with its `text` spec): bevy_text lays it out and rasterises it and bevy_sprite_render orders it with the sprites by z, so TextBounds (`bounds`), FontSmoothing::None (`font_smoothing`), Text2dShadow (`shadow`), LineBreak, its <TextSpan>s, a z under a sprite and a scaled quad's pixelated look are Bevy's. After the Canvas3D it is the page's Text, as before; the page refuses bounds, shadow and "None", which it can't draw. 2d/text2d is exact at frames 10 and 60 (SSIM 1.000000, tile 0); with FontSmoothing::None taken out it fails (tile 40, 5308 px off in that block).

TextureAtlasBuilder (raea/sprite, raea/image): pictures packed by Bevy's own builder in the order added (padding, sampler), a sprite showing the whole atlas or one picture (sources.handle(texture), the row's atlas_pick, which sync_2d no longer resets to a sheet's cell). 2d/texture_atlas lists textures/rpg in load_folder's order and passes at 0.998551; its packed atlases match Bevy's.

2d/rotation: the port took the direction to the ship as -at, so the enemy straight above had x = -0 and copysign turned it the other way; player - enemy (0 - 0 = +0) as Bevy subtracts. Passes at 0.999751, its turning enemies within 8 grey of Bevy's at frames 10 and 60 (the bar alone passed a 10 degree a second error).

All 2D ports and shader/pipeline_constants rerun: 155 ported, 155 passing.

skills/ pins raea-skills f81678f (#9), whose generated sdk.md lists TextureAtlasBuilder.
2026-11-08 21:27:59 -05:00
shinyobjectz 5a77c3c834 Windows: a page's root-absolute files load from its roots (an app's posters and pictures). FileNet, FrameNet and page_fetch took a file URL's path from url's to_file_path, which on Windows refuses a path with no drive: every /media/x a page names, as file:///media/x, was None before any root was looked in, so the Windows app's cards drew no poster (its log: file:///media/pong.jpg isn't a file). A file URL's path is to_file_path's, else its decoded path as written, which the roots join as on the Mac and Linux 2026-11-08 18:11:30 -08:00
shinyobjectz 9f8a94cdfd raea's own git commits work on a clean Mac: apps/workspace git_cmd sets EMAIL ([email protected]) when it's unset
A new Mac has no user.email and a hostname git can't make one from, so the first project's commit failed with
"Author identity unknown" and onboarding never made the person's first project (found in tools/raea-app/journey.sh
from a fresh HOME). git reads $EMAIL only when user.email isn't set, so nobody's own identity is overridden. Used by
workspace::git and the controllers' commit.
2026-11-08 18:05:19 -08:00
shinyobjectz 2c5b71fef8 Every 2D primitive and ring in Mesh2d, 2D drawn with Bevy's MSAA and exact colours; Bevy parity for 2d/2d_shapes
Mesh2d takes all of bevy_math's 2D primitives (CircularSector, CircularSegment, Annulus, Capsule2d, Rhombus,
Triangle2d, Segment2d, Polyline2d, ConvexPolygon beside Circle, Rectangle, Ellipse and RegularPolygon), each with its
reflected fields, and any of them as Bevy's Ring: `ring={thickness}` (to_ring) or `inner={...}`. A Shape2D row
carries the spec as `primitive` and raea-sys-mesh's primitive_mesh builds it, as Bevy's mesher does.

Two fidelity gaps 2d_shapes exposed, fixed for every 2D part:
- A Mesh2d's ColorMaterial colour reached the GPU rounded to a hex. It now goes as the Srgba's floats (`srgb`).
- 2D drew single-sampled, where Bevy's Camera2d defaults to 4x MSAA, so edges between pixels snapped. An edit with
  2D mesh rows now gets MSAA (raea_sys_sprite::has_2d, beside has_3d at the two MSAA call sites only, not the
  encoder's), and the 2D camera keeps to the 3D camera's MSAA every frame, sharing its main texture. The frame tag's
  Camera2d on the same target keeps to it too: Bevy makes one 2D depth texture per target, so differing sample
  counts were a validation error.

A relative import of a file under raea's sdk/ that isn't an SDK package's source (a bench's shared helper) is now
copied into the bundle like any outside import; before, everything under sdk/ was assumed to come by name.

New bench helper sdk/raea/bench/bevy-parity/helpers/theme.ts: examples/helpers' basic_example_theme, option checkbox
and bottom-left column, used by 14 Bevy examples.

2d_shapes passes at 0.99987: the shapes area matches with 0 pixels off by more than 2%; the rest is the checkbox
captions' glyph edges (the known text item). Every port was rerun after the MSAA change: 152 of 152 pass.

skills/ pins raea-skills 004b866 (#8), whose generated sdk.md lists the new primitives.
2026-11-08 20:57:45 -05:00
shinyobjectz 121cdc7a0a raea-page-host's --css is a list as PATH is (split_paths: ; on Windows): split on ':', a C:\ path was two files and the page lost its stylesheets 2026-11-08 17:39:52 -08:00
shinyobjectz ce8f2d29d2 Windows: raea play no longer crashes as its mixer opens. warm_audio found the output device on a thread of its own, but on Windows cpal keeps one device enumerator a process (a OnceLock) made on the thread that first asks, and that thread's COM is torn down when it ends: where nothing else held MMDevApi.dll (GitHub's runners, no audio device) it was unloaded, and the mixer's open called through the enumerator into it, an access violation in every play since the JS error before it was fixed. The warm is for CoreAudio's start-up and runs only on Apple now; elsewhere the mixer finds the device on the play's own thread. release.yml's Live play runs without the Vulkan loader's debug lines and prints each failing case's log tail, and bevy-ts's check.sh doesn't take the loader's INFO lines for a failure's reason 2026-11-08 17:36:03 -08:00
shinyobjectz 894f9821b4 Texture binding arrays in an own Material; Bevy parity for shader_advanced/texture_binding_array, exact
A <Material>'s textures may give one list of 1 to 16 pictures, bound as the source's binding_array<texture_2d<f32>>
(ui_bind's ARRAY slot, binding 57). Bevy's AsBindGroup derive can't own an array of views, so a new
OwnArrayMaterial (systems/shader/src/own_array.rs) wraps the part's OwnMaterial and builds its bind group directly,
as Bevy's example does: the derived entries, then the array with the fallback image past the list. Its layout leaves
out the uniform buffers, because wgpu refuses a binding array beside one, so build refuses uniforms on such a source.
Its pipelines are OwnMaterial's (same key, specialize), and own_live patches it too. A source with no texture_2d of
its own samples with the first sampler, which becomes the list's first picture's. 2D and devices without texture
binding arrays are refused. The depth and picture helpers move to own_images.rs (own.rs stays under 500 lines).

The port is exact at frames 5 and 10. Two tiles swapped and linear filtering each still passed the 0.99 bar
(0.992, 0.990); a missing tile failed it.
2026-11-08 17:08:08 -08:00
shinyobjectz 4175c116fb MeshPass with depth and vertex colours, Mesh3d material={false}; Bevy parity for shader_advanced/specialized_mesh_pipeline, exact
Bevy's specialized_mesh_pipeline draws meshes that have no material by a SpecializedMeshPipeline of its own: positions
at location 0 (compressed or not), colours at 1 under VERTEX_COLORS when the mesh has them, depth tested and written
GreaterEqual, under the view's MSAA. raea's <MeshPass> now does all of it:
- `depth`: it tests and writes the view's depth as an opaque mesh does. The pass always attaches the view's depth (a
  pipeline's depth state must match the pass), so without `depth` it compares Always and writes nothing, as before.
- a mesh's colours go to location 1 under VERTEX_COLORS, as Bevy's own specialize does.
- the pipeline takes the view's MSAA sample count (it assumed 1, so it only worked with Msaa off).
And <Mesh3d material={false}> (any <Mesh>) gets no material at all, as a Bevy Mesh3d without a MeshMaterial3d, so
only its own pass draws it: row no_material, spawned beside the toon branch (engine/render line-neutral).

Parity: SSIM 1.000000, worst tile 0, batch keys 0 / 0 at frames 5 and 10. Without material={false} the pixels were
already exact, but raea drew 2 batch keys of default material Bevy doesn't. Mutants: without the vertex colours it
fails (0.961897, tile 147); without `depth` it is unchanged, since the rectangle is behind the triangles and the pass
draws far to near. custom_render_phase, custom_phase_item, custom_shader_instancing, 3d_scene and mesh2d still pass.
150 ported, 150 passing.
2026-11-08 16:42:57 -08:00
shinyobjectz 426567fb63 A camera's depth as a texture: <DepthCopy>, depth images and depth textures in <Material>; Bevy parity for shader_advanced/render_depth_to_texture
Three pieces, as Bevy's render_depth_to_texture uses them:
- "render:NAME:WxH:depth" names a depth image (Depth32Float, its sampler comparing Always), shared by every field
  that names it, as "render:NAME" images are (raea-runtime-plugins fields.rs; raea-sys-shader own::depth_image).
- <DepthCopy image> in a Camera3d (raea-sys-phase DepthCopy) copies the camera's depth buffer into that image after
  its prepass and before its main pass. A depth-only camera is Bevy's own components: RenderTarget::None { size },
  DepthPrepass and Msaa off, with an order before the main camera's.
- A <Material> may bind a texture_depth_2d and a sampler_comparison (rebind slots 25 and 26, raea-sys-shader-wgsl
  ui_bind DEPTH), its texture given by name as any other. Bevy has no depth fallback image, so a Material that binds
  none gets a shared 1 x 1 depth image there.

Parity: the scene is pixel-exact at frames 5, 10, 30 and 60 (SSIM 0.999617). The only difference left is the
instruction text's glyph edges (tile 6), the same text-over-3D blend fullscreen_material records. Mutants: without
the DepthCopy it fails (0.957, tile 35); the cube one update behind passes the bar (0.995), but the real port differs
from Bevy only in the text. Every port with a Material or StandardMaterial under shader/, shader_advanced/ and 2d/
still passes (29 ports). 149 ported, 149 passing.
2026-11-08 16:34:29 -08:00
shinyobjectz 0620a51e85 raea-sys-shader-wgsl: a WGSL source read as text, split from raea-sys-shader
raea-sys-shader was at 1989 of its 2000 lines, with a depth texture for <Material> (FC2d, Bevy's
render_depth_to_texture) still to add. Its source-text modules move to a crate of their own, unchanged:
layout.rs (an own uniform struct's fields and uniform layout), storage_layout.rs (a storage buffer's words) and
ui_bind.rs (bindings renumbered into raea's slots); raea-sys-shader imports them under the same names. Four
pub(crate) helpers are pub now. Tests: the same 12 pass (6 in each crate).
2026-11-08 16:21:10 -08:00
shinyobjectz c240b8e99d Mesh shaders: <MeshShaderPass> on a camera, and Bevy parity for shader_advanced/mesh_shader_intro, exact
A camera's MeshShaderPass (raea-sys-phase mesh_shader.rs) runs your task shader (when given) and mesh shader, which
make primitives on the GPU and hand them to your fragment shader, straight into the view's colour and depth (compared
GreaterEqual) after the main opaque pass, as Bevy's mesh_shader_intro does. Each stage is a shader file compiled as
written; bind group 0 is Globals and the view uniform; `groups` is draw_mesh_tasks' workgroup count. raea's shared
device already takes every adapter feature, so Apple silicon's mesh shaders are there; a GPU without them logs once
and draws nothing. In TSX it is <MeshShaderPass task mesh fragment groups> from raea/3d.

Found on the way and fixed: a shader file's `import super::NAME` was read a line at a time, so a statement over
lines (`import super::{\n bindings::{globals, TaskPayload},\n};`, as the example's three files write it) imported
nothing, and a nested list would have read its items as modules; it is now read to its `;` with each top-level
item's first name. And raea-sys-phase's own shaders (PhaseItem, MeshPass, ShaderInstances, GBufferPass) are now
registered in a folder of their own with their super:: imports, as a Material's are.

Parity: SSIM 1.000000 with a worst tile of 0 at frames 5, 10, 30, 60, 120, 240 and 300. Frames 240 and 300 (64 and
125 cubes) are there because the bar passed a port with no pass at all at frame 120 (0.997961, tile 23: the cubes
are small); with them that mutant fails (0.984513 and 0.967070), and one without its task shader fails at 0.0001.
The ports that read shader files (shader_material, extended_material, shader_material_2d, deferred_raymarch,
custom_render_phase, custom_phase_item, custom_shader_instancing, manual_material) still pass. 148 ported, 148 passing.
2026-11-08 16:14:57 -08:00
shinyobjectz 9a6f3d7358 Bevy parity: shader_advanced/manual_material, exact
The example prepares its ImageMaterial by hand (ErasedRenderAsset, its own bind group layout and allocator) rather
than through the Material trait; in raea it is a <Material> with manual_material.wesl as written, the Bevy logo as
its texture and wgpu's SamplerDescriptor::default() (nearest filtering, nearest mipmaps, clamp to edge) as its
sampler. SSIM 1.000000 with a worst tile of 0 at frames 5, 10 and 30. Mutants: linear filtering moves it off exact
(0.999147, tile 4), and the cube 5 cm higher fails (0.972591, tile 75). 147 ported, 147 passing.
2026-11-08 15:56:37 -08:00
shinyobjectz c5fec6aeb9 hanabi: a <Particles> mounted part way through a render draws, not a panic: its effect on a child of the part
build_particles put the ParticleEffect on the part's own entity, beside its Mesh3d, so Bevy's mesh queue and
hanabi's binned the same main entity in one phase. That passed when both came on the first frame, but a
<Particles> mounted mid-render (a fountain from frame 8) panicked "Binning main entity ... when it was already
binned" on the next frame. The effect is now a child of the part, so it follows the part's transform; the
mid-render fountain starts on its frame, and the plugin bench (check.sh avian hanabi) still passes, hanabi at
SSIM 1.000000.
2026-11-08 15:46:35 -08:00
shinyobjectz 20ff5785b6 Plugins in a sequential render: a component held for its frame lands in a fed render too; an import written in a string stays text
A render to MP4 is a fed render (each frame's rows handed to a live engine), and keyed_rows stood aside for any
live engine, so a <BevyComponent from={N}> (an avian RigidBody, a hanabi Particles) waited in Keyed for good: a
row held for its frame never changes after the load, so the frames' rows never carry it either. keyed_rows now
applies them in a live engine as well, each once on its frame. A render to a PNG folder, or of one --frame, was
right already; the cube that turns dynamic at frame 10 now falls in the MP4 too.

The bundle's import rewrite (runtime/bundle rewrite.rs) matched `import ... from "..."` anywhere in the text,
so a template string a code chip types (`import { RigidBody } from "raea/plugins/avian"`) came out as
"../plugins/avian.gen". A lexer's pass now marks strings, template text, comments and regular expressions,
and a match inside one is left as written.
2026-11-08 15:07:06 -08:00
shinyobjectz bcfdb9e2b0 Windows: live play bundles the live runtime's React again. The edit resolver took an importer as the edit's own only when its path started with the work folder's canonical one, but the resolver names a module as its path was given: on GitHub's Windows runners TEMP is the 8.3 C:\Users\RUNNER~1\.., which canonicalize() spells runneradmin, so no importer was the edit's, the live harness's react went to the engine's CommonJS copy, and every raea play threw "not a function" (its __h) before the first frame, in every Windows build so far. The importer is canonicalized as the folders are, and a package is told by a node_modules component, not a /node_modules/ substring a backslashed id never has. A unit test names the work folder by a symlink 2026-11-08 14:40:10 -08:00
shinyobjectz eeea139ade Bevy's deferred_raymarch, exact: a GBufferPass, drawn in the camera's viewport; cameras and lights placed by their own rotation
shader_advanced/deferred_raymarch (docs/control.feature FC2d) ports with a <GBufferPass> on the camera
(systems/phase gbuffer.rs): a shader file's fullscreen fragment writes Bevy's deferred G-buffer, the
lighting pass id and depth after the late deferred prepass, and its shadow entry writes every shadow view
the camera's lights draw, so Bevy's deferred lighting lights it and it casts shadows. It matches Bevy to
the pixel (SSIM 1.000000, 0 px off at frames 5, 10 and 30); the whole suite (147 ports) passes on pixels.

Three gaps closed on the way, each found by probing the shader's inputs on both sides:
- The pass sets the camera's viewport, as Bevy's own passes do. raea's target is w x (h + 1) (its tag
  row), so a fullscreen triangle drawn without it stretched its uv over 721 rows: rays a pixel low at the
  bottom.
- Camera3d sends its rotation, and the engine places the camera by it (rot_qx..qw, exact). It used to send
  a look-at point the engine turned back into a rotation in f32, about a millionth of a radian off. Bevy's
  lights do the same (their direction was also rounded to 1e-6).
- Transform.lookingAt computes in f32 as glam does (Dir3::new, cross, try_normalize,
  Quat::from_rotation_axes), the same quaternion to the bit; glam.test.ts holds it to glam's own bits.

The port sets Bevy's shadow defaults in a <Shadows> (2048 texels, cascades to 150 m, the first to 10 m,
overlap 0.2), as the other shadowed ports do. Mutants (no shadow entry, the first cascade at 8 m, 7000 lux,
the cube moved 5 cm, the camera's target 1 cm up) are each thousands of pixels off.
2026-11-08 14:40:08 -08:00
shaneandshinyobjectz ce63b7a280 Release CI: the skills unpack without raea-skills' root symlink, the macOS and Linux packing gets its disk back, and a failed styles check says why (#61)
- tools/release.sh's skills_at takes raea-skills' skills/ folder alone. Its whole tree held AGENTS.md, a link to
  CLAUDE.md, which Windows' tar can't make, so rc1's Windows packing stopped there.
- release.yml frees target/ once the binaries are in ship/ (packing and its checks read ship/ only): macos-15 ran out
  of disk packing rc1 ("No space left on device"). It prints the disk before and after.
- release-check keeps the styled render's log and prints its end when styles.gen.ts isn't written (rc0's macOS check
  failed there with its output thrown away), and a failed check uploads every step's log, not only the app's frames.

Co-authored-by: shinyobjectz <[email protected]>
2026-11-08 17:39:20 -05:00
shinyobjectz d6c7bf8d36 R3F: a mesh swapped in with another shader program is another part, not the old one's layout
A part's three.js shader and its uniform layout are its first frame's, and an unnamed mesh's part is named by its
place in the tree. So a <primitive object> given another mesh in the same place kept the first mesh's program: a
sequential render drew the old shader, or refused when the new uniforms didn't fit its layout (a mat4 where a float
was), while a single --frame render was right. A mesh part with a ThreeShaderMaterial is now named for its program
too (a hash of its GLSL or WGSL and uniform types), so the same program keeps its part and another one gets its own.
2026-11-08 13:52:24 -08:00
shinyobjectz be8bdd597e A three.js shader's uniforms get 254 vec4 slots, not 62: lettra's default scramble() runs as its graph
lettra's scramble() with its default pool (every glyph in the font) takes 78 vec4 slots for 66 glyphs, over the 62 a
three shader had, so it fell back to flat quads with a warning; its README's own example did too. The uniform block is
256 vec4s (4 KB), the last two still the material's own (three's time, how the colour is read), now named from the
total in tone.wesl too, and the TSL reader's limit is the same 254. R3F parity: all 28 cases pass.
2026-11-08 13:49:10 -08:00
shinyobjectz 4217941ad5 A staticFile path is found in the media folders wherever a source is resolved, a three.js shader's texture too
resolve_src read /media/fonts/x.png as a file at the root, so an R3F ShaderMaterial or TSL node material whose texture
came from new THREE.TextureLoader().load(staticFile("fonts/x.png")) found no such file, and its render was refused
(a material's map, drei's Environment files and every other source already went through media_path). /media/ paths
now go through raea-core-scene media_path in resolve_src itself, with a test.
2026-11-08 13:43:14 -08:00
shinyobjectz be388ffe80 FC2d: a mesh drawn many times in one draw by your shader; shader_advanced/custom_shader_instancing passes
<ShaderInstances shader stride attributes words> inside a mesh draws it once per instance in one draw, in the camera's
Transparent3d phase: Bevy's mesh pipeline with its vertex and fragment shader swapped for your file as written, and a
second vertex buffer of your words stepped per instance (raea-sys-phase ShaderInstances, as the example's
CustomPipeline and DrawMeshInstanced). The phase components' shader registration is one function for all three now.

The port is pixel-identical to Bevy at frames 5 and 10. Moving the instances 2 cm, making a colour 2% darker or a cube
1 cm shorter puts 10,000 to 48,000 pixels off. 145 of 438 ported, 145 passing.
2026-11-08 13:38:14 -08:00
shinyobjectz de1a6830c2 An SVG shape's transform from a <style> inside its <svg> turns it, as Chrome does (closes #60)
In a composition, a <style> inside an <svg> goes to usvg in the SVG's markup (raea's HTML host turns it into a hidden
div first, so HTML pages weren't hit). Blitz had already computed the shape's transform from the cascade, with its
transform-box and transform-origin, and written it as a transform attribute; usvg then applied the sheet's own
transform and transform-origin over it. `rotate(30deg)` isn't SVG transform syntax, so the shape drew unturned, and
a class giving only transform-box and transform-origin turned an inline transform about the SVG's 0,0.

The computed transform now goes into the element's style attribute with transform-origin: 0 0 (its origin is in
the matrix), where usvg lets it win over a sheet's rule as CSS does; the identity is written too, so a sheet can't
turn a shape the cascade leaves unturned. The separate transform attribute is no longer written.

bench/svg-css-transform/check.sh: the class-turned square against the inline-turned one, 78 px differ (antialiased
edges; before 8827), and a class's box and origin with an inline turn against all-inline, 0 px (before 5598). The
svg-css-paint, svg-stroke-box, rotated-paint and background-clip-text benches pass; the P26 rows that draw SVG
score the same as before (studio 3/3, css/svg 1/1; bevy/datamaps is 0.971-0.976 on main with or without this).
2026-11-08 13:34:33 -08:00
shinyobjectz 3f95080394 LinearRgba.from takes an Srgba and names the fix when given anything else
LinearRgba.from("#ff3fa4") read a hex string's missing channels as NaN, and an emissive made from it drew nothing,
silently. Bevy's From takes an Srgba, so the string form now throws with the call that works:
LinearRgba.from(Srgba.hex("#ff3fa4")).
2026-11-08 13:30:14 -08:00
shinyobjectz 4103559dac FC2d: a mesh drawn again in a phase of its own, and compressed meshes; shader_advanced/custom_render_phase passes
<MeshPass shader> inside a mesh draws it again by your shader file as written, in a sorted phase after the camera's
main opaque pass, onto the colour target with no depth attachment and back faces culled, with Bevy's mesh view and
mesh bind groups: raea-sys-phase's MeshPass, Bevy's custom_render_phase stencil phase made a component. A mesh's
`compressed` prop compresses its geometry as Bevy's compressed_mesh(&MeshCompressionArgs::regular()) does
(raea-sys-mesh finished), so a shader reads its positions under VERTEX_POSITIONS_COMPRESSED; engine/render's mesh
build calls it in the same line, keyed on it.

The port is pixel-identical to Bevy at frames 5 and 10 (0 pixels differ). A 1 to 3 cm move of the sphere, camera or
cube still passes the SSIM bar but is 177 to 629 pixels off, so the exact match is the port's, not the bar's. The parity
host gets indexmap and nonmax, the example's own dependencies. 144 of 438 ported, 144 passing.
2026-11-08 13:28:22 -08:00
shinyobjectz 4081e5ac17 A three.js-style emissiveIntensity of 1 is Bevy's 1.0, not 998 nits: glows no longer draw white
core/scene's EMISSIVE took a three.js emissive of 1 as 1.2 x 2^9.7 cd/m², what Bevy's default exposure shows as 1.0.
But a StandardMaterial's emissive skips the camera's exposure (emissive_exposure_weight 0, pbr_functions.wesl), so
every 3d.tsx and R3F glow drew about 1000 times too bright: an emissiveIntensity of 0.25 on #ff5fa2 came out white,
and a transmissive knot over it read as opaque white glass. EMISSIVE is now 1.0; a Bevy material's emissive_nits is
still taken as written.

sdk/r3f's parity suite gets an in-glass case (clear, clearcoated glass over a thin emissive knot), drawn by three.js
in Chrome: SSIM 0.930. The other 26 cases still pass.
2026-11-08 13:10:07 -08:00
shinyobjectz 087949140d A page draw past Vello's buffers is painted again before its frame is encoded, in the fed render too
A page past raea's smaller Vello bump buffers draws nothing, and only its sentinel read back says so (#23). The fed
render (pages handed to raea-render, the default for a page composition's mp4) never checked: the log said "drawn
again", but the skipped draw went into the film as it was. A heavy first frame came out black, and a layer could drop
for a frame (seen as a grain overlay flickering under 70 clipped, blurred, 3D-transformed shards).

- raea-sys-page skipped.rs: wait_drawn waits for the last draw's sentinel read back (its submission alone).
- raea-gpu-device check.rs fed_checked: once every read back has answered, a skip paints the frame again at Vello's
  own sizes, and a skip even then refuses the frame by its number, as the other render paths do; runtime/export
  fed.rs calls it after each frame's page is painted.

bench/vello-skip/check.sh: shards.tsx's mp4 frame 0 has mean luma 21 (the page); with the raea before this, 0. The
wait costs nothing measurable on an ordinary 1080p page (300 frames, alternating: 256.8 and 263.6 fps before, 262.8
and 263.7 after). Still to look at: the redrawn first frame lacks one shard that a render at Vello's own sizes from
the start draws (4,400 pixels, also in a --frame 0 still, whose redraw is skip_checked's).
2026-11-08 12:54:48 -08:00
shinyobjectz e9b22879a0 shader_advanced/fullscreen_material: a FullscreenMaterial is a <FramePass file> before tonemapping
Bevy's FullscreenMaterial runs its fragment shader (fullscreen_effect.wesl, a chromatic aberration) in Core3d's
PostProcess before tonemapping, its intensity (sin(2t) + 1) / 2 * 0.015 from update_intensity. The port is the file
as written in a <FramePass file at="before-tonemap">, with the example's cube, light, camera and text.

Parity: frames 10, 30 and 60 at ssim 0.99975. The only differences are the text's antialiased edges: Bevy blends UI
over a Camera3d in linear light (CompositingSpace allows sRGB blending only for a Camera2d), and raea's page over its 3D
blends sRGB-encoded, as Chrome does. That gap is shared by every port with text over 3D (split_screen 0.99897) and
is recorded in control.feature FC2d, not changed here.

Mutants: a doubled intensity fails the bar; a halved frequency, the camera 0.2 further back and a darker cube pass it,
with the probe counting 6,118 and 8,672 pixels off for the first two (the cube's colour moves luma by under 2%).
Before or after tonemapping gives identical frames, in Bevy as in raea: a non-HDR camera tonemaps in the material
shader, so the tonemapping node is skipped.
2026-11-08 12:42:22 -08:00
shinyobjectz 6684ea7c77 An <EffectComposer> with a DepthOfField renders: raea's stand-in WebGL context takes every call
@react-three/postprocessing's composer renders each frame, and pmndrs postprocessing's DepthOfField blits the depth
buffer through the raw context (gl.bindFramebuffer, gl.blitFramebuffer). The stand-in context answered only what a
composer asks as it's made, so every frame threw "gl.bindFramebuffer is not a function". It's now a Proxy, as the
stand-in renderer is: its methods do nothing, its constants are 0, and `then` stays undefined so it never reads as a
promise. raea draws the effect from the composer's DepthOfFieldEffect (post.ts), as before.

test/post.test.ts runs postprocessing's own EffectComposer with a DepthOfFieldEffect on the stand-in renderer for three
frames; without this change it fails with the same error.
2026-11-08 12:32:08 -08:00
shinyobjectz c60db71abf An <R3F> scene's first frame waits for what it loads: a render holds the frame while the scene suspends
drei's <Environment> suspends while its HDR loads, and so do useGLTF and useTexture. raea took frame 0 before the
load came, so an mp4's first frame was the 2D alone and a looping film opened blank (launch post 02 trimmed it off).

- sdk/r3f hold.tsx: <R3F> renders its children under a Suspense whose fallback opens a hold on raea's frame
  (globalThis.__raeaHold), and the last release wakes the frame, so <R3F> draws it again with what loaded.
- runtime/bundle entry.rs: the frame isn't marked done while a hold is open (the React Marker and the lite
  entry), and a wake marks it, or draws it again in the lite entry.

sdk/r3f/test/hold/check.sh renders a scene whose box colour comes from a promise resolved 50 ms later: frame 0 of the
mp4 and a --frame 0 still are the red box. With the raea before this change, the mp4's frame 0 is the background.
bench/at-0, bench/compute-frames, sdk/r3f's input/clock/roundtrip tests and a pong live play are unchanged.
2026-11-08 12:27:41 -08:00
shinyobjectz ae61cbb3e6 A mesh carries its own vertex attributes, and a Material reads the ones it names (shader_advanced/custom_vertex_attribute)
Bevy's custom_vertex_attribute gives a cube a BlendColor attribute and lays out the material's vertex buffer as
[POSITION at 0, BLEND_COLOR at 1] in its specialize. raea now does both:

- sdk/render: MeshVertexAttribute.new(name, id, format) and Mesh's ATTRIBUTE_* constants; Mesh3d `attributes`
  ([[attribute, values]], a value a vertex); Material `vertex_attributes` ([[attribute, location]]).
- runtime/scene: the mesh row carries `attributes` from the first frame.
- raea-sys-mesh attribute.rs: with_attributes inserts them into the mesh (names interned once, as Bevy's are
  &'static str); engine/render's shared mesh keys on them, line-neutral.
- raea-sys-shader own.rs: the layout is part of the pipeline key, and swap sets the vertex buffer to
  layout.0.get_layout of the named attributes, as Bevy's specialize does.

Parity: frames 5 and 10 at ssim 1.000000, 0 pixels off. Mutants: a green BlendColor, BlendColor at location 0 and
four blue vertices fail the bar. Moving the cube 0.1 up and halving the uniform's red pass the bar but the probe
counts 6,067 and 36,685 pixels off (the known SSIM blind spot; the real port is 0).

skills/ pins raea-skills 5218644 (#7), whose generated sdk.md lists the new names.
2026-11-08 15:20:15 -05:00
shinyobjectz 1a516a8de1 A compute's uniforms follow the frame, in a PNG render and an mp4
Two gaps a launch film found in <Compute>, both of one cause: its uniforms never reached it after frame 0.

A compute's uniforms travelled only inside its `shader` spec, which a row holds from its first frame, so an inline
compute (or one as written) saw frame 0's values on every frame. They now also go as a keyed `uniforms` column, as a
frame pass's do. raea-sys-compute's `follow` repacks them when the column changes: an inline compute's into its slots
by name (a name it wasn't built with is refused), one as written through its packer (written::follow_uniforms;
`Ranged` is kept for every compute as written, and a field that is a mesh's slab range is still packed each frame).

An mp4 render draws its 3D live (LiveScene): each frame's changed columns are set on the live rows. The compute's and
the frame pass's `follow` read the timeline's columns (`FrameRows::cols`), which in a live render hold only the load's
first frame, so an mp4 of a compute driven by its uniforms stayed black. FrameRows::at reads a row's value by its
place, the live row's when there is one; both follows use it.

bench/compute-frames/check.sh renders level.tsx (an inline compute filling an image with the grey `level`, f / 20,
gives) to PNGs and to an mp4: frame 0 is black and frame 10 grey 188 in both (the mp4 within 4, its YUV round trip).
Before, frame 10 was black in both. shader/compute_shader_game_of_life, shader_advanced/compute_mesh,
custom_phase_item and custom_post_processing still pass pixel for pixel.
2026-11-08 12:00:17 -08:00
shaneandshinyobjectz eaf5406f39 One raea skill, in raea-skills (skills/): raea pins it, and its release ships it from the pin (#58)
The raea skill moves from sdk/skills to the raea-skills submodule, in its framework (skills/skills/raea/SKILL.md
with raea-tested-against and raea-verbs, checked by its skillcheck), and raea-bevy is folded into it: its router
is the skill's 3d.md and its topic files are in 3d/. An agent loads one skill for everything raea does.

- `raea skill` and `raea skills install` find a checkout's skill in skills/skills (an install's share/raea/skills is
  unchanged) and skip raea-skills' _template. `raea skill raea-bevy` says where its text went, and install removes
  an older raea's raea-bevy copy.
- tools/skills.sh gen writes the references into skills/skills/raea/reference and copies the Bevy craft guides
  (sdk/guides/craft/bevy) in as the 3D topic files, which were links: a clone of raea-skills, or GitHub, reads them
  whole. check fails on a copy that differs from its guide, on one whose guide is gone, and on an uninitialised
  submodule.
- tools/release.sh gates on the pointer (skills in the gate inputs), adds raea-skills at the pin to the gate's tree,
  packs share/raea/skills from it, and lists raea-skills' own commits in the skills notes.
- The core-rules test reads the skill from the submodule, and the surface test checks it.
- The Claude Code plugin names the one skill folder; README, the guides and the SDK docs say raea's 3D guide.

Co-authored-by: shinyobjectz <[email protected]>
2026-11-08 14:36:53 -05:00
shinyobjectz c1acc96d8d bevy-parity runs headless: the Bevy examples open no window
A full bevy-parity suite opened one window per example, each taking focus, so the Mac was unusable while it ran. The
Bevy side now runs with no window whenever its pictures are taken (RAEA_PARITY_PNG). The host's build.rs gives each
example `crate::plugins(DefaultPlugins)`: its DefaultPlugins without WinitPlugin. In WinitPlugin's place,
raea_sys_parity::Reserve makes as many empty entities as the window's plugin makes before an example's Startup (11:
its observers and a Monitor for this Mac's display). The example's own entities then get the indices they get with a
window: a port matches some by index (image_node_resizing's debug outline colours), and an index breaks ties in UI
draw order (scrollbars' thumbs). Reserve also sends what winit sends as it makes the window, WindowCreated and then
WindowResized, which split_screen lays its viewports out on. The probe's `run` is the App's loop, as Bevy's
ScheduleRunnerPlugin runs one, with no wait between updates. The primary Window entity is still there, for the
examples that read its size, and its cameras already drew into the probe's offscreen image (FC0a, 11-07).
RAEA_PARITY_WINDOW=1 opens the window again to watch an example. raea's side was already headless (raea render, raea
play --offscreen).

The whole suite was run headless. Every ported example's picture scores what it scored with a window (split_screen
0.998973, scrollbars 0.994530, image_node_resizing 0.998153, standard_widgets 0.994691). Four failed only the
frame-time bar while another session rendered a film on the same machine; their pixels pass. The results docs here are
left at the last windowed run's, and the cost bar will be rerun on a quiet machine.
2026-11-08 11:33:24 -08:00
shinyobjectz 94d62d7fd7 The frame tag has its own camera: render --at works for TSX compositions again
Since a3db7b6db, `raea render X.tsx --at N` refused every TSX composition ("no two readbacks with its tag agreed in
240 updates"). That commit gave every camera on the Engine's target a w x h Viewport above the tag row. The frame tag,
a 16 x 1 UI node in that row, was laid out under the scene's camera (UiTargetCamera), so bevy_ui clipped it to the
viewport and no readback ever carried a tag. Full renders and HTML stills don't wait on the tag and kept working.

The tag now has a camera of its own (raea-sys-frame spawn_tag, called where load.rs spawned the node): a Camera2d on
the same target, ordered last, on no render layer (so it draws no sprite or mesh), with no tone mapping, dither or
MSAA. Its texture is cleared to transparent and alpha-blended over the target, so every pixel but the tag's is left
as the frame's cameras drew it. tag_row_view leaves it out of the viewport it gives the rest.

bench/at-0/check.sh renders a one-colour composition with --at 0 and checks the frame is 160 x 160, one colour, and
#246 in its last row. It refused on a3db7b6db and passes now. bench/at-3d still passes (its four frames are
pixel-identical to the frozen render's), an mp4 render works, and the whole bevy-parity suite was rerun with the change.
2026-11-08 10:56:20 -08:00
shinyobjectz 6f6daa1b3b A composition that paints no background is black behind it in a video too, as in a PNG
A video takes the fed path (pages handed to the encoder on the GPU), whose program has no camera row; runtime/view's
camera_bg then gave raea's old dark blue (13,10,26), so every transparent part of an mp4 or mov was navy while the
same frame as a PNG (raea-export's program, which clears 2D pages to #000000) was black. #13's snapcn sweep met it:
text-swap, text-build, text-highlight and cursor-track read as a 0.52 SSIM drop against Chrome until the harness's
page took the navy. The default is now black, as program.rs's.

bench/clear-backdrop/check.sh: white text on nothing to an mp4 and a PNG, both corners black. Before: the mp4's
13,9,26 (the 02:20 build), the PNG 0,0,0. After: both 0,0,0.
2026-11-08 10:54:18 -08:00
shinyobjectz ac39b671ee raea/text loadFont: a composition asks for a Google Fonts family by name and the page gets it (part of #13)
snapcn's components (#13) load their families by name from Google Fonts; raea had no way for a composition
to ask for one. Google families came only with RAEA_PAGE_GOOGLE_FONTS=1, which fetches every family a
page names, so it is off by default (Chrome loads only what a page links, and every composition's root names Inter).

loadFont("Space Grotesk") (sdk/video/src/fonts.ts, exported from raea/text) returns { fontFamily } and calls the
new native fonts.google, which marks that family wanted in raea-sys-fonts google.rs: the page fetches its Latin
faces, every weight and style, once through raea's URL cache, so a render stays a function of its code and plays
offline once cached. Families nobody asked for still fall back as before. Outside raea (a browser) it links Google's
stylesheet, so the same code shows the same family there.

bench/load-font/check.sh: "Hello raea" in Rubik Mono One with loadFont differs from the fallback by 12885 px, and an
offline render from the cache matches the first exactly. Needs the network on the first render.
2026-11-08 10:38:36 -08:00
shinyobjectz ffd2738dcc A <Video> whose src is an http(s) URL plays it, fetched once into raea's URL cache (closes #57)
core/scene's media_path joined an https src to the composition's folder, so a remote clip was refused as
"<dir>/https:/…: no video track" (seven snapcn components in #13: hero-launch, laptop-frame, phone-frame,
phone-stack, reel-collage, reel-wall, screen-recording).

raea_io_net::cache::remote(src) gives an http(s) src's file through cache::fetch (keyed by the URL, which is in
the composition's source, so a render stays a function of its code; under $RAEA_CACHE beside the render cache)
and None for a file. The page's video elements, the export's sounds and live play's video list ask it first.
A src that can't be fetched refuses the frame saying why: "video <url>: HTTP 404 Not Found", or "(not in
raea's cache): not sent, because RAEA_OFFLINE is set". The cache's status errors no longer name the URL twice.

bench/remote-media/check.sh: a local server's red clip plays (centre 252,0,0), plays again offline from the
cache, an uncached URL offline refuses, a 404 refuses with its status. Before: all four read the URL as a path.
laptop-frame (snapcn) renders its remote clip, 240 frames at 7.0 ms a frame.
2026-11-08 10:34:24 -08:00
shinyobjectz a3db7b6dba FC2d: a compute writes a mesh, your own phase item, a frame pass as written; three shader_advanced ports pass
Three of Bevy's shader_advanced examples now run as written, each through a general feature.

A compute writes a mesh (shader_advanced/compute_mesh). A <Compute file> binds each var<storage> its file declares:
either its own buffer, its first contents in the type's storage layout and kept from frame to frame, or a mesh's
vertex or index slab in Bevy's MeshAllocator, found by its part's name (systems/compute/src/slab.rs). A uniform
field given { start: NAME } or { end: NAME } is that mesh's range in the slab, counted in the array's elements, and
is packed each frame once the allocator has placed the mesh. The allocator's slabs carry STORAGE usage, set before
MeshAllocatorPlugin's finish makes the allocator, as the example's plugin sets it. A <BufferMesh> with indices and
normals is now Bevy's indexed Mesh, its index buffer kept, instead of flat triangles (systems/mesh/src/indexed.rs);
3d/vertex_colors, which takes that path, still passes. Every row with a name now gets a Bevy Name, not only bare
entities.

Your own phase item (shader_advanced/custom_phase_item). <PhaseItem> puts raea-sys-phase's PhaseItem and an Aabb on
an <Entity>. A new crate, systems/phase, queues it into each view's Opaque3d phase with a pipeline of its shader
file as written, drawing its own vertex buffer (its stride and attributes) and index buffer with its depth state,
as the example's queue_custom_phase_item does.

A frame pass as written (shader_advanced/custom_post_processing). A <FramePass file> binds its file's own @group(0)
declarations: each texture_2d<f32> is the frame (the one `frame` names) or an image, each sampler Bevy's default or
the one given, each var<uniform> its value (systems/framepass/src/written.rs). Its uniforms may change frame by
frame: like a compute's entry and bind, they are a keyed string column, and the pass repacks them when they change.
FramePass moves out of materials.tsx (at its 500-line limit) into 3d/framepass.tsx. The group(0) declaration parser
the compute and the pass share is raea-sys-shader's bindings::group0.

A camera on the Engine's target now draws a w x h Viewport of the w x (h + 1) tag-row target, as orthographic
cameras already did. A perspective camera had a sub view of the whole target, so a draw in clip space, such as the
phase item's triangle, mapped to 721 rows: its bottom edge landed 0.75 px low and the port passed at SSIM 0.9936 with
2355 pixels off. It is now pixel-exact. The whole suite was rerun with the change.

Results:
- compute_mesh passes at frames 5 and 10 (SSIM 0.999999, 2 pixels off at a 2% threshold). Eight mutants all fail the
  bar: no dispatch, either range set to 0, indices written into the vertex slab, the compute's mesh unnamed, the
  other cube's colour, no shadows, and the other cube moved.
- custom_phase_item passes at frames 5 and 10 with SSIM 1.0 and 0 pixels off. Mutants: the second attribute at
  offset 12, a vertex given another colour, and the top vertex at y 0.9 all fail the bar; a vertex moved from 0.866 to
  0.86 passes on SSIM (0.9953) but leaves 1556 pixels off, where the port leaves 0.
- custom_post_processing passes at frames 10, 30 and 60 (SSIM 0.99995, 0 pixels off). Mutants: no white clear colour
  fails the bar; intensity times 4/3 (8100 pixels off), a slower turn (4256), a linear sampler (16) and sin(t) for
  sin(sin(t)) (2964 at frame 60) pass on SSIM but leave pixels off. The pass before tone mapping draws the same
  frame, as it should: the camera is not HDR, so Bevy tone-maps in the material shader and its tonemapping node is
  skipped.
- After the change, the whole suite passes: 141 of 141 ported (two first-run misses rerun clean: standard_widgets
  missed its replayed menu click on the Bevy side, automatic_instancing missed its frame-time bar under another load).
2026-11-08 10:31:46 -08:00
shinyobjectz 21f9dd6936 Windows: an app's press reaches its handlers. A file the bundle's resolver names has one module id however its path was written: raea:script's ids are rebuilt from their components (one separator, no . or doubled ones) and lose canonicalize()'s verbatim prefix. On Windows an app's @raea/ui aliases were joined with mixed separators (sdk/ui/src under a backslashed home) while Rolldown resolved react.ts's ./wire with backslashes only, so the bundle carried two wires; the second took __ui_deliver with none of the first's handlers, and every press was dropped with no error. A unit test gives two spellings of one file one id (#51) 2026-11-08 10:20:40 -08:00
shane d356bf5819 Merge #53: skills/ is the raea-skills repo as a submodule
skills/: the raea-skills repo as a submodule
2026-11-08 13:10:20 -05:00
shinyobjectz c6157d0d81 skills/ is the raea-skills repo (github.com/shinyobjectz/raea-skills) as a submodule: the home of raea's agent skills from here on; sdk/skills moves there once that repo has its first layout 2026-11-08 10:06:21 -08:00
shinyobjectz 8de480c11a The raea skill's description names the work only raea does first, so an agent with other video skills installed picks raea for it (fixes #22, wording from watzon's suggestion): 3D scenes, matchmove, games, cutting by words, beat-timed cuts, local foley and instruments 2026-11-08 10:04:16 -08:00
shinyobjectz 498d7765cd FC2a: storage buffers in any WGSL type; shader/gpu_component_array_buffer passes pixel-exact
A <Material>'s storage buffer is no longer limited to an array of numbers or vectors. It can be any host-shareable
type its source declares: scalars and vectors, matCxR<f32>, fixed and runtime arrays, and the source's own structs,
including fields under @if. Each is written in WGSL's storage layout (systems/shader/src/storage_layout.rs), as
Bevy's examples write such buffers with encase. In TSX a buffer is a StorageValue: a number, a list (a vector's
components, an array's elements, a matrix's columns) or a struct's { field: value }. Struct fields may also share a
line (`struct S { a: f32, b: vec2<f32> }`); layout.rs splits them at the commas outside a type's <>.

The parity bench's ChaCha8Rng gains next_u64, random_bool and random_index, matching rand's draws for seed 12345
(lib/rand.test.ts). The parity host depends on bytemuck, which the example uses.

shader/gpu_component_array_buffer passes at frames 60, 180, 240 and 400 with SSIM 1.0 and 4 pixels off at a 2%
threshold. The port replays the example's add_cube and remove_cube on Bevy's clock. Two details matter. A part keeps
its row across frames by its name, not its React key, so each cube is named by its spawn number; otherwise a cube
that moves up the list takes the texture of the cube that was there first. And when both timers fire on one update,
the cube spawned then is not yet in the other cubes' archetype, so the despawn swaps in the previous last cube and
the new one joins after it.

Nine mutants all fail the bar: swapped textures, swapped colour channels, a constant MeshTag, a 310 ms spawn timer,
the new cube put first, another seed, cube scale, camera target and a mirrored z. All 19 shader ports still pass.
2026-11-08 09:39:48 -08:00
shinyobjectz 4e83e0b4b2 SECURITY.md: report security problems privately through the Security tab (private vulnerability reporting is on) 2026-11-08 09:31:39 -08:00
shinyobjectz 47545d9212 FC2d: a compute as written; shader/compute_shader_game_of_life passes pixel-exact
A <Compute file> compiles its shader file as written, binding its own @group(0) storage textures and uniforms
(systems/compute/src/written.rs). Each frame picks the entry point and which image each storage texture binds, as
a Bevy example's render-graph node picks its pipeline and bind group. Its images are render:NAME images in the
storage format the file declares, each with a sampler if one is given.

Strings can now change from frame to frame. A row column holds a number per frame, so a changing string is kept
as the list of values it takes plus a keyed index into it (raea-runtime-look's keyed_strings, read back with
raea-sys-frame's keyed). The changing-picture code for ImagePlane already worked this way and now uses the helper.
A Compute's entry and bind use it, and so does a Sprite's src: a Sprite can show a render:NAME image and switch
to another by name each frame.

The render-image registry (RenderImages) moves into raea-sys-frame, so the sprite system can look images up by
name. raea-runtime-plugins re-exports it.

A still renders only the frames it needs and their neighbours. When a scene has a compute that carries state
between frames (a file's images, or its own buffers), every frame up to the wanted one is now rendered, because
the GPU state can't be rebuilt from one frame.

Load checks every entry name and binding the run uses. A frame whose entry leaves a storage texture unbound is
logged and skips its dispatch.

shader/compute_shader_game_of_life passes at frames 10, 11, 30 and 60 with SSIM 1.0 and 0 pixels off. Frame 11
was added so each of the two images' samplers is drawn. Mutants are caught either by the bar or by the 2% pixel
probe: init a frame late, swapped bindings, alive colour, sprite parity, either image's sampler, clear colour,
scale, and one extra row of workgroups. The extra-row mutant passes SSIM at 0.9994; the probe finds 784 pixels off,
against 0 for the real port.
2026-11-08 09:19:32 -08:00
shinyobjectz 011cd1bd6c FC2: clay.rs moves to raea-sys-material (re-exported by scene3d, whose crate was over 2000 lines); rot_of and scale_of, no longer read, folded into transform_by
The fast path for placed rows grew raea-runtime-scene3d to 2010 lines. Clay is a material concern (every standard surface drawn grey and matte) and depends only on Bevy, so it moves to raea-sys-material; scene3d re-exports it, so every caller keeps its path.
2026-11-08 08:23:07 -08:00
shinyobjectz f5cb4f3ae2 FC2: automatic_instancing and pipeline_constants pass; gpu_readback excluded (136/136)
shader/automatic_instancing: 65 536 cubes, one mesh and one Material, each with a MeshTag (a BevyComponent) its
vertex shader reads a texel by, moved in z every frame. The update was 103 ms against Bevy's 9: every moving row's
values were made into a map each frame. The timeline now records which columns move per row (Timeline::moving), and
a row only its placement moves has, once its other values are applied, its transform read straight from the frame's
columns (FrameRows::moves_only, placer, transform_by): 7.4 ms against Bevy's 8.3. The parity probe formatted a string
for every visible mesh each probed frame, in the next frame's measured time, on both sides; it now formats a size once.
Mutants: the tag off by one (SSIM 0.977) and the phase (0.397) fail the bar.

shader/pipeline_constants: a Material's `constants` are its fragment's pipeline-overridable constants (WGSL override),
set in its pipeline as the example's specialize pushes LEVELS; kept by hash so its key stays Copy (SpriteMaterial's
combined key is a packed struct). Its quads are pixel-exact; LEVELS + 1 and no constants both fail the bar. A Text2d
inside a layered Canvas3D was silently not drawn (the bar passed it at SSIM 0.9946); it now throws, saying to put it
after the Canvas3D.

shader/gpu_readback is excluded: it spawns no camera and draws no frame; its behaviour is the GPU results it reads back
and logs, the world check's, not a picture.
2026-11-08 08:17:42 -08:00
shinyobjectz 0dd03f7c24 FC2b: an extension file's own bindings, any numbers (shader/extended_material_bindless, 134/134)
A MaterialExtension's fragment file is compiled as written but for its material-group bindings' numbers, which go to
ShaderExt's slots in the order declared: its uniform struct at 100 (its uniforms packed in its layout), up to four
texture_2d at 101-107 and their one sampler at 102 (ext_bind.rs, through ui_bind's rebind_with). A declaration under
@if(BINDLESS) is left as written and compiles out, so Bevy's extended_material_bindless binds its @else set (50, 51,
52), as it does without bindless; the @binding(100) struct is read from outside those spans.

The port is pixel-exact at frames 30 and 60. Mutants on a dark scene the bar's SSIM threshold can't see: the
modulate colour (30k px off at a 2% probe), the rotation by 0.1 rad (9k), the sphere's sectors (2k); the base
colour under the checker moves SSIM 1.0 to 0.9995.
2026-11-08 07:22:25 -08:00
shinyobjectz 2ff13ee50b FC2a: bindless Materials as Bevy draws them without bindless (shader/shader_material_bindless, shader_material_2d_bindless, 133/133)
A Material's declarations under @if(BINDLESS) are left as written: raea's Materials aren't bindless, so that set
compiles out and the @else set binds, as Bevy's does on a GPU without bindless (ui_bind.rs bindless_spans).

A Cylinder alone is drawn as Bevy's Cylinder mesh (32 sides, one segment), with its normals and texture coordinates,
as a lone sphere, cuboid and plane already are: a shader reading its uv now compiles (core/shape cylinder_of).

Mutants: the cylinder's colour, its logo and the cube's blue are each caught (the blue by a pixel probe, 236 against
214); the radius by the pixel count. In 2D a logo swap is caught; Mask against Opaque draws the same picture in Bevy
too (a custom Material2d doesn't discard, and the Mask pipeline doesn't blend).
2026-11-08 07:13:06 -08:00
shinyobjectz fa6a5ed17f FC2a: a Material reads the camera's prepasses (shader/shader_prepass, 131/131); live play's 3D under the page drawn opaque, as a window shows it
shader/shader_prepass passes at 4 frames, one per prepass view (transparent, depth, normals, motion vectors), stepped by
scripted Space presses. The camera carries Bevy's DepthPrepass, NormalPrepass and MotionVectorPrepass and Msaa::Off as
<BevyComponent>s, and show_prepass.wesl reads them through bevy_pbr::prepass::utils as written. The opaque Material
cube writes into the prepass and turns with Time::elapsed_secs.

Live play drew its 3D under the page blended by the 3D's alpha, which a window ignores, so custom_material's
COLOR_MULTIPLIER alpha of 0.5 faded the opaque cube toward the page's white. The 3D under a whole page is now copied
opaque (place_under, fs_opaque), as raea render and Bevy's window present it.

Outside the text block at most 574 pixels differ (edges). Mutants fail: the normals view off, NormalPrepass removed,
the cube's turn frozen, the opaque cube blended. A Mask cutoff of 0.2 against 1.0 passes the bar but moves the pixel
probe (2350 to 2474 px): the icon's alpha is all but 0 or 1. The ports with input scripts rerun pass.
2026-11-08 07:00:32 -08:00
shinyobjectz 5acc123835 FC2a: one reader for the component a part holds its own Material by (3D, 2D or a sprite's) 2026-11-08 06:38:33 -08:00
shinyobjectz 1b6fbfc390 FC2a: a Sprite's own Material (Bevy's SpriteMaterial), its values per frame in live play, and scripted keys in the parity host (shader/sprite_material, 130/130)
<Sprite><Material/></Sprite> is Bevy's SpriteMaterial<M>: raea's OwnMaterial is also a MaterialExtension2d, so it
extends the sprite's own SpriteMeshMaterial and its shader reads the sprite through sprite_mesh::functions. A
Material's fixed slots now start at 30, past the sprite's own bindings (a UiMaterial's still start at 0), and an
alpha mode the spec doesn't give leaves the sprite's own.

Live play now carries a Material's values frame by frame: a one-frame program sends its own:uniforms row, and a
component whose target keeps its render id (a sprite, a 2D shape) is no longer dropped.

The parity host's input script takes key names (KeyCode's: "Space"), held in ButtonInput<KeyCode> after Bevy's
input systems, so input_just_pressed sees a press on its update.

shader/sprite_material passes at 6 frames across two Space presses (SSIM 0.99983, the text's tile). Mutants of the
amount, the burn edge's width and the delta fail. A burn-edge colour mutant passes the bar, which can't see a thin
edge's colour, but the edge probe catches it: the same 1721 edge pixels, green total 1428 real against 1266 mutant,
and 1428 in Bevy's. The Material, sprite and 2D ports rerun pass.
2026-11-08 06:34:46 -08:00
shinyobjectz 21182ec6ba FC2a: one check for a name a Material's shader doesn't declare (uniform or storage buffer); materials.tsx back under 500 lines 2026-11-08 06:05:57 -08:00
shinyobjectz 8ff3d0cf00 FC2a: a Material's texture_2d_array, its layer picked by each cube's MeshTag (shader/array_texture, 129/129) 2026-11-08 05:58:11 -08:00
shinyobjectz 4f7944c463 FC2a: a Material's storage buffers and its values frame by frame; parts with one spec share one Material (128/128)
A <Material>'s `buffers` are its read-only storage buffers (var<storage, read> NAME: array<T(, N)>, up to two, at
OwnMaterial's 23 and 24), each laid out as WGSL stores its element type (own_live.rs storage; a vec3 takes 16 bytes).
Its uniforms and buffers may change from frame to frame: raea-runtime-look own_uniforms sends them as keyed
`own:uniforms` component rows from each frame they change, and own_live.rs patch packs them into the part's
Material and ShaderBuffers (a row that arrives before shade_rows puts the Material on waits on the part, Pending).
Parts whose spec is the same share one Material, as Bevy's examples share a handle: a varying spec carries its
track's hash, so parts share only when every frame's values match too (own.rs shared, OwnMade, cleared per load).
layout.rs's word encoding is shared by uniforms and buffers.

Port: shader/storage_buffer (SSIM 0.999999 at 30 and 60): 91 cubes with MeshTags (<BevyComponent
bevy_mesh::components::MeshTag>), the example's vertex and fragment shaders from its one file, its colour buffer
recomputed each frame as its update system does. Freezing the colours at frame 0 fails (97310 px off), as does
tagging every cube 0 (76718). The other shader ports rerun and pass.
2026-11-08 05:55:22 -08:00
shinyobjectz fff38cbcd6 FC2a: a Material's textures of every dimension (1d, 2d_array, cube, cube_array, 3d), up to 6 samplers, and Bevy's fallback image for a texture it doesn't give (127/127)
rebind_in takes `dims`: a Material's (not a UiMaterial's) textures of the other dimensions go to their own slots
of OwnMaterial, one of each (16 1d, 18 2d_array, 20 cube, 21 cube_array, 22 3d), and its samplers, in the order
the source declares them, to 9, 11, 13, 15, 17 and 19 (Bevy's view binds up to 8 of the fragment stage's 16). A
texture the source declares and the spec doesn't give binds Bevy's fallback image of its dimension, as an
Option<Handle<Image>> left None does; a 2d_array takes the spec's texture array ({ layers }).

Port: shader/fallback_image (SSIM 1.000000). Its fragment writes nothing, so the frame alone can't show the
bindings: a raea-only variant that samples all six textures draws the cube (worst tile 158 against Bevy's empty
frame), so the six bind and sample. A unit test puts fallback_image_test.wesl's twelve bindings in their slots.
2026-11-08 05:43:27 -08:00
shinyobjectz ffc9962cd0 Fold three new copies in own.rs: one specialize for Material and Material2d (a macro), the shader handle inline, and no is_own 2026-11-08 05:35:58 -08:00
shinyobjectz 66195f7472 FC2a: your own Material in 2D (Bevy's Material2d), and a shared-texture 2D camera's output replaces as Bevy's first camera does (126/126)
A <Material> in a Mesh2d is Bevy's Material2d: raea-sys-shader's OwnMaterial implements both Material and Material2d
(group 3 in 3D, 2 in 2D), so the bindings, the imports beside the file and the packing are one code path;
alpha_mode maps to AlphaMode2d (Opaque, Mask, else Blend), and cull_mode now keeps the pipeline's own unless given
(Back in 3D, none in 2D, as Bevy's pipelines have them). Mesh2d carries it to Shape2D as `shader`, the shape row
keeps it as a JSON column, and raea-sys-sprite's spawn_shape puts MeshMaterial2d<OwnMaterial> on in place of the
ColorMaterial, its textures decoded at once (own::picture, which the UiMaterial now uses too).

raea's 2D camera draws over the 3D camera on its target. With the 3D camera single-sampled and not Hdr (a 2D-only
scene's), the two share one main texture, so the 2D camera's blit used to alpha-blend the finished frame over
itself (Bevy blends every camera after the first on a target). It now replaces, as a lone Camera2d's does: a 2D
fragment's alpha below 1 reaches the frame as Bevy leaves it. Found by shader/shader_material_2d, whose Mask(0.5)
material writes alpha 0.5 and never discards: Bevy's centre pixel (0, 0, 40), raea's was (29, 29, 43) and is now
(0, 0, 40). A mixed scene (a multisampled 3D camera) keeps the blend.

Port: shader/shader_material_2d, SSIM 1.000000 (the Blend mutant fails, 16384 px off). The full sweep passes
126 of 126.
2026-11-08 05:29:32 -08:00
shinyobjectz a28118696e FC2a: your own Material is Bevy's Material, not an extension: its own bindings, imports beside it, alpha mode, depth bias, cull mode; 3 shader ports (125/125)
raea/pbr's <Material> now draws as raea-sys-shader's OwnMaterial (own.rs), an `impl Material` whose bind group
takes any author's layout: the file's @group(MATERIAL_BIND_GROUP) bindings are renumbered into fixed slots in the
order the source declares them (8 uniforms of any type up to 256 bytes, packed in their declared types, a struct's
from { field: value }; 4 textures and their samplers), as the UiMaterial's are (ui_bind.rs rebind_in, generalized
to any group). `import super::NAME` reads NAME.wesl beside the file: the module is registered under an embedded
folder per source folder, which is the module path WESL resolves super:: to. alpha_mode and depth_bias are its
Material methods', cull_mode its specialize's (Back; null culls none), and `vertex` names a vertex shader for the
main pass. A shader's textures given as staticFile paths are now found as its fragment is.

Ports: shader/shader_material (SSIM 1.000000: its own bindings at 0-2, the relative import, AlphaMode::Blend; the
Opaque mutant fails at 36143 px off, and a cull_mode null mutant moves SSIM to 0.992), shader/shader_defs
(0.999999: its uniform a struct, IS_RED from defs), shader/shader_material_screenspace_texture (0.9989 at 10 and
60, max 12 grey off: view.viewport uv under the turning camera). animate_shader, extended_material and
ui/ui_material rerun and pass as before.
2026-11-08 05:29:32 -08:00
shinyobjectz 6aff2de92a L2 checks the generated plugin bindings against the commit's registry
sdk/plugins/src/bevy.gen.tsx drifted from 10-31 to 11-08 over four landings (d708518be): a landed material registers
a MeshMaterial3d<..>, and only the plugin build (raea-bevy-sdk, required-features bevy-plugins) can read the type
registry. tools/bevy-plugins.sh check compares the generated TypeScript with that registry and catches it (a mutant
dropping one wrapper's type fails it), but nothing ran it: L1 only cargo-checks the plugin build, and a fresh one
takes about 20 minutes, too much for every landing. L2 already builds it in its own clean checkout of the commit,
so it now runs the check after that build (about 50 s) and reports "plugin bindings: ok" or "drift" with the fix, in
its summary line and summary.json.
2026-11-08 05:10:31 -08:00
shinyobjectz d708518be1 sdk/plugins regenerated: four material components the plugin build now reflects
bevy.gen.tsx was last generated 10-31. Since then, landed materials made Bevy register four MeshMaterial3d /
MaterialNode components, which tools/bevy-plugins.sh gen now writes as wrappers (380 -> 384 components):
- MeshMaterial3d<ShadowCatchMaterial>, raea-sys-material's shadow_catch (88ccb8284);
- MeshMaterial3d<ThreeShader>, raea-sys-three-shader, R3F's shaders (d3c399b4d);
- MaterialNode<RaeaUiMaterial>, raea-sys-shader's ui, FC0a's ui_material (c703bb308);
- MeshMaterial3d<ExtendedMaterial<StandardMaterial, Procedural>>, raea-sys-procmat.
plugins.lock.json: every plugin's schema hash moves with the shared registry. Regenerated on the current tree (no
uncommitted Rust touches reflection); tools/bevy-plugins.sh check sdk/raea/bench/bevy-plugins matches its lock.
2026-11-08 05:05:46 -08:00
shinyobjectz ced8fe55a2 Fold two new copies into shared readers: keyed_vec (a camera's up, a 2D part's quat) and the sprite Tiled flags 2026-11-08 04:58:41 -08:00
shinyobjectz 5f5e7190db Split crates back under 2000 lines: raea-sys-mesh and raea-runtime-scene2d
- raea-sys-mesh: a row's mesh from JSON (Bevy's primitives by name, rings, extrusions, buffer meshes), moved out of
  raea-sys-material, which re-exports it as its `mesh`.
- raea-runtime-scene2d: the 2D parts' rows (<Sprite>, <Shape2D>), moved out of raea-runtime-scene.
- The part-row helpers both use (visible, sheet, tint) now live in raea-runtime-look's parts.rs.

raea-sys-material had gone to 2048 lines and raea-runtime-scene to 2040 with the FC0a additions.
2026-11-08 04:52:35 -08:00
shinyobjectz e4a0704178 FC0a: 2D at Bevy's exact size, Bevy's primitives by name, Model nodes, sprite modes; 7 more ports (122/122)
2D was drawn 0.14% small. An orthographic camera on the engine's w x (h + 1) target (the frame and its tag row) saw
the frame through Bevy's SubCameraView, whose orthographic math sizes its area from the 721-row target. A white rect
at (90, 510) drew at 41..140 instead of 40..139. Every 2D port still passed the pixel bar. Orthographic cameras now
get a w x h Viewport instead (engine target.rs, line-neutral). 2d/sprite and 2d/move_sprite went from SSIM 0.998
(worst tile 8-9) to 1.000000.

New in the SDK:
- Bevy's primitive meshers by name (systems/material mesh.rs): CircularSector, CircularSegment, Segment2d/3d,
  Polyline2d/3d, ConvexPolygon, Ring (`inner`, or `ring: thickness` as Bevy's to_ring), Extrusion, the Sphere's uv or
  ico kind and Plane3d subdivisions.
- <Model nodes>: glTF nodes' local transforms by name, each frame.
- Lights' shadow_depth_bias and shadow_normal_bias.
- <Sprite image_mode> (Bevy's SpriteImageMode: Auto, Scale, Sliced and Tiled) and <Sprite sampler>. A sprite sheet is
  no longer forced to nearest; the ports whose examples use ImagePlugin::default_nearest ask for it.
- Text2d's Anchor, and it no longer wraps (Bevy's Text2d is unbounded).
- Srgba.hex takes Bevy's 3, 4, 6 or 8 digits.
- Quat.slerp.
- The parity probe marks the example's highest-order window camera as the UI camera, unless the example marked one
  itself.

New ports, all passing: camera/2d_on_ui, gltf/load_gltf, gltf/gltf_skinned_mesh, animation/animated_transform, 3d/fog,
3d/3d_shapes, 2d/sprite_scale and 2d/sprite_slice.

Mutants:
- Caught by the bar: skinned mesh without the joint pose and at PI/3; animated_transform without the controller's
  turn; 3d_shapes with a Cuboid for the Tetrahedron.
- Caught by pixels off: 3d_shapes' ring thickness (4736 vs 2911) and animated_transform's scale key (728 vs 0).
- Passing the bar: fog's end and colour (SSIM 0.989 / 0.990). The real fog port matches Bevy to within 1/255 in every
  fogged region, and its 5819 pixels off are the help text.
- sprite_scale's gabe sheets match Bevy byte for byte at frames 10 and 60.
2026-11-08 04:52:35 -08:00
shinyobjectz 0105bb67c4 FC0a: 2D parts take Bevy's quaternion (quat), for camera/2d_on_ui 2026-11-08 04:52:35 -08:00
shinyobjectz 65a687182f GPU particles the same on every run: bevy_hanabi vendored with two raea: changes (closes #52)
sdk/raea/bench/bevy-plugins/hanabi.tsx, with seed 7 on both fountains, differed from itself on the same build: 110 to
113 of its 120 frame hashes, from frame 7 or so (seen in #38's live-3d corpus as a route difference; it wasn't one).
Only the alpha-blended fountain varied. bevy_hanabi (rev 77630ff) builds its draw list with atomicAdd, so blended
particles drew in an order that changed from run to run, and it seeds a new particle from the dead slot it recycles,
which threads take in atomic order too, so once particles die the new ones differed as well.

vendor/bevy_hanabi is that rev, src/ byte for byte but for four files, all marked raea: (tools/vendor: 104 lines):
- vfx_init.wesl: a new particle's seed is its index in this frame's spawns, not its slot;
- mod.rs, sort.rs, vfx_sort_fill.wesl: blended effects (not opaque, not alpha-masked) go through the sort pass that
  only ribbons used, keyed by view depth from the main camera (the near plane of SimParams' frustum, which sort-fill
  now binds), far first as Bevy sorts its transparent phase, AGE breaking ties. The sort's layout key no longer needs
  RIBBON_ID or AGE.
Its Cargo.toml drops the examples, GPU tests, dev-dependencies and [workspace] (Cargo.toml.orig is upstream's). A git
[patch] in the root Cargo.toml points at it; only the plugin build compiles it (raea-cli without plugins doesn't).
LICENSES/bevy_hanabi moves into the vendored folder, as for the other vendored crates (tools/licenses.sh).
engine/bevy-plugins' hanabi.rs tags the first 3D camera HanabiMainCamera, so the sort has a camera.

bench/hanabi-repeat/check.sh renders it 4 times on the program route: before, 110 to 113 of 120 frames differed run to
run; now every frame is the same, and program vs live (RAEA_LIVE3D_CHECK) matches on all 120 frames. At frame 30,
before any particle dies, sorted vs unsorted (the same build, sort switched off) differs in 9 pixels, as two unsorted
runs do (8.5): order where particles overlap, not coverage. bevy-ts plugin-hanabi passes.
2026-11-08 04:47:40 -08:00
shinyobjectz 01538b57e7 The live-3d corpus as a script, honest about what it skips (part of #38)
bench/live-3d/corpus.sh renders each composition in bench/live-3d/corpus.txt (the 190 files #38's run used) for 30
frames on RAEA_3D=program and on the live route, and compares the frame hashes. A failure there is now a real gap,
not the harness:
- a .tsx without registerRoot is a module (bunting, wake, cloud, contrail, smoke, bevy/view/scene and the generated
  plugin modules), so it is skipped;
- a case with // build: plugins or a raea/plugins import renders with the plugin build (motion.sh, or
  RAEA_PLUGIN_BIN), the way bevy-ts/check.sh does;
- animated-character (its glb was deleted), brick-rush (it needs the playable host) and rotate_environment_map
  (multi-layer textures, off by default) are expected skips, each with its reason.

shader-character's card-body/body.glb has its one joint renamed from CMU's Hips to pelvis, the game_engine name
sdk/character now looks for, so the case passes again.

Run: 169 same, 6 failed (examples/character x5 and bevy/passes: their kid body.glb is on the CMU rig), 4 differ
(hanabi varies between two program runs despite its seed; live-world, world-host and world-render differ at frame 0
only), 11 skipped.
2026-11-08 03:54:11 -08:00
shinyobjectz 392e4c7f1b FC1b: many_lights and many_foxes pass frame time: pipelined updates, and each row's values made once a frame (114 of 114)
raea_sys_frame::pipe does inside the engine's own update what Bevy's PipelinedRenderingPlugin does: a render thread (one for the engine's life) draws the frame the last update extracted while the main world runs this one; then this frame is extracted and the render world waits, home in the App, so what reads it between updates is unchanged. A render's frames and a live engine's catch-up steps pipeline; a live draw still hands its frame on drawn. RAEA_SERIAL or RAEA_PIPELINE=0 turn it off. Vello's renderer moves from a NonSend to a resource (in a SyncCell) so the render world can change threads.

FrameRows::vals made a row's values on every call, and six of the 3D's systems call it for every row (44% of a many_foxes update); set_cols now keeps each row's values, made on first ask, for the frame.

many_lights 6.2 -> 3.9 ms against Bevy's 4.9, many_foxes 11.8 -> 5.5-6.2 against 6.05; pixels identical with pipelining on and off. tools/bevy-parity: 114 of 114 ported examples pass.
2026-11-08 03:25:59 -08:00
shinyobjectz c94e26cc2a The Linux and Windows releases ship raea song: raea-perceive and the Beat This! model are packed on every platform since #43, release-check maps a 12 s 120 BPM drum loop with the unpacked raea, and the Windows job plays bevy-ts's play cases live after its pack and check (ImageMagick for check.sh's pixel reads) 2026-11-08 03:23:58 -08:00
shinyobjectz ec8669acba ui-parity's WPT run leaves SMIL tests out, with the reason in skipped.jsonl, since raea doesn't run SMIL by design. A test whose page has <animate> (and its kin) or <set> is skipped as "SMIL animation (<animate>, <set>), which raea doesn't run", so its failure isn't read as a regression. In the pinned checkout's areas that is one test, css-masking's clip-path-animation-neutral-keyframe-svg-smil. It had passed only because the test and its reference were drawn equally wrong, until #45 brought stylesheet paint to SVG and its CSS fill showed where Chrome animates it. 2026-11-08 03:22:09 -08:00
shinyobjectz fb7a4e4aeb An SVG shape's transform-box: stroke-box resolves as Chrome's: fill-box under vector-effect: non-scaling-stroke, and wide by a stylesheet's stroke (closes #50). WPT's svgbox-stroke-box-003/004 (a rect with id="target", a 20-wide non-scaling stroke, stroke-box, scale(0.5) translateY(-100%)) drew the rect smaller and off by a few pixels. It used to pass only because, before #45, the test and its reference were both drawn as plain black rects. Three things in blitz-dom were wrong:
- css-transforms-1 (csswg-drafts#9640) uses fill-box for stroke-box and border-box when the shape has vector-effect: non-scaling-stroke. svg_css_transform now does, from the computed value or the attribute.
- svg_stroke_width read stroke and stroke-width from the style attribute and attributes only, so a stylesheet's stroke didn't widen the stroke box (svgbox-stroke-box-001/002 and svgbox-border-box moved by the fill box's size). It now reads each as usvg sees the serialized element: its style attribute, then a rule's computed value that svg_css_paint writes there, then its attribute, then what it inherits.
- A non-scaling stroke reaches anyrender_svg as an id starting raea-nss-, since usvg drops vector-effect but keeps ids. An element with an id of its own was never marked, so its stroke scaled. mark_non_scaling_strokes now renames an element's own id to carry the mark when nothing in the source refers to it (`#id`); a referred-to id keeps its name (and its stroke still scales). The unit test covers both.

bench/svg-stroke-box/check.sh moves two stroked rects by translateX(50%) of their stroke box: a (stylesheet stroke: moves 60) and b (non-scaling stroke with its own id under scaleY(0.5): moves 50, its stroke 20 wide). Chrome 148 gives the probed pixels. The raea before this fails three probes; the raea with it passes. WPT css-transforms transform-box: 15 of the 28 tests Chrome passes before, 20 after (border-box, stroke-box-001 to 004), none lost.

fps, the same 120-frame page back to back, three runs each: 3.2, 3.8, 4.1 ms a frame before, 3.0, 3.8, 3.2 after (about 280 fps both).

Upstream candidate (Blitz): blitz-dom serialize.rs's stroke box and svg.rs's mark (the mark itself is raea's, for anyrender_svg).
2026-11-08 03:20:57 -08:00
shinyobjectz ac27341206 T1f: what release.yml's third run found on Windows: check-cli compares cli.md's text, not its line ends, since a Windows checkout has CRLF (Git's autocrlf) and raea's help LF; the run failed before packing, so it left no zip to look into 2026-11-08 03:17:46 -08:00
shinyobjectz 1db765c97d T1f: what release.yml's third run found: Linux's web app check panicked in raea-page-host because xkbcommon's X11 part wasn't installed. The runner installs libxkbcommon-x11-dev, and the README's Ubuntu build list names both xkbcommon packages 2026-11-08 03:17:46 -08:00
shinyobjectz 167f1b6e12 T1f: what release.yml's second run found: sdk/skills/raea/reference/cli.md was stale on main (raea render --review and --clay, raea solid, raea blender's library scripts), regenerated from the help, which the runners' own builds now check; Linux's runner installs libxkbcommon-dev, which raea-rune-host links 2026-11-08 03:17:46 -08:00
shinyobjectz 99003a573e T1f: a failed release check can be looked into without a rebuild: tools/release-check.sh keeps its folder at RAEA_CHECK_DIR, release.yml uploads the app check's frames and logs when a job's check fails, and Windows's zip is kept as an artifact whatever its check says (only windows-verify attaches it) 2026-11-08 03:17:46 -08:00
shinyobjectz f5596c75c6 T1f: what release.yml's first run found: Linux's runner installs NASM (rav1d's assembly), and the key scan counts an AWS key only standing alone, so a run of base64 (Bevy's inlined default font) isn't one 2026-11-08 03:17:46 -08:00
shinyobjectz 8e0c2b8d3d T1f: a release checks cli.md against its own build on every platform: tools/skills.sh check-cli compares the reference with RAEA_BIN's help alone and needs no feed app, and tools/release.sh runs it on a public checkout with the raea it just built, where the rest of the gate's pass comes from the tag. No other checkout checks cli.md strictly, since each one's raea holds other lanes' code 2026-11-08 03:17:46 -08:00
shinyobjectz 4667346f40 T1f: Windows joins release.yml: built on windows-latest, packed by tools/release.sh, attested, then unzipped on a fresh runner, installed through the published install.ps1 and checked before it's attached. The skills gate reads the private feed app, so a public checkout on any platform takes the commit where it passed from the annotated tag's "skills-passed: <sha>" line (or the skills_passed input) and checks the gate's inputs are unchanged since; without one the release refuses 2026-11-08 03:17:46 -08:00
shinyobjectz 53b0ce3fbb A 3D render draws the same pixels every time it runs (closes #48). Two renders of sdk/react/bench/games/room3d with one binary differed in 147 (RAEA_3D=program) to 369 (the live route) of their 7200 frames, by one pixel a frame: a single MSAA sample where a wall's foot meets the floor. There the two surfaces tie in depth, and the draw order decides the tie. Within a Bevy multidraw batch set, draws go in the order their bins were added, with removed bins swap-removed. await_models ran full updates while glTFs loaded, so the render world binned each mesh at the update its load landed on, and the trees' meshes joined at a different update each run. Bisected: without <Outside> (the glTF garden) 0 of 30 stills differ; with the trees alone they differ. Waiting for the GPU each frame (RAEA_SERIAL), the single-threaded executor and RGBA readback all still differ.
While models load, await_models now holds the active cameras off (raea-sys-post's views.rs). The render world still prepares meshes, textures and pipelines, but bins nothing. It turns them on before the first frame, so every view bins the whole scene into new phases in queue order. Turning views off after a draw was binned instead loses what Bevy extracts only on a change. And a morph mesh first seen by a view after loading would keep "no morph" for good: Bevy 0.20 gives it a descriptor only once its instance was collected, and collects an instance only when it changes. So views::on runs one update and then marks each morphed mesh's Mesh3d changed (bevy-ts morph drew its card unmorphed without that; the old loading updates collected it again by chance). An earlier try, updating only the main world while models load, broke the same case: messages the render world extracts by didn't reach it.

bench/room3d-repeat/check.sh renders room3d 8 times at frames where the seam ties and wants every run to match the first. The raea before this fails 5 of 7 runs; the raea with it passes. Five full renders (7200 frames each) hash the same. Frame 0 is pixel-identical to the raea before on room3d, bevy-parity many_foxes, bevy/model and bevy-ts morph. bench/live-3d is 13 of 13, and bevy-ts is 92 pass with 1 open (shader-character's body.glb, open before too).

fps, the full room3d render back to back, alternating: 124.3 and 109.7 fps before, 125.7 and 108.1 after. First-frame render, three each alternating: room3d 1.00, 0.66, 0.70 s before and 0.68, 0.68, 0.68 s after; many_foxes 1.26, 0.95, 0.95 s before and 0.96, 0.95, 0.94 s after.
2026-11-08 03:16:35 -08:00
shinyobjectz ffc337b68f FC0a: 3d/transparency_3d passes (0.998646 at frame 10): the 3D under the page is composited as premultiplied
Bevy blends into the 3D's target, so it holds premultiplied colour. raea laid it over black as if it were straight, multiplying each channel by its alpha again. That darkened every pixel where a fragment wrote alpha under 1 into an opaque pass: the AlphaToCoverage cube at frame 10 came out at 0.70x Bevy's colour, which is the 0.69 its resolved samples hold. Over black, a premultiplied picture is its own colour, which is what a Bevy window shows whatever alpha was written. bevy_over_3d (runtime/export bevy_frame.rs) and the fed render's GPU pass (engine/page feed.rs) now both take it that way, integer for integer. All 114 registered ports rerun: 112 pass. many_lights and many_foxes miss only on frame time, as before.
2026-11-08 02:50:25 -08:00
shinyobjectz 3d170ce60d A song map's tempo is the beats' own (part of #49). It was a line fitted through the downbeats against their bar count. Where Beat This! marks downbeats two beats apart in places, that counted each half bar as a whole one: a 99 BPM song read as 112.8 on Symphonia's decode and 116.6 on AVFoundation's, whose 12 ms offset moved three downbeats. Now the line goes through every beat against its count (a missed beat counted by its gap), so both decodes give 99.0. The hits come out 9 vs 6 rather than 62 vs 13, since they followed the tempo. Bars and one section boundary still follow the downbeats the model gives each decode. A unit test with every third bar half reads 99.17 for beats 0.605 s apart (119.26 before) 2026-11-08 02:27:18 -08:00
shinyobjectz 5c7540f91c CI's guard falls back to gitleaks' ghcr.io image when GitHub's release host keeps answering 504: on 11-08 every retry of the download failed for #39's and #45's landings (4219d620f, 0ef223922), before anything was scanned 2026-11-08 02:26:21 -08:00
shinyobjectz 450f8e4a97 FC0a: ui/widgets/standard_widgets under scripted input: the menu opens, its popup placed by Bevy's Popover
The bar can now drive an interactive example. A row of bench/bevy-parity/runs.tsv may name an input script, in the format `raea play --input-script` takes ({"FRAME": ["Pointer:X:Y:down"]}). The example gets it as RAEA_PARITY_INPUT: systems/parity input.rs writes bevy_picking's PointerInput messages on the picture the cameras draw into. The port's pictures then come from `raea play` under the same script; cost still comes from the render.

Gaps found and patched on the way:
- raea play sent its pointer only to useInput, never to page elements, so a composition's onClick never ran. The live step now hit tests the pointer on the page (BevyPage::hit_path) and sends its React handlers the events a browser fires, in a browser's order: over/out, enter/leave, move, down/up, and click on what both the press and the release were over (runtime/live pointer.rs).
- bevy_ui_widgets' Popover: Node takes `popover` ({positions: [{side, align, gap}], window_margin}). raea's Blitz places the popup after layout beside its parent's box (inside its border), at the first placement the window hides least, as position_popover does (vendor/blitz-dom bevy_popover.rs). It's drawn and hit tested there. Node also takes bevy_picking's handlers (onClick, onPointerDown/Up/Over/Out/Enter/Leave/Move; sdk/render ui-pick.ts). The page bridge keeps data-raea-bevy-popover.
- After any state change in play, bevy text was drawn broken at min-content width: raea's bevy_text min-content measure breaks lines at width 0, and a box whose layout taffy kept from its cache never broke them back. A measure now puts back the lines a laid-out box keeps (blitz-dom inline.rs, TextLayout::performed_width).

The port's Button reads "Hover" and "Press" as set_button_style has it; the menu button toggles spawn_menu's popup of four items, each lit while hovered; activating an item closes the menu. Under a click on Menu, then the pointer on the first item: 0.994691, worst tile 17. Without the toggle, the popover, GlobalZIndex or hover, with the side flipped, a 6 px gap, three items or 90% width, the bar fails; a gray border passes it and the probe catches it (7217 px off against 6465). conformance/ui-pick.test.tsx; blitz-dom bevy_popover tests; runtime/live pointer test.
2026-11-08 02:24:37 -08:00
shinyobjectz 3fcd4e56f3 raea song builds and runs off Apple (fixes #43). raea-sys-vision compiled modules that use Core ML and Apple Vision on every platform. depth and object are now Apple-only, and AppleVision with its text_lines moved into apple_vision.rs. The Vision trait and the portable helpers stay in vision.rs, and image becomes a dependency everywhere. raea-sys-layout's motion module (pure Rust) is no longer gated. raea-perceive gates the eyes, vad, track and hands commands to Apple, and read-lines and faces to builds that have a backend. Footage's store and content_hash (beats --store) move out of the Apple-only ingest module into store.rs. Off Apple, song and beats decode in process with the soft backend (Symphonia), since a Windows install has no ffmpeg: on a 163 s mp3 the map matches the ffmpeg backend's (264 beats, the same sections; strengths within 0.003). Models live in raea_io_home::models(): %LOCALAPPDATA%\raea\models on Windows, which has no HOME, and ~/.local/share/raea-models elsewhere as before. raea-perceive is found as raea-perceive.exe on Windows (io/assets perceive_bin, and the CLI's native.ts, whose PATH lookup now splits on the platform's delimiter). raea-perceive checks for Linux and Windows except opus's C build, which the soft backend brings and only a native toolchain compiles. The release doesn't ship raea-perceive for Windows or Linux yet 2026-11-08 02:17:06 -08:00
shinyobjectz 0ef2239226 An inline SVG's fill, stroke and the other paint properties set from a stylesheet are drawn, as Chrome draws them (closes #45). raea draws an inline SVG by serializing it and handing the source to usvg, which reads attributes and the style attribute only. Stylo computed #a path { fill: none; stroke: #13502B }, but nothing carried it into the serialized source, so the path was drawn with usvg's defaults: a black square.
blitz-dom's serializer (svg_css_paint) now writes each SVG element's computed paint properties into its style attribute: fill, stroke and their opacities, fill-rule, stroke-width, -linecap, -linejoin, -miterlimit, -dasharray and -dashoffset where they differ from the parent's computed value (they inherit, so a rule on the <svg> stays on the <svg>), and vector-effect where it isn't none. currentcolor is written as the element's color, as presentation attributes already were. The style attribute beats presentation attributes in usvg as in CSS, so a rule's fill wins over a fill="" attribute, as Chrome has it. vendor/stylo now has vector-effect for Servo too (it was Gecko-only), so a stylesheet's non-scaling-stroke reaches the source and isn't reported as not applied.

bench/svg-css-paint/check.sh draws five squares: a and b from a stylesheet rule on the path (a with vector-effect), c with attributes, d with a fill attribute under a rule on the <svg> (the attribute wins, as it's on the path), and e with a rule on the path over a fill attribute (the rule wins). Chrome 148 draws a, b and c as green outlines, d orange and e green. The raea before this drew a and b as black squares and e orange, and noted vector-effect as not applied; the raea with it passes.

WPT css-transforms, an 11-07 build vs this tree (won/lost lists; the newer build has #39 and other lanes' changes too): 18 svg-document-styles, svg-external-styles and svg-inline-styles tests now pass (their transforms' boxes are drawn with CSS fill). Three tests that passed because the test and its reference were drawn equally wrong now fail on their real gaps: svgbox-stroke-box-003/004 (with non-scaling-stroke, Chrome uses stroke-box as fill-box) and css-masking's clip-path-animation-neutral-keyframe-svg-smil (raea doesn't run SMIL <animate>, so the CSS fill shows where Chrome animates it).

fps, the same 120-frame page back to back, three runs each: 3.7, 3.9, 3.5 ms a frame before, 2.4, 3.3, 3.4 after (about 280 fps both).

Upstream candidate: blitz-dom serialize.rs's svg_css_paint (Blitz), stylo's vector-effect for Servo.
2026-11-08 02:15:24 -08:00
shinyobjectz 4219d620f6 An absolutely positioned box is painted inside the opacity (or other stacking context) between it and its containing block, as Chrome paints it (closes #39). blitz-dom hands an out-of-flow box to its containing block to paint (hoisted_children), and the containing block painted it in its own layer. So in <div style="opacity:0.3"><div style="position:absolute">, where the wrapper isn't positioned and the containing block is further up, the box was drawn at full opacity, outside the group it belongs to. Chrome 148 draws it faded, since a stacking context paints everything inside it, positioned or not.
blitz-dom's paint tree now gives such a box to the nearest stacking context between it and its containing block (paint_owner); that stacking context takes it from its containing block's list (take_out_of_flow), z-sorted with its other children. Its place still comes from its containing block (hoisted_child_position subtracts the stacking context's own chain), so a margin that moves the wrapper doesn't move the box. In blitz-paint, the group's layer reaches over the taken boxes (hoisted_content_bbox), and they are drawn after the stacking context's overflow clip layer, since the containing block that places them is above that clip (draw_from_above). Drawing them inside the clip layer made a mix-blend-mode box in an overflow:scroll stacking context blend with an empty layer (WPT compositing mix-blend-mode-with-transform-and-preserve-3D/fixed, caught and fixed before this commit).

bench/opacity-out-of-flow/check.sh draws four black boxes in groups at opacity 0.3 (an absolute child of an unpositioned wrapper; an in-flow child; an absolute child of a positioned wrapper; the first moved down by its wrapper's margin) and probes each for Chrome's grey 178. The raea before this draws 1 and 4 black (0) and fails; the raea with it passes, as Chrome 148 does.

WPT, raea before and after this and #45 together (won/lost lists, not counts): compositing 12 of 43 both, the same tests; css-masking +2 (clip-path-blending-offset, mask-image-ib-split-2) and one false pass gone (clip-path-animation-neutral-keyframe-svg-smil: CSS fill now reaches the SVG, and raea doesn't run its SMIL <animate>); css-transforms 22 won (18 svg-document/external/inline-styles, #45's; subpixel-transform-changes-001 to 004) and two false passes gone (svgbox-stroke-box-003/004: the test and its reference were both drawn as black rects; with their CSS paint they now differ by raea's stroke-box under non-scaling-stroke, which Chrome uses as fill-box).

fps, the same 120-frame page back to back, three runs each: 3.6, 4.6, 4.8 ms a frame before, 2.4, 4.2, 3.9 after (about 240 fps both).

Upstream candidate (Blitz): blitz-dom paint_tree.rs (paint_owner, take_out_of_flow, hoisted_child_position) and blitz-paint render.rs (from_above, draw_from_above, the layer's bounds).
2026-11-08 02:13:10 -08:00
shinyobjectz 85beee43c6 text-autospace's initial value is no-autospace, as Chrome's and Gecko's are (closes #44). raea's stylo enabled text-autospace for Servo (for parley's layout/autospace.rs) with an initial value of normal, so every page without the property got Chrome's ideograph-alpha/ideograph-numeric spacing anyway: "2026년" at 48px sans-serif drew 6 px wider unstyled than with text-autospace: no-autospace. Chrome 148 draws the unstyled line as no-autospace and only text-autospace: normal wider. The initial value is now NO_AUTOSPACE (vendor/stylo longhands.toml); parley's comments said Chrome's initial was normal and now say what it is.
bench/text-autospace/check.sh draws three "2026년" lines (unstyled, normal, no-autospace) and finds where each line's ink ends. The unstyled line must end where no-autospace's does, and normal's 5-7 px further right. The raea before this ends them at 202/202/196 and fails, the raea with it at 196/202/196 and passes; Chrome 148 ends them at 184/190/184 (a different sans-serif, the same 6 px). WPT css-text --only text-autospace: 13 of 26 pass before and after, the same tests.

fps, the same 120-frame text-autospace page back to back, three runs each: 4.3, 3.3, 3.9 ms a frame before, 3.7, 3.5, 4.3 after (about 260 fps both).

Upstream candidate: stylo's text-autospace is Gecko-only upstream; enabling it for Servo would need this initial value.
2026-11-08 02:07:51 -08:00
shinyobjectz 16b9726fdc url_path is src's file URL without its scheme (part of #40-#42), rather than a second forward of the same shape (dupes stay at 295) 2026-11-08 01:45:53 -08:00
shinyobjectz d45b38ef60 An HTML page's files load on Windows (fixes #40, fixes #41, fixes #42). The HTML runtime was handed the page's folder as Windows wrote it: canonicalized to a verbatim \\?\D:\ path (#40), or as D:/..., which a URL reads as scheme d (#41). The cached Google Fonts face came back from html.read as C:\... (#42). Its backslashes became CSS escapes in url(), and the drive a URL scheme in src. Now the folder is canonicalized without the verbatim prefix (raea_io_home::plain), and the runtime gets every path in URL form: raea_io_home::url_path, /D:/work/page on Windows, which the page's file:/// base joins into file:///D:/work/page. That covers the page folder, the font folder and html.read's answers. What the runtime names back (html.read's urls, a video's file, a sound's src) is read through from_url_path. Nothing changes on Unix, where both are the path itself. io/home's test checks the forms on any system, and joins them to file:/// as Blitz does: the result is a file URL, not scheme d 2026-11-08 01:40:12 -08:00
shinyobjectz ef05474017 CI's guard retries the gitleaks download: two runs on main (2a71a69d9, b36c58f95) failed on a single 504 from GitHub's release host before scanning anything 2026-11-08 01:12:23 -08:00
shinyobjectz 695f54b966 FC0a: camera_pass writes a Camera only when its row changes it
The live route calls camera_pass every frame. Assigning to the Camera through get_mut marked it changed every frame, even with the same values, and that moved two edge pixels in frame 10 of bench/bevy/paint/edit between the live and program routes (#38). It now compares the row's order, clear and viewport with what the Camera holds, and writes only when one differs. paint/edit's frame 10 matches across routes again; two_passes and split_screen pass as before (0 and 673 px off live).
2026-11-08 01:10:41 -08:00
shinyobjectz b36c58f95d A video with 3D makes its 3D live, stepping React once a frame (part of #38, #26)
The last part of #26: a full 3D video stepped React twice per frame, once in runtimes of its own to make the 3D rows beforehand and again for the page. When the page's render meets its first 3D frame, it now starts again with its 3D made live as each frame steps, as a game's render does. Each frame's scene is kept (LIVE_CLIPS) for the clipping check at the end, and --aov works on the live engine too. RAEA_3D=program keeps the old route. The program fallback's two returns are now one (render_bundle_with with scene.is_some()).

This was parked until #38's cases matched (environment, kept mounts, text3d, volumetric glass, world answers, material fields: all landed). Checks with this build:
- 190 compositions, default route vs RAEA_3D=program, 30 frames each: 151 identical. 35 fail on both routes as before (compositions that throw, plugins not compiled in). The three world cases differ on frame 0 only, which is expected (useWorldAnswer). bevy/paint differs on frame 10: two edge pixels by at most 15 levels. That is present without this change too (the previous build shows it on RAEA_3D=live) and is listed on #38.
- #26's scene (bench/at-3d), full 360-frame render, whole run, old default vs new, back to back: 13.2/12.5/13.2 s vs 10.7/10.6/10.4 s, frame hashes identical. Its ms-a-frame line reads 24.0/24.1/25.5 vs 26.3/27.8/27.2, because React's one step is now counted inside the frame.
- bevy-ts: 92 pass, 1 open (shader-character, open before too).
2026-11-08 01:05:25 -08:00
shinyobjectz 2a71a69d95 FC0a: 3d/two_passes and 3d/split_screen, several cameras in one window
<Camera3d> takes Bevy's Camera order, clear_color (ClearColorConfig: Default, None, Custom) and viewport (physical px). Every camera in a scene gets a camera row: the first is "cam", and each one after it is cam1, cam2 and so on (runtime/look camera.rs). Renders and live play spawn them all, and raea-sys-frame's camera_pass puts each row's order, clear and viewport on its Camera. Per-camera UI goes in a <Viewport> inside <UiTargetCamera>.

two_passes: 0.999025, 0 px off in render and live. split_screen: 0.998973, 1142 px off in render, 673 in live play. Mutation tests: a missing viewport, a shifted viewport, a moved camera and a changed justify_content fail the bar. The pixel probe catches the light angle, button width, padding, margin and plane size. Reversing the camera order is equivalent because the viewports don't overlap. In live play, extra cameras keep the place they had on the first frame.
2026-11-08 01:01:17 -08:00
shinyobjectz a800f3cfa5 FC0a: ui/text/font_atlas_debug passes (0.99966): bevy_text's glyph atlas in raea's TSX. raea/ui's FontAtlasSet.atlases(font, font_size, text) is the pages a Text of that text fills, made natively by bevy_text's own code (the fonts.atlases call, raea-sys-fonts atlas.rs: the text shaped in the face as bevy_text shapes it, each glyph its layout meets rasterized by swash and packed by add_glyph_to_atlas, 2 px padding, 512 px pages), each a PNG data: URL an ImageNode shows. The port grows the yellow FiraSans-Bold text every third frame from the example's ChaCha8Rng (rand's random::<u8>() as char: "a6Ò" and a control character by frame 10, drawn as .notdef in both) and shows the page beside it a frame after it's made: the atlas's packing, Ò's base and accent as two glyphs, matches Bevy's. The bar fails 7 of the 10 mutants; of the 3 it passes, the off-pixel probe catches the atlas size (1552 against 680) and its top (1353), and a probe of the text's fully yellow pixels its colour (0 against 1680); the tenth (dropping the repeat check) draws the same three characters by frame 10. runtime/calls tests/fonts.rs (atlases: one page, a glyph met twice packed once). 2026-11-08 00:35:23 -08:00
shinyobjectz d7982d95e5 #38: a mesh's alpha mode follows its opacity each frame, on both routes (part of #38)
What changes for authors: a mesh at opacity 1 draws opaque and writes depth, on every frame where it's at 1, even if it fades on other frames. Below 1 it blends. Before, a render made any mesh with an opacity column (one that faded at any point) a blended surface for its whole life, while live play blended only from the first frame below 1. A mesh whose alpha mode is given (alpha: blend, mask...), or a blended picture (a glyph over its atlas, a textured mesh that fades), keeps its own mode at 1.

bevy/volumetric-glass differed between the routes on frames 20-39, where its pane is at opacity 1 and the fixture says it "must draw as the opaque one" (frame 19). The live route did that. The program route drew the pane blended, so it wrote no depth: the froxel hero shaft was integrated to the wall behind it and then dimmed by the pane's full opacity, and the shaft in front of the pane was lost. systems/material maps.rs now spawns a mesh opaque at opacity 1, and runtime/scene3d sync_meshes and the toon sync switch Opaque and Blend both ways each frame. froxel_glass already drops a surface's fog copy once it stops blending.

Checks:
- volumetric-glass: all 90 frames equal between the routes. The program route's frames 20-39 changed and now equal frame 19; no other frame changed.
- bench/live-3d/check.sh adds it: 13/13 pass. bevy-ts: 92 pass, 1 open (shader-character's body.glb, open before too).
- Old vs new binary, program route, frame hashes: no change in broll (p26), bevy-parity mesh_ray_cast, texture, transparency_3d, bevy-ts alpha-mask, bevy/materials, bevy/studio, conformance layered-clear, react box3d. room3d isn't deterministic (two runs of the old binary differ on 147 frames); its one fade is a Decal, which this doesn't touch.
- The 1 to 0.99 edge (a scratch cube held at 1, then 0.99, 0.98 over a sphere): frame 9 to 10 changes as much as 10 to 11 (about 15 px, at most 4 levels), and the same on both routes, before and after.
- No golden reference fades a mesh.

volumetric-glass, program route, ms a frame before vs after, back to back: 7.3/7.6/7.5 vs 7.5/7.5/7.9.
2026-11-08 00:29:53 -08:00
shinyobjectz bdf9e53397 FC0a: ui/text/system_fonts passes (0.98794): the system's font families in raea's TSX, as Bevy's FontCx lists them. raea/ui's FontCx.family_names() is the native call fonts.families (runtime/calls: a fontique collection of the system's faces alone, sorted, each once; Bevy lists 516 on this Mac, the hidden "." families among them). Gaps found and patched on the way:
- a face parley can't scale (Apple's bitmap-only GB18030 Bitmap has no head table, so its advances are infinite) blacked the whole page: every box after it was NaN. blitz now measures a bevy_ui Text whose lines are no finite size as 0 by 0, as bevy_text's buffer_dimensions does.
- a FontSource::Family face missing a character fell to CSS's serif (Times), then to CoreText's pick for the face, where bevy_text falls to the collection's fallback families (Helvetica for Latin). The SDK now writes such a family as `"Name", "raea-bevy fallback"`: blitz appends no serif to it and parley asks no FallbackHook for it (NO_HOOK_FAMILY).
The bar passes every mutant but two (the count off by one, the rows' blue 0.25 to 0.22); a probe of the count line (473 px off against 556) and of a row's background (srgb 51 51 64 against 56) catches both. All 72 ui ports pass. Open: lines mixing a face with its fallback sit about 0.4 px lower than Bevy's, and their stems are softer (Bevy's atlas is sampled nearest; snapping glyphs to whole pixels didn't bring it closer).
2026-11-08 00:15:34 -08:00
shinyobjectz 485cb7b8aa #38: a glyph faded in on the live route is opaque once its fade is done (part of #38)
In bevy/text3d, "render anything" stayed half see-through on the live route from the frame it typed on. `reveal` fades each glyph through 0, 0.5 and 1. A live frame makes its rows from that frame alone, so a glyph's row has an opacity column only on a frame where it is below 1, and nothing was sent when it reached 1: the glyph kept 0.5. A mesh already gets opacity 1 back on a frame that leaves the column out (a render's keyed column says 1 there); LiveScene::diff now does the same for a glyph. The title's `pop` had the same fault, and caused the small differences from frame 5.

Test: runtime/scene's a_faded_glyph_is_opaque_once_done fails before the fix (no opacity sent) and passes after. bench/live-3d/check.sh adds bevy/text3d: 12/12 pass, all 72 frames equal between the routes (frames 5-71 differed before). The fast path needs no change, since it hands glyph rows to the full path.

bevy/text3d, live route, ms a frame before vs after, back to back: 13.8/12.9/12.8 vs 13.1/12.7/13.2.
2026-11-08 00:10:07 -08:00
shinyobjectz a6d7ab2c6b #38: a live scene's camera multisamples once a frame brings 3D (part of #38)
kept-mount and kept-unmount drew the cube with hard edges on the live route from frame 10, where it mounts: the live camera spawns before any 3D part, so spawn_camera's has_3d check left MSAA off, while the program route's camera sees every frame's rows at load and turns it on. Engine::set_rows now calls raea_sys_post::msaa_for_3d, which turns MSAA on for a 3D camera once its rows have 3D, under spawn_camera's own rule (not with ssao, aa, outline, frame_looks or passes, not in preview).

bench/live-3d/check.sh adds both cases: 11/11 pass, every frame equal between the routes (frames 10-19 differed before, program 158 vs live 216 at the cube's edge).

kept-mount, live route, ms a frame before vs after, back to back: 26.9/23.0/23.7 vs 24.5/21.6/22.6.
2026-11-07 23:53:02 -08:00
shinyobjectz ba97a973c0 Live play cuts from one <Environment> panorama to another, lit and with its sky, as a render does (part of #38). bevy/environment cuts from venice_sunset to museum_of_ethnography at frame 30. A render's camera row lists both panoramas at load (env_srcs) and keys which one each frame shows (env_i), and the engine bakes both lights up front. A live frame's row names only its own panorama, and env_srcs wasn't a column live frames send, so live play kept the first panorama for good: frames 30-59 of the case showed Venice in live play and in the parked live render route.
LiveScene's camera row now lists every panorama shown so far (runtime/look's env_shown: the list last sent, then this frame's if new), with env_i pointing into it, and sends env_srcs when the list grows. Engine::set_rows hands a live frame's rows to raea-sys-environment's live_rows. It makes and bakes a new panorama at the first one's face size (grow, which shares panorama() with the load's environment()), then keeps updating until the new light is filtered, so the frame of the cut isn't lit by empty targets. Those updates draw nothing and step no time: the time strategy is held at zero and put back. A camera that had no panorama gets its whole environment the same way. The code sits in raea-sys-environment and raea-runtime-look because raea-render and raea-runtime-scene are at their 2000-line limit.

bench/live-3d/check.sh adds bevy/environment and material-field-0 (c0fd55f43): 9/9 compositions' per-frame hashes are identical between RAEA_3D=program and RAEA_3D=live with RAEA_LIVE3D_CHECK=1, where the raea before this differs on 30 of environment's frames. bevy-ts check.sh: 92 pass, 1 open (shader-character, open before).

fps, bevy/environment rendered live back to back, three runs each: 19.0, 19.2, 19.7 ms a frame before, 20.6, 18.7, 20.6 after (the second panorama decoded and baked once at the cut, which live play skipped before). The program route doesn't take this path.
2026-11-07 23:41:00 -08:00
shinyobjectz c703bb308c FC0a: UiMaterial, as Bevy's ui/ui_material runs it (docs/control.feature FC2a). raea/ui's MaterialNode draws a node with a fragment shader of the author's, compiled as written: its @group(1) bindings are renumbered into raea's slots (up to 8 uniforms of any type to 256 bytes, 4 textures and their samplers; raea-sys-shader ui_bind.rs) and it reads UiVertexOutput as in Bevy. raea-sys-shader's ui.rs runs Bevy's own UiMaterialPlugin with one material type: each node is drawn by a Camera2d of its own into a texture of its border box (the node's border widths and corner radii as Bevy resolves them), which the page shows in the node's place, on the GPU or read back. ui/ui_material passes with no pixel off at frame 10; its probe caught every mutant (colour, border colour, slider, the border's width and radius, the texture). The rerun of every registered port changes nothing else (107 of 110 pass; the 3 that fail are the known frame-time and transparency_3d ones). 2026-11-07 23:29:58 -08:00
shinyobjectz c0fd55f43d A material: row sets only the fields it gives on the part's own StandardMaterial, the rest as they were (part of #38). patch_material deserialized the given fields as a whole StandardMaterial, every field it wasn't given at its default, and applied all of them. So material-field's patch of emissive_exposure_weight also blacked out the cube's emissive and turned its black base white. On frame 0 the scene sync put the row's colours back. From frame 1 on, a render leaves an unchanged mesh alone (StillSynced), so the program route drew the cube grey (red 49) at a weight of 0.14, in stills too. Live play re-synced every frame, which hid it, and so the two routes differed on 29 of 30 frames. Each given field is now deserialized by its own type and applied to that field alone. An unknown field is refused by name.
material-field-0, red at the cube's centre on frames 0, 1, 5, 10, 20, 29: the program route was 216, 49, 49, 49, 49, 49 and now draws 215, 206, 165, 101, 14, 14, the same as live play. That's the ramp Bevy's emissive * mix(1, exposure, weight) gives the rows' eased track. At frame 20 the cube is the black base's specular (14, 9, 10), not grey. The grey (50, 48, 49) that control.feature FC1c recorded was this bug, and the case comments now say dark. The probes (r>150 at 0, r<80 at 20 and live) pass as before. A unit test (a_material_row_sets_only_its_fields) checks that a patch keeps the emissive and base colour; it fails on the old patch with emissive black and base white. bevy-ts check.sh: 92 pass, 1 open (shader-character: its body.glb has no joint it names, open before this too).

fps, material-field-0 back to back, three runs each: 21.9, 16.9, 23.0 ms a frame before, 22.2, 21.7, 17.4 after.
2026-11-07 23:06:11 -08:00
shinyobjectz 900411c90e FC0a: the five ui/text input examples port: editable_text_filter 1.00000, ime_support 0.99822, multiline_text_input 0.99804, multiple_text_inputs 0.99233 and text_input 0.99909, each at its first frames with the AutoFocus'd input's caret where Bevy draws it (none where the focus lands on no input).
Gaps found and patched. An empty Text is parley's empty line: bevy_text leaves its empty span out, so parley lays out nothing in its default style, 16 px high and 0 wide whatever the Text's font. text_input's empty output box was 16 px short without it (0.959). EditableText takes max_characters, filter (EditableTextFilter) and read_write_mode (TextReadWriteMode; Static draws no caret, as bevy_ui_render's extract skips it). The first two act on typing, so a starting text past them is kept, as Bevy keeps it. multiple_text_inputs: TextEditChange fires as EditableText::new sets the text, so the "value" boxes show each input's text from the start; of the two AutoFocus inputs the later one holds the focus, and update_row_border_colors dims the others (SLATE_300.darker(0.75)).

Mutants: the bar fails a missing caret in multiline (and the probe counts 1618 px off, not 1402), 7 for 8 visible lines, a Left setting, no "value" text, focus on the first section, darker(0.5) borders, visible_width 9, a non-empty output and a 240 px IME box or a serif output. It passes a missing caret in editable_text_filter (SLATE_700 on DARK_SLATE_GRAY is low contrast), but a pixel probe at the caret (x 530 to 535, row 360) matches Bevy's srgb(51, 65, 85) exactly, which the mutant leaves as the background. It also passes 6 px padding (1904 px off, not 0) and an 8 px scrollbar (7361, not 1402). Dropping read_write_mode changes nothing here, as it should: only Static hides a caret, and the Static row has no focus. All 61 ui ports pass. conformance/feathers.test.tsx (EditableText's new props, the empty Text).
2026-11-07 22:57:07 -08:00
shinyobjectz 1af64f2a41 raea/world's answers are read in a component with useWorldAnswer(ticket), which renders that component again the frame the answer arrives, in live play and in a render alike (part of #38). world.answer(ticket) was the only read, a pull with no subscription, so a component that never re-rendered never saw its answer. bevy-ts's world-render, world-host and live-world drew green in a render only because the program route steps React twice: the first pass's Engine answers the calls queued at load, and the second pass reads them at frame 0. Made live (one pass, RAEA_3D=live), all three stayed red on every frame.
The hook is useSyncExternalStore over a small store of answers by ticket (an answer comes once and never changes, so a reader gets the same object each time, and it outlives the Engine's queue of the last few hundred). It subscribes to its Clock's tick (clock.tsx's onClockTick) only until its answer is in, and only the components that read an answer render again. world.answer(ticket) stays the plain read for code outside React, through the same store. The three cases read their answers with the hook. Under RAEA_3D=live they're now green from frame 1 on, and the program route is unchanged (green from frame 0). Frame 0 can't match in one pass: the calls name parts ("cube") that exist only once frame 0 has rendered, so the program's frame-0 answers were the double step's. raea-bevy's limits.md now points agents at the hook.

bevy-ts check.sh: world-render, world-host and live-world pass (default route; live-world in live play). fps, world-render back to back with the case before and after, three runs each: 7.1, 6.7, 6.8 ms a frame before, 7.0, 6.9, 7.5 after.
2026-11-07 22:53:56 -08:00
shinyobjectz 43eb20fbd7 FC0a: ui/styling/box_shadow ports at 0.99880, and bevy_ui's drop shadow is drawn as Bevy draws it. The port is the example's first frame: a 164 px square with a 1 px white border on CSS gray, its BoxShadow black at 0.8, offset 20, spread 15, blur 10, under BoxShadowSamples(6), and the settings pane (examples/helpers' radio and number inputs) over the dark theme with its pane body at 0.9 alpha.
The shadow: a node with a box shadow is marked data-raea-bevy-shadow with its BoxShadowSamples (new, @bevy bevy_ui_render::BoxShadowSamples, 4 unless a <BoxShadowSamples> above sets it). raea's Blitz spreads its outer shadows by bevy_ui's rule (width + spread, height and corners by the same ratio) and paints each from a CPU bitmap of box_shadow.wesl's rounded-box shadow: across, the exact erf integral; down, the Gaussian summed in SAMPLES steps over 3 deviations each side, clamped to the box; on the quad of the shadow's size plus 6 blur radii. Vello's analytic shadow is a different approximation of the blur, so it is no longer used for bevy_ui nodes (CSS box-shadow is unchanged).

The bar is blind to a soft shadow: spread 15 -> 12 or 14, blur 10 -> 8 or 9, samples 6 -> 4, x offset 20 -> 18 and alpha 0.8 -> 0.7 all pass it. A pixel probe over the shadow (crop 260x260+580+280, max difference) tells each from the real port: the real port differs by at most 1 level, the mutants by 2, 4, 1 (samples 4: Bevy's own 4 and 6 differ by about that), 6 and 14; samples 6 -> 1 fails the bar. All 56 ui ports rerun: they pass, overflow_transform (0.99543) and feathers_gallery (0.99561) among them. image_node_resizing's camera index is 430 again: registering this example put one more startup entity in the parity host (454 -> 455), and its comment now says how to tell.

The parity host's build.rs makes an example's #[path] modules absolute and its `use crate::` a `use self::`, since the example is a module of the host (box_shadow takes its helpers that way).
2026-11-07 22:46:26 -08:00
shinyobjectz 0ee51a1c64 Inline text in a scrolled element is scrolled once, as Chrome scrolls it, not twice (closes #46). blitz-paint's render_element drew a scroller's contents scrolled two ways: it subtracted the scroll offset from content_position, and (since #18) pre-translated the transform by it. Inline text and a text input's text are placed by both, so a box with scrollTop 60 showed its text 120 px up: "Three" over "Four" where Chrome 148 shows "Two" over "Three". Block children are drawn through the transform alone, which is why sdk/ui's overflow-scroll case (block rows) never caught it. content_position now stays put and the transform scrolls everything. #37's text mask is unchanged: Chrome masks a scroller's background with its text unscrolled (scrollTop read back 60, and a forced repaint kept the mask at "One" over "Two"), and raea's mask already ignored the scroll. Its doc comment now says so instead of calling the offset a gap.
bench/background-clip-text/check.sh adds scrolled.tsx: a plain scroller and a text-clipped one, each scrolled down a line. Only "Three" reaches past x 112, so a strip at x 112-140 tells the lines apart. The raea before this fails both of the plain scroller's strips, and the raea with it passes all of them.

fps, the same 120-frame scrolled.tsx back to back, three runs each: 4.7, 4.0, 4.5 ms a frame before, 4.5, 4.4, 4.0 after (about 230 fps both; the change removes a subtraction).
2026-11-07 22:41:07 -08:00
shinyobjectz 9fe4c0c307 FC0a: ui/widgets/feathers_gallery ports at 0.99561, with the rest of bevy_feathers: panes, sub-panes and groups; menus, selects, list views and tool buttons; checkboxes, radios, toggle switches, disclosure toggles and the slider; the text input, colour swatch, colour slider, colour plane and colour input; and its icons
The gallery brought four gaps, now patched rather than skipped:
- Okhsla: bevy_color's Okhsla (in f32, as Bevy computes it), and Okhsla gradients sampled from okhsl's mix, which CSS has no space for. An Hsla track keeps its stops' hues, so the hue slider runs the long way back to red as Bevy's does.
- A spreading BoxShadow: bevy_ui widens the shadow by the spread and scales its height and corners by the same ratio. The spread is now sent, and a node marked data-raea-bevy-shadow is spread by that rule in raea's Blitz (vendor/blitz-paint box_shadow.rs, unit tested).
- A translucent border blended over the node's own background. Bevy draws the background inside the border only, so the border blends over what lies under the node. Feathers' disabled switch slide showed it.
- The alpha checkerboard and the colour plane are UiMaterials in Bevy. raea has no UiMaterial yet (FC2), so the checkerboard is a tiled conic gradient centred on the node, and the plane is a bitmap of color_plane.wesl's formulas.

Where Bevy 0.20 itself differs from its intent, the port draws what Bevy draws:
- The list view's scrollbar never finds its scroll area (#inner, passed through the scrollbar's props, resolves to no entity), so Bevy draws its track and no thumb, and keeps the gutter.
- The hex field's InheritableFont { font: MONO } never reaches the input's own text, so it shows in feathers' regular face.

ui/images/image_node_resizing's camera index moves to 429: every example's Bevy run now has one fewer startup entity in the parity host, and this port is the only one that names an absolute index.

Probes caught all 11 gallery mutants, against 4 for the bar alone: the swatch's opaque part, the checker's phase and colours, a mirrored thumb, a lost middle stop, a flat alpha track, swapped plane axes, the plane's fixed channel, the list track, the border blend and the colour input's size. All 55 ui ports pass again.
2026-11-07 21:32:37 -08:00
shinyobjectz 601296ea0e FC0a: ui/widgets/feathers_number_input ports at 0.99748, with feathers' FeathersNumberInput: the value as Rust's Display prints it ("1", not "1.0"), held within its HardLimit and shown through its units (LengthMeters, TimeSeconds, AngleDegrees: PI radians reads 180°), over a hard-stop gradient bar to its place in its SoftLimit, dimmed when disabled, with a sigil strip and an "X" label. NumberInputValue and NumberInputRange in f32, f64, i32 and i64. Blitz drew nothing for a one-sided border on a rounded box: the corner split angle divided by the other side's zero width (NaN); its limit now gives the whole arc to the side with the width (vendor/blitz-paint, with a unit test). The bar passes a moved soft-limit bar, an undimmed disabled field, the wrong sigil colour, radians for degrees and a missing label; pixel and region probes catch all five. borders, gradients and standard_widgets score as before. 98 of 102 ported examples pass 2026-11-07 19:45:22 -08:00
shinyobjectz b269cbc12e FC0a: ui/widgets/feathers_counter ports at 0.99994, with feathers' display: caption (a ThemedText), label, label_dim and label_small (Fira Sans in the theme's text colour, which no propagation overrides), and ThemeBackgroundColor, ThemeBorderColor and ThemeTextColor, which colour the one element inside from the UiTheme. A button's caption takes Fira Sans 14 px; the count, a caption outside any widget, keeps Bevy's default font, as in Bevy. A pane background fails the bar; a plain Text caption (298 pixels off, not 15) and no margin (237) pass it and are caught. 97 of 101 ported examples pass 2026-11-07 19:34:56 -08:00
shinyobjectz 133e637b80 FC0a: ui/widgets/standard_widgets ports at 0.99765: the headless widgets at rest after the style systems' first frame, the RadioGroup with only Snap's mark (update_widget_values checks the radio matching the resource) and the menu Button closed. The bar fails only a centred menu; probes catch Drag checked (its mark 191, not 44), a checked checkbox (191, not 44) and no menu square (38, not 128); rings and marks sit at Bevy's boxes, the rest is glyph edges. 96 of 100 ported examples pass 2026-11-07 19:32:10 -08:00
shinyobjectz e31303c7fd FC0a: ui/widgets/standard_widgets_observers ports at 0.99874: the headless Button, Slider and Checkbox as their observers leave them at rest, the thumb at 50% once update_widget_values inserts the resource's value. The bar fails only the Hover mutant; probes catch the rest (the thumb at 0%: its pixel 13, not 191; a checked mark: 191, not 44; no TextShadow: the button's region 207 pixels off, not 168). 95 of 99 ported examples pass 2026-11-07 19:29:37 -08:00
shinyobjectz c4e528f56a FC0a: ui/widgets/virtual_keyboard ports at 0.99371, on raea/feathers (bevy_feathers) and EditableText. raea/feathers carries feathers' dark theme (its palette, semantic colours, surface-level overrides and 150 token assignments, generated from dark_theme.rs and tokens.rs; with no UiTheme every token is FUCHSIA, as Bevy's empty ThemeProps), FeathersButton, VirtualKeyboard and ThemedText: a widget's font and text colour reach only a ThemedText, as feathers' Propagate is filtered With<ThemedText>, so the keyboard's plain Text keys keep Bevy's default font, as Bevy draws them. Feathers' own Fira Sans (four faces) and Fira Mono Medium are bundled whole in core/fonts, and its fonts name them by family. EditableText measures as TextInputMeasure (visible_lines of line height, rounded up; visible_width in ch, the advance of 0) and draws parley's caret, cursor_width of the font size wide, for the first half of each blink period while it has focus. Oklcha gains lighter, darker and with_alpha. 94 of 98 ported examples pass 2026-11-07 19:27:22 -08:00
shinyobjectz 00327576cc #35's test of an SVG <text>'s attribute names takes its frames from the walk (part of #27). It handed Tree::diff a frame written by hand with $ns already in it, so nothing tested the walk giving it: with elements.rs's page.insert("$ns", "svg") taken out, every test still passed. The test now builds the React tree a composition's commit leaves (a <text> in an <svg>, and a <title> under its <foreignObject>), walks it on each of two frames as BevyPage does, and sends the walk's wants through Tree::diff to ops::apply. It checks that the <text> has $ns and the HTML <title> doesn't, and that the second frame's fontSize and textAnchor keep their SVG names. With the insert taken out, it now fails at "the walk names the <text> SVG's". world.rs's walk (a plain App's page) now also starts from IN_3D 0 and IN_SVG false, as BevyPage's does. 2026-11-07 19:14:20 -08:00
shane ea501764b2 Merge public PR #35 from JimGHTB12: an SVG <text>, <image> and <title> keep their SVG attribute names
Closes #27.
2026-11-07 22:09:40 -05:00
shinyobjectz 0d3d0401de FC0a: ui/widgets/vertical_slider ports at 0.99900, and a bevy_ui page's curves are flattened to 0.02 px, not Vello's 0.25 (vendor/vello_shaders flatten_tol, on config.blend_linear). The chords drew the 12 px round thumb a quarter pixel small, every edge pixel's coverage about 0.12 short of Bevy's distance-field edge; now the thumbs differ by no pixel at 3% (their mean error a quarter of what it was). Text is drawn through the same flattening, and the old inset happened to sit nearer Bevy's glyph rasteriser: the text ports move by up to -0.0009, the shapes by up to +0.0023, all 49 UI ports still pass. 93 of 97 ported examples pass 2026-11-07 19:08:49 -08:00
shinyobjectz 90f65721d9 A 3D scene made live (live play, a game's render) draws what its program draws (part of #26). Each frame's live rows now send what a render keys, the way it keys it. Toward making a full 3D render step React once (#26's leftover): its 3D made live as each frame is stepped, as a game's is, instead of in runtimes of their own beforehand. Rendering 155 3D compositions both ways (RAEA_3D=program and =live, per-frame hashes) found these differences, all bugs in live play too:
- A spot's cone (inner, outer) wasn't sent after its first frame. On 3d/spotlight, live scored SSIM 0.94 against Bevy's own frame 20, the program 0.99.
- A zero scale's rotation came out NaN and was sent again every frame, since NaN never equals itself. It is now the identity, or the frame before's in the program.
- The fast path sent a bulb's place as the World's f32, where the program rounds it to 6 decimals.
- Live frames sent only the camera's place, look, fov, focus and ambient. They now send every column a render keys (cam_keyed: a roll's up_*, the view window, sky and environment, aberration, depth of field, lens, motion blur, paint). Both live paths build the camera row with the program's own camera code (camera_row, camera_diff); the fast path's copy of it is gone.
- Colour columns were rounded to 6 decimals, while a hex colour is its byte over 255, so a part whose colour ever changes drew a hair off on every frame until it did. They are exact now, in the program too.
- The fast path kept glam's sign for a rotation where the full path takes the identity's side. That's the same matrix, but RAEA_LIVE3D_CHECK=1 refused it.

Test: bench/live-3d/check.sh renders seven compositions both ways (live with RAEA_LIVE3D_CHECK=1) and requires identical hashes. It fails five on the build before this and passes all seven after. bench/at-3d/check.sh still passes. The wider run: 144 of 155 identical. The other 11 (the Engine's World cases, material fields, environment, text3d, kept mounts, volumetric glass) are #38, so a full render still makes its rows beforehand and still steps twice.

fps: live play's frame cost is unchanged. #26's 360-frame, 200-mesh scene rendered live, before and after, back to back in three rounds: 20.5/20.5/20.3 vs 20.1/20.5/20.2 ms a frame.
2026-11-07 19:08:07 -08:00
shinyobjectz fb35f5d908 FC0a: ui/widgets/viewport_node ports at 0.99987: a second camera with a Viewport over the node's border box. A camera with a Viewport keeps its own shape: the engine no longer gives it the whole frame's SubCameraView, which sized its projection to 16:9. 92 of 96 ported examples pass 2026-11-07 18:57:04 -08:00
shinyobjectz 9f1152a6f9 FC0a: ui/widgets/tab_navigation ports at 0.9980: four TabGroups of four buttons, none focused. 91 of 95 ported examples pass 2026-11-07 18:45:54 -08:00
shinyobjectz 0652b75313 FC0a: ui/widgets/headless_tabs ports at 0.9930: four tab lists coloured as update_tab_styles leaves them (selected, disabled, the rest). 90 of 94 ported examples pass 2026-11-07 18:43:33 -08:00
shinyobjectz a5663cb511 FC0a: ui/navigation/directional_navigation_overrides ports at 0.9961. A bevy_text box's min-content is its lines broken at no width with their trailing spaces (parley's full_width, as bevy_text measures it), so a wrapped, centred label sits where Bevy puts it; the 44 other UI ports score as before. 89 of 93 ported examples pass 2026-11-07 18:41:15 -08:00
shinyobjectz f546e1d8c5 FC0a: ui/navigation/directional_navigation ports at 0.9981. A bordered bevy_ui Node's background is clipped to its padding box, as bevy_ui draws it (only the area inside the border), so a see-through border shows what's under the node; the other 43 UI ports score as before. 88 of 92 ported examples pass 2026-11-07 18:34:44 -08:00
shinyobjectz 1a23d1f9bb FC0a: ui/ui_drag_and_drop ports at 0.9990. A bevy_ui Outline's colour goes as written, for the page to blend in linear light, instead of mixed into the parent's background: it lies outside the node and over its siblings, so a Color::NONE outline drew 2 px grey seams over every tile. 87 of 91 ported examples pass 2026-11-07 18:29:13 -08:00
shinyobjectz 3892ac4367 background-clip: text clips a background to the element's text, as Chrome does (closes #37). Gradient text, a common headline style, came out as a gradient box with the text invisible. Two gaps: the vendored stylo knew the text value only for Gecko, so in Servo mode the declaration didn't parse (and #34's note didn't list it: stylo doesn't report a drop of a property the block already set, here through its background shorthand), and blitz-paint had no text clip. Now stylo takes text for Servo too, and blitz-paint draws a background with a text clip in a group that the text then masks (Compose::DestIn). The mask is the element's own inline layout plus the text of every element inside it, at its place (draw_text_mask: glyphs opaque, without their shadows). A scroller's offset isn't applied inside the mask.
Test: bench/background-clip-text/check.sh draws "Gradient" three ways: with background-clip, with -webkit-background-clip alone, and through a block inside the clipped one. The G's stem must be the gradient's pink, and the box beside and above each word must be the page's #111, as Chrome 148 gives them. Before: 6 of 10 pixels failed (the gradient box). After: PASS. TSX's backgroundClip and WebkitBackgroundClip, and an inline <span> inside, also match Chrome by eye.

fps, the same 300-frame page with three clipped lines, before (17:54 build) and after, back to back in three rounds: 493/542/533 vs 518/599/489 fps incl. encode, no cost beyond the noise.
2026-11-07 18:28:19 -08:00
shinyobjectz b6053cf8a7 FC0a: ui/render_ui_to_texture ports at 0.99998. UiTexture and targetImage draw bevy_ui into an image a StandardMaterial samples: the UI is laid out as a Screen's picture (painted alone, handed to raea-render by name each frame), and a material texture of raea-screen:name@WxH resolves to that screen's image (raea-sys-screen named_image). 86 of 90 ported examples pass 2026-11-07 18:18:57 -08:00
James DimachkieandClaude Opus 5.5 07908a430d #27: the regression test moves to raea-runtime-page, through the frame diff
raea-sys-page is at its 2000-line limit (tools/size.sh), so the test of an SVG <text>'s attribute names leaves ops.rs.
In raea-runtime-page it takes the path a composition's frames take: the walk's Wants (the <text> with `$ns`), then
Tree::diff, whose second frame sends only the changed fontSize and textAnchor, then ops::apply. It fails without the
ops.rs change: the update adds fontsize and textanchor beside the stale font-size.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 18:15:43 -08:00
James DimachkieandClaude Opus 5.5 2e6ff46aea #27: an SVG <text>, <image> and <title> keep their SVG attribute names
The composition walk never said `$ns: "svg"` for the three SVG tags HTML also has, so inside an <svg> they became
HTML elements and their camelCase attributes were lowercased (textAnchor to textanchor, fontSize to fontsize), which
usvg doesn't know. The walk now tracks whether it is inside an <svg> and not back in HTML under a <foreignObject>
(IN_SVG, beside IN_3D), and gives those three `$ns: "svg"` there, as sdk/ui's host does. An update in ops.rs also
treats a node as SVG's when its element is in SVG's namespace, so an animated fontSize keeps `font-size` on every
frame, on sdk/ui's path too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 18:15:42 -08:00
shinyobjectz fd4d06c4e4 raea-sys-page's op wire is a crate of its own, raea-sys-page-ops (systems/page-ops): ops.rs and ops/attrs.rs moved whole, with ALL_DAMAGE, which they mark damage with. raea-sys-page re-exports it as ops (and ALL_DAMAGE), so every raea_sys_page::ops path reads as before. raea-sys-page had reached 2000 lines through the day's landings, so a fix in it (PR #35, #37's next) had no room; it's 1424 now. No code changed: the moved tests pass (cargo test -p raea-sys-page-ops) and raea-sys-page checks with its tests. 2026-11-07 18:12:46 -08:00
shinyobjectz a00a49319e The copies part of #28 added are folded (dupes 297 -> 295): urls.rs takes the writer of a file's URL as a parameter instead of a test-only twin of raea_io_home::src, and the fixed-quantiser tests join io/soft/tests/quality.rs, sharing its frames of rings and its MP4 encode. tools/dupes.max goes down to exact=295 2026-11-07 18:00:09 -08:00
shinyobjectz c7918660d5 The skill says what a render is on each platform (part of #28): H.264 High and AAC on a Mac, Constrained Baseline and Opus from openh264 on Windows and Linux. It said H.264 High for all 2026-11-07 18:00:09 -08:00
shinyobjectz 0c419d8164 openh264 takes the fixed quantiser it's asked for (part of #28). With rate control off it ignored the QP range and wrote QP 26: the optimized copy's QP 16 and a GOP's QP gave the same bytes as any other. fixed_qp now uses its Quality mode with the range pinned. That mode needs a bitrate other than 0 (it moves nothing once the QP is pinned), and it refuses a QP under 14, so a lower one is raised to 14. A frame too detailed for openh264's buffer at QP 16 (some 1.6 MB a 1080p frame, noise rather than footage) fails with Native:3, so the copy is made again at QP 26, as every copy was before. io/soft/tests/qp.rs: QP 16 writes over twice QP 40's bytes for the copy and a GOP, a GOP is the same bytes each time, and QP 4 is QP 14; before, 12 and 40 were identical 2026-11-07 18:00:09 -08:00
shinyobjectz 67114ed2ca A stylesheet's url()s naming the composition's files reach the page as file URLs on Windows (part of #28). An inline <style>'s font URL was written as a raw Windows path, whose backslashes CSS read as escapes and whose C: it read as a URL scheme. One rewriter (runtime/bundle urls.rs) now serves inline <style> text, style props, brand.css and the CSS a bundle imports, writing each file through raea_io_home::src as <img> does. A relative URL starts from the stylesheet's folder (brand/ for brand.css, the edit's folder otherwise), and /media/ from the edit's. Its unit tests check a Windows path on any system: no backslash is left, and the URL is file:///C:/... 2026-11-07 18:00:09 -08:00
shinyobjectz 3e1efbab77 #32: an HTML page renders to PNGs, a folder (-o DIR, one frame-NNNNN.png a frame) or one still (-o OUT.png: frame 0, or the one --at names), and --alpha gives them a transparent canvas, as a TSX composition's do. The direct path wrote only video or hashes, so -o frames wrote an MP4 named frames, failed with "Is a directory" when the folder was there, and --alpha couldn't apply.
How: gpuview's direct render has an RGBA mode (GpuView.rgba): its three-deep readback ring copies the composite itself (RGBA8 premultiplied) instead of making NV12, so a PNG costs no extra pass. runtime/encode writes each frame straight-coloured (straight(), the engine path's un-premultiply, now shared). RenderOpts.alpha (apps/media's --alpha, refused for video) sets the page's canvas row to #00000000; the camera's clear colour was read as RGB with alpha forced to 255, so a clear canvas came out black. runtime/view's camera_bg reads #rrggbbaa, premultiplied, for gpuview and cpuview (one function where each had its own copy). The help and cli.md say OUT.png and --alpha for PAGE.html.

Check: bench/html-png/check.sh (a half-opaque red box sliding over an empty canvas): -o DIR --at 0,29 writes two PNGs, and the box moved between them; -o DIR into a folder that's there works; -o OUT.png --at 29 is byte-identical to the folder's frame 29, and -o OUT.png is frame 0; opaque, the canvas is white and the box pink (255,127,127); with --alpha the canvas is 0,0,0,0 and the box straight red at half alpha (255,0,0,128); --alpha to an MP4 is refused. It fails on the raea before this and passes on this one. bench/html-repeat, bench/frame-panic and bench/dropped-css still pass.

Video is unchanged: bench/html-repeat to .txt gives identical hashes for all 270 frames before and after. fps to MP4, seven alternating rounds on a shared, busy machine (the "before" build is about an hour older, with other lanes' changes): median 181 before vs 170 after, ranges 165-202 and 159-198, no difference beyond the noise (closes #32)
2026-11-07 17:56:27 -08:00
shinyobjectz 30960ed5fa #34: a render says once, when it ends, what its page didn't apply, and its output loses the warnings no one acts on.
Dropped CSS: stylo drops what it can't parse silently unless a ParseErrorReporter is passed, and blitz-dom passed none, so a render printed APPLIED over a picture missing some of its code. vendor/blitz-dom/src/not_applied.rs is that reporter, passed at every author parse (stylesheets and @imports in net.rs, <style> in document.rs, style attributes in node/element.rs, CSSOM in cssom.rs; never the user-agent sheet). It keeps each drop once per property and selector, never its value ("-webkit-text-stroke in .outline", "... in a style attribute"), since a style attribute is parsed again on every frame it changes. FileNet's loads that fail join the list ("the file ... (it didn't load)"). The render prints it once after APPLIED (engine/cli for TSX, apps/media for HTML) as "NOTE  the page didn't apply N things, and is drawn without them:", one per line, at most 20, and --manifest gets it as not_applied. RAEA_NOT_APPLIED=0 parses as before (docs/settings.md), for measuring.

Vendored stylo change, to upstream later: report_one_css_error (properties/declaration_block.rs) returned before reporting any unknown property with a -webkit-, -ms- or -o- prefix, which hid the reporter's main case, -webkit-text-stroke (Gecko-only in stylo, drawn as nothing). It reports them now, and raea's reporter skips the prefixed properties that change nothing in a picture (text-size-adjust, tap-highlight-color, font-smoothing, appearance, user-select and the like), so Tailwind's preflight adds no lines (a Tailwind page with gradients, rings, blur and truncate printed no NOTE). A value error is also named by the property stylo parsed, with the value after it. vendor.toml says both.

Noise: Bevy's bevy_asset::io::web and io::source warnings (printed by every render) and fontdb's skipped faces (system fonts it can't parse, which the reporter saw on Windows; a missing @font-face file, which the NOTE names) are filtered at both LogPlugins (engine/page motion.rs, engine/render open.rs). io/trace's `log` logger, which every third-party `log` record goes through, prints only warnings and errors now, and not fontdb's (Bevy's Ctrl+C handler printed two INFO lines on every render); every record still goes to the trace's events.jsonl.

Check: bench/dropped-css/check.sh renders the reporter's page as TSX (30 frames, its outline moving so its style attribute is parsed each frame) and as HTML. Each must exit 0 and print one NOTE naming -webkit-text-stroke and the missing font once each, with no INFO line and no bevy_asset or fontdb warning, and the TSX render's manifest must list both under not_applied. It fails on the raea before this (no NOTE) and passes on this one.

fps, one build with the reporter on and off (RAEA_NOT_APPLIED), seven alternating rounds on a shared, busy machine: the worst case (bench/dropped-css's page at 600 frames, dropping a declaration on every frame) median 516 on vs 479 off; bench/html-repeat median 202 on vs 172 off. No cost shows above the noise (min to max spans 315 to 620). (closes #34)
2026-11-07 17:46:28 -08:00
shinyobjectz e4bab2a77a FC0a: ui/images/image_node_resizing passes (SSIM 0.9981, worst tile 9). It brings bevy_ui's debug overlay and NodeImageMode's Auto and Stretch.
- GlobalUiDebugOptions, and a node's own ui_debug (UiDebugOptions, which replaces it): Blitz draws each enabled node's outlines after the whole document, above every UI node as bevy_ui_render's extract_debug_overlay keeps them (vendor/blitz-paint render/bevy_debug.rs).
  - An outline is a ring of line_width inside the border, padding or content box, following the corners' radii.
  - It is cut by the ancestors' overflow unless show_clipped.
  - Its colour is Hsla::sequential_dispersed of a debug_color_index, which Bevy takes from the entity's index, unless line_color_override.
- The port's indices are setup's spawn order from the camera's entity, 430, the one base whose colours match all four outlines measured (container, column, group and the 40% image). The text's observer is allocated later, when the commands apply.
- ImageNode's Auto now draws the picture contained in its content box, its aspect kept, as Bevy does; it was filled. Stretch gives the node no picture size and stretches the picture over its content box.
- The other image and UI ports keep their scores.

Probes:
- Every outline pixel along column 900 and rows 156 and 158 matches Bevy's exactly, colour and place (947 along the group's top edge).
- The first Auto icon's anti-aliased disc edges match Bevy's pixel for pixel.

Mutants:
- Base 431 fails the bar (0.9465).
- Stretch as Auto fails it (0.7387).
- The outlines drawn in reverse order fail it (0.9779) and the probe.
- Auto filled instead of contained passes the bar; the icon-edge probe catches it.

Test: conformance/ui-debug.test.tsx (the hues, global and own options, UiScale, refusals) and the ImageNode modes in ui.test.tsx.
2026-11-07 17:41:13 -08:00
shinyobjectz 22074b5ded An HTML page's vendor-prefixed inline styles apply: the page's style object keys one as Chrome's does (webkitTextStroke, webkitLineClamp: the HTML runtime's cssProp), and systems/page's kebab gave a lowercase prefix no leading dash, so it came out webkit-text-stroke, which stylo drops. Every prefixed inline style on an HTML page was lost (-webkit-line-clamp, -webkit-background-clip and -webkit-mask among them); TSX's WebkitX was right. kebab now gives webkitX, mozX and msX their dash as it gave WebkitX and MozX. Found by #34's new note, which listed a style attribute's -webkit-background-clip as webkit-background-clip. Test: ops/attrs.rs a_vendor_prefix_keeps_its_dash_however_it_is_keyed (it failed on webkitLineClamp before). bench/dropped-css/index.html's gradient clip is applied now and no longer listed (part of #34) 2026-11-07 17:36:01 -08:00
shinyobjectz 342bcfc3c0 FC0a: ui/text/font_query passes (SSIM 0.9933, worst tile 19), with TextFont's width: font_width (a share of the normal width, FontWidth's constants) is CSS's font-stretch, which Blitz's parley turns into the variable face's wdth as bevy_text's does. A bevy_ui Text now takes no synthetic italic skew, as bevy_text draws an Italic or Oblique run of a face with no slant upright (MonaSans has none); page text keeps Chrome's. The other text ports keep their scores. Mutants: font_width ignored fails the bar (tile 58), the skew back fails it (tile 33). Test: conformance/ui.test.tsx's font_width. 2026-11-07 17:27:34 -08:00
shinyobjectz f0094cbc3b #28 (3): EncodeOpts' doc says what openh264 does with a quality: it has no constant-quality mode and scales kbps by it (raea_io_soft::quality_kbps, 298d32431); it said kbps was ignored where a quality is set (part of #28) 2026-11-07 17:11:37 -08:00
shinyobjectz f84a89cd52 FC0a: ui/scroll_and_overflow/overflow_debug passes (SSIM 0.9965, worst tile 10): the six clipping cells at the paused animation's t = 0, moved by (-50%, 0), scaled by (1.5, 1) and turned 45 radians, with the instructions' Overflow Debug span. Mutants (no clip, no rotation, no move, no scale, no span) each fail the bar. 2026-11-07 17:10:59 -08:00
shinyobjectz 298d32431b #28 (3): --quality reaches openh264 (Windows' and Linux's encoder). It ignored EncodeOpts.quality, so draft and master wrote byte-identical files. openh264 has no constant-quality mode the crate reaches (a fixed QP with rate control off is dropped, since the crate never sets the layer's QP; Quality mode and a pinned QP range under Bitrate mode fail with Native:3), so the quality now scales the bitrate: io/soft quality_kbps, 2x per 0.1 from high (0.85, the given bitrate unchanged), so master is twice it and draft under a fifth. No --quality keeps the bitrate as before. io/soft/tests/quality.rs encodes three seconds of 640x360 at draft, high and master and needs each a quarter larger than the last (before: one file, three times). Encode speed is openh264's at a different bitrate, nothing added per frame (part of #28) 2026-11-07 17:10:13 -08:00
shinyobjectz ec33f6b871 FC0a: ui/scroll_and_overflow/scrollbars passes (SSIM 0.9945, worst tile 21), with bevy_ui's ScrollPosition and IgnoreScroll, bevy_ui_widgets' Scrollbar and ScrollbarThumb, and UiScale laid out at its scale.
- ScrollPosition (Node's scroll_position): scrolls only a Scroll axis. Blitz keeps it in the scroller's range once layout has its content and floors it to whole physical px, as bevy_ui's layout does (vendor/blitz-dom bevy_scroll.rs, from resolve).
- IgnoreScroll (ignore_scroll): Blitz moves the node back by its parent's scroll on those axes.
- Scrollbar (target by a Node's new `name`, orientation, min_thumb_length) is a Node track. ScrollbarThumb isn't laid out: after layout, Blitz sizes and places it in the track from the target's size, content and asked ScrollPosition, as update_scrollbar_thumb's size_and_pos does.
- The page bridge keeps the new attributes (data-raea-bevy-scroll, -ignore-scroll, -scrollbar, -thumb).
- UiScale is now CSS zoom, not a transform of a logical layout. Bevy lays the UI out and shapes its text in physical px, so a 3 px padding at 1.25 is 4 px; scaled-up text sat about 1 px low. A sliced ImageNode's corner limit and tile stretch take the scale with it (ui_texture_slice_flip_and_tile is pixel-exact).

Tests:
- conformance/ui-scrollbar.test.tsx and the UiScale test.
- blitz-dom's bevy_scroll unit tests: thumb maths and the track attribute.

Mutants:
- No ScrollPosition fails the bar (tile 82).
- Thumbs not placed fails it (tile 44).
- UiScale as a transform fails it (tile 37).
- A thumb that ignores the offset passes the bar. A pixel probe catches it: rows 41-157 against Bevy's 49-165, where the real port matches Bevy exactly (49-165, and 4-240 across).

The other UiScale ports keep their scores.
2026-11-07 17:08:18 -08:00
shinyobjectz 1dca9ace77 #28 (5): ShaderMesh's doc says its uniforms may change from frame to frame and the shader isn't compiled again; it said they were set at load, which agents reading the SDK for types took literally (#26's scene sets one each frame and renders it) 2026-11-07 17:04:14 -08:00
shinyobjectz 6998f9e3e6 #28 (4): the export cache's key takes every file in the edit's folder, not a list of media extensions, so an edited .svg (or .jpeg, or anything a page loads) makes the next render miss; an <img src="/media/logo.svg"> recoloured came back from the cache in its old colour. Dot-files, the output and exports this cache wrote stay out as before. A false miss costs a render, a false hit a stale video. Test: runtime/bundle/tests/cache_inputs.rs (an edited logo.svg and shot.jpeg each change the key; it failed on the .svg before) 2026-11-07 17:02:08 -08:00
shinyobjectz 1eb646f7b9 #33: a panic as a frame draws ends the render with an error naming the frame and the panic, and keeps the frames drawn before it. Each frame loop catches a panic in its drawing (raea_gpu_device::check::frame_caught, or around the pipelined engine's run, which names the newest frame sent) and returns it as an error, "raea panicked drawing frame N: <message>"; the panic hook still prints it and where it was, and the crash log keeps it. On that error, or any other mid-render, the direct path drains the frames in flight to the encoder, the fed path finishes the file without sound, the engine path finishes its encoder, and hashes so far are written, so the file holds every frame before N and the error says how many and where ("no frame was written" when none). Exit 1 now, not a panic's 101. RAEA_PANIC_FAULT=N (docs/settings.md) panics as frame N draws, for the check: bench/frame-panic/check.sh renders an HTML page to .mp4 and .txt, a 2D page to .mp4 and .txt, and a 3D scene to .mp4 and a PNG folder at RAEA_PANIC_FAULT=100, and each exits 1 naming frame 100 with exactly 100 frames kept; without the fault the same renders give all their frames. Speed, two builds of this tree with and without the change, five runs each alternating (the machine was busy: medians), to .mp4: a 2D page 427 fps before, 435 after; #20's HTML page 214 before, 235 after; a 3D scene 71.7 before, 71.5 after (a frame catch costs nothing until something panics).
(closes #33)
2026-11-07 17:00:09 -08:00
shinyobjectz ca41f80d16 #28 (2): a 3D still or --at with --manifest writes the manifest, as a 2D render does. The 3D stills branch (bevy_ui, the page over its 3D) returned without writing it, so none was written and one left from an earlier run stayed, looking current. The three places that write it share write_manifest now (lib.rs); a 3D still's has the frames' boxes and text as drawn, the 3D's clipping from its check, and no sounds. To make room under the crate's 2000-line limit, scene3d.rs (27 lines of wrappers over raea-runtime-scene) is gone: scene.rs keeps items and all_items, and program.rs calls raea-runtime-scene directly. bench/at-3d/check.sh now also needs its --at render's manifest to list the four frames: it fails on the raea before this (no manifest) and passes on this one; a 2D render's manifest is byte-identical before and after. 2026-11-07 16:57:06 -08:00
shinyobjectz 36cbb99227 FC0a: ui/scroll_and_overflow/drag_to_scroll passes (SSIM 0.99999; not a pixel off at 1% fuzz, where hues spread over 260 degrees put 4995 off): 2400 hue tiles at UiScale 0.5 in a scroller at 0 until dragged 2026-11-07 16:42:30 -08:00
shinyobjectz 3675c7a9f9 FC0a: ui/scroll_and_overflow/scroll passes (SSIM 0.9972): a Scroll axis draws no scrollbar (bevy_ui draws none; Blitz's overlay thumb would show once scrolled), Node's scrollbar_width is the gutter taffy keeps beside a scrolling axis (right of a y scroller, below an x one, past the padding), and IgnoreScroll is taken (a page isn't scrolled yet, so it keeps nodes where they are). The parity host has accesskit, a Bevy dev-dependency the example imports. Most of the example lies past the window (the root is as wide as its content, the viewport grid's auto track, in Bevy as here); a 40% list fails 2026-11-07 16:39:59 -08:00
shinyobjectz 9f91e35a8f FC0a: ui/ui_transform passes (SSIM 0.9991): buttons turned by UiTransform about their centres (a Left turned the other way or an unturned Bottom fails) 2026-11-07 16:36:40 -08:00
shinyobjectz abc859cf5d #20: the same page renders to the same frames every time. Vello's fine stage (area antialiasing, what raea-page draws with) summed a tile's coverage in f32 in the order its segments arrived, and path_count hands out their slots with atomicAdd, so the order, and the sum's last bits, changed from run to run: a pixel now and then came out a level apart, so frame hashes and the export cache disagreed between renders. Each contribution is now summed as a fixed-point i32 (2^20 to the pixel), which no order changes, and made a float once. bench/html-repeat/check.sh renders #20's page 8 times to frame hashes and needs every run the same as the first: before, 6 of 7 runs differed (frames 161, 175, 269); after, all 8 match (and 12 of 12 in a longer run). Speed, two builds of this tree with and without the change, five runs each back to back, to frame hashes: the #23 bench page 154-194 fps before, 167-193 after (medians 193.2 and 191.8); #20's page 145-160 before, 154-160 after (medians 155.9 and 157.1). Ten pictures (eight parity cases and bench/rotated-paint's two) are pixel-identical before and after; only frames that fell on that rounding change, by a level.
(closes #20)
2026-11-07 16:36:04 -08:00
shinyobjectz 99428724de FC0a: ui/text/text_debug passes (SSIM 0.984): a TextSpan of size 0 or less is left out, as bevy_text's TextPipeline leaves it, and its Text's other runs laid out without it. The port works out the example's frame-rate figures over the host's 1/60 s steps from a first update at elapsed 0 (66.0 avg fps, 2852.5 deviation at frame 10, as Bevy draws them); a first update one step later fails 2026-11-07 16:34:20 -08:00
shinyobjectz 9027f9d1e5 FC0a: ui/text/text passes (SSIM 0.9909): FontFeatures on a Text or a TextSpan (FontFeatureTag's OpenType tags, as CSS's font-feature-settings, which Blitz gives parley). The parity host has a default_font feature of its own, on, since Bevy's examples ask cfg(feature = "default_font") of the crate they're built in. FPS shows 60.00 (the host steps by 1/60 s); pixel probes of the animated text's colour and the FPS digits tell a doubled clock and 59.99 from the real port 2026-11-07 16:31:57 -08:00
shinyobjectz 6654b93639 #19: children of a preserve-3d parent follow its transform when a script sets it. blitz-dom's resolve_transforms returned an undamaged node's cached place unless it was seen through a perspective, so a node in its parent's 3D rendering context kept the projection from before the parent's new transform (the card under the issue's rig was drawn at its untransformed place, below the frame). A node in a 3D context, or holding a projection (which may have lost its context since), is now placed again on every resolve, as one under a perspective already was. Test: resolve::tests::a_child_follows_its_preserve_3d_parent_set_later (the card's projection with the transform set after the first resolve equals the one with it in the first style; it failed without the fix). The issue's page now renders pixel-identical to the same transform in the stylesheet, and a GSAP rig animating the world shows the card (0 yellow pixels before at t=0.5 and 0.95, 290k and 520k after). Cost, a static preserve-3d world of 300 cards over 300 frames, three runs each back to back, the raea before this against this one: 9.27-9.87 fps before, 9.38-9.63 after (no change past noise).
(closes #19)
2026-11-07 16:28:57 -08:00
shinyobjectz 7ca949df87 FC0a: ui/scroll_and_overflow/overflow_transform passes (SSIM 0.9954): UiTransform (Val2 translation, Rot2 rotation clockwise, scale, about the node's centre after layout) as CSS's transform; BoxShadow as CSS's box-shadow, its blur Bevy's Gaussian deviation so CSS's is twice it (a spread or a percent is refused until Bevy's width-ratio spread is drawn); and bevy_color's Luminance darker and lighter on Srgba and LinearRgba. Each checked by conformance and a mutant; in the port, no shadow, reversed turns and no scale fail, and a pixel probe of the shadow's strip is closest at Bevy's offset and blur 2026-11-07 16:27:48 -08:00
shinyobjectz 1acea1b83e FC0a: ui/layout/size_constraints passes (SSIM 0.9915): its radio buttons are bevy_ui_widgets' headless RadioButton, so they're their Nodes 2026-11-07 16:23:23 -08:00
shinyobjectz 9e3f99ff54 FC0a: ui/ui_scaling (SSIM 0.9999; UiScale holds at 1 until an arrow key) and ui/layout/anchor_layout (0.9974; an absolute label's auto margins leave it at its static position, in Bevy as in CSS) pass 2026-11-07 16:23:23 -08:00
shinyobjectz aef305429a #18: what an element paints at an offset of its own is placed in its own axes, so it turns with a rotated ancestor. blitz-paint added background-position, a background's tiles (image and gradient), box-shadow offsets (outer and inset), text-shadow offsets, the scroll offset, an inline SVG's and a custom widget's content-box origin after the element's transform (then_translate), in the page's axes; they now go before it (pre_translate), as an <img>'s already did. One image split across stacked divs by background-position stopped lining up under a -4deg parent, and an inset shadow's band came out uneven. The inset shadow's offset also takes the page's scale now, as the outer one's does. bench/rotated-paint/check.sh draws the same picture twice under -4deg (three background slices of one image and of one gradient, and a box shadow, against one div each and a box behind): 7,811 pixels differ by more than 10% on the raea before this, 37 after (the slices' antialiased seams); it passes at 200. Eight unrotated parity cases (background-image, background-shorthand, gradient-tiles, shadow, shadow-forms, overflow-scroll, repeating-gradient, conic-gradient) are pixel-identical before and after.
(closes #18)
2026-11-07 16:22:49 -08:00
shinyobjectz c7530ccbdd FC0a: ui/layout/grid passes (SSIM 0.995): a Node's visibility (Inherited, Hidden, Visible) as CSS's, and a wrapped bevy_text box as wide as its widest line with its trailing spaces (parley's full_width, as TextPipeline::compute_size measures it), which centres a justify_items Center paragraph where Bevy does 2026-11-07 16:17:57 -08:00
shinyobjectz 089acda03a #26: a 3D still or --at list steps only its frames and their neighbours, not the whole timeline up to the last. scene_frames takes the wanted frames: when they and the frame either side of each are under half the timeline, each run of them is stepped in the one runtime and every frame between holds the stepped scene before it (never drawn; frames are pure); the clipping check reads the wanted frames alone. #26's 360-frame scene on this Mac, three runs each back to back, the raea on PATH (main before this) against this build: --at 30,150,270,330 steps React in 990-1048 ms before, 54-60 ms after (5.6-6.3 s to 2.2-2.5 s in all); --frame 330 in 912-988 ms before, 28-29 ms after. Pixels are identical to before, and bench/at-3d/check.sh checks them against the same four frames frozen in a 4-frame composition (which steps every frame), failing on the old raea and passing on this one. A full render still steps every frame for the rows and again while it draws; that's left open.
(closes #26)
2026-11-07 16:15:56 -08:00
shinyobjectz bea844ba6c FC0a: ui/text/text_wrap_debug ported (every LineBreak under every JustifyContent, at its default scale) 2026-11-07 16:12:52 -08:00
shinyobjectz 8c96f67da8 FC0a: UiTargetCamera (its roots drawn by their own Camera2d: a layer stacked by the camera's order; the window's main texture cleared by the first camera only, as bevy_render's ViewTarget does); ui/ui_target_camera ported 2026-11-07 16:11:08 -08:00
shinyobjectz 1b023081a6 FC0a: Viewport, the UI camera's viewport (bevy_camera's Viewport: its roots laid out in that region of the window, clipped to it); ui/relative_cursor_position ported 2026-11-07 16:08:12 -08:00
shinyobjectzandJimGHTB12 e94514d243 Page: a <style> removed in the same mutation batch as its text no longer panics the render ("invalid SlotMap key used", on runs whose removals came in that order): Blitz's process_removed_subtree drops a removed node from the style, form and title nodes the batch flushes (vendor/blitz-dom, noted in vendor.toml), and raea's own re-parse of a changed <style> skips one that is gone (closes #24)
Co-authored-by: JimGHTB12 <[email protected]>
2026-11-07 16:06:02 -08:00
shinyobjectz e63a155739 raea-sys-page: draw.rs's premultiply WGSL test reads it from raea-sys-filters, where it moved in 318b1939a (the crate's tests didn't compile) 2026-11-07 16:03:32 -08:00
shinyobjectz be661a5f0b FC0a: bevy_ui's GhostNode (no box: its children its parent's, display: contents; at the top each a root); ui/layout/ghost_nodes ported, the parity host with Bevy's ghost_nodes feature 2026-11-07 16:00:26 -08:00
shinyobjectz c0d5f8306f bevy-ts's check.sh runs in Git's bash on Windows, for a Windows play --offscreen check: a play case's seconds are added with awk instead of bc, and RAEA_PLUGIN_BIN names the raea a build: plugins case runs (default the plugin build here; a release's raea has the plugin catalog). Its 13 play cases still pass on macOS. 2026-11-07 15:55:58 -08:00
shinyobjectz 5af23ab8d4 HTML: a page's canvas is white, as a browser paints it (CSS Backgrounds 3, the canvas background), instead of black, so a page that sets no background shows its default black text; a root's or body's background still covers the canvas (closes #30) 2026-11-07 15:51:44 -08:00
shinyobjectz abd167408a Page: a Vello draw that was skipped (a scene past its bump buffers: Vello's fine stage then writes nothing and reports no error, so a pooled layer showed its last frame's picture, or nothing) is found by a sentinel texel read back without a wait, and the frame read back next and those in flight are drawn again at Vello's own sizes, which stay on; a draw skipped at those too refuses the frame by its number. The check's cost on an ordinary 1080p page, five alternating 300-frame renders each: 257.7 fps without it, 253.3 with it. RAEA_VELLO_BUMP=full and RAEA_PAGE_DRAWN_CHECK=0 in docs/settings.md (closes #23) 2026-11-07 15:42:58 -08:00
shinyobjectz 5ada160314 A render's sweep keeps the work folder of a render that still runs, however long since its folder changed. The two-hour rule now removes only folders whose process isn't known to run (gone, unknown, or no PID in the name): a render running past two hours stops touching its folder's top level well before it ends, and the next render's sweep deleted it. This render's own folders count as running. pid.rs's test sweeps a folder of aged ones as it would run three hours on. (closes #31) 2026-11-07 15:40:18 -08:00
shinyobjectz 03eaef2b66 FC0a: bevy_ui's grid (grid_template_rows and _columns of RepeatedGridTracks, grid_auto_rows/_columns/_flow, grid_row and grid_column GridPlacements, as CSS grid), UiRect.AUTO, and bevy_text's FontSource on a Text (a file, a family by name, a generic family as Bevy's fontique resolves it: raea-sys-fonts registers fontique's own generics as "raea-bevy <generic>" before mapping the page's as Chrome's); ui/text/generic_font_families ported, the parity host with system_font_discovery 2026-11-07 15:37:20 -08:00
shinyobjectz b2d07d1165 A render's sweep of leftover work folders asks the system whether their render still runs (runtime/bundle pid.rs: kill(pid, 0) on Unix, OpenProcess and GetExitCodeProcess on Windows) instead of running the kill found on PATH. Under Git Bash on Windows that kill is MSYS's, which knows no Windows PID, so every live render looked dead and its folder was deleted mid-bundle when renders overlapped. A process the system won't answer for (another user's, a protected one) keeps its folder. pid.rs's tests cover a live and an ended process and the sweep itself. (closes #29) 2026-11-07 15:31:12 -08:00
shinyobjectz 934d9b0a72 HTML and React DOM: path, line, polyline, polygon, circle, ellipse and rect are SVGGeometryElements with getTotalLength and getPointAtLength, measured on the true outline (every path command, arcs included; within 0.03% of Chrome on straight edges and curves, and on circles and rounded corners the exact length, which Chrome flattens about 0.16% short), so a line-draw page's script no longer throws (closes #16) 2026-11-07 15:28:21 -08:00
shinyobjectz 08a4b7df02 openh264's MP4s say they are BT.709: both encoders (io/soft h264_encoder and GopEncoder) write the colour description in the stream's VUI (BT.709 primaries, transfer and matrix, limited range), as frames are converted and as the Mac's encoder tags them. Untagged, ffmpeg and other players read Windows and Linux renders as BT.601 and shifted reds and greens. io/soft's colour test reads the SPS each encoder writes. (closes #25) 2026-11-07 15:24:00 -08:00
shinyobjectz ee771c453c T6c: Rune layers in a Blitz page: what's under data-raea-renderer="rune" (sdk/rune's <RuneLayer>) is drawn by Rune on Bevy's device and shown in its slot
raea-runtime-dom's commits pass through a split (set_split), where raea-rune-layer's Router takes each layer's ops out of the batch in the JS's order, the slot standing for the layer page's root; a page that never makes a slot isn't routed. raea-rune-slots keeps each layer as a raea-rune-page Page in a raea-rune-bevy Tree (its new before_frame hook takes the routed ops), sized each frame to its slot's content box at the page's scale and shown there through ElementImages. Pointer input reaches it through the slot twin's picking events, a held press capturing the pointer as setPointerCapture does; its page's events reach the root's JS (deliver_to). raea-page-host adds it (RAEA_RUNE_LAYERS=0: all Blitz). Said, not dropped: a move between the page and a layer, and that a layer's elements aren't in the layout snapshot. vendor/rune-taffy: Rune and Blitz in one build need taffy's flexbox_balance arms in encode_wrap. Tests (engine/rune/slots/tests/slot.rs, through the page host): the slot's subtree is the layer's and not Blitz's, the layer is the slot's size and shown there, a press reaches the page's JS, and a press released off the layer still ends there; mutants without the split, the deliveries or the capture each fail one. The skill says how to use <RuneLayer> and what it doesn't do yet.
2026-11-07 15:20:38 -08:00
shinyobjectz 461c7491ac HTML: name in el.style is true only for CSS properties (Chrome's list, custom properties and webkit-prefixed names), not any camelCase name, so GSAP's tl.set(el, { textContent }) sets the element's text instead of writing a style (closes #17) 2026-11-07 15:20:08 -08:00
shinyobjectz b7c4052f30 HTML: a page whose script throws before any timeline registers fails to open, so raea render exits non-zero with the script's error and the unregistered composition, instead of writing its first frame held for the whole video; data-no-timeline on the root keeps a still page with a failing script rendering. A script's error message is printed beside its stack, which JavaScriptCore's leaves out (closes #15) 2026-11-07 15:19:17 -08:00
shinyobjectz 4e570ce401 FC0a: bevy_ui's BorderGradient (the bottom layer over the border box, a node's own gradients over it clipped to the padding box; none without a border; a translucent background gradient over one refused); ui/styling/gradients ported 2026-11-07 15:18:13 -08:00
shinyobjectz 1fdc431b72 Gates: taxonomy reads each Bevy crate at the version the lock pins (bevy_app and 20 others are 0.20.1), not a fixed 0.20.0 that only an older cache still holds 2026-11-07 15:14:23 -08:00
shinyobjectz 082aa7489f README: building from source needs CMake, and NASM on Linux; rustup takes the version rust-toolchain.toml pins (closes #14) 2026-11-07 15:10:56 -08:00
shinyobjectz 318b1939ab raea-page's premultiply pass (Premul, its WGSL and straight_target) moved to raea-sys-filters with the page's other fullscreen passes, raea-sys-page back under its 2000 lines 2026-11-07 15:08:26 -08:00
shinyobjectz d03eb9d7c9 FC0a: bevy_ui's gradients (BackgroundGradient: LinearGradient, RadialGradient, ConicGradient, ColorStops with hints, UiPosition, Bevy's radial shapes, Oklab by default) as CSS gradients, and a bevy_ui page blending in linear light as Bevy's UI does: vendor/vello_shaders' fine stage decodes every colour, ramp and texel from sRGB, blends, and encodes once (set_blend_linear, marked by data-raea-blend on each root Node); ui/styling/stacked_gradients ported 2026-11-07 15:05:29 -08:00
shinyobjectz 71a65438d8 FC0a: bevy_ui's stacking: every node a stacking context (ZIndex ranks among siblings above their parent), GlobalZIndex hoisted to the root's stacking context in Blitz, a cleared layered Canvas3D under the whole page; ui/layout/z_index ported (exact) 2026-11-07 14:49:48 -08:00
shinyobjectz 0730b9cd73 FC0a: InlineImage (a tinted picture in a Text's line), a Text's box its own measured block, as wide as its widest line once wrapped (bevy_text's laid-out size), Outline white by default; ui/text/inline_image and ui/window_fallthrough ported 2026-11-07 14:40:52 -08:00
shinyobjectz e3df1da170 FC0a: outline-offset and Bevy's outline corners in Blitz, corners resolved as Bevy's (CornerRadius, BorderRadius.px, clamped to the node), BorderColor per side, ImageNode in its own file; ui/styling/borders ported 2026-11-07 14:30:53 -08:00
shinyobjectz c33faa7e5e CI: only a pull request's runs cancel each other; every push to main runs to the end 2026-11-07 14:30:20 -08:00
shinyobjectz fa46f4ebb6 Gates: taxonomy fetches the locked crates first when Bevy's sources aren't unpacked yet (a fresh checkout), so it sees Bevy's names there too 2026-11-07 14:30:12 -08:00
shinyobjectz b4558ac472 FC0a: TextShadow and LetterSpacing on UI text, a centred or right-justified Text justified within its node's width; ui/widgets/button and ui/text/letter_spacing ported 2026-11-07 14:22:03 -08:00
shinyobjectz c0aec0a804 CI: the gates job installs ripgrep, which sdk-coverage reads the SDK with 2026-11-07 14:16:37 -08:00
shinyobjectz b952bb580b FC0a: a sliced UI picture takes an atlas cell (its rect in the layout, scaled to the sheet as Bevy's atlas UVs are); ui/images/ui_texture_atlas_slice ported 2026-11-07 14:14:59 -08:00
shinyobjectz 3a2b027488 FC0a: sliced and sampled UI pictures, UiScale, OverflowClipMargin, a 2D sampler and uv_transform, Text2d, and five more examples ported
UI. raea's Blitz draws CSS border-image (css-backgrounds-3: slice, width, outset, fill, and stretch, repeat, round or
space per axis), loading border-image-source as a third image layer beside backgrounds and masks. ImageNode's
image_mode { Sliced: TextureSlicer } is that border-image, and data-raea-bevy-slice gives Blitz bevy_ui's own rules: the
corners are the slices times min(the node over the picture, max_corner_scale), and Tile tiles a part from its start
every slice times stretch_value. A flipped sliced picture is mirrored on a layer behind its children. An ImageNode's
image can carry its own sampler ({ path, sampler: { filter } }). UiScale lays its roots out in a window 1/value of the
frame and scales it up. Node takes overflow_clip_margin, which Blitz honours for every clipping overflow as bevy_ui's
resolve_clip_rect does. The page bridge resolves url(..) in a style value (a background, a border-image) as it does
an img's src, which no CSS picture did before.

2D. Shape2D and Mesh2d's ColorMaterial take a texture with its own sampler (raea-sys-sampler) and a uv_transform
(Affine2). Text2d places a Text at its Transform, centred as Bevy's Anchor::CENTER. The shape2d row carries the sampler,
the uv_transform and the vertex colours as JSON in one loop, which keeps raea-runtime-scene under 2,000 lines.

Ported, each with a mutant that fails:
  ui/images/ui_texture_slice_flip_and_tile  1.0000 (stretched instead of tiled 0.7857, unflipped 0.8360)
  ui/images/ui_texture_slice                0.9990 (corner scale halved 0.9800)
  ui/scroll_and_overflow/overflow_clip_margin 0.9968 (without the margin 0.9890, tile 120)
  2d/mesh2d_repeated_texture                0.9912 (no uv_transform 0.9420, no sampler 0.9666, Text2d not centred 0.9789)
  ui/layout/flex_layout                     0.9909 (a Center row as FlexStart 0.9463)
58 of 61 ported pass; many_lights, many_foxes and transparency_3d still fail, as before.
2026-11-07 14:07:55 -08:00
shinyobjectz b78afb5676 Licences: the catalog regenerated against the public lock (five crates the engine no longer reaches move into it), and licenses.sh keeps LICENSES/Apache-2.0.txt, which NOTICE's credits cite 2026-11-07 14:07:24 -08:00
shinyobjectz 86af87a90d CI: the gates job installs sdk/raea's packages (bun, frozen lock) before sdk coverage, since node_modules aren't in git 2026-11-07 14:03:29 -08:00
shinyobjectz 8bd8e2c986 CI: one-version resolves each lock offline first and online when that fails (a fresh checkout has no registry cache), still --locked 2026-11-07 14:01:15 -08:00
shinyobjectz adb442d0f2 CI: the names gate reads its pattern as PCRE, so the Mac sees the same retired names as Linux (macOS git ignored \b and saw none); the 20 files left are recorded in names.allow, and the engine jobs install nasm for rav1d 2026-11-07 13:49:23 -08:00
shinyobjectz adedccddf0 Docs: the face test skips where the footage fixtures are absent (they are private now), and the release notes no longer mention the retired export script 2026-11-07 13:47:50 -08:00
1940 changed files with 441807 additions and 6862 deletions

No files matched your search

+9
View File
@@ -3,6 +3,15 @@
[target.aarch64-apple-darwin]
linker = "tools/link-jit.sh"
# every Windows executable's main thread gets 8 MB of stack, as on macOS and Linux (Windows' default is 1 MB). The
# desktop app's raea-page-host overflowed 1 MB inside a window callback (#112); engine/cli/build.rs did this for raea
# alone. A DLL's link ignores /STACK.
[target.x86_64-pc-windows-msvc]
rustflags = ["-C", "link-arg=/STACK:8388608"]
[target.aarch64-pc-windows-msvc]
rustflags = ["-C", "link-arg=/STACK:8388608"]
# no strip after linking: rustc's strip pass re-signs the binary and drops the entitlement (release has no debug info
# of its own; std's stays)
[profile.release]
+6 -3
View File
@@ -1,11 +1,14 @@
{
"name": "raea",
"owner": { "name": "Shane Murphy", "url": "https://raea.io" },
"owner": { "name": "raea", "url": "https://raea.io" },
"metadata": {
"description": "raea's plugin for Claude, from the skills/ folder of shinyobjectz/raea-skills: the raea skill and its hooks."
},
"plugins": [
{
"name": "raea",
"source": "./",
"description": "Make video, motion graphics, games and 3D with raea, the Render Anything Engine."
"source": { "source": "git-subdir", "url": "https://github.com/shinyobjectz/raea-skills.git", "path": "skills" },
"description": "Make video, motion graphics, games and 3D scenes with raea, the Render Anything Engine: the raea skill, and hooks that run raea's quick check on a composition after it's saved and show media in the raea app instead of the Mac's viewer."
}
]
}
-11
View File
@@ -1,11 +0,0 @@
{
"name": "raea",
"version": "0.1.0",
"description": "Make video, motion graphics, games and 3D with raea, the Render Anything Engine: write raea compositions, render them on the GPU, check the frames.",
"author": { "name": "Shane Murphy", "url": "https://raea.io" },
"homepage": "https://raea.io",
"repository": "https://github.com/shinyobjectz/raea",
"license": "FSL-1.1-ALv2",
"skills": ["./sdk/skills/"],
"keywords": ["video", "motion-graphics", "game-development", "rendering", "bevy", "react", "agent-skills"]
}
+21 -6
View File
@@ -15,7 +15,8 @@ permissions:
concurrency:
group: ci-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
# a pull request's newer push replaces its run; main's pushes each finish (on a busy main, cancelling meant none did)
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
env:
CARGO_TERM_COLOR: never
@@ -31,8 +32,13 @@ jobs:
with:
fetch-depth: 0
- name: gitleaks
# GitHub's release host answered 504 for minutes at a time on 11-08, through every retry; the same version's
# container image on ghcr.io is the fallback
run: |
curl -fsSL https://github.com/gitleaks/gitleaks/releases/download/v8.30.1/gitleaks_8.30.1_linux_x64.tar.gz | tar -xz -C /usr/local/bin gitleaks
v=8.30.1
curl -fsSL --retry 3 --retry-all-errors https://github.com/gitleaks/gitleaks/releases/download/v$v/gitleaks_${v}_linux_x64.tar.gz | tar -xz -C /usr/local/bin gitleaks \
|| { c=$(docker create ghcr.io/gitleaks/gitleaks:v$v) && sudo docker cp "$c:/usr/bin/gitleaks" /usr/local/bin/gitleaks && docker rm "$c"; }
gitleaks version
- name: public-guard
run: |
base=${{ github.event.pull_request.base.sha || github.event.before }}
@@ -54,7 +60,10 @@ jobs:
- name: tools
run: |
rustup show active-toolchain
cargo install --locked cargo-shear cargo-dupes
sudo apt-get update && sudo apt-get install -y ripgrep
# the versions L0 runs on the Mac, so a new release can't change the verdict (cargo-shear 1.14.1 calls
# engine/cli's feature-only ignores redundant, which 1.14.0 needs; both ran red on main 11-13)
cargo install --locked [email protected] [email protected]
- name: layers
run: bash tools/layers.sh
- name: names
@@ -71,6 +80,9 @@ jobs:
run: cargo shear --color never --deny-warnings
- name: tasks
run: bash tools/rask.sh check
- name: sdk packages
# sdk-coverage reads csstype and @types/react from them; node_modules aren't in git
run: cd sdk/raea && bun install --frozen-lockfile
- name: sdk coverage
run: bash tools/sdk-coverage --check
- name: sdk props
@@ -92,10 +104,10 @@ jobs:
lfs: false
- name: Linux libraries
if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install -y cmake ninja-build libasound2-dev libfontconfig1-dev libvulkan-dev libudev-dev
run: sudo apt-get update && sudo apt-get install -y cmake ninja-build libasound2-dev libfontconfig1-dev libvulkan-dev libudev-dev nasm
- name: macOS tools
if: runner.os == 'macOS'
run: brew install cmake ninja
run: brew install cmake ninja nasm
- uses: oven-sh/setup-bun@v2
with:
bun-version: 1.4.2
@@ -103,4 +115,7 @@ jobs:
- name: cargo check
run: cargo check --locked -p raea-cli --tests
- name: unit tests (the crates with no GPU or media device)
run: cargo test --locked -p raea-io-media -p raea-core-fonts -p raea-native
# debug info off: with it the test binaries of the app crates filled 27 GB of a runner's disk (#90)
env:
CARGO_PROFILE_TEST_DEBUG: "0"
run: cargo test --locked -p raea-io-media -p raea-core-fonts -p raea-native -p raea-core-brief -p raea-core-k -p raea-bundle -p raea-app-check -p raea-app-check-flash -p raea-io-ffmpeg -p raea-app-workspace -p raea-app-tools -p raea-app-targets
+279 -7
View File
@@ -1,8 +1,18 @@
# A release, built here where anyone can read how (public #6; docs/public-first.feature PF5): for a v* tag, macOS on
# Apple Silicon and Linux on x86_64 are built from the tag on GitHub's runners, packed by tools/release.sh, checked by
# tools/release-check.sh, attested (anyone can check a download with
# Apple Silicon, Linux on x86_64 and Windows on x86_64 are built from the tag on GitHub's runners, packed by
# tools/release.sh, checked by tools/release-check.sh, attested (anyone can check a download with
# `gh attestation verify raea-VERSION-macos-arm64.tar.gz -R shinyobjectz/raea`) and attached to the tag's release.
# Windows builds in windows.yml's release mode. The release's notes and whether it's a pre-release are set by hand.
# The skills gate reads the feed app, which is private, so it runs in a maintainer's checkout first
# (tools/skills.sh check), and the tag names the commit it passed on; tools/release.sh checks the gate's inputs haven't
# changed since (tools/release/skills-passed.sh):
# git tag -a v0.1.0 -m "raea 0.1.0" -m "skills-passed: <full sha>"
# A tag with a suffix (v0.1.0-rc1, v0.1.0-canary.3) is made a pre-release; a plain version (v0.1.0) is a full release,
# GitHub's latest. The release's notes are set by hand.
# A release whose code is a candidate's is promoted, not compiled again (tools/release/promoted-from.sh: the tag's
# "promoted-from: v0.1.0-rc5" line, which tools/agents/release-go.sh writes): each job takes the candidate's attested
# binaries for its platform (tools/release/promoted-bins.sh) and packs, checks, attests and attaches them as the
# release, in minutes instead of the three hours a cold build takes. Run by hand, dry_run packs and checks without
# attesting or attaching (the archives are the run's artifacts), for trying a promote before the real one.
name: release
on:
@@ -11,9 +21,21 @@ on:
workflow_dispatch:
inputs:
tag:
description: the tag to build (v0.1.0-canary.4)
description: the tag to build (v0.1.0)
required: true
type: string
skills_passed:
description: the full SHA where tools/skills.sh check passed with the feed app (else the tag's skills-passed line)
default: ""
type: string
promote_from:
description: a candidate tag (v0.1.0-rc5) whose binaries this release is, else the tag's promoted-from line; none builds from source
default: ""
type: string
dry_run:
description: pack and check only; nothing attested or attached (the archives are this run's artifacts)
default: false
type: boolean
permissions:
contents: write
@@ -34,9 +56,10 @@ jobs:
- os: macos-15
lib: libraea_bundle.dylib
extra: raea-perceive
# raea-perceive (`raea song`'s map) builds off Apple since #43
- os: ubuntu-24.04
lib: libraea_bundle.so
extra: ""
extra: raea-perceive
runs-on: ${{ matrix.os }}
# a cold thin-LTO build of raea-cli with the plugin catalog is the long part; GitHub's own limit is 6 hours
timeout-minutes: 340
@@ -46,9 +69,13 @@ jobs:
ref: ${{ env.TAG }}
submodules: true
lfs: false
- name: Promoted from a candidate, or built (tools/release/promoted-from.sh)
env:
GH_TOKEN: ${{ github.token }}
run: bash tools/release/promoted-from.sh "$TAG" "${{ inputs.promote_from }}"
- name: Linux libraries
if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install -y cmake ninja-build libasound2-dev libfontconfig1-dev libvulkan-dev libudev-dev mesa-vulkan-drivers xvfb
run: sudo apt-get update && sudo apt-get install -y cmake ninja-build nasm libxkbcommon-dev libxkbcommon-x11-dev libasound2-dev libfontconfig1-dev libvulkan-dev libudev-dev mesa-vulkan-drivers xvfb
- name: macOS tools
if: runner.os == 'macOS'
run: brew install cmake ninja
@@ -65,7 +92,20 @@ jobs:
curl -fsSL "$url" -o "$HOME/.local/share/raea-models/$path"
echo "$sha $HOME/.local/share/raea-models/$path" | shasum -a 256 -c -
done < tools/release/models.tsv
# rc3's build left 576 MB of macos-15's 320 GB free, and rc4's dSYMs (#88) ran it out linking raea-page-host
# (ld: write() failed, errno=28): the image's other Xcodes and the Android and .NET SDKs go first
- name: Room for the build
if: runner.os == 'macOS' && env.RAEA_PROMOTED_FROM == ''
run: |
df -h . | tail -1
keep=$(cd "$(xcode-select -p)/../.." && pwd -P)
for x in /Applications/Xcode*.app; do [ -L "$x" ] || [ "$(cd "$x" && pwd -P)" = "$keep" ] || sudo rm -rf "$x" & done
sudo rm -rf "$HOME/Library/Android" "$HOME/.dotnet" /usr/local/share/dotnet &
wait
echo "kept $keep"
df -h . | tail -1
- name: Build
if: env.RAEA_PROMOTED_FROM == ''
run: |
feat=$(bash tools/bevy-plugins.sh features sdk/raea/bench/bevy-plugins)
cargo build --profile dist --locked -p raea-cli --bin raea --no-default-features --features "$feat"
@@ -75,17 +115,249 @@ jobs:
mkdir ship
cp target/dist/raea target/dist/${{ matrix.lib }} target/dist/raea-rune-host target/dist/raea-page-host ship/
if [ -n "${{ matrix.extra }}" ]; then cp target/dist/${{ matrix.extra }} ship/; fi
# the Mac's dSYMs (tools/link-jit.sh made them as it stripped each binary, #88); release.sh keeps them
if [ -d target/dist/symbols ]; then cp -R target/dist/symbols ship/; fi
- name: The candidate's binaries (tools/release/promoted-bins.sh)
if: env.RAEA_PROMOTED_FROM != ''
env:
GH_TOKEN: ${{ github.token }}
run: bash tools/release/promoted-bins.sh "$RAEA_PROMOTED_FROM" ship
# the packing and its checks need only ship/, and macos-15's disk ran out packing rc1 with target/ kept
- name: Free the build's disk
run: |
df -h . | tail -1
rm -rf target
df -h . | tail -1
- name: Where the skills gate passed
run: bash tools/release/skills-passed.sh "$TAG" "${{ inputs.skills_passed }}"
- name: Pack and check (tools/release.sh)
env:
RAEA_CHECK_DIR: ${{ runner.temp }}/release-check
run: |
v=${TAG#v}
if [ "$RUNNER_OS" = Linux ]; then xvfb-run -a -s "-screen 0 1280x1024x24" bash tools/release.sh "$v" ship HEAD
else bash tools/release.sh "$v" ship HEAD; fi
# a failed check's own files (the app check's frames, every step's log), not the unpacked release
- uses: actions/upload-artifact@v4
if: failure()
with:
name: release-check-${{ runner.os }}
path: |
${{ runner.temp }}/release-check/app
${{ runner.temp }}/release-check/**/*.log
retention-days: 7
if-no-files-found: ignore
# the stripped binaries' symbols (#88), for symbolicating a crash report from this release; never published
- uses: actions/upload-artifact@v4
with:
name: symbols-${{ runner.os }}
path: dist/raea-*-symbols
retention-days: 90
if-no-files-found: warn
- uses: actions/attest-build-provenance@v2
if: ${{ !inputs.dry_run }}
with:
subject-path: dist/raea-*.tar.gz
- name: Attach to the release
if: ${{ !inputs.dry_run }}
env:
GH_TOKEN: ${{ github.token }}
run: |
gh release view "$TAG" >/dev/null 2>&1 || gh release create "$TAG" --prerelease --title "raea ${TAG#v}" --notes "Built by .github/workflows/release.yml; notes follow."
gh release view "$TAG" >/dev/null 2>&1 || gh release create "$TAG" ${{ contains(env.TAG, '-') && '--prerelease' || '' }} --title "raea ${TAG#v}" --notes "Built by .github/workflows/release.yml; notes follow."
gh release upload "$TAG" dist/raea-*.tar.gz dist/raea-*.tar.gz.sha256 --clobber
- uses: actions/upload-artifact@v4
if: ${{ inputs.dry_run }}
with:
name: dry-run-${{ runner.os }}
path: dist/raea-*.tar.gz*
retention-days: 3
compression-level: 0
# Windows in Git's bash on GitHub's runner, with the Visual Studio Build Tools in its image (their image terms; we
# accept no licence and download no Microsoft files). The C runtime is the DLL one (the VC++ redistributable): ort's
# prebuilt ONNX Runtime is built against it, so crt-static doesn't link (LNK2019 on __imp_ symbols, 10-29).
windows:
runs-on: windows-latest
timeout-minutes: 350
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@v4
with:
ref: ${{ env.TAG }}
submodules: true
lfs: false
- name: Promoted from a candidate, or built (tools/release/promoted-from.sh)
env:
GH_TOKEN: ${{ github.token }}
run: bash tools/release/promoted-from.sh "$TAG" "${{ inputs.promote_from }}"
- name: Toolchain (rust-toolchain.toml's pin)
if: env.RAEA_PROMOTED_FROM == ''
run: rustup show active-toolchain || rustup toolchain install
# jq for Windows ends -r lines with CRLF, so tools/bevy-plugins.sh read "ahoy\r" and lost its Bevy 0.20 block
# (feature `ahoy` not found, 11-04); -b writes LF
- name: jq that writes LF
run: |
mkdir -p "$RUNNER_TEMP/jq"
printf '#!/bin/bash\nexec "%s" -b "$@"\n' "$(command -v jq)" > "$RUNNER_TEMP/jq/jq"
chmod +x "$RUNNER_TEMP/jq/jq"
echo "$RUNNER_TEMP/jq" >> "$GITHUB_PATH"
- uses: oven-sh/setup-bun@v2
with:
bun-version: 1.4.2
- name: The runtime's packages
run: for d in sdk/react/js sdk/react/tw; do (cd "$d" && bun install --frozen-lockfile); done
# `raea song`'s beat model, which release.sh packs (into Git bash's ~/.local/share/raea-models, as on the others)
- name: Models (pinned by URL and sha256 in tools/release/models.tsv)
run: |
while IFS=$'\t' read -r path url sha; do
case $path in ''|'#'*) continue ;; esac
mkdir -p "$HOME/.local/share/raea-models/$(dirname "$path")"
curl -fsSL "$url" -o "$HOME/.local/share/raea-models/$path"
echo "$sha $HOME/.local/share/raea-models/$path" | sha256sum -c -
done < <(tr -d '\r' < tools/release/models.tsv)
# the app targets' hosts a cargo call each: with raea-cli's crates in one call taffy's features unify and
# rune-taffy doesn't build; raea-perceive (`raea song`'s map, #43) a call of its own too
- name: Build
if: env.RAEA_PROMOTED_FROM == ''
run: |
feat=$(bash tools/bevy-plugins.sh features sdk/raea/bench/bevy-plugins)
cargo build --profile dist --locked -p raea-cli --bin raea --no-default-features --features "$feat"
cargo build --profile dist --locked -p raea-rune-host
cargo build --profile dist --locked -p raea-page-host --features window
cargo build --profile dist --locked -p raea-perceive
- name: The candidate's binaries (tools/release/promoted-bins.sh)
if: env.RAEA_PROMOTED_FROM != ''
env:
GH_TOKEN: ${{ github.token }}
run: bash tools/release/promoted-bins.sh "$RAEA_PROMOTED_FROM" target/dist
# which DLLs raea needs from the machine (the CRT's come from the VC++ redistributable)
- name: What raea.exe imports
run: |
{ echo '### what raea.exe, raea_bundle.dll and raea-perceive.exe import'; echo '```'
dumpbin=$(ls "/c/Program Files/Microsoft Visual Studio"/*/*/VC/Tools/MSVC/*/bin/HostX64/x64/dumpbin.exe | head -1)
"$dumpbin" -nologo -dependents target/dist/raea.exe target/dist/raea_bundle.dll target/dist/raea-perceive.exe | grep -iE '\.dll$|Dump of' | sed 's/^ *//'
echo '```'; } | tee -a "$GITHUB_STEP_SUMMARY" || true
# release.sh's checks render on Mesa's lavapipe (software Vulkan, MIT; on the runner only, never in the zip): the
# runner has no GPU, and WARP, Windows' own software DX12, crashes compiling one of Bevy's compute shaders there
# (d3d10warp ComputeShaderTransformer::ConstructLoadStoreSets, an access violation; 11-04)
- name: Software Vulkan
run: bash tools/release/lavapipe.sh
- name: Where the skills gate passed
run: bash tools/release/skills-passed.sh "$TAG" "${{ inputs.skills_passed }}"
- name: Pack and check (tools/release.sh)
env:
RAEA_CHECK_DIR: ${{ runner.temp }}/release-check
run: bash tools/release.sh "${TAG#v}" target/dist HEAD
# live play on Windows (PT20 left it unproven): bevy-ts's play cases, `play --offscreen` with an input script and
# a snapshot's pixels probed, run by the raea just built; check.sh reads the pixels with ImageMagick, which the
# image has only sometimes, and choco's PATH change doesn't reach the next step, so its folder goes on GITHUB_PATH
- name: ImageMagick (check.sh reads a snapshot's pixels)
shell: pwsh
run: |
if (-not (Get-Command magick -ErrorAction SilentlyContinue)) { choco install imagemagick -y --no-progress | Out-Null }
$im = Get-ChildItem "C:\Program Files" -Directory -Filter "ImageMagick-*" | Select-Object -First 1
if ($im) { Add-Content $env:GITHUB_PATH $im.FullName }
# without the loader's debug lines (lavapipe.sh sets them for the driver's registration), and a failing case's
# log tail in the job's log, since the runner and its logs go when the job ends
# each case is bounded by check.sh (RAEA_CASE_SECONDS: a fresh runner's first play opens in about 100s, the next in
# seconds); the step's own bound is for the rest
- name: Live play (bevy-ts's play cases)
timeout-minutes: 75
env:
VK_LOADER_DEBUG: ""
RAEA_CASE_SECONDS: "300"
# the zip's raea, unpacked, with RAEA_NO_TREE=1 and the cases copied out of the checkout, as a user's machine has
# them: target/dist's raea has no share/raea beside it, so its home is this checkout, 2 h of build in target/
# included, and there its 3D cases ran past 300 s each (rc1) where the unpacked zip's open in under 70 s
run: |
u="$RUNNER_TEMP/play-zip"; c="$RUNNER_TEMP/play-cases"
mkdir -p "$u" && 7z x -y -o"$u" dist/raea-*.zip > /dev/null && cp -r sdk/raea/bench/bevy-ts/cases "$c"
b="$u/raea/bin/raea.exe"
out="${TMPDIR:-/tmp}/raea-bevy-ts"
s=0; RAEA_NO_TREE=1 RAEA_BIN="$b" RAEA_PLUGIN_BIN="$b" bash sdk/raea/bench/bevy-ts/check.sh $(grep -l '^// play:' "$c"/*.tsx) 2>&1 | tee "$RUNNER_TEMP/play.txt" || s=$?
cat "$RUNNER_TEMP/play.txt" >> "$GITHUB_STEP_SUMMARY"
for n in $(sed -n 's/^\([^ ]*\) (.*): OPEN.*/\1/p' "$RUNNER_TEMP/play.txt"); do echo "--- $n"; { grep -v "known driver" "$out/$n.log" || echo "(its log is empty)"; } | tail -25; done
exit $s
- uses: actions/attest-build-provenance@v2
if: ${{ !inputs.dry_run }}
with:
subject-path: dist/raea-*.zip
# kept even when its check fails, with the check's own files, so a failure can be looked into on a fresh runner
# without a rebuild; only windows-verify attaches it to the release
- uses: actions/upload-artifact@v4
if: always()
with:
name: windows-zip
path: dist/raea-*.zip*
retention-days: 7
compression-level: 0
if-no-files-found: ignore
- uses: actions/upload-artifact@v4
if: failure()
with:
name: release-check-Windows
path: ${{ runner.temp }}/release-check/app
retention-days: 7
if-no-files-found: ignore
# the zip alone, on a runner that never had raea's sources, as a user's machine gets it; it also tests the
# published installer (raea.io/install.ps1), pointed at the zip by RAEA_DOWNLOAD. Only a zip that passes is attached.
windows-verify:
needs: windows
runs-on: windows-latest
timeout-minutes: 20
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@v4
with:
ref: ${{ env.TAG }}
lfs: false
sparse-checkout: |
tools/release-check.sh
tools/release/lavapipe.sh
sparse-checkout-cone-mode: false
path: check
- uses: actions/download-artifact@v4
with:
name: windows-zip
path: ${{ runner.temp }}/zip
- name: Software Vulkan
run: bash check/tools/release/lavapipe.sh
- name: The zip, unpacked and checked
run: |
set -e
v=${TAG#v}
cp check/tools/release-check.sh "$RUNNER_TEMP/"
rm -rf check
cd "$RUNNER_TEMP/zip"
sha256sum -c "raea-$v-windows-x86_64.zip.sha256"
bash "$RUNNER_TEMP/release-check.sh" "$PWD/raea-$v-windows-x86_64.zip" | tee -a "$GITHUB_STEP_SUMMARY"
- name: install.ps1, then a render from PATH
shell: pwsh
run: |
$v = $env:TAG.Substring(1)
$rel = Join-Path $env:RUNNER_TEMP "rel"
New-Item -ItemType Directory -Force -Path (Join-Path $rel "v$v") | Out-Null
Copy-Item (Join-Path $env:RUNNER_TEMP "zip/raea-$v-windows-x86_64.zip*") (Join-Path $rel "v$v")
$env:RAEA_DOWNLOAD = $rel; $env:RAEA_VERSION = $v; $env:RAEA_NO_SKILLS = "1"
& ([scriptblock]::Create((Invoke-RestMethod https://raea.io/install.ps1)))
$p = Join-Path $env:RUNNER_TEMP "user"; New-Item -ItemType Directory -Force -Path $p | Out-Null; Set-Location $p
$env:RAEA_NO_TREE = "1"; $env:RAEA_API = "http://127.0.0.1:9"
raea init
if ($LASTEXITCODE) { throw "raea init failed" }
Set-Content hello.tsx 'import { AbsoluteFill, Composition, registerRoot } from "raea"; registerRoot(() => <Composition id="hello" component={() => <AbsoluteFill style={{ background: "#123", color: "#fff", fontSize: 90, justifyContent: "center", alignItems: "center" }}>raea on Windows</AbsoluteFill>} width={640} height={360} fps={30} durationInFrames={30} />);'
$h = Join-Path $env:RUNNER_TEMP "hello"; New-Item -ItemType Directory -Force -Path $h | Out-Null; Move-Item hello.tsx $h; Set-Location $h
raea render hello.tsx --frame 1 -o hello.png
if ($LASTEXITCODE -or -not (Test-Path hello.png)) { throw "raea render failed" }
Get-Item hello.png | Format-List Name, Length
- name: Attach to the release
if: ${{ !inputs.dry_run }}
env:
GH_TOKEN: ${{ github.token }}
run: |
gh release view "$TAG" -R "$GITHUB_REPOSITORY" >/dev/null 2>&1 || gh release create "$TAG" -R "$GITHUB_REPOSITORY" ${{ contains(env.TAG, '-') && '--prerelease' || '' }} --title "raea ${TAG#v}" --notes "Built by .github/workflows/release.yml; notes follow."
gh release upload "$TAG" -R "$GITHUB_REPOSITORY" "$RUNNER_TEMP"/zip/raea-*.zip "$RUNNER_TEMP"/zip/raea-*.zip.sha256 --clobber
+3
View File
@@ -1,3 +1,6 @@
[submodule "tools/rask"]
path = tools/rask
url = https://github.com/shinyobjectz/rask.git
[submodule "skills"]
path = skills
url = https://github.com/shinyobjectz/raea-skills.git
Generated
+634 -21
View File
File diff suppressed because it is too large. Load diff
+56
View File
@@ -5,6 +5,7 @@ resolver = "2"
members = [
"core/animate",
"core/brief",
"core/facts",
"core/ease",
"core/fonts",
"core/program",
@@ -23,6 +24,8 @@ members = [
"systems/animate",
"systems/framepass",
"systems/compute",
"systems/phase",
"systems/shader/wgsl",
"systems/sampler",
"systems/parity",
"systems/shader",
@@ -48,6 +51,8 @@ members = [
"engine/rune/style",
"engine/rune/bevy",
"engine/rune/js",
"engine/rune/layer",
"engine/rune/slots",
"engine/page/stage",
"engine/page/window",
"io/trace",
@@ -63,6 +68,8 @@ members = [
"io/ffmpeg",
"io/apple",
"io/apple-coding",
"io/alpha",
"io/capcut",
"io/shell",
"gpu/device",
"core/k",
@@ -71,9 +78,14 @@ members = [
"systems/tone",
"systems/mix",
"systems/ml",
"systems/mlx",
"systems/speech",
"systems/layout",
"systems/vision",
"systems/columns",
"systems/fingerprint",
"systems/fingerprint-use",
"systems/fingerprint-things",
"systems/song",
"systems/perceive",
"systems/footage",
@@ -81,6 +93,7 @@ members = [
"systems/bake",
"systems/contact",
"systems/light-meter",
"systems/measure",
"systems/canvas",
"systems/tweak",
"systems/filters",
@@ -88,7 +101,9 @@ members = [
"systems/procmat",
"systems/page",
"systems/page-net",
"systems/page-ops",
"systems/frame",
"systems/layers",
"systems/splat",
"systems/sprite",
"systems/rt",
@@ -103,6 +118,7 @@ members = [
"systems/look",
"systems/compose",
"systems/material",
"systems/mesh",
"systems/post",
"systems/fog",
"systems/fog-half",
@@ -112,8 +128,10 @@ members = [
"systems/image",
"runtime/twins",
"runtime/dom",
"runtime/dom/media",
"runtime/edit",
"runtime/view",
"runtime/world",
"runtime/encode",
"runtime/plugins",
"runtime/input",
@@ -123,31 +141,47 @@ members = [
"engine/seedling",
"engine/web",
"runtime/react",
"runtime/track",
"runtime/pagestore",
"runtime/cssurls",
"bench/bridge",
"bench/bevy-parity",
"bench/bridge/swatch",
"bench/rerender/ios",
"core/alloc",
"runtime/bake",
"runtime/bundle",
"runtime/bundle/lib",
"engine/shape-web",
"runtime/calls",
"runtime/shots",
"runtime/canvas",
"runtime/export",
"runtime/live",
"runtime/page",
"runtime/sound",
"runtime/look",
"runtime/scene",
"runtime/scene2d",
"runtime/shared",
"apps/check",
"apps/check/flash",
"apps/direction",
"apps/notes",
"apps/fingerprint",
"apps/sound",
"apps/workspace",
"apps/workspace/registry",
"apps/ci",
"apps/tools",
"apps/engines",
"apps/interchange",
"apps/judge",
"apps/solid",
"apps/media",
"apps/targets",
"apps/game",
"apps/capcut",
"apps/play",
"tools/sdk-props",
]
@@ -256,12 +290,18 @@ split-debuginfo = "packed"
[patch.crates-io]
# the MP4 muxer, vendored
muxide = { path = "vendor/muxide" }
# usvg 0.48.1 spacing a chunk's last letter as Chrome does (changes marked "raea:", docs/layout-reads.feature LR10)
usvg = { path = "vendor/usvg" }
# bevy_seedling 0.8.0 without its cpal 0.18 paths, ported to Bevy 0.20 (changes marked "raea:")
bevy_seedling = { path = "vendor/bevy_seedling" }
# bevy_text 0.20.0 on parley 0.12, so one parley builds (changes marked "raea:", docs/bevy-upgrade.md)
bevy_text = { path = "vendor/bevy_text" }
# bevy_ui 0.20.0 on Taffy 0.15, Blitz's, so one Taffy builds (changes marked "raea:", docs/bevy-upgrade.md)
bevy_ui = { path = "vendor/bevy_ui" }
# bevy_solari 0.20.0 with alpha-tested and alpha-blended materials traced by their alpha, StandardMaterial's
# uv_transform, and a panorama's sun sampled as a light rather than found by reflection rays alone (changes marked
# "raea:", docs/raytracing.feature RT6). Back to upstream once Solari has these.
bevy_solari = { path = "vendor/bevy_solari" }
# bevy_ui_widgets 0.20.0 on parley 0.12, Blitz's (docs/blitz-bevy.feature B0a)
bevy_ui_widgets = { path = "vendor/bevy_ui_widgets" }
# blitz-paint 0.3.0-beta.4 with angled gradients in tiles laid out around the tile, many-tile gradient layers drawn
@@ -298,9 +338,25 @@ anyrender_svg = { path = "vendor/anyrender_svg" }
# BumpAllocationSizes; changes marked "raea:"): raea-page sizes them for its pages, not Vello's 165 MiB of defaults.
# Back to upstream once #1861 lands.
vello_encoding = { path = "vendor/vello_encoding" }
# vello_shaders 0.11.0 with linear-light blending in the fine stage, switched by vello_encoding's set_blend_linear
# (changes marked "raea:"): raea-page blends a bevy_ui page as Bevy does (bevy_ui on Blitz). No upstream
# equivalent yet (linebender/vello blends the encoded values).
vello_shaders = { path = "vendor/vello_shaders" }
# Firewheel 0.12 on Bevy 0.20: bevy_reflect 0.20 and a glam-33 feature (BillyDM/Firewheel#144; changes marked "raea:")
firewheel = { path = "vendor/firewheel" }
firewheel-core = { path = "vendor/firewheel-core" }
firewheel-graph = { path = "vendor/firewheel-graph" }
firewheel-macros = { path = "vendor/firewheel-macros" }
firewheel-nodes = { path = "vendor/firewheel-nodes" }
[patch."https://github.com/anomalyco/rune"]
# rune-taffy at the rev above with encode_wrap covering taffy's flexbox_balance modes, which Blitz turns on: a crate
# with Rune and Blitz in one build (raea-rune-slots) doesn't compile without it (changes marked "raea:"). Back to
# upstream once Rune has it.
rune-taffy = { path = "vendor/rune-taffy" }
[patch."https://github.com/djeedai/bevy_hanabi"]
# bevy_hanabi at engine/bevy-plugins' rev with frame-pure particles: a new particle seeded by its spawn index, not the
# slot it recycles, and blended effects drawn back to front (changes marked "raea:", raea #52). Only the plugin build
# compiles it. Back to upstream once hanabi has a deterministic mode.
bevy_hanabi = { path = "vendor/bevy_hanabi" }
@@ -174,3 +174,28 @@ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2020 Andrew Straw
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@@ -1,4 +1,4 @@
Copyright (c) 2018 Raph Levien
Copyright (c) 2020 Andrew D. Straw
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2020 Andrew Straw
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@@ -1,4 +1,4 @@
Copyright 2020 the Vello Authors
Copyright (c) 2020 Andrew D. Straw
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
-20
View File
@@ -1,20 +0,0 @@
meshopt 0.6.2 ships no licence file of its own. Its Cargo.toml declares MIT OR Apache-2.0, by Graham Wihlidal <[email protected]>.
---- Apache-2.0: the text is LICENSES/texts/Apache-2.0.txt ----
---- MIT ----
Copyright (c) Graham Wihlidal <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+12
View File
@@ -0,0 +1,12 @@
Copyrights in the Rand project are retained by their contributors. No
copyright assignment is required to contribute to the Rand project.
For full authorship information, see the version control history.
Except as otherwise noted (below and/or in individual files), Rand is
licensed under the Apache License, Version 2.0 <LICENSE-APACHE> or
<http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
<LICENSE-MIT> or <http://opensource.org/licenses/MIT>, at your option.
The Rand project includes code from the Rust project
published under these same licenses.
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
https://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+26
View File
@@ -0,0 +1,26 @@
Copyright 2018 Developers of the Rand project
Copyright (c) 2014 The Rust Project Developers
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
@@ -1,11 +1,13 @@
Copyright (c) 2014-2020 Optimal Computing (NZ) Ltd
The MIT License (MIT)
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
Copyright (c) 2014 Mathijs van de Nes
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
@@ -14,6 +16,6 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+4 -8
View File
@@ -92,7 +92,6 @@ LICENSES/<crate>-<version>/.
bevy_flipbook 0.1.0: MIT
bevy_ghx_grid 0.10.0: MIT OR Apache-2.0
bevy_ghx_proc_gen 0.10.0: MIT OR Apache-2.0
bevy_hanabi 0.20.0-dev: MIT OR Apache-2.0
bevy_heavy 0.6.0: MIT OR Apache-2.0
bevy_http_client 0.12.0: MIT OR Apache-2.0
bevy_hui 0.8.0: MIT OR Apache-2.0
@@ -193,13 +192,11 @@ LICENSES/<crate>-<version>/.
fast_image_resize 6.1.0: MIT OR Apache-2.0
fastbloom 0.17.0: MIT OR Apache-2.0
fastnoise-lite 1.1.1: MIT
fearless_simd 0.4.1: Apache-2.0 OR MIT
fid-rs 0.2.0: MIT OR Apache-2.0
file-id 0.2.3: MIT OR Apache-2.0
fixed 1.31.0: MIT/Apache-2.0
flagset 0.4.7: Apache-2.0
float_next_after 2.0.0: MIT
float-cmp 0.10.0: MIT
float-ord 0.3.2: MIT / Apache-2.0
fs_extra 1.3.0: MIT
fsevent-sys 4.1.0: MIT
@@ -212,7 +209,6 @@ LICENSES/<crate>-<version>/.
ghx_proc_gen 0.10.0: MIT OR Apache-2.0
glam_matrix_extras 0.4.0: MIT OR Apache-2.0
glam 0.19.0: MIT OR Apache-2.0
glifo 0.2.0: Apache-2.0 OR MIT
gloo-timers 0.3.0: MIT OR Apache-2.0
governor 0.10.4: MIT
hash32 0.2.1: MIT OR Apache-2.0
@@ -224,6 +220,8 @@ LICENSES/<crate>-<version>/.
i_overlay 4.5.2: MIT OR Apache-2.0
i_shape 1.18.0: MIT
i_tree 0.18.0: MIT
iana-time-zone-haiku 0.1.2: MIT OR Apache-2.0
iana-time-zone 0.1.65: MIT OR Apache-2.0
ilattice 0.1.0: MIT OR Apache-2.0
imagesize 0.13.0: MIT
inout 0.1.4: MIT OR Apache-2.0
@@ -275,7 +273,6 @@ LICENSES/<crate>-<version>/.
louds-rs 0.7.0: MIT OR Apache-2.0
lz4_flex 0.13.1: MIT
memoffset 0.9.1: MIT
meshopt 0.6.2: MIT OR Apache-2.0
metis-sys 0.3.2: MIT OR Apache-2.0
metis 0.2.2: MIT OR Apache-2.0
metrics-util 0.20.4: MIT
@@ -332,6 +329,7 @@ LICENSES/<crate>-<version>/.
quick-xml 0.31.0: MIT
quick-xml 0.38.4: MIT
radix_trie 0.2.1: MIT
rand_chacha 0.3.1: MIT OR Apache-2.0
rand_xorshift 0.3.0: MIT OR Apache-2.0
rand_xoshiro 0.7.0: MIT OR Apache-2.0
rapidhash 4.5.1: MIT OR Apache-2.0
@@ -348,7 +346,6 @@ LICENSES/<crate>-<version>/.
rune-kit 0.0.1: MIT
rune-motion 0.1.0: MIT
rune-staging 0.0.1: MIT
rune-taffy 0.0.1: MIT
rune 0.0.1: MIT
rusticata-macros 4.1.0: MIT/Apache-2.0
rustls-native-certs 0.8.5: Apache-2.0 OR ISC OR MIT
@@ -367,6 +364,7 @@ LICENSES/<crate>-<version>/.
sif-itree 0.4.1: MIT OR Apache-2.0
sketches-ddsketch 0.3.1: Apache-2.0
smart-default 0.7.1: MIT
spin 0.9.9: MIT
spinning_top 0.3.0: MIT/Apache-2.0
spki 0.8.1: Apache-2.0 OR MIT
steamworks-sys 0.13.0: MIT / Apache-2.0
@@ -399,8 +397,6 @@ LICENSES/<crate>-<version>/.
unsafe-libyaml 0.2.11: MIT
urlencoding 2.1.3: MIT
usvg 0.45.1: Apache-2.0 OR MIT
vello_common 0.1.0: Apache-2.0 OR MIT
vello_cpu 0.1.0: Apache-2.0 OR MIT
vleue_navigator 0.17.0: MIT OR Apache-2.0
voracious_radix_sort 1.2.0: MIT
vox_bake 0.1.0: MIT
+20 -8
View File
@@ -24,7 +24,7 @@
<p align="center">
<img alt="licence FSL-1.1-ALv2" src="https://img.shields.io/badge/licence-FSL--1.1--ALv2-black">
<img alt="status canary" src="https://img.shields.io/badge/status-canary-black">
<img alt="latest release" src="https://img.shields.io/github/v/release/shinyobjectz/raea?label=release&color=black">
<img alt="macOS, Apple Silicon" src="https://img.shields.io/badge/macOS-Apple%20Silicon-black">
<img alt="Linux x86_64" src="https://img.shields.io/badge/Linux-x86__64-black">
<img alt="Windows x86_64" src="https://img.shields.io/badge/Windows-x86__64-black">
@@ -32,8 +32,14 @@
---
> **Canary.** raea changes daily. Releases run on macOS (Apple Silicon), Linux (x86_64) and, new and least tested,
> Windows (x86_64). Expect breaking changes, rough edges and gaps in the docs.
> **v0.1.1** is raea's first full release: the engine and, for the first time, the desktop app, on macOS (Apple
> Silicon), Linux (x86_64) and, newest and least tested, Windows (x86_64). raea is young: expect rough edges and gaps
> in the docs.
## The app
The raea app is where you make video and games with your AI. Download it from [raea.io](https://raea.io) for the Mac,
Windows or Linux. It tells you when a new version is out; on the Mac it updates itself.
## Install
@@ -94,16 +100,22 @@ floor (`raea check hello.mp4`). `raea init` starts a project, and `raea --help`
## Use it from your agent
- **Agent skills.** [`sdk/skills/raea`](sdk/skills/raea/SKILL.md) teaches an agent to write, render and check raea
compositions; [`sdk/skills/raea-bevy`](sdk/skills/raea-bevy) covers 3D and games. The installer adds both to
`~/.claude/skills`.
- **Claude Code plugin.** `/plugin marketplace add shinyobjectz/raea`, then `/plugin install raea@raea`.
- **Agent skills.** They live in [raea-skills](https://github.com/shinyobjectz/raea-skills), pinned here as
[`skills/`](skills): `raea` teaches an agent to write, render and check raea compositions, 3D and games
included. The installer adds it to `~/.claude/skills`, and `raea skills install --agent NAME` to other agents.
- **Claude plugin.** The raea skill and two hooks (raea's quick check after a composition is saved, and media shown in
the raea app). In Claude Code: `/plugin install raea --marketplace shinyobjectz/raea-skills`. It's the `skills/`
folder of raea-skills, and `/plugin marketplace add shinyobjectz/raea` installs the same one.
- **Craft guides.** `raea guide` prints the floor every edit is held to and the guides for pitches, explainers, stories,
games, motion, music and layout. `raea context PROJECT` says what to read before working on a project.
## Build from source
Requirements: [Rust](https://rustup.rs) (stable) and [bun](https://bun.sh). On macOS, Xcode's command-line tools; on Linux, the ALSA, fontconfig and Vulkan libraries.
Requirements: [Rust](https://rustup.rs) (rustup reads the pinned version from rust-toolchain.toml), [bun](https://bun.sh)
and CMake. On macOS, Xcode's command-line tools; on Linux, the ALSA, fontconfig, udev, xkbcommon (with its X11
part, which the app targets' windows also load at run time) and Vulkan libraries and NASM (Ubuntu: `cmake ninja-build
nasm libasound2-dev libfontconfig1-dev libudev-dev libvulkan-dev libxkbcommon-dev libxkbcommon-x11-dev`), as public CI
installs them.
```sh
git clone https://github.com/shinyobjectz/raea && cd raea
+4
View File
@@ -0,0 +1,4 @@
# Security
Report security problems privately through this repository's Security tab ("Report a vulnerability"), not in public
issues. Fixes go into the latest release and main.
+18
View File
@@ -0,0 +1,18 @@
[package]
name = "raea-app-capcut"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "`raea export capcut`: a composition as a CapCut draft ready in its timeline, its footage and sounds as clips of their files and what raea draws as transparent overlays (docs/capcut.feature)"
[dependencies]
raea-runtime-bundle = { path = "../../runtime/bundle" }
raea-io-capcut = { path = "../../io/capcut" }
raea-io-alpha = { path = "../../io/alpha" }
raea-io-media = { path = "../../io/media", default-features = false, features = ["soft-audio", "apple"] }
raea-io-home = { path = "../../io/home" }
# the renderer's own lookup of a staticFile path (/media/x), so the export finds the files the render drew
raea-core-scene = { path = "../../core/scene" }
serde_json = "1"
image = { version = "0.25", default-features = false, features = ["jpeg"] }
+292
View File
@@ -0,0 +1,292 @@
//! `raea export capcut EDIT.tsx` (docs/capcut.feature CC2): the composition as a CapCut draft ready in its timeline.
//! And `raea render ... -o OUT.mov --alpha` (CC1), the transparent movie its overlays are, for any editor.
//! Three renders of it: as it is, with its manifest (the reference render, and what shows when: each file's runs,
//! each sound clip); with its footage and the backgrounds holding it hidden, transparent (what raea draws over the
//! footage); and with only those backgrounds (what it draws under). The footage and sounds become clips of their own
//! files at their trims and gains; what raea draws becomes clips of transparent movies (raea-io-alpha), cut where the
//! drawing comes and goes, the one under the footage left out when it's black; raea-io-capcut writes the draft.
mod media;
pub mod plan;
#[cfg(test)]
mod tests;
use std::path::{Path, PathBuf};
use std::process::Command;
use raea_io_capcut::{Clip, Kind, Media, MediaKind, Place, Timeline, Track};
use raea_runtime_bundle::flag;
use serde_json::Value;
pub type R<T> = Result<T, String>;
pub const USAGE: &str = "raea export capcut EDIT.tsx [--composition ID] [-o DIR] [--name NAME] [--alpha-codec prores|hevc|rle|png] [--no-register] (the composition as a CapCut draft ready in its timeline: its footage and sounds as clips of their own files at their trims and gains, everything raea draws as transparent overlay clips above them; into CapCut's projects, entered in its project list while CapCut is closed, or a draft folder in DIR; the reference render and the overlay movie kept in out/capcut/NAME)";
/// `export capcut ...` (or what export takes), and `render ... -o OUT.mov --alpha` through `render`, the CLI's own;
/// None for anything else.
pub fn cli(args: &[String], render: impl Fn(&[String]) -> R<String>) -> Option<R<String>> {
match args.first().map(String::as_str) {
Some("export") => Some(match args.get(1).map(String::as_str) {
Some("capcut") => export(&args[2..]),
other => Err(format!("raea export takes where to export to{}: capcut\nusage: {USAGE}", other.map_or(String::new(), |o| format!(", not {o:?}")))),
}),
Some("render") => movie(args, render),
_ => None,
}
}
/// `render ... -o OUT.mov --alpha`: the frames as transparent PNGs, then one movie of them, the overlay an editor lays
/// over footage (raea-io-alpha, docs/capcut.feature CC1); None for any other render.
fn movie(args: &[String], render: impl Fn(&[String]) -> R<String>) -> Option<R<String>> {
let out = flag(args, "-o").filter(|o| args.iter().any(|a| a == "--alpha") && o.to_lowercase().ends_with(".mov"))?;
let quality = match flag(args, "--quality").map(|q| raea_io_media::parse_quality(&q)).transpose() {
Ok(q) => q.unwrap_or(0.9),
Err(e) => return Some(Err(e.to_string())),
};
Some(raea_io_alpha::render_movie(args, Path::new(&out), flag(args, "--alpha-codec").as_deref(), flag(args, "--manifest").map(PathBuf::from), quality, render))
}
/// `raea render ARGS` by this same program, with `env` set; its output said through, its failure the export's.
fn render(args: &[String], env: &[(&str, &str)]) -> R<()> {
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let mut c = Command::new(exe);
c.arg("render").args(args);
for (k, v) in env {
c.env(k, v);
}
let out = c.output().map_err(|e| e.to_string())?;
if !out.status.success() {
let said = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
return Err(format!("the render failed:\n{}", said.trim()));
}
Ok(())
}
fn export(args: &[String]) -> R<String> {
let tsx = args.first().filter(|a| !a.starts_with('-')).ok_or(USAGE)?;
let tsx = PathBuf::from(tsx).canonicalize().map_err(|e| format!("{tsx}: {e}"))?;
let dir = tsx.parent().unwrap().to_path_buf();
let codec = flag(args, "--alpha-codec").map_or(Ok(raea_io_alpha::Codec::default_here()), |c| raea_io_alpha::Codec::parse(&c))?;
let (root, in_store) = match flag(args, "-o") {
Some(o) => (PathBuf::from(o), false),
None => {
let s = raea_io_capcut::store_root().ok_or("CapCut keeps its projects only on a Mac or Windows: -o DIR writes the draft folder anywhere")?;
if !s.parent().is_some_and(Path::exists) {
return Err(format!("CapCut hasn't kept a project on this machine ({} isn't there): open CapCut once, or write the draft folder with -o DIR", s.display()));
}
if !args.iter().any(|a| a == "--no-register") && raea_io_capcut::capcut_running() {
return Err("CapCut is open: it rewrites its project list when it quits, which would drop the new draft from it. Quit CapCut and export again, or pass --no-register (the draft lands in its folder, unlisted) or -o DIR".into());
}
(s, true)
}
};
let stem = tsx.file_stem().unwrap().to_string_lossy().into_owned();
let mut name = flag(args, "--name").unwrap_or(stem);
if root.join(&name).exists() {
let base = name.clone();
name = (2..).map(|k| format!("{base} {k}")).find(|n| !root.join(n).exists()).unwrap();
}
let work = dir.join("out/capcut").join(&name);
std::fs::create_dir_all(&work).map_err(|e| format!("{}: {e}", work.display()))?;
let comp: Vec<String> = flag(args, "--composition").map(|c| vec!["--composition".into(), c]).unwrap_or_default();
let s = |p: &Path| p.display().to_string();
// 1. as it is: the reference render and its manifest
let (reference, manifest_path) = (work.join("reference.mp4"), work.join("render.json"));
render(&[[s(&tsx), "-o".into(), s(&reference), "--manifest".into(), s(&manifest_path)].as_slice(), &comp].concat(), &[])?;
let manifest: Value = serde_json::from_str(&std::fs::read_to_string(&manifest_path).map_err(|e| e.to_string())?).map_err(|e| e.to_string())?;
let (w, h, fps) = (manifest["width"].as_u64().unwrap_or(0) as u32, manifest["height"].as_u64().unwrap_or(0) as u32, manifest["fps"].as_f64().unwrap_or(30.0));
let (wf, hf) = (w as f64, h as f64);
// 2. its footage hidden, transparent: what raea draws over it
let runs = plan::runs(&manifest, fps);
let frames = work.join(format!("overlay.{}.frames", std::process::id()));
let drawn_result = render(&[[s(&tsx), "-o".into(), format!("{}/", frames.display()), "--alpha".into()].as_slice(), &comp].concat(), &[("RAEA_HIDE_MEDIA", "1")]);
// footage the overlay covers (opaque over most of its box at its middle frame) is drawn over the overlay: what the
// composition draws under it, a background
let covered: Vec<bool> = runs.iter().map(|r| drawn_result.is_ok() && opaque_under(&frames, r)).collect();
let overlay = work.join(format!("overlay.{}.mov", ext_of(codec)));
let made = drawn_result.and_then(|_| raea_io_alpha::encode_dir(&frames, &overlay, codec, fps, 0.9));
// the frames folder this export made, and only it
let _ = std::fs::remove_dir_all(&frames);
let made = made?;
// 3. only the backgrounds holding the footage: what raea draws under it, unless that's black (CapCut's canvas)
let under = if runs.is_empty() {
None
} else {
let frames = work.join(format!("under.{}.frames", std::process::id()));
let out = work.join(format!("under.{}.mov", ext_of(codec)));
let done = render(&[[s(&tsx), "-o".into(), format!("{}/", frames.display()), "--alpha".into()].as_slice(), &comp].concat(), &[("RAEA_HIDE_MEDIA", "under")])
.and_then(|_| if lit(&frames) { raea_io_alpha::encode_dir(&frames, &out, codec, fps, 0.9).map(|m| Some((out, m))) } else { Ok(None) });
let _ = std::fs::remove_dir_all(&frames);
done?
};
// 4. the timeline
let mut notes: Vec<String> = Vec::new();
let mut media: Vec<Media> = Vec::new();
let mut index = std::collections::HashMap::<PathBuf, usize>::new();
let mut sounds = plan::sounds(&manifest);
let (mut main, mut rest, mut above) = (Vec::new(), Vec::new(), Vec::new());
for (r, cov) in runs.iter().zip(&covered) {
let path = plan::resolve(&dir, &r.src);
let m = add(&mut media, &mut index, path.clone(), media::video)?;
let (mw, mh) = (media[m].width as f64, media[m].height as f64);
let (place, warn) = plan::place(&r.bx, &r.fit, mw.max(1.0), mh.max(1.0), wf, hf, r.opacity);
let what = format!("{} (frames {}-{})", r.src, r.start, r.end - 1);
if let Some(wn) = warn {
notes.push(format!("{what}: {wn}"));
}
if r.moved {
notes.push(format!("{what}: moves or scales in its box; placed as its first frame shows it (CapCut keyframes don't carry yet)"));
}
if r.faded {
notes.push(format!("{what}: fades; placed at its first frame's opacity"));
}
// its own sound: the manifest's sound clip of the same file over the same frames from the same time
let own = sounds.iter().position(|c| plan::resolve(&dir, &c.src) == path && (c.from - r.start).abs() <= 1 && (c.to - r.end).abs() <= 1 && (c.at - r.at).abs() <= 1.5 / fps);
let volume = own.map_or(0.0, |k| 10f64.powf(sounds.remove(k).gain_db / 20.0));
let clip = Clip { media: m, start: r.start, frames: r.end - r.start, source_in: r.at, speed: r.rate.unwrap_or(1.0).max(0.01), volume, place, ..Clip::default() };
if *cov {
notes.push(format!("{what}: raea draws over all of it from outside what holds it (a layer before it in the page); placed over the overlay, so the overlay's drawing over it is hidden in CapCut"));
}
match (*cov, plan::full(&r.bx, wf, hf)) {
(true, _) => above.push(clip),
(false, true) => main.push(clip),
(false, false) => rest.push(clip),
}
}
// the main track first (the clips covering the canvas), the rest above it in the page's order, then the overlay,
// then footage the overlay draws under
let mut tracks: Vec<Track> = Vec::new();
if let Some((path, m)) = &under {
tracks.extend(drawn(&mut media, path, m, fps, "raea under"));
}
tracks.extend(plan::lay(Kind::Video, if under.is_some() { "footage" } else { "" }, main));
tracks.extend(plan::lay(Kind::Video, "footage", rest));
tracks.extend(drawn(&mut media, &overlay, &made, fps, "raea overlay"));
tracks.extend(plan::lay(Kind::Video, "footage over", above));
let mut audio = Vec::new();
for c in sounds {
let m = add(&mut media, &mut index, plan::resolve(&dir, &c.src), media::sound)?;
audio.push(Clip { media: m, start: c.from, frames: c.to - c.from, source_in: c.at, speed: c.rate, volume: 10f64.powf(c.gain_db / 20.0), fade_in: c.fade_in, fade_out: c.fade_out, ..Clip::default() });
}
tracks.extend(plan::lay(Kind::Audio, "sound", audio));
let notes_made = manifest["sounds"]["notes"].as_array().map_or(0, Vec::len);
if notes_made > 0 {
notes.push(format!("the Tone graph's music ({notes_made} notes) has no file to place: it is in the reference render's sound"));
}
let tl = Timeline { width: w, height: h, fps, media, tracks };
// 5. the draft
let markers = raea_io_capcut::seed(&root);
let written = raea_io_capcut::write(&tl, &root, &name, &markers, media::cover(&reference).as_deref())?;
notes.extend(written.warnings.iter().cloned());
let listed = if !in_store || args.iter().any(|a| a == "--no-register") {
"not entered in CapCut's project list".to_string()
} else {
match raea_io_capcut::register(&root, &written.dir, &written.meta, written.info_bytes, &backups()) {
Ok(b) => format!("entered in CapCut's project list (its list before: {})", b.display()),
Err(e) => format!("not entered in CapCut's project list: {e}"),
}
};
let count = |k: Kind, n: &str| tl.tracks.iter().filter(|t| t.kind == k && t.name.starts_with(n)).map(|t| t.clips.len()).sum::<usize>();
let mut said = format!(
"APPLIED CapCut draft \"{name}\" at {}: {} tracks, {}, {} ({}, {:.1} MB){}, {}; {:.2} s at {fps} fps, {w}x{h}; {listed}; markers from {}\n the reference render and the movies raea drew: {}",
written.dir.display(),
tl.tracks.len(),
many(count(Kind::Video, "") - count(Kind::Video, "raea "), "footage clip"),
many(count(Kind::Video, "raea overlay"), "overlay clip"),
codec.name(),
made.bytes as f64 / 1e6,
under.as_ref().map_or(String::new(), |(_, m)| format!(", {} under the footage ({:.1} MB)", many(count(Kind::Video, "raea under"), "clip"), m.bytes as f64 / 1e6)),
many(count(Kind::Audio, ""), "sound"),
written.duration_us as f64 / 1e6,
markers.from.as_deref().map_or("CapCut 8.5.0 (no draft CapCut made is in the store)".to_string(), |d| format!("the draft \"{d}\" CapCut made")),
work.display()
);
for n in notes {
said.push_str(&format!("\n note {n}"));
}
Ok(said)
}
/// "1 clip", "4 clips"
fn many(k: usize, what: &str) -> String {
if k == 1 { format!("1 {what}") } else { format!("{k} {what}s") }
}
/// Where CapCut's project list is copied before a draft is entered in it: the person's own folder, ~/.raea/capcut/backups
/// ($RAEA_CAPCUT_BACKUPS; %LOCALAPPDATA%\raea\capcut\backups on Windows, which sets no HOME). Never raea's home, which
/// is its install or, from a checkout, the source tree (11-11: a list's backup landed in the repository).
fn backups() -> PathBuf {
match std::env::var_os("LOCALAPPDATA").filter(|d| cfg!(windows) && !d.is_empty() && std::env::var_os("RAEA_CAPCUT_BACKUPS").is_none()) {
Some(d) => PathBuf::from(d).join("raea").join("capcut").join("backups"),
None => raea_io_home::env_path("RAEA_CAPCUT_BACKUPS", ".raea/capcut/backups"),
}
}
/// A movie raea drew, as clips of it wherever it draws, full frame on tracks named `name`; none when it draws nothing.
fn drawn(media: &mut Vec<Media>, path: &Path, m: &raea_io_alpha::Made, fps: f64, name: &str) -> Vec<Track> {
let spans = plan::spans(&m.drawn);
if spans.is_empty() {
return Vec::new();
}
let k = media.len();
media.push(Media { path: path.to_path_buf(), kind: MediaKind::Video, seconds: m.frames as f64 / fps, width: m.width, height: m.height, has_audio: false });
let clips = spans.iter().map(|&(a, b)| Clip { media: k, start: a, frames: b - a, source_in: a as f64 / fps, volume: 0.0, place: Place::centred(m.width, m.height), ..Clip::default() }).collect();
plan::lay(Kind::Video, name, clips)
}
/// A file's place in the media list, probed the first time it's named.
fn add(media: &mut Vec<Media>, index: &mut std::collections::HashMap<PathBuf, usize>, p: PathBuf, probe: fn(&Path) -> R<Media>) -> R<usize> {
if let Some(i) = index.get(&p) {
return Ok(*i);
}
media.push(probe(&p)?);
index.insert(p, media.len() - 1);
Ok(media.len() - 1)
}
fn ext_of(c: raea_io_alpha::Codec) -> &'static str {
match c {
raea_io_alpha::Codec::ProRes => "prores",
raea_io_alpha::Codec::Hevc => "hevc",
raea_io_alpha::Codec::Rle => "rle",
raea_io_alpha::Codec::Png => "png",
}
}
/// Whether the overlay is opaque over 90% of a run's box at its middle frame (a grid of points inside it).
fn opaque_under(frames: &Path, r: &plan::Run) -> bool {
let mid = (r.start + r.end - 1) / 2;
let Ok((px, w, h)) = raea_io_alpha::read_png(&frames.join(format!("frame-{mid:05}.png"))) else { return false };
let (mut n, mut opaque) = (0, 0);
for j in 0..16 {
for i in 0..16 {
let x = (r.bx[0] + r.bx[2] * (i as f64 + 0.5) / 16.0) as i64;
let y = (r.bx[1] + r.bx[3] * (j as f64 + 0.5) / 16.0) as i64;
if x < 0 || y < 0 || x >= w as i64 || y >= h as i64 {
continue;
}
n += 1;
opaque += usize::from(px[((y as usize) * w as usize + x as usize) * 4 + 3] >= 250);
}
}
n > 0 && opaque * 10 >= n * 9
}
/// Whether any frame in `frames` draws anything but black, at any alpha (a grid of points on each).
fn lit(frames: &Path) -> bool {
raea_io_alpha::frames_in(frames).iter().any(|p| {
let Ok((px, w, h)) = raea_io_alpha::read_png(p) else { return true };
(0..32).any(|j| {
(0..32).any(|i| {
let (x, y) = ((w as usize * (2 * i + 1)) / 64, (h as usize * (2 * j + 1)) / 64);
let k = (y * w as usize + x) * 4;
px[k + 3] >= 8 && px[k..k + 3].iter().any(|&c| c >= 8)
})
})
})
}
+50
View File
@@ -0,0 +1,50 @@
//! The files a draft uses, probed through raea's media backends (a picture's upright size and length, whether it has
//! sound; a sound's length), and the draft's cover: the reference render's first frame as a small JPEG.
use std::path::Path;
use raea_io_capcut::{Media, MediaKind};
use crate::R;
/// A video file: its display size (rotation applied) and length from the first backend that opens it, and whether a
/// short window of its sound decodes to samples.
pub fn video(path: &Path) -> R<Media> {
let mut why = Vec::new();
for b in raea_io_media::preferred() {
match b.open_video(path) {
Ok(d) => {
let i = d.info();
let has_audio = raea_io_media::decode_audio_window(path, 0.0, 0.05).is_ok_and(|a| a.len() > 0);
return Ok(Media { path: path.to_path_buf(), kind: MediaKind::Video, seconds: i.duration, width: i.width, height: i.height, has_audio });
}
Err(e) => why.push(format!("{}: {e}", b.name())),
}
}
Err(format!("{} didn't open as video ({})", path.display(), why.join("; ")))
}
/// A sound file: its length from its container.
pub fn sound(path: &Path) -> R<Media> {
let seconds = raea_io_media::probe_seconds(path).ok_or_else(|| format!("{}: no sound length", path.display()))?;
Ok(Media { path: path.to_path_buf(), kind: MediaKind::Audio, seconds, width: 0, height: 0, has_audio: true })
}
/// The first frame of `video`, at most 540 pixels on its long side, as a JPEG.
pub fn cover(video: &Path) -> Option<Vec<u8>> {
let mut d = raea_io_media::preferred().into_iter().find_map(|b| b.open_video(video).ok())?;
let f = d.frame_at(0.0).ok()?;
let (w, h) = (f.width as usize, f.height as usize);
let step = (w.max(h)).div_ceil(540).max(1);
let (tw, th) = (w / step, h / step);
let mut rgb = Vec::with_capacity(tw * th * 3);
for y in 0..th {
for x in 0..tw {
let k = ((y * step) * w + x * step) * 4;
rgb.extend_from_slice(&f.rgba[k..k + 3]);
}
}
let mut out = Vec::new();
image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 82).encode(&rgb, tw as u32, th as u32, image::ExtendedColorType::Rgb8).ok()?;
Some(out)
}
+182
View File
@@ -0,0 +1,182 @@
//! The render's manifest as a CapCut timeline (docs/capcut.feature CC2): each run of frames showing one file as a
//! clip of it, each sound clip as an audio clip (or as its footage's own sound), each run of frames the overlay draws
//! as a clip of the overlay movie, and the tracks they go on. Pure: the export (lib.rs) renders and probes around it.
use std::path::{Path, PathBuf};
use raea_io_capcut::{Clip, Kind, Place, Track};
use serde_json::Value;
/// One file shown over a run of frames, as the manifest's frames say: its first source time and rate, its box and
/// fit at its first frame, its place in the page's order (lower draws first), and whether it moved or faded.
#[derive(Clone, Debug, PartialEq)]
pub struct Run {
pub src: String,
pub key: String,
pub start: i64,
pub end: i64,
pub at: f64,
pub last_at: f64,
pub rate: Option<f64>,
pub bx: [f64; 4],
pub fit: String,
pub opacity: f64,
pub z: usize,
pub moved: bool,
pub faded: bool,
}
/// One sound clip of the manifest: its file, frames, source time, gain, rate and fades.
#[derive(Clone, Debug, PartialEq)]
pub struct Sound {
pub src: String,
pub from: i64,
pub to: i64,
pub at: f64,
pub gain_db: f64,
pub rate: f64,
pub fade_in: f64,
pub fade_out: f64,
}
/// The footage's runs, frame by frame: a run goes on while the same element shows the same file with its source time
/// advancing at one rate; a jump in source time (a cut within one take) starts another.
pub fn runs(manifest: &Value, fps: f64) -> Vec<Run> {
let mut done: Vec<Run> = Vec::new();
let mut open: Vec<Run> = Vec::new();
let frames = manifest["frames"].as_array().cloned().unwrap_or_default();
for (i, fr) in frames.iter().enumerate() {
let f = fr["frame"].as_i64().unwrap_or(i as i64);
let mut next = Vec::new();
for (z, v) in fr["videos"].as_array().into_iter().flatten().enumerate() {
let src = v["src"].as_str().unwrap_or_default().to_string();
let key = format!("{src}|{}|{}|{}", v["loc"], v["use"], v["index"]);
let at = v["at"].as_f64().unwrap_or(0.0);
let bx: [f64; 4] = std::array::from_fn(|k| v["box"][k].as_f64().unwrap_or(0.0));
let opacity = v["opacity"].as_f64().unwrap_or(1.0);
let continues = |r: &Run| {
let step = at - r.last_at;
r.key == key && r.end == f && step > 0.0 && match r.rate {
Some(rate) => (step - rate / fps).abs() <= 0.6 / fps,
None => step * fps <= 8.0,
}
};
if let Some(k) = open.iter().position(continues) {
let mut r = open.remove(k);
r.rate.get_or_insert((at - r.last_at) * fps);
r.moved |= r.bx.iter().zip(&bx).any(|(a, b)| (a - b).abs() > 1.0);
r.faded |= (r.opacity - opacity).abs() > 0.02;
(r.end, r.last_at) = (f + 1, at);
next.push(r);
} else {
next.push(Run { src, key, start: f, end: f + 1, at, last_at: at, rate: None, bx, fit: v["fit"].as_str().unwrap_or("fill").to_string(), opacity, z, moved: false, faded: false });
}
}
done.append(&mut open);
open = next;
}
done.append(&mut open);
// the rate over the whole run (source times are whole milliseconds, so one step's can be 1% off), to hundredths
for r in &mut done {
if r.end - r.start > 1 {
r.rate = Some(((r.last_at - r.at) * fps / (r.end - r.start - 1) as f64 * 100.0).round() / 100.0);
}
}
done.sort_by_key(|r| (r.start, r.z));
done
}
/// The manifest's sound clips.
pub fn sounds(manifest: &Value) -> Vec<Sound> {
let s = &manifest["sounds"]["clips"];
s.as_array()
.into_iter()
.flatten()
.map(|c| Sound {
src: c["src"].as_str().unwrap_or_default().to_string(),
from: c["from"].as_i64().unwrap_or(0),
to: c["to"].as_i64().unwrap_or(0),
at: c["at"].as_f64().unwrap_or(0.0),
gain_db: c["gainDb"].as_f64().unwrap_or(0.0),
rate: c["rate"].as_f64().unwrap_or(1.0),
fade_in: c["fadeIn"].as_f64().unwrap_or(0.0),
fade_out: c["fadeOut"].as_f64().unwrap_or(0.0),
})
.filter(|c| c.to > c.from)
.collect()
}
/// Runs of frames that draw something.
pub fn spans(drawn: &[bool]) -> Vec<(i64, i64)> {
let mut out = Vec::new();
let mut f = 0;
while f < drawn.len() {
if !drawn[f] {
f += 1;
continue;
}
let a = f;
while f < drawn.len() && drawn[f] {
f += 1;
}
out.push((a as i64, f as i64));
}
out
}
/// Whether a box covers the whole canvas.
pub fn full(bx: &[f64; 4], w: f64, h: f64) -> bool {
bx[0] <= 1.0 && bx[1] <= 1.0 && bx[0] + bx[2] >= w - 1.0 && bx[1] + bx[3] >= h - 1.0
}
/// Where a picture of `mw` x `mh` sits to show as it does in its box with its object-fit, in CapCut's terms (scale 1:
/// fitted inside the canvas; a crop is fitted as the part it keeps). A warning when CapCut can't show it so.
pub fn place(bx: &[f64; 4], fit: &str, mw: f64, mh: f64, w: f64, h: f64, opacity: f64) -> (Place, Option<String>) {
let (bw, bh) = (bx[2].max(1.0), bx[3].max(1.0));
let (x, y) = (bx[0] + bw / 2.0, bx[1] + bh / 2.0);
let fit0 = (w / mw).min(h / mh);
let mut warn = None;
let contain = (bw / mw).min(bh / mh);
let (scale, crop) = match fit {
"cover" if full(bx, w, h) => ((bw / mw).max(bh / mh) / fit0, [0.0, 0.0, 1.0, 1.0]),
"cover" => {
let s = (bw / mw).max(bh / mh);
let (cw, ch) = (bw / (mw * s), bh / (mh * s));
let fitc = (w / (mw * cw)).min(h / (mh * ch));
(bw / (mw * cw * fitc), [(1.0 - cw) / 2.0, (1.0 - ch) / 2.0, (1.0 + cw) / 2.0, (1.0 + ch) / 2.0])
}
"none" => (1.0 / fit0, [0.0, 0.0, 1.0, 1.0]),
"scale-down" => (contain.min(1.0) / fit0, [0.0, 0.0, 1.0, 1.0]),
"contain" => (contain / fit0, [0.0, 0.0, 1.0, 1.0]),
_ => {
if ((bw / bh) - (mw / mh)).abs() > 0.01 * (mw / mh) {
warn = Some(format!("stretched to its {bw:.0}x{bh:.0} box in raea (object-fit: fill), fitted inside it in CapCut"));
}
(contain / fit0, [0.0, 0.0, 1.0, 1.0])
}
};
(Place { x, y, scale, opacity, crop }, warn)
}
/// Clips laid on as few tracks as hold them without overlap, first come first: `kind` tracks named `name`, `name 2`...
pub fn lay(kind: Kind, name: &str, clips: Vec<Clip>) -> Vec<Track> {
let mut tracks: Vec<Track> = Vec::new();
for c in clips {
let end = |t: &Track| t.clips.last().map_or(i64::MIN, |l| l.start + l.frames);
match tracks.iter_mut().find(|t| end(t) <= c.start) {
Some(t) => t.clips.push(c),
None => {
let n = tracks.len();
tracks.push(Track { kind, name: if n == 0 || name.is_empty() { name.to_string() } else { format!("{name} {}", n + 1) }, clips: vec![c] });
}
}
}
tracks
}
/// A file the manifest names, as a path, found as the renderer finds it: a staticFile path (/media/x) in the edit's
/// media/, then the project's media/ and assets/; else absolute; else relative to the composition's folder.
pub fn resolve(dir: &Path, src: &str) -> PathBuf {
let p = raea_core_scene::media_path(dir, src);
p.canonicalize().unwrap_or(p)
}
+85
View File
@@ -0,0 +1,85 @@
//! CC2a-c without a render: a manifest's frames as footage runs, its sound clips, the overlay's spans, where a picture
//! sits in CapCut's terms, and clips laid on tracks.
use serde_json::json;
use crate::plan::*;
use raea_io_capcut::{Clip, Kind};
/// 90 frames at 30 fps: one take cut into two pieces (a jump in its source time at frame 45), another file in a
/// corner from frame 60, moving one pixel at frame 70. Source times in whole milliseconds, as the manifest has them.
fn manifest() -> serde_json::Value {
let ms = |t: f64| (t * 1000.0).round() / 1000.0;
let frames: Vec<_> = (0..90)
.map(|f| {
let mut v = vec![json!({"src": "media/a.mp4", "at": ms(if f < 45 { 0.5 + f as f64 / 30.0 } else { 3.0 + (f - 45) as f64 / 30.0 }), "box": [0.0, 0.0, 1080.0, 1920.0], "fit": "cover", "opacity": 1.0})];
if f >= 60 {
v.push(json!({"src": "media/pip.mp4", "at": ms((f - 60) as f64 / 15.0), "box": [if f >= 70 { 662.0 } else { 660.0 }, 200.0, 360.0, 360.0], "opacity": 1.0}));
}
json!({"frame": f, "videos": v})
})
.collect();
json!({"width": 1080, "height": 1920, "fps": 30.0, "frames": frames, "sounds": {"clips": [{"src": "/m/music.wav", "from": 0, "to": 90, "at": 0.0, "gainDb": -6.0, "fadeOut": 0.5}]}})
}
#[test]
fn footage_runs_break_where_the_source_jumps() {
let r = runs(&manifest(), 30.0);
assert_eq!(r.iter().map(|r| (r.src.as_str(), r.start, r.end)).collect::<Vec<_>>(), [("media/a.mp4", 0, 45), ("media/a.mp4", 45, 90), ("media/pip.mp4", 60, 90)]);
assert!((r[1].at - 3.0).abs() < 1e-9);
assert_eq!((r[0].rate, r[1].rate), (Some(1.0), Some(1.0)), "a take at its own speed, though each step is 33 or 34 ms");
assert!((r[2].rate.unwrap() - 2.0).abs() < 1e-6, "the corner plays at twice its speed");
assert!(r[2].moved && !r[0].moved);
assert_eq!(r[2].fit, "fill");
}
#[test]
fn sounds_keep_gain_and_fades() {
let s = sounds(&manifest());
assert_eq!(s.len(), 1);
assert_eq!((s[0].from, s[0].to, s[0].gain_db, s[0].fade_out), (0, 90, -6.0, 0.5));
}
#[test]
fn overlay_spans_are_runs_of_drawn_frames() {
assert_eq!(spans(&[false, true, true, false, false, true]), [(1, 3), (5, 6)]);
assert!(spans(&[false; 4]).is_empty());
}
#[test]
fn pictures_sit_as_their_fit_shows_them() {
// a landscape take covering a portrait canvas: scaled past the fitted width until it fills the height
let (p, w) = place(&[0.0, 0.0, 1080.0, 1920.0], "cover", 1920.0, 1080.0, 1080.0, 1920.0, 1.0);
assert!(w.is_none() && (p.scale - (1920.0 / 1080.0) / 0.5625).abs() < 1e-9 && p.crop == [0.0, 0.0, 1.0, 1.0]);
assert_eq!((p.x, p.y), (540.0, 960.0));
// a square in a corner, contained: a third of the canvas's width
let (p, _) = place(&[660.0, 200.0, 360.0, 360.0], "contain", 640.0, 640.0, 1080.0, 1920.0, 1.0);
assert!((p.scale - 1.0 / 3.0).abs() < 1e-9 && (p.x, p.y) == (840.0, 380.0));
// a landscape take covering a square box: cropped to its middle square, which then fits as a square
let (p, _) = place(&[0.0, 0.0, 540.0, 540.0], "cover", 1920.0, 1080.0, 1080.0, 1920.0, 1.0);
assert!((p.crop[0] - 0.21875).abs() < 1e-9 && (p.crop[2] - 0.78125).abs() < 1e-9 && p.crop[1] == 0.0);
assert!((p.scale - 0.5).abs() < 1e-9);
// stretched in raea: said
assert!(place(&[0.0, 0.0, 500.0, 100.0], "fill", 640.0, 640.0, 1080.0, 1920.0, 1.0).1.is_some());
}
#[test]
fn clips_go_on_as_few_tracks_as_hold_them() {
let c = |start, frames| Clip { start, frames, ..Clip::default() };
let t = lay(Kind::Audio, "sound", vec![c(0, 90), c(10, 5), c(15, 10), c(90, 5)]);
assert_eq!(t.iter().map(|t| (t.name.as_str(), t.clips.len())).collect::<Vec<_>>(), [("sound", 2), ("sound 2", 2)]);
}
/// staticFile("x.mp4") is "/media/x.mp4" in the manifest: the export finds it where the render did, in media/ beside
/// the edit, as it finds a relative path; an absolute path stays as it is
#[test]
fn a_static_file_is_found_in_the_edits_media_folder() {
let dir = std::env::temp_dir().join(format!("raea-capcut-resolve-{}", std::process::id()));
std::fs::create_dir_all(dir.join("media")).unwrap();
std::fs::write(dir.join("media/a.mp4"), "").unwrap();
let want = dir.join("media/a.mp4").canonicalize().unwrap();
assert_eq!(resolve(&dir, "/media/a.mp4"), want);
assert_eq!(resolve(&dir, "media/a.mp4"), want);
assert_eq!(resolve(&dir, want.to_str().unwrap()), want);
std::fs::remove_dir_all(&dir).unwrap();
}
+10
View File
@@ -9,4 +9,14 @@ description = "`raea check`: the floor's measurable lines on an export, ranked P
[dependencies]
# taste.ts rules, as the raea CLI evaluates them (docs/projects.feature PJ0)
raea-core-brief = { path = "../../core/brief" }
# a transcript's words, read as `raea world` reads them (docs/direction.feature DR1)
raea-core-facts = { path = "../../core/facts" }
# a check's record named by when it was (UTC, DR3)
raea-io-trace = { path = "../../io/trace" }
# ffmpeg's flag for every decoded frame, by its version
raea-io-ffmpeg = { path = "../../io/ffmpeg" }
# caption contrast and loudness, measured as `raea world` measures a render (DR2)
raea-sys-measure = { path = "../../systems/measure" }
# the flashing screen (WCAG 2.3.1), split out to keep this crate small
raea-app-check-flash = { path = "flash" }
serde_json = "1"
+7
View File
@@ -0,0 +1,7 @@
[package]
name = "raea-app-check-flash"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "`raea check`'s flashing screen (WCAG 2.3.1): opposing swings in a frame's windows, from decoded RGB"
+232
View File
@@ -0,0 +1,232 @@
//! The flashing screen behind `raea check` (apps/check flash.rs feeds it the decoded frames): a pure measure of pixels,
//! in a crate of its own so the check stays small (tools/size.sh).
/// Flashing past WCAG 2.3.1: more than three flashes in any one second, over enough of the frame to matter. A flash is a
/// pair of opposing changes in the same pixels, so a shape sliding past isn't one. Each window, a third of the frame wide
/// and high, stands in for WCAG's quarter of a 10-degree field (the real area depends on the screen and how far away it
/// is, which a file doesn't say), and a quarter of its pixels must swing together: by 0.10 relative luminance with the
/// darker end under 0.80, or by 20 of saturated red ((R-G-B)*320, where R/(R+G+B) is at least 0.8). Every decoded frame
/// counts, on its own timestamp, and the picture is sampled twice, by area and by point, so fine patterns don't average
/// away. A screen for review, not a Harding or PEAT certification; an interlaced picture isn't split into its fields.
const FLASH_MOST: usize = 6;
const FLASH_PAIR_S: f64 = 1.0 + 1e-9;
/// A pixel in one measure: its value, and whether it can count. Red's value runs on through the saturation line, and a change
/// counts when either end of it is saturated; a one-level step across the line isn't a jump from zero.
#[derive(Clone, Copy)]
struct Px {
value: f32,
counts: bool,
}
struct Swing {
at: f64,
direction: f32,
moved: Vec<bool>,
plain: bool,
kept: bool,
}
/// One window's swings in one measure: the ones an opposite swing within a second moves back in the same pixels. The
/// general measure leaves out swings where another quarter of the window moved the other way at once (a moving pattern).
struct Swings {
by: f32,
under: f32,
mixed_counts: bool,
pivot: Vec<Px>,
extreme: Vec<Px>,
at: f64,
direction: f32,
recent: std::collections::VecDeque<Swing>,
ends: Vec<f64>,
}
impl Swings {
fn new(by: f32, under: f32, mixed_counts: bool) -> Swings {
Swings { by, under, mixed_counts, pivot: Vec::new(), extreme: Vec::new(), at: 0.0, direction: 0.0, recent: Default::default(), ends: Vec::new() }
}
fn moves(&self, a: Px, b: Px, direction: f32) -> bool {
(b.value - a.value) * direction >= self.by && a.value.min(b.value) < self.under && (a.counts || b.counts)
}
fn changed(&self, earlier: &[Px], later: &[Px], direction: f32) -> bool {
earlier.iter().zip(later).filter(|(a, b)| self.moves(**a, **b, direction)).count() * 4 >= earlier.len()
}
fn push(&mut self, t: f64, px: &[Px]) {
if self.pivot.is_empty() {
self.pivot = px.to_vec();
self.extreme = px.to_vec();
self.at = t;
return;
}
if self.direction == 0.0 {
for direction in [1.0, -1.0] {
if self.changed(&self.pivot, px, direction) {
self.direction = direction;
self.extreme = px.to_vec();
self.at = t;
break;
}
}
return;
}
if self.changed(&self.extreme, px, -self.direction) {
self.record();
self.pivot = std::mem::replace(&mut self.extreme, px.to_vec());
self.at = t;
self.direction = -self.direction;
} else if self.changed(&self.pivot, px, self.direction) && self.went_further(px) {
self.extreme = px.to_vec();
}
}
/// Whether the pixels swinging from the pivot went further than the saved extreme, judged on those pixels alone: the
/// rest of the window can dim by less than counts and still outweigh a patch that's flashing.
fn went_further(&self, px: &[Px]) -> bool {
let further: f32 = self.pivot.iter().zip(px).zip(&self.extreme).filter(|((p, n), _)| self.moves(**p, **n, self.direction)).map(|((_, n), e)| (n.value - e.value) * self.direction).sum();
further > 0.0
}
fn record(&mut self) {
if !self.changed(&self.pivot, &self.extreme, self.direction) {
return;
}
let moved: Vec<bool> = self.pivot.iter().zip(&self.extreme).map(|(a, b)| self.moves(*a, *b, self.direction)).collect();
let plain = self.mixed_counts || !self.changed(&self.pivot, &self.extreme, -self.direction);
let (at, direction) = (self.at, self.direction);
let mut kept = false;
for other in self.recent.iter_mut().rev() {
if at - other.at > FLASH_PAIR_S {
break;
}
let same = moved.iter().zip(&other.moved).filter(|(x, y)| **x && **y).count();
if other.direction == -direction && same * 4 >= moved.len() {
other.kept = true;
kept = true;
}
}
self.recent.push_back(Swing { at, direction, moved, plain, kept });
while self.recent.front().is_some_and(|s| at - s.at > FLASH_PAIR_S) {
self.retire();
}
}
/// The oldest swing leaves the second it could still pair within; only the seconds' ends are kept for good.
fn retire(&mut self) {
if let Some(s) = self.recent.pop_front()
&& s.plain
&& s.kept
{
self.ends.push(s.at);
}
}
/// The most swings in any one second, and when that second starts.
fn busiest(&mut self) -> (usize, f64) {
if self.direction != 0.0 {
self.record();
self.direction = 0.0;
}
while !self.recent.is_empty() {
self.retire();
}
self.ends.sort_by(f64::total_cmp);
let (mut best, mut from, mut j) = (0, 0.0, 0);
for i in 0..self.ends.len() {
while self.ends[i] - self.ends[j] >= 1.0 - 1e-9 {
j += 1;
}
if i - j + 1 > best {
(best, from) = (i - j + 1, self.ends[j]);
}
}
(best, from)
}
}
/// Frames of two pictures side by side, each `w` by `h` RGB: the area sample and the point sample of one frame.
pub struct FlashScreen {
w: usize,
h: usize,
last: Vec<u8>,
linear: Vec<f32>,
luma: Vec<Px>,
red: Vec<Px>,
cut: Vec<Px>,
windows: Vec<(usize, usize, Swings, Swings)>,
}
impl FlashScreen {
pub fn new(w: usize, h: usize) -> FlashScreen {
let (ww, wh) = (w / 3, h / 3);
let places = |size: usize, window: usize| {
let mut at: Vec<usize> = (0..=size - window).step_by((size / 6).max(1)).collect();
at.push(size - window);
at.dedup();
at
};
let mut windows = Vec::new();
for sample in 0..2 {
for &y in &places(h, wh) {
for &x in &places(w, ww) {
windows.push((x + sample * w, y, Swings::new(0.10, 0.80, false), Swings::new(20.0, f32::INFINITY, true)));
}
}
}
let linear = (0..=255u32)
.map(|c| {
let c = c as f32 / 255.0;
if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) }
})
.collect();
FlashScreen { w, h, last: Vec::new(), linear, luma: Vec::new(), red: Vec::new(), cut: Vec::new(), windows }
}
pub fn push(&mut self, rgb: &[u8], t: f64) {
if rgb == self.last {
return;
}
self.luma.clear();
self.red.clear();
for px in rgb.chunks_exact(3) {
let (r, g, b) = (self.linear[px[0] as usize], self.linear[px[1] as usize], self.linear[px[2] as usize]);
self.luma.push(Px { value: 0.2126 * r + 0.7152 * g + 0.0722 * b, counts: true });
let sum = r + g + b + 1e-9;
self.red.push(Px { value: ((r - g - b) * 320.0).max(0.0), counts: r / sum >= 0.8 });
}
let (stride, ww, wh) = (self.w * 2, self.w / 3, self.h / 3);
for (x, y, general, saturated) in &mut self.windows {
self.cut.clear();
for r in 0..wh {
self.cut.extend_from_slice(&self.luma[(*y + r) * stride + *x..][..ww]);
}
general.push(t, &self.cut);
self.cut.clear();
for r in 0..wh {
self.cut.extend_from_slice(&self.red[(*y + r) * stride + *x..][..ww]);
}
saturated.push(t, &self.cut);
}
self.last.clear();
self.last.extend_from_slice(rgb);
}
/// (swings in the worst second, when it starts, which measure) when past the limit
pub fn finish(mut self) -> Option<(usize, f64, &'static str)> {
let mut worst: Option<(usize, f64, &'static str)> = None;
for (_, _, general, saturated) in &mut self.windows {
for (swings, kind) in [(general, "general"), (saturated, "red")] {
let (n, from) = swings.busiest();
if n > FLASH_MOST && worst.is_none_or(|w| n > w.0) {
worst = Some((n, from, kind));
}
}
}
worst
}
}
#[cfg(test)]
mod tests;
+100
View File
@@ -0,0 +1,100 @@
use super::*;
/// a 96x54 picture drawn by `paint(frame index, sample, x, y)`, sample 0 the area sample and 1 the point sample, for
/// `frames` frames at `fps`
fn flash_samples(frames: usize, fps: f64, paint: impl Fn(usize, usize, usize, usize) -> [u8; 3]) -> Option<(usize, f64, &'static str)> {
let (w, h) = (96, 54);
let mut screen = FlashScreen::new(w, h);
for f in 0..frames {
let mut rgb = Vec::with_capacity(w * 2 * h * 3);
for y in 0..h {
for sample in 0..2 {
for x in 0..w {
rgb.extend_from_slice(&paint(f, sample, x, y));
}
}
}
screen.push(&rgb, f as f64 / fps);
}
screen.finish()
}
fn flash_of(seconds: usize, paint: impl Fn(usize, usize, usize) -> [u8; 3]) -> Option<(usize, f64, &'static str)> {
flash_samples(seconds * 60, 60.0, move |f, _, x, y| paint(f, x, y))
}
/// two colours taking turns `hz` times a second, over a box of the frame
fn turns(hz: usize, on: [u8; 3], off: [u8; 3], bx: (usize, usize, usize, usize)) -> Option<(usize, f64, &'static str)> {
flash_of(3, move |f, x, y| {
let inside = x >= bx.0 && x < bx.0 + bx.2 && y >= bx.1 && y < bx.1 + bx.3;
if inside && f * hz * 2 / 60 % 2 == 0 { on } else { off }
})
}
#[test]
fn flashing_is_found_past_three_a_second_and_not_at_it() {
let (white, black) = ([255, 255, 255], [0, 0, 0]);
let all = (0, 0, 96, 54);
assert_eq!(turns(3, white, black, all), None, "three a second is the limit, not past it");
let (swings, _, kind) = turns(4, white, black, all).expect("four a second");
assert_eq!((swings / 2, kind), (4, "general"));
// a small box: under a quarter of any window, and then over it
assert_eq!(turns(5, white, black, (40, 20, 10, 10)), None);
assert!(turns(5, white, black, (30, 18, 32, 18)).is_some());
// too small a change, and both ends too bright for WCAG to count it
assert_eq!(turns(5, [60, 60, 60], [30, 30, 30], all), None);
assert_eq!(turns(5, [255, 255, 255], [235, 235, 235], all), None);
// a dark saturated red: too dim to count as a general flash, past the limit as a red one
assert_eq!(turns(5, [150, 0, 0], black, all).map(|t| t.2), Some("red"));
}
#[test]
fn a_flash_of_single_frames_counts_at_any_frame_rate() {
// 120 fps with one white frame in every 30: four flashes a second, each gone within a sixtieth of a second
let found = flash_samples(360, 120.0, |f, _, _, _| if f % 30 == 1 { [255, 255, 255] } else { [0, 0, 0] });
assert_eq!(found.map(|(swings, _, kind)| (swings / 2, kind)), Some((4, "general")));
}
#[test]
fn a_flash_the_area_sample_averages_away_is_found_in_the_point_sample() {
let found = flash_samples(180, 60.0, |f, sample, _, _| {
if sample == 0 {
return [128, 128, 128];
}
if f * 5 * 2 / 60 % 2 == 0 { [255, 255, 255] } else { [0, 0, 0] }
});
assert!(found.is_some(), "the same flash in the point sample alone");
}
#[test]
fn a_shape_sliding_past_and_ordinary_cuts_are_not_flashing() {
let (white, black) = ([255, 255, 255], [0, 0, 0]);
assert_eq!(flash_of(3, move |f, x, _| if x < f { white } else { black }), None, "one wipe across the frame");
assert_eq!(flash_of(4, move |f, _, _| if (f / 30) % 2 == 0 { white } else { black }), None, "a cut every half second");
}
#[test]
fn a_patch_strobing_while_its_background_dims_is_still_found() {
// a third of a window: 0 then 124 on a 148 background, then the background settles at 124 and the patch cycles 124 and 160.
// The background's drop is under the 0.10 that counts, but it outweighs the patch in the window's mean.
let found = flash_samples(180, 60.0, |f, _, x, y| {
let patch = x < 16 && y < 12;
let level = match (patch, f) {
(true, 0) => 0,
(true, 1) => 124,
(true, _) => if (f - 2) * 5 * 2 / 60 % 2 == 0 { 160 } else { 124 },
(false, 0 | 1) => 148,
(false, _) => 124,
};
[level, level, level]
});
assert!(found.is_some(), "the patch flashes five times a second");
}
#[test]
fn a_colour_crossing_the_saturation_line_is_not_a_red_flash() {
// one level of green moves the pixel across R/(R+G+B) = 0.8 and hardly changes its red at all
let found = flash_samples(180, 60.0, |f, _, _, _| if f * 5 * 2 / 60 % 2 == 0 { [100, 49, 0] } else { [100, 50, 0] });
assert_eq!(found, None);
}
+152
View File
@@ -0,0 +1,152 @@
use super::*;
/// The defects Fingerprint's axes map to that a measure finds exactly (docs/fingerprint.feature FP4c), so the check
/// wins over a head: clipping, a dropout, and a flash frame. Each on the same decoded sound or a small grey picture;
/// each with red-team cases in tests.rs (a loud clean tone, a faded pause, a cut).
///
/// Clipping: a run of 3 samples or more at full scale (|x| 0.999 or more), or a flat top: 4 or more samples the same
/// to the bit at a level a sound rarely holds still at (0.05 or more), as a hard limiter or a clamp leaves them.
/// Counted per second; a second with CLIP_RUNS runs or more is a finding.
pub(crate) const FULL: f32 = 0.999;
pub(crate) const FLAT_LEVEL: f32 = 0.05;
pub(crate) const CLIP_RUNS: usize = 3;
pub(crate) fn clipped(x: &[f32]) -> Vec<(f64, String)> {
let mut per: Vec<usize> = vec![0; x.len() / SR + 1];
let mut i = 0;
while i < x.len() {
let v = x[i];
let mut j = i + 1;
if v.abs() >= FULL {
while j < x.len() && x[j].abs() >= FULL && x[j].signum() == v.signum() {
j += 1;
}
if j - i >= 3 {
per[i / SR] += 1;
}
} else if v.abs() >= FLAT_LEVEL {
while j < x.len() && x[j].to_bits() == v.to_bits() {
j += 1;
}
if j - i >= 4 {
per[i / SR] += 1;
}
}
i = j;
}
let mut out = Vec::new();
let mut s = 0;
while s < per.len() {
if per[s] < CLIP_RUNS {
s += 1;
continue;
}
let mut e = s;
while e + 1 < per.len() && per[e + 1] >= CLIP_RUNS {
e += 1;
}
let runs: usize = per[s..=e].iter().sum();
out.push((s as f64, format!("the sound clips: {runs} flat-topped runs over {} s; bring the level down before it hits the ceiling", e - s + 1)));
s = e + 1;
}
out
}
/// A dropout: the sound falls from level (-45 dBFS or more) to digital silence (under -80 dBFS) in one 10 ms step and
/// comes back within two, to within 10 dB of where it was, 50 ms to 3 s later. A pause that fades out or in isn't one.
pub(crate) const SILENT: f64 = -80.0;
pub(crate) const HAD_LEVEL: f64 = -45.0;
pub(crate) fn dropouts(x: &[f32]) -> Vec<(f64, String)> {
let rms: Vec<f64> = x.as_chunks::<HOP>().0.iter().map(|f| crate::sound::db(f)).collect();
let step = HOP as f64 / SR as f64;
let mut out = Vec::new();
let mut i = 1;
while i < rms.len() {
// a step that is silent, or nearly (the source cut partway through it), after one with level
if !(rms[i] < HAD_LEVEL - 20.0 && rms[i - 1] >= HAD_LEVEL) {
i += 1;
continue;
}
let mut j = i + 1;
while j < rms.len() && rms[j] < SILENT {
j += 1;
}
let gap = (j - i) as f64 * step;
let silent_inside = j > i + 1;
// back at once: within two steps, to within 10 dB of the level before the gap (a fade in takes longer)
let before = rms[i - 1];
let back = rms[j.min(rms.len())..(j + 2).min(rms.len())].iter().any(|l| *l >= HAD_LEVEL.max(before - 10.0));
if silent_inside && back && (0.05..=3.0).contains(&gap) {
out.push((i as f64 * step, format!("the sound drops out for {:.2} s and comes back; a dropout, not a pause (no fade either side)", gap)));
}
i = j.max(i + 1);
}
out
}
/// A flash frame: one or two frames whose mean brightness differs from the frames either side by FLASH_STEP or more
/// (0-1), while those two agree within FLASH_SAME: a black or white frame dropped into a shot. A cut (the brightness
/// moves and stays) and a fade aren't flash frames.
pub(crate) const FLASH_STEP: f32 = 0.25;
pub(crate) const FLASH_SAME: f32 = 0.08;
pub(crate) fn flash_frames(luma: &[f32], fps: f64) -> Vec<(f64, String)> {
let mut out = Vec::new();
let mut i = 1;
while i + 1 < luma.len() {
let found = (1..=2).find(|&k| {
let (before, after) = (luma[i - 1], luma.get(i + k - 1 + 1).copied());
let Some(after) = after else { return false };
(before - after).abs() <= FLASH_SAME && luma[i..i + k].iter().all(|&l| (l - before).abs() >= FLASH_STEP && (l - after).abs() >= FLASH_STEP)
});
match found {
Some(k) => {
out.push((i as f64 / fps, format!("{k} frame{} flash{} {} in the middle of a shot; a dropped or stray frame", if k == 1 { "" } else { "s" }, if k == 1 { "es" } else { "" }, if luma[i] < luma[i - 1] { "dark" } else { "bright" })));
i += k + 1;
}
None => i += 1,
}
}
out
}
/// Each frame's mean brightness (0-1), decoded small and grey
fn lumas(video: &str) -> R<(Vec<f32>, f64)> {
let out = Command::new("ffmpeg")
.args(["-v", "error", "-nostdin", "-i", video, "-map", "0:v:0", "-vf", "scale=32:18:flags=area,format=gray", "-f", "rawvideo", "-"])
.output()
.map_err(|e| format!("ffmpeg: {e}"))?;
if !out.status.success() {
return Err(format!("ffmpeg couldn't read the picture of {video}: {}", String::from_utf8_lossy(&out.stderr).trim()));
}
let l = out.stdout.as_chunks::<{ 32 * 18 }>().0.iter().map(|f| f.iter().map(|&p| p as f32).sum::<f32>() / (32.0 * 18.0 * 255.0)).collect();
let rate = ffmpeg_stderr(&["-hide_banner", "-i", video])?;
let fps = rate.split(" fps").next().and_then(|s| s.rsplit(", ").next()).and_then(|s| s.trim().parse().ok()).unwrap_or(30.0);
Ok((l, fps))
}
pub(crate) fn flash_frame_rule(video: &str, issues: &mut Vec<Issue>, passed: &mut Vec<String>) -> R<()> {
let (l, fps) = lumas(video)?;
let found = flash_frames(&l, fps);
if found.is_empty() {
passed.push("flash-frame: no stray black or white frame".into());
}
issues.extend(moments("flash-frame", 1, found));
Ok(())
}
/// Each moment a rule found, as an issue of that priority
pub(crate) fn moments(rule: &'static str, p: u8, found: Vec<(f64, String)>) -> impl Iterator<Item = Issue> {
found.into_iter().map(move |(at, says)| Issue { rule, p, at: Some(at), says })
}
/// The sound's defects on the decoded mix (sound.rs decodes it once)
pub(crate) fn sound_defects(x: &[f32], issues: &mut Vec<Issue>, passed: &mut Vec<String>) {
for (rule, found, ok) in [("clipping", clipped(x), "clipping: no flat-topped runs"), ("dropout", dropouts(x), "dropout: the sound never drops to silence and back")] {
if found.is_empty() {
passed.push(ok.into());
}
issues.extend(moments(rule, 1, found));
}
}
+4 -238
View File
@@ -1,243 +1,9 @@
use super::*;
use raea_app_check_flash::FlashScreen;
/// Flashing past WCAG 2.3.1: more than three flashes in any one second, over enough of the frame to matter. A flash is a
/// pair of opposing changes in the same pixels, so a shape sliding past isn't one. Each window, a third of the frame wide
/// and high, stands in for WCAG's quarter of a 10-degree field (the real area depends on the screen and how far away it
/// is, which a file doesn't say), and a quarter of its pixels must swing together: by 0.10 relative luminance with the
/// darker end under 0.80, or by 20 of saturated red ((R-G-B)*320, where R/(R+G+B) is at least 0.8). Every decoded frame
/// counts, on its own timestamp, and the picture is sampled twice, by area and by point, so fine patterns don't average
/// away. A screen for review, not a Harding or PEAT certification; an interlaced picture isn't split into its fields.
/// The width each frame is decoded at for the flashing screen (raea-app-check-flash: its rule and its windows), twice over:
/// the area sample and the point sample side by side
const FLASH_W: usize = 192;
const FLASH_MOST: usize = 6;
const FLASH_PAIR_S: f64 = 1.0 + 1e-9;
/// A pixel in one measure: its value, and whether it can count. Red's value runs on through the saturation line, and a change
/// counts when either end of it is saturated; a one-level step across the line isn't a jump from zero.
#[derive(Clone, Copy)]
struct Px {
value: f32,
counts: bool,
}
struct Swing {
at: f64,
direction: f32,
moved: Vec<bool>,
plain: bool,
kept: bool,
}
/// One window's swings in one measure: the ones an opposite swing within a second moves back in the same pixels. The
/// general measure leaves out swings where another quarter of the window moved the other way at once (a moving pattern).
struct Swings {
by: f32,
under: f32,
mixed_counts: bool,
pivot: Vec<Px>,
extreme: Vec<Px>,
at: f64,
direction: f32,
recent: std::collections::VecDeque<Swing>,
ends: Vec<f64>,
}
impl Swings {
fn new(by: f32, under: f32, mixed_counts: bool) -> Swings {
Swings { by, under, mixed_counts, pivot: Vec::new(), extreme: Vec::new(), at: 0.0, direction: 0.0, recent: Default::default(), ends: Vec::new() }
}
fn moves(&self, a: Px, b: Px, direction: f32) -> bool {
(b.value - a.value) * direction >= self.by && a.value.min(b.value) < self.under && (a.counts || b.counts)
}
fn changed(&self, earlier: &[Px], later: &[Px], direction: f32) -> bool {
earlier.iter().zip(later).filter(|(a, b)| self.moves(**a, **b, direction)).count() * 4 >= earlier.len()
}
fn push(&mut self, t: f64, px: &[Px]) {
if self.pivot.is_empty() {
self.pivot = px.to_vec();
self.extreme = px.to_vec();
self.at = t;
return;
}
if self.direction == 0.0 {
for direction in [1.0, -1.0] {
if self.changed(&self.pivot, px, direction) {
self.direction = direction;
self.extreme = px.to_vec();
self.at = t;
break;
}
}
return;
}
if self.changed(&self.extreme, px, -self.direction) {
self.record();
self.pivot = std::mem::replace(&mut self.extreme, px.to_vec());
self.at = t;
self.direction = -self.direction;
} else if self.changed(&self.pivot, px, self.direction) && self.went_further(px) {
self.extreme = px.to_vec();
}
}
/// Whether the pixels swinging from the pivot went further than the saved extreme, judged on those pixels alone: the
/// rest of the window can dim by less than counts and still outweigh a patch that's flashing.
fn went_further(&self, px: &[Px]) -> bool {
let further: f32 = self.pivot.iter().zip(px).zip(&self.extreme).filter(|((p, n), _)| self.moves(**p, **n, self.direction)).map(|((_, n), e)| (n.value - e.value) * self.direction).sum();
further > 0.0
}
fn record(&mut self) {
if !self.changed(&self.pivot, &self.extreme, self.direction) {
return;
}
let moved: Vec<bool> = self.pivot.iter().zip(&self.extreme).map(|(a, b)| self.moves(*a, *b, self.direction)).collect();
let plain = self.mixed_counts || !self.changed(&self.pivot, &self.extreme, -self.direction);
let (at, direction) = (self.at, self.direction);
let mut kept = false;
for other in self.recent.iter_mut().rev() {
if at - other.at > FLASH_PAIR_S {
break;
}
let same = moved.iter().zip(&other.moved).filter(|(x, y)| **x && **y).count();
if other.direction == -direction && same * 4 >= moved.len() {
other.kept = true;
kept = true;
}
}
self.recent.push_back(Swing { at, direction, moved, plain, kept });
while self.recent.front().is_some_and(|s| at - s.at > FLASH_PAIR_S) {
self.retire();
}
}
/// The oldest swing leaves the second it could still pair within; only the seconds' ends are kept for good.
fn retire(&mut self) {
if let Some(s) = self.recent.pop_front()
&& s.plain
&& s.kept
{
self.ends.push(s.at);
}
}
/// The most swings in any one second, and when that second starts.
fn busiest(&mut self) -> (usize, f64) {
if self.direction != 0.0 {
self.record();
self.direction = 0.0;
}
while !self.recent.is_empty() {
self.retire();
}
self.ends.sort_by(f64::total_cmp);
let (mut best, mut from, mut j) = (0, 0.0, 0);
for i in 0..self.ends.len() {
while self.ends[i] - self.ends[j] >= 1.0 - 1e-9 {
j += 1;
}
if i - j + 1 > best {
(best, from) = (i - j + 1, self.ends[j]);
}
}
(best, from)
}
}
/// Frames of two pictures side by side, each `w` by `h` RGB: the area sample and the point sample of one frame.
pub(crate) struct FlashScreen {
w: usize,
h: usize,
last: Vec<u8>,
linear: Vec<f32>,
luma: Vec<Px>,
red: Vec<Px>,
cut: Vec<Px>,
windows: Vec<(usize, usize, Swings, Swings)>,
}
impl FlashScreen {
pub(crate) fn new(w: usize, h: usize) -> FlashScreen {
let (ww, wh) = (w / 3, h / 3);
let places = |size: usize, window: usize| {
let mut at: Vec<usize> = (0..=size - window).step_by((size / 6).max(1)).collect();
at.push(size - window);
at.dedup();
at
};
let mut windows = Vec::new();
for sample in 0..2 {
for &y in &places(h, wh) {
for &x in &places(w, ww) {
windows.push((x + sample * w, y, Swings::new(0.10, 0.80, false), Swings::new(20.0, f32::INFINITY, true)));
}
}
}
let linear = (0..=255u32)
.map(|c| {
let c = c as f32 / 255.0;
if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) }
})
.collect();
FlashScreen { w, h, last: Vec::new(), linear, luma: Vec::new(), red: Vec::new(), cut: Vec::new(), windows }
}
pub(crate) fn push(&mut self, rgb: &[u8], t: f64) {
if rgb == self.last {
return;
}
self.luma.clear();
self.red.clear();
for px in rgb.chunks_exact(3) {
let (r, g, b) = (self.linear[px[0] as usize], self.linear[px[1] as usize], self.linear[px[2] as usize]);
self.luma.push(Px { value: 0.2126 * r + 0.7152 * g + 0.0722 * b, counts: true });
let sum = r + g + b + 1e-9;
self.red.push(Px { value: ((r - g - b) * 320.0).max(0.0), counts: r / sum >= 0.8 });
}
let (stride, ww, wh) = (self.w * 2, self.w / 3, self.h / 3);
for (x, y, general, saturated) in &mut self.windows {
self.cut.clear();
for r in 0..wh {
self.cut.extend_from_slice(&self.luma[(*y + r) * stride + *x..][..ww]);
}
general.push(t, &self.cut);
self.cut.clear();
for r in 0..wh {
self.cut.extend_from_slice(&self.red[(*y + r) * stride + *x..][..ww]);
}
saturated.push(t, &self.cut);
}
self.last.clear();
self.last.extend_from_slice(rgb);
}
/// (swings in the worst second, when it starts, which measure) when past the limit
pub(crate) fn finish(mut self) -> Option<(usize, f64, &'static str)> {
let mut worst: Option<(usize, f64, &'static str)> = None;
for (_, _, general, saturated) in &mut self.windows {
for (swings, kind) in [(general, "general"), (saturated, "red")] {
let (n, from) = swings.busiest();
if n > FLASH_MOST && worst.is_none_or(|w| n > w.0) {
worst = Some((n, from, kind));
}
}
}
worst
}
}
/// Every decoded frame, once: -fps_mode from FFmpeg 5.1 on, -vsync before it.
fn passthrough() -> [&'static str; 2] {
let out = Command::new("ffmpeg").args(["-hide_banner", "-version"]).output().map(|o| o.stdout).unwrap_or_default();
let head = String::from_utf8_lossy(&out);
let version = head.split("version ").nth(1).and_then(|v| {
let mut parts = v.trim_start_matches('n').split(|c: char| !c.is_ascii_digit());
Some((parts.next()?.parse::<u32>().ok()?, parts.next()?.parse::<u32>().ok()?))
});
[if version.is_some_and(|v| v < (5, 1)) { "-vsync" } else { "-fps_mode" }, "passthrough"]
}
/// A frame's number and time from showinfo's log, exact: its `pts` in ticks of the time base. `pts_time` is rounded to six
/// significant digits, which is enough to push a legal third flash across the one-second line.
@@ -269,7 +35,7 @@ pub(crate) fn flashing(video: &str, probe: &Probe, issues: &mut Vec<Issue>, pass
let w = FLASH_W;
let h = (((w as f64 * probe.h / probe.w.max(1.0)) / 2.0).round() as usize * 2).max(6);
let graph = format!("showinfo,split=2[area][point];[area]scale={w}:{h}:flags=area[a];[point]scale={w}:{h}:flags=neighbor[b];[a][b]hstack=inputs=2,format=rgb24");
let sync = passthrough();
let sync = raea_io_ffmpeg::passthrough();
let mut child = Command::new("ffmpeg")
.args(["-hide_banner", "-nostats", "-nostdin", "-loglevel", "level+info", "-i", video, "-map", "0:v:0", "-vf", &graph, sync[0], sync[1], "-f", "rawvideo", "-"])
.stdin(std::process::Stdio::null())
+204
View File
@@ -0,0 +1,204 @@
//! `raea hook [AGENT]` (docs/agents.feature A5d, A5e; docs/skills.feature SK10): one runner for every agent harness's
//! tool hooks, whichever harness runs the agent (Claude Code, Codex, Gemini CLI, Kimi Code; `raea skills install
//! --agent A` adds them, and they hold inside the raea app too, which leaves each agent its own shell). Before a shell
//! command: media opened in the Mac's viewer or a browser is stopped once while the raea app is installed, the reason
//! naming `raea show`; the same command tried again goes through, so an agent that means it says so twice. After a
//! file is saved: the quick check on a composition. A stop is exit 2 with the reason on stderr, which every harness
//! hands its agent; the quick check's findings go back in the shape each one reads.
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
type R<T> = Result<T, String>;
/// What a still, a video or a sound ends with: what the raea app shows as an item.
const MEDIA: [&str; 25] = ["png", "jpg", "jpeg", "gif", "webp", "heic", "heif", "tif", "tiff", "bmp", "avif", "exr", "mp4", "mov", "m4v", "webm", "mkv", "avi", "wav", "mp3", "m4a", "aac", "flac", "aif", "aiff"];
/// A stopped command tried again within this many seconds goes through.
const AGAIN: u64 = 600;
/// The harness that sent this input, when the hook's command doesn't name it: Gemini CLI names its events BeforeTool and
/// AfterTool, Kimi Code says its client; Claude Code and Codex share one shape.
fn agent_of(v: &Value) -> &'static str {
match (v["hook_event_name"].as_str().unwrap_or(""), v["client_type"].as_str().unwrap_or("")) {
("BeforeTool" | "AfterTool", _) => "gemini",
(_, c) if c.contains("kimi") => "kimi",
_ => "claude",
}
}
/// The shell command a tool call runs, if it's a shell tool's (Bash, shell, shell_command, exec_command,
/// run_shell_command): Codex's apply_patch carries its patch in `command` too, and isn't one.
fn shell_command(v: &Value) -> Option<&str> {
let cmd = v["tool_input"]["command"].as_str()?;
(v["tool_name"].as_str() != Some("apply_patch") && !cmd.trim_start().starts_with("*** Begin Patch")).then_some(cmd)
}
/// A shell segment's words, quotes taken off (enough for `open "a b.png"`, not a shell).
fn words(seg: &str) -> Vec<String> {
let (mut out, mut cur, mut quote, mut any) = (Vec::new(), String::new(), None, false);
for c in seg.chars() {
match (quote, c) {
(Some(q), c) if c == q => quote = None,
(Some(_), c) => cur.push(c),
(None, '\'' | '"') => (quote, any) = (Some(c), true),
(None, c) if c.is_whitespace() => {
if any || !cur.is_empty() {
out.push(std::mem::take(&mut cur));
}
any = false;
}
(None, c) => cur.push(c),
}
}
if any || !cur.is_empty() {
out.push(cur);
}
out
}
/// The media files a command opens in the Mac's viewer or a browser (`open`, `open -a Preview`, `xdg-open`,
/// `qlmanage -p`); `open -a raea`, `open -R` (Finder), links and other files aren't.
pub fn opened_media(cmd: &str) -> Vec<String> {
let mut found = Vec::new();
for seg in cmd.split(['\n', ';', '|', '&']) {
let w = words(seg);
let mut it = w.iter().skip_while(|t| t.contains('=') && !t.starts_with('-') || ["command", "exec", "nohup", "env"].contains(&t.as_str()));
let Some(tool) = it.next() else { continue };
if !["open", "xdg-open", "qlmanage"].contains(&tool.rsplit_once('/').map_or(tool.as_str(), |(_, name)| name)) {
continue;
}
// the files it names, apart from the app an -a or -b names; one naming raea, or Finder's -R, opens nothing here
let (mut files, mut app, mut ours) = (Vec::new(), false, false);
for t in it {
if app {
ours |= t.to_lowercase().contains("raea");
app = false;
} else if t == "-a" || t == "-b" {
app = true;
} else if t == "-R" {
ours = true;
} else if !t.starts_with('-') && !t.contains("://") && t.rsplit_once('.').is_some_and(|(_, e)| MEDIA.contains(&e.to_lowercase().as_str())) {
files.push(t.clone());
}
}
if !ours {
found.extend(files);
}
}
found
}
/// The raea app on this Mac (RAEA_APP, /Applications or ~/Applications).
fn app_installed(home: &str) -> bool {
[std::env::var("RAEA_APP").unwrap_or_default(), "/Applications/raea.app".into(), format!("{home}/Applications/raea.app")].iter().any(|p| !p.is_empty() && std::path::Path::new(p).exists())
}
/// True when this command was stopped for this session within AGAIN seconds (the agent's second yes, which clears it);
/// else it's noted and false.
fn tried_before(dir: &Path, key: &str) -> bool {
let h = key.bytes().fold(0xcbf29ce484222325u64, |h, b| (h ^ u64::from(b)).wrapping_mul(0x100000001b3));
let at = dir.join(format!("{h:016x}"));
let fresh = std::fs::metadata(&at).and_then(|m| m.modified()).ok().and_then(|t| t.elapsed().ok()).is_some_and(|e| e.as_secs() < AGAIN);
if fresh {
let _ = std::fs::remove_file(&at);
return true;
}
let _ = std::fs::create_dir_all(dir).and_then(|_| std::fs::write(&at, key));
false
}
/// Why the command stops, for the agent: what to run instead, and that the same command again goes through.
pub fn steer(files: &[String]) -> String {
let list = files.iter().map(|f| if f.contains(' ') { format!("{f:?}") } else { f.clone() }).collect::<Vec<_>>().join(" ");
format!("raea: the raea app is installed here, so show this in it, not the Mac's viewer: `raea show {list}` (several stills make a storyboard; add --ask \"what you want from the person\"; inside the raea app, feed_post does the same). It brings the app's window up on it as an item the person can answer, and their answer comes to the inbox file it prints. If the Mac's viewer really is what's wanted (the person asked for it, or raea show can't), run the same command again and it goes through.")
}
/// The files a tool call saved: `file_path` or `path` (Claude Code, Kimi Code, Gemini CLI), or the files an apply_patch
/// adds or updates (Codex).
fn saved(v: &Value) -> Vec<String> {
let i = &v["tool_input"];
if let Some(p) = i["file_path"].as_str().or(i["path"].as_str()).or(i["absolute_path"].as_str()) {
return vec![p.to_string()];
}
let patch = i["command"].as_str().or(i["input"].as_str()).unwrap_or("");
patch.lines().filter_map(|l| ["*** Add File: ", "*** Update File: "].iter().find_map(|head| l.strip_prefix(head))).map(str::trim).map(String::from).collect()
}
/// Findings for the agent in the shape its harness reads after a tool: Gemini CLI's AfterTool context, Kimi Code's
/// plain stdout, Claude Code's and Codex's PostToolUse context.
fn after(agent: &str, text: &str) -> String {
match agent {
"kimi" => text.to_string(),
"gemini" => json!({"hookSpecificOutput": {"hookEventName": "AfterTool", "additionalContext": text}}).to_string(),
_ => json!({"hookSpecificOutput": {"hookEventName": "PostToolUse", "additionalContext": text}}).to_string(),
}
}
/// `raea hook [claude|codex|gemini|kimi]`: the harness's hook input on stdin. Prints what goes back to the agent, or
/// stops the call (exit 2, the reason on stderr).
pub fn hook(args: &[String]) -> R<String> {
let named = args.first().map(String::as_str);
if named.is_some_and(|a| !["claude", "codex", "gemini", "kimi"].contains(&a)) {
return Err("usage: raea hook [claude|codex|gemini|kimi] (an agent's tool hooks; raea skills install --agent A adds them)".into());
}
let mut input = String::new();
std::io::Read::read_to_string(&mut std::io::stdin(), &mut input).map_err(|e| e.to_string())?;
let v: Value = serde_json::from_str(&input).unwrap_or_default();
let agent = named.unwrap_or_else(|| agent_of(&v));
if let Some(cmd) = shell_command(&v) {
let home = std::env::var("HOME").unwrap_or_default();
let files = opened_media(cmd);
let key = format!("{}\n{}\n{cmd}", v["session_id"].as_str().unwrap_or(""), v["cwd"].as_str().unwrap_or(""));
if !files.is_empty() && app_installed(&home) && !tried_before(&PathBuf::from(&home).join(".raea/hooks/again"), &key) {
eprintln!("{}", steer(&files));
std::process::exit(2);
}
return Ok(String::new());
}
let mut found = Vec::new();
for path in saved(&v).iter().filter(|p| p.ends_with(".tsx") && std::fs::read_to_string(p).is_ok_and(|t| t.contains("registerRoot"))) {
let (report, _) = crate::quick::quick(std::slice::from_ref(path), Vec::new())?;
found.extend(report.lines().skip(1).filter(|l| !l.starts_with("ok ")).map(String::from));
}
Ok(if found.is_empty() { String::new() } else { after(agent, &format!("raea check --quick after this save:\n{}", found.join("\n"))) })
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn media_opened_in_a_viewer_is_found_and_the_rest_isnt() {
assert_eq!(opened_media("open out/a.png out/b.PNG"), ["out/a.png", "out/b.PNG"]);
assert_eq!(opened_media("cd /tmp && open -a Preview \"sheet 1.jpg\""), ["sheet 1.jpg"]);
assert_eq!(opened_media("FOO=1 /usr/bin/open cut.mp4; echo done"), ["cut.mp4"]);
assert_eq!(opened_media("qlmanage -p still.webp >/dev/null 2>&1"), ["still.webp"]);
assert_eq!(opened_media("xdg-open take.mov"), ["take.mov"]);
for none in ["open -a raea", "open -a raea out/a.png", "open -R out/a.png", "open https://x.io/a.png", "open notes.pdf", "open .", "cat a.png", "git open a.png", "echo open a.png > x"] {
assert!(opened_media(none).is_empty(), "{none}: {:?}", opened_media(none));
}
}
#[test]
fn each_harness_is_told_apart_and_answered_in_its_shape() {
assert_eq!(agent_of(&json!({"hook_event_name": "BeforeTool", "tool_name": "run_shell_command"})), "gemini");
assert_eq!(agent_of(&json!({"hook_event_name": "PreToolUse", "client_type": "kimi_code_cli"})), "kimi");
assert_eq!(agent_of(&json!({"hook_event_name": "PreToolUse", "tool_name": "Bash"})), "claude");
assert_eq!(shell_command(&json!({"tool_name": "shell_command", "tool_input": {"command": "open a.png"}})), Some("open a.png"));
assert_eq!(shell_command(&json!({"tool_name": "apply_patch", "tool_input": {"command": "*** Begin Patch\n"}})), None);
assert_eq!(saved(&json!({"tool_input": {"command": "*** Begin Patch\n*** Update File: a/E.tsx\n@@\n*** Add File: b.ts\n"}})), ["a/E.tsx", "b.ts"]);
assert_eq!(saved(&json!({"tool_input": {"path": "E.tsx"}})), ["E.tsx"]);
assert_eq!(after("kimi", "x"), "x");
assert!(after("gemini", "x").contains("AfterTool") && after("codex", "x").contains("PostToolUse"));
assert!(steer(&["a b.png".into()]).contains("`raea show \"a b.png\"`"));
}
#[test]
fn the_same_command_again_goes_through_once() {
let d = std::env::temp_dir().join(format!("raea-hook-again-{}", std::process::id()));
assert!(!tried_before(&d, "s\n/x\nopen a.png"));
assert!(tried_before(&d, "s\n/x\nopen a.png"));
assert!(!tried_before(&d, "s\n/x\nopen a.png"), "a third try is a new first");
assert!(!tried_before(&d, "other\n/x\nopen a.png"));
let _ = std::fs::remove_dir_all(&d);
}
}
+96 -48
View File
@@ -1,4 +1,4 @@
//! `raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--shape 9:16]
//! `raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--things T.json] [--shape 9:16]
//! [--platform tiktok|reels|shorts] [-o check.json]`: the floor's measurable lines on an export (docs/craft-system.md, I; sdk/guides/craft/floor.md).
//! Each issue is ranked P0 (breaks the piece) to P3 (polish), with where it is and what to do. Rules on the file alone:
//! loudness and true peak, a steady sound that stops dead (a source run out, a cut with no fade), stretches where nothing
@@ -11,7 +11,7 @@
//! rules in their taste.ts files that carry a check (`{ text: "Captions sit clear of the bottom.", check: { form:
//! "text-above", value: 62 } }`), each a P1 when broken, since the person's rule beats the floor's default (docs/craft-system.md, J). Exits 1 when a P0 or P1 is found.
use serde_json::{Value, json};
use std::collections::BTreeMap;
use raea_core_facts::{Finding, Level, finding};
use std::process::Command;
mod sound;
@@ -20,9 +20,12 @@ mod picture;
use picture::*;
mod flash;
use flash::*;
mod defects;
use defects::*;
mod text;
use text::*;
pub mod quick;
pub mod hook;
#[cfg(test)]
mod tests;
@@ -39,35 +42,47 @@ struct Issue {
/// `raea check …` with the person's taste, none or more (taste.ts and the kinds beside it, which the raea CLI evaluates: it owns the engine):
/// its rules' checks hold the export to the person's own lines.
pub fn cli_with(args: &[String], tastes: Vec<raea_core_brief::Taste>) -> i32 {
match run(args, tastes) {
said(run(args, tastes), "REFUSED ")
}
/// A check's report printed, and its exit code: 1 when it found an error, 2 when it couldn't check (said after
/// `refused`). `raea check EDIT.tsx` (apps/direction) ends the same way.
pub fn said(ran: R<(String, bool)>, refused: &str) -> i32 {
match ran {
Ok((report, bad)) => {
println!("{report}");
i32::from(bad)
}
Err(e) => {
eprintln!("REFUSED {e}");
eprintln!("{refused}{e}");
2
}
}
}
/// A command's words: its arguments that are neither flags nor a flag's value (`takes`: the flags that take one).
/// What `raea check` checks is its first; `raea workspace` and `raea project` read theirs the same way.
pub fn words<'a>(args: &'a [String], takes: &[&str]) -> Vec<&'a str> {
args.iter().enumerate().filter(|(i, a)| !a.starts_with('-') && !(*i > 0 && takes.contains(&args[i - 1].as_str()))).map(|(_, a)| a.as_str()).collect()
}
fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> {
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).map(String::as_str)
}
pub const USAGE: &str = "raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--shape 16:9|9:16|4:5|1:1] [--platform tiktok|reels|shorts] [--taste taste.ts|DIR] [-o check.json] (an export against the floor: clipped text, contrast, safe areas, freezes, flashing, cues, loudness, blotching, a placeholder brand kit; P0-P3)";
pub const USAGE: &str = "raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--things T.json] [--shape 16:9|9:16|4:5|1:1] [--platform tiktok|reels|shorts] [--taste taste.ts|DIR] [-o check.json] (an export against the floor: clipped text, contrast, safe areas, freezes, flashing, cues, loudness, blotching, a placeholder brand kit, and with --things what `raea fingerprint things --json` found: a thing floating or passing through another, the camera lurching mid-move, an empty frame; its findings errors, warns and notes)";
/// A rule from the person's taste: a form raea can measure, its value, and the taste line it stands for.
#[derive(Clone, Debug, PartialEq)]
struct Taste {
form: String,
form: &'static str,
value: f64,
line: String,
}
/// The checks among a person's taste rules (taste.ts and its kinds), each with the line it stands for.
fn taste_rules(tastes: &[raea_core_brief::Taste]) -> Vec<Taste> {
tastes.iter().flat_map(|t| &t.sections).flat_map(|s| &s.rules).filter_map(|r| r.check.map(|c| Taste { form: c.form().to_string(), value: c.value(), line: r.text.clone() })).collect()
tastes.iter().flat_map(|t| &t.sections).flat_map(|s| &s.rules).filter_map(|r| r.check.map(|c| Taste { form: c.form(), value: c.value(), line: r.text.clone() })).collect()
}
fn taste_of<'a>(rules: &'a [Taste], form: &str) -> Option<&'a Taste> {
@@ -82,7 +97,7 @@ fn taste_text(rules: &[Taste], runs: &[Run], w: f64, h: f64, issues: &mut Vec<Is
for t in runs {
let [x, y, bw, bh] = t.box_;
let q = quote(&t.text);
let why = match r.form.as_str() {
let why = match r.form {
"text-hold" if t.to - t.from + 0.05 < r.value => Some(format!("{q} is on for {:.1} s, under your {:.1} s", t.to - t.from, r.value)),
"text-above" if y + bh > h * r.value / 100.0 + 1.0 => Some(format!("{q} reaches {:.0}% down the frame, below your {:.0}%", (y + bh) / h * 100.0, r.value)),
"text-below" if y < h * r.value / 100.0 - 1.0 => Some(format!("{q} starts {:.0}% down the frame, above your {:.0}%", y / h * 100.0, r.value)),
@@ -94,7 +109,7 @@ fn taste_text(rules: &[Taste], runs: &[Run], w: f64, h: f64, issues: &mut Vec<Is
};
if let Some(why) = why {
broke += 1;
issues.push(Issue { rule: "taste", p: 1, at: Some(t.from), says: format!("{why} (\"{}\")", r.line) });
issues.push(Issue { rule: r.form, p: 1, at: Some(t.from), says: format!("{why} (\"{}\")", r.line) });
}
}
if broke == 0 && r.form.starts_with("text-") {
@@ -104,17 +119,33 @@ fn taste_text(rules: &[Taste], runs: &[Run], w: f64, h: f64, issues: &mut Vec<Is
}
/// the flags `raea check` takes, each with a value
const TAKES: [&str; 7] = ["--manifest", "--words", "--perception", "--shape", "--platform", "--taste", "-o"];
const TAKES: [&str; 8] = ["--manifest", "--words", "--perception", "--things", "--shape", "--platform", "--taste", "-o"];
fn run(args: &[String], tastes: Vec<raea_core_brief::Taste>) -> R<(String, bool)> {
let video = args.iter().enumerate().find(|(i, a)| !a.starts_with('-') && !(*i > 0 && TAKES.contains(&args[i - 1].as_str()))).map(|(_, a)| a.clone()).ok_or(USAGE)?;
let (video, issues, passed, fps) = measured(args, taste_rules(&tastes))?;
report(&video, issues, Vec::new(), passed, flag(args, "-o"), fps)
}
/// raea's floor on a video (`args` as raea check takes them) as Findings, printed and kept nowhere: `raea check
/// EDIT.tsx` runs it on the composition's newest render beside its other checks (apps/direction, DR4). `held`: the
/// rules of the named checks it measures on the video itself (loudness, still-max), each its form, value and line.
/// `without`: its own rules that a named check holds there instead (`reading`, which text-read holds against when
/// a text can be read, not when it's on: DR28).
pub fn floor(args: &[String], held: &[(&'static str, f64, String)], without: &[&str]) -> R<Vec<Finding>> {
let held = held.iter().map(|(form, value, line)| Taste { form: *form, value: *value, line: line.clone() }).collect();
let (_, mut issues, _, fps) = measured(args, held)?;
issues.retain(|i| without.iter().all(|w| *w != i.rule));
Ok(findings_of(issues, Vec::new(), fps))
}
/// The video's issues and what passed, measured, and its frame rate.
fn measured(args: &[String], taste: Vec<Taste>) -> R<(String, Vec<Issue>, Vec<String>, f64)> {
let video = words(args, &TAKES).first().map(|v| v.to_string()).ok_or(USAGE)?;
if !std::path::Path::new(&video).exists() {
return Err(format!("no file at {video}\n{USAGE}"));
}
let probe = Probe::of(&video)?;
let mut issues = Vec::new();
let mut passed = Vec::new();
let taste = taste_rules(&tastes);
let (mut issues, mut passed) = (Vec::new(), Vec::new());
let manifest: Option<Value> = match flag(args, "--manifest") {
Some(m) => Some(serde_json::from_str(&std::fs::read_to_string(m).map_err(|e| format!("{m}: {e}"))?).map_err(|e| format!("{m}: {e}"))?),
None => None,
@@ -127,8 +158,12 @@ fn run(args: &[String], tastes: Vec<raea_core_brief::Taste>) -> R<(String, bool)
}
freezes(&video, &probe, taste_of(&taste, "still-max"), &mut issues, &mut passed)?;
flashing(&video, &probe, &mut issues, &mut passed)?;
flash_frame_rule(&video, &mut issues, &mut passed)?;
blotching(&video, &probe, &mut issues, &mut passed)?;
brand_kit(&[flag(args, "--manifest").unwrap_or(""), video.as_str()], &mut issues, &mut passed);
if let Some(p) = flag(args, "--things") {
things(p, &mut issues, &mut passed)?;
}
if let Some(manifest) = &manifest {
let runs = text_runs(manifest);
let (w, h) = (manifest["width"].as_f64().unwrap_or(probe.w), manifest["height"].as_f64().unwrap_or(probe.h));
@@ -143,36 +178,56 @@ fn run(args: &[String], tastes: Vec<raea_core_brief::Taste>) -> R<(String, bool)
face_cover(&runs, &faces, &mut issues, &mut passed);
}
}
report(&video, issues, passed, flag(args, "-o"))
Ok((video, issues, passed, fps))
}
/// The issues ranked, written to -o as JSON when asked, and the report's text; true when a P0 or P1 is among them.
fn report(video: &str, mut issues: Vec<Issue>, passed: Vec<String>, out: Option<&str>) -> R<(String, bool)> {
/// What `raea fingerprint things FILE --json` found (docs/fingerprint.feature FP13c): a thing floating, two passing
/// through each other, the camera lurching mid-move, an empty frame; measured there, from depth, masks and the camera's
/// path, never by a head
fn things(p: &str, issues: &mut Vec<Issue>, passed: &mut Vec<String>) -> R<()> {
let v: Value = serde_json::from_str(&std::fs::read_to_string(p).map_err(|e| format!("{p}: {e}"))?).map_err(|e| format!("{p}: {e}"))?;
let before = issues.len();
for i in v["issues"].as_array().into_iter().flatten() {
let Some(rule) = ["floating", "passing-through", "camera-speed", "empty-frame"].into_iter().find(|r| i["rule"] == *r) else { continue };
issues.push(Issue { rule, p: i["p"].as_u64().unwrap_or(2).min(3) as u8, at: i["at"].as_f64(), says: i["says"].as_str().unwrap_or_default().into() });
}
if issues.len() == before {
passed.push("things: nothing floats, passes through, lurches or is empty".into());
}
Ok(())
}
/// The issues as Findings (docs/direction.feature DR3: P0 and P1 errors, P2 a warn, P3 a note; a time is its frame at
/// `fps`), with `more` (a render's own), worst first then by time.
fn findings_of(mut issues: Vec<Issue>, more: Vec<Finding>, fps: f64) -> Vec<Finding> {
issues.sort_by(|a, b| a.p.cmp(&b.p).then(a.at.unwrap_or(0.0).total_cmp(&b.at.unwrap_or(0.0))));
let bad = issues.iter().any(|i| i.p <= 1);
let mut found = Vec::new();
for i in &issues {
// an issue at a second is about the frame it falls on
let (f, fr) = (Finding::new(i.rule, Level::of_rank(i.p), &i.says, "raea check"), (i.at.unwrap_or(0.0) * fps).round() as i64);
found.push(if i.at.is_some() { f.frames(fr, fr + 1) } else { f });
}
finding::ranked(found.into_iter().chain(more).collect())
}
/// The findings (`findings_of`), written to -o as JSON when asked, and the report's text with the count last. True
/// when an error is among them.
fn report(video: &str, issues: Vec<Issue>, more: Vec<Finding>, passed: Vec<String>, out: Option<&str>, fps: f64) -> R<(String, bool)> {
let found = findings_of(issues, more, fps);
let bad = found.iter().any(|f| f.level == Level::Error);
if let Some(out) = out {
let j = json!({
"file": video,
"issues": issues.iter().map(|i| json!({"rule": i.rule, "p": format!("P{}", i.p), "at": i.at, "says": i.says})).collect::<Vec<_>>(),
"passed": passed,
});
let j = json!({"file": video, "fps": fps, "findings": found, "passed": passed});
std::fs::write(out, serde_json::to_string_pretty(&j).unwrap()).map_err(|e| format!("{out}: {e}"))?;
}
let mut by = BTreeMap::new();
for i in &issues {
*by.entry(i.p).or_insert(0) += 1;
let mut s = format!("raea check {video}\n");
// kept in its project's record beside its renders (DR3), what `raea findings` and `raea next` read
let kept = raea_core_facts::record::keep("raea check", std::path::Path::new(video), out.map(std::path::Path::new), &found, vec![], &raea_io_trace::utc(std::time::SystemTime::now()).1);
let kept = kept.map(|e| format!("raea check: kept in the project's record as {} (raea findings reads it)", e.id));
for line in found.iter().map(Finding::line).chain(passed.iter().map(|p| format!("ok {p}"))).chain(kept) {
s.push_str(&line);
s.push('\n');
}
let counts = by.iter().map(|(p, n)| format!("P{p} {n}")).collect::<Vec<_>>().join(", ");
let mut s = format!("raea check {}: {}\n", video, if issues.is_empty() { "nothing to fix".to_string() } else { format!("{} to fix ({counts})", issues.len()) });
for i in &issues {
let at = i.at.map(|t| format!("{t:6.2} s")).unwrap_or_else(|| " ".into());
s.push_str(&format!("P{} {:<9} {at} {}\n", i.p, i.rule, i.says));
}
for p in &passed {
s.push_str(&format!("ok {p}\n"));
}
Ok((s.trim_end().to_string(), bad))
Ok((s + &format!("raea check: {}", finding::count(&found)), bad))
}
struct Probe {
@@ -200,10 +255,8 @@ fn last_packet_end(video: &str) -> Option<f64> {
impl Probe {
fn of(video: &str) -> R<Probe> {
let out = Command::new("ffprobe")
.args(["-v", "error", "-show_entries", "stream=codec_type,width,height,r_frame_rate,duration,start_time:format=duration,start_time", "-of", "json", video])
.output()
.map_err(|e| format!("ffprobe: {e}"))?;
let entries = "stream=codec_type,width,height,r_frame_rate,duration,start_time:format=duration,start_time";
let out = Command::new("ffprobe").args(["-v", "error", "-show_entries", entries, "-of", "json", video]).output().map_err(|e| format!("ffprobe: {e}"))?;
let v: Value = serde_json::from_slice(&out.stdout).map_err(|e| format!("ffprobe: {e}"))?;
let streams = v["streams"].as_array().cloned().unwrap_or_default();
let vid = streams.iter().find(|s| s["codec_type"] == "video").ok_or("no video stream")?;
@@ -214,12 +267,7 @@ impl Probe {
Some(length) => seconds(&vid["start_time"]).unwrap_or(origin) - origin + length,
None => last_packet_end(video).map_or(duration, |end| end - origin),
};
Ok(Probe {
w: vid["width"].as_f64().unwrap_or(1920.0),
h: vid["height"].as_f64().unwrap_or(1080.0),
duration,
picture,
audio: streams.iter().any(|s| s["codec_type"] == "audio"),
})
let audio = streams.iter().any(|s| s["codec_type"] == "audio");
Ok(Probe { w: vid["width"].as_f64().unwrap_or(1920.0), h: vid["height"].as_f64().unwrap_or(1080.0), duration, picture, audio })
}
}
+38 -50
View File
@@ -1,87 +1,75 @@
//! `raea check EDIT.tsx --quick` and `raea hook claude` (docs/skills.feature SK10). The quick check renders three stills
//! of a composition (a quarter in, the middle, the last frame) with their manifest, about a second, and runs the full
//! check's text rules and the person's text taste on it: clipped and cramped text, safe areas, sizes. The hook is
//! Claude Code's PostToolUse command (`raea skills install --agent claude` adds it): after a .tsx that registers a root
//! is written, the quick check's findings go back to the agent; a clean check says nothing.
//! `raea check EDIT.tsx --quick` (docs/skills.feature SK10). The quick check renders three stills of a composition (a
//! quarter in, the middle, the last frame, of the length frame 0's render reports) with their manifest, and runs the text rules
//! and the person's text taste on it: clipped and cramped text, safe areas, sizes. Every agent's after-save hook runs
//! it (hook.rs): after a .tsx that registers a root is saved, its findings go back to the agent; a clean check says
//! nothing.
use super::*;
use std::path::Path;
/// The composition's length in frames, read from its source (the first `durationInFrames={N}`), 90 without one.
fn frames(src: &str) -> u64 {
src.split("durationInFrames={").nth(1).and_then(|r| r.split('}').next()).and_then(|n| n.trim().parse().ok()).unwrap_or(90)
/// The stills' frames: a quarter in, the middle and the last of the length a render reports (render.json's `length`,
/// the composition's own however it's written; #86 read its source's `durationInFrames={N}` and took 90 for a name).
fn samples(m: &Value) -> Option<[u64; 3]> {
let n = m["length"].as_u64()?.max(1);
Some([n / 4, n / 2, n - 1])
}
/// `raea check EDIT.tsx --quick [--shape S] [--platform P] [-o check.json]`: (report, P0 or P1 found). `tastes` are the
/// person's, evaluated by the raea CLI when --taste names them.
pub fn quick(args: &[String], tastes: Vec<raea_core_brief::Taste>) -> R<(String, bool)> {
let file = args.iter().find(|a| a.ends_with(".tsx")).ok_or("raea check --quick takes a composition: EDIT.tsx")?;
let src = std::fs::read_to_string(file).map_err(|e| format!("{file}: {e}"))?;
let n = frames(&src).max(1);
let at = format!("{},{},{}", n / 4, n / 2, n - 1);
let tmp = std::env::temp_dir().join(format!("raea-quick-{}", std::process::id()));
std::fs::create_dir_all(&tmp).map_err(|e| format!("{}: {e}", tmp.display()))?;
let manifest = tmp.join("render.json");
let me = std::env::current_exe().map_err(|e| e.to_string())?;
let out = std::process::Command::new(me).arg("render").arg(file).args(["--at", &at, "-o"]).arg(format!("{}/", tmp.display())).arg("--manifest").arg(&manifest).output().map_err(|e| e.to_string())?;
let result = if out.status.success() {
on_manifest(file, &manifest, args, tastes)
// the stills are part of this check, which keeps the one entry in the project's record (DR3)
let render = |at: &str| std::process::Command::new(&me).arg("render").arg(file).args(["--at", at, "-o"]).arg(format!("{}/", tmp.display())).arg("--manifest").arg(&manifest).env("RAEA_RECORD", "off").output().map_err(|e| e.to_string());
// frame 0 first, for the length (its manifest's), then the three stills
let mut out = render("0")?;
let at = std::fs::read_to_string(&manifest).ok().and_then(|t| samples(&serde_json::from_str(&t).ok()?));
if let Some(at) = at {
let _ = std::fs::remove_file(&manifest);
out = render(&at.map(|f| f.to_string()).join(","))?;
}
// rendered when its manifest was written: a render whose stills clip exits 1 (DR3), and those findings are read here
let result = if let (Some(at), true) = (at, manifest.is_file()) {
on_manifest(file, &manifest, args, tastes, at)
} else {
// a render that fails is the finding: the agent sees why
let (err, out) = (String::from_utf8_lossy(&out.stderr), String::from_utf8_lossy(&out.stdout));
let mut why = Vec::new();
for line in err.lines().chain(out.lines()) {
if line.contains("REFUSED") || line.contains("rror") {
why.push(line);
}
}
let why = why.join("\n");
Ok((format!("raea check {file}: it doesn't render\nP0 render {why}"), true))
let why: Vec<&str> = err.lines().chain(out.lines()).filter(|l| l.contains("REFUSED") || l.contains("rror")).collect();
let f = raea_core_facts::Finding::new("render", raea_core_facts::Level::Error, why.join("\n"), "raea check --quick");
Ok((format!("raea check {file}: it doesn't render\n{}\nraea check: {}", f.line(), raea_core_facts::finding::count(&[f])), true))
};
let _ = std::fs::remove_dir_all(&tmp);
result
}
/// `raea hook claude`: Claude Code's PostToolUse input on stdin; for a saved composition, the quick check's findings as
/// the hook's additionalContext. Anything else, or a clean check, prints nothing.
pub fn hook(args: &[String]) -> R<String> {
if args.first().map(String::as_str) != Some("claude") {
return Err("usage: raea hook claude (Claude Code's PostToolUse hook; raea skills install --agent claude adds it)".into());
}
let mut input = String::new();
std::io::Read::read_to_string(&mut std::io::stdin(), &mut input).map_err(|e| e.to_string())?;
let v: serde_json::Value = serde_json::from_str(&input).unwrap_or_default();
let path = v["tool_input"]["file_path"].as_str().unwrap_or_default();
let composition = path.ends_with(".tsx") && std::fs::read_to_string(path).map(|t| t.contains("registerRoot")).unwrap_or(false);
if !composition {
return Ok(String::new());
}
let (report, _) = quick(&[path.to_string()], Vec::new())?;
if report.lines().nth(1).is_none_or(|l| l.starts_with("ok ")) {
return Ok(String::new());
}
let found: Vec<&str> = report.lines().filter(|l| !l.starts_with("ok ")).collect();
Ok(json!({"hookSpecificOutput": {"hookEventName": "PostToolUse", "additionalContext": format!("raea check --quick after this save:\n{}", found.join("\n"))}}).to_string())
}
/// `raea check --quick`'s half (docs/skills.feature SK10): the text rules and the person's text taste on the manifest
/// of a few stills (`raea render EDIT.tsx --at ... --manifest`), no video. What it can't see (contrast, freezes,
/// sound, blotching) waits for the full check on the export.
fn on_manifest(file: &str, manifest: &Path, args: &[String], tastes: Vec<raea_core_brief::Taste>) -> R<(String, bool)> {
fn on_manifest(file: &str, manifest: &Path, args: &[String], tastes: Vec<raea_core_brief::Taste>, [a, b, c]: [u64; 3]) -> R<(String, bool)> {
let at = manifest.display();
let m: Value = serde_json::from_str(&std::fs::read_to_string(manifest).map_err(|e| format!("{at}: {e}"))?).map_err(|e| format!("{at}: {e}"))?;
let (mut issues, mut passed) = (Vec::new(), Vec::new());
let (mut issues, mut passed) = (Vec::new(), vec![format!("looked at frames {a}, {b} and {c} of {}", c + 1)]);
let runs = text_runs(&m);
let (w, h) = (m["width"].as_f64().unwrap_or(1080.0), m["height"].as_f64().unwrap_or(1920.0));
text_rules(&runs, None, w, h, flag(args, "--shape"), flag(args, "--platform"), &mut issues, &mut passed);
taste_text(&taste_rules(&tastes), &runs, w, h, &mut issues, &mut passed);
report(file, issues, passed, flag(args, "-o"))
// and what the render of the stills found (the 3D's clipping, DR3)
let more = serde_json::from_value(m["findings"].clone()).unwrap_or_default();
report(file, issues, more, passed, flag(args, "-o"), m["fps"].as_f64().unwrap_or(30.0))
}
#[cfg(test)]
mod tests {
use serde_json::json;
/// the length is the render's, so a `durationInFrames={DUR}` (#86: 300 frames, read as 90) is sampled to its end
#[test]
fn frames_come_from_the_source() {
assert_eq!(super::frames("<Composition durationInFrames={240} fps={30} />"), 240);
assert_eq!(super::frames("no composition"), 90);
fn frames_come_from_the_render() {
assert_eq!(super::samples(&json!({"length": 240})), Some([60, 120, 239]));
assert_eq!(super::samples(&json!({"length": 300})), Some([75, 150, 299]));
assert_eq!(super::samples(&json!({"length": 1})), Some([0, 0, 0]));
// a render that reported no length: no stills to look at, so the frame-0 render's failure is the finding
assert_eq!(super::samples(&json!({"width": 640})), None);
}
}
+13 -9
View File
@@ -27,6 +27,12 @@ pub(crate) fn pct(v: &[f64], q: f64) -> f64 {
/// a bed that stops under a voice shows in the band the voice doesn't fill (a projector's clatter in the highs). A band's
/// level is its share of the step's mean square (Parseval, undoing the Hann window's power), so a tone reads the same in
/// its band as in the mix
/// A stretch of sound's level in dB (its RMS)
pub(crate) fn db(f: &[f32]) -> f64 {
let ms = f.iter().map(|&v| (v as f64).powi(2)).sum::<f64>() / f.len().max(1) as f64;
20.0 * (ms.sqrt() + 1e-9).log10()
}
pub(crate) fn levels(x: &[f32]) -> (Vec<f64>, [Vec<f64>; 3]) {
use std::f64::consts::PI;
let n = x.len() / HOP;
@@ -44,8 +50,7 @@ pub(crate) fn levels(x: &[f32]) -> (Vec<f64>, [Vec<f64>; 3]) {
let scale = 2.0 / (HOP * HOP) as f64 / (hann.iter().map(|h| h * h).sum::<f64>() / HOP as f64);
let (mut rms, mut bands) = (Vec::with_capacity(n), [Vec::with_capacity(n), Vec::with_capacity(n), Vec::with_capacity(n)]);
for f in x.chunks_exact(HOP) {
let ms = f.iter().map(|&v| (v as f64).powi(2)).sum::<f64>() / HOP as f64;
rms.push(20.0 * (ms.sqrt() + 1e-9).log10());
rms.push(db(f));
let w: Vec<f64> = f.iter().zip(&hann).map(|(&v, h)| v as f64 * h).collect();
let mut e = [0.0; 3];
for (b, tw) in &bins {
@@ -163,7 +168,8 @@ pub(crate) fn sound(video: &str, words: Option<&[Word]>, issues: &mut Vec<Issue>
}
let x: Vec<f32> = out.stdout.chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect();
let (rms, bands) = levels(&x);
let found = |list: Vec<(f64, String)>, p: u8| list.into_iter().map(move |(at, says)| Issue { rule: "sound", p, at: Some(at), says });
sound_defects(&x, issues, passed);
let found = |list: Vec<(f64, String)>, p: u8| crate::defects::moments("sound", p, list);
let stops = dead_stops(&rms, &bands);
if stops.is_empty() {
passed.push("sound: no steady sound stops dead".into());
@@ -206,17 +212,15 @@ pub(crate) fn ffmpeg_stderr(args: &[&str]) -> R<String> {
/// -14 LUFS integrated (±1) and a true peak at or below -1 dBTP (the floor's mix line)
pub(crate) fn loudness(video: &str, taste: Option<&Taste>, issues: &mut Vec<Issue>, passed: &mut Vec<String>) -> R<()> {
let err = ffmpeg_stderr(&["-hide_banner", "-nostats", "-i", video, "-vn", "-af", "ebur128=peak=true", "-f", "null", "-"])?;
let summary = err.rsplit("Summary:").next().unwrap_or("");
let num = |key: &str| summary.lines().find(|l| l.trim_start().starts_with(key)).and_then(|l| l.split_whitespace().nth(1)).and_then(|x| x.parse::<f64>().ok());
let (Some(i), peak) = (num("I:"), num("Peak:")) else { return Ok(()) };
// the same measure `raea world` joins to a render as its Mix (raea-sys-measure, DR2)
let Some((i, peak)) = raea_sys_measure::loudness(std::path::Path::new(video)) else { return Ok(()) };
let mut ok = true;
let target = taste.map_or(-14.0, |t| t.value);
if (i - target).abs() > 1.0 {
ok = false;
let says = format!("{i:.1} LUFS integrated; master at {target} (±1) with <Mix lufs={{{target}}} />");
issues.push(match taste {
Some(t) => Issue { rule: "taste", p: 1, at: None, says: format!("{says} (\"{}\")", t.line) },
Some(t) => Issue { rule: t.form, p: 1, at: None, says: format!("{says} (\"{}\")", t.line) },
None => Issue { rule: "loudness", p: 1, at: None, says },
});
}
@@ -258,7 +262,7 @@ pub(crate) fn freezes(video: &str, probe: &Probe, taste: Option<&Taste>, issues:
for &(s, d) in &stretches {
let says = format!("nothing changes for {d:.1} s; give it a reason to hold, or cut it shorter");
issues.push(match taste {
Some(t) => Issue { rule: "taste", p: 1, at: Some(s), says: format!("{says} (\"{}\")", t.line) },
Some(t) => Issue { rule: t.form, p: 1, at: Some(s), says: format!("{says} (\"{}\")", t.line) },
None => Issue { rule: "frozen", p: if d >= 6.0 || d >= probe.duration * 0.5 { 1 } else { 2 }, at: Some(s), says },
});
}
+91 -92
View File
@@ -64,8 +64,8 @@ fn taste_checks_hold_text_to_the_persons_line() {
]}]})).unwrap();
let rules = taste_rules(&[taste]);
assert_eq!(rules, vec![
Taste { form: "text-above".into(), value: 62.0, line: "Captions sit clear of the bottom.".into() },
Taste { form: "text-hold".into(), value: 2.0, line: "Text holds two seconds".into() },
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 };
@@ -73,7 +73,7 @@ fn taste_checks_hold_text_to_the_persons_line() {
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();
// the low caption breaks the placement line (860 of 1080 is 80%); the short one breaks the hold
assert_eq!(says, vec![("taste", 1, Some(1.0)), ("taste", 1, Some(5.0))]);
assert_eq!(says, vec![("text-above", 1, Some(1.0)), ("text-hold", 1, Some(5.0))], "a taste line is the named check of its form (DR4)");
}
/// `RAEA_CHECK_ARGS="film.mp4 --manifest film.render.json --taste DIR" cargo test -p raea-runtime-react --lib
@@ -292,72 +292,6 @@ fn a_sign_the_camera_carries_off_isnt_clipped_but_a_title_held_off_is() {
assert_eq!(rules, vec![("safe-area", "THE NIGHT MARKET".to_string()), ("clipped", "WIDE".to_string())]);
}
/// a 96x54 picture drawn by `paint(frame index, sample, x, y)`, sample 0 the area sample and 1 the point sample, for
/// `frames` frames at `fps`
fn flash_samples(frames: usize, fps: f64, paint: impl Fn(usize, usize, usize, usize) -> [u8; 3]) -> Option<(usize, f64, &'static str)> {
let (w, h) = (96, 54);
let mut screen = FlashScreen::new(w, h);
for f in 0..frames {
let mut rgb = Vec::with_capacity(w * 2 * h * 3);
for y in 0..h {
for sample in 0..2 {
for x in 0..w {
rgb.extend_from_slice(&paint(f, sample, x, y));
}
}
}
screen.push(&rgb, f as f64 / fps);
}
screen.finish()
}
fn flash_of(seconds: usize, paint: impl Fn(usize, usize, usize) -> [u8; 3]) -> Option<(usize, f64, &'static str)> {
flash_samples(seconds * 60, 60.0, move |f, _, x, y| paint(f, x, y))
}
/// two colours taking turns `hz` times a second, over a box of the frame
fn turns(hz: usize, on: [u8; 3], off: [u8; 3], bx: (usize, usize, usize, usize)) -> Option<(usize, f64, &'static str)> {
flash_of(3, move |f, x, y| {
let inside = x >= bx.0 && x < bx.0 + bx.2 && y >= bx.1 && y < bx.1 + bx.3;
if inside && f * hz * 2 / 60 % 2 == 0 { on } else { off }
})
}
#[test]
fn flashing_is_found_past_three_a_second_and_not_at_it() {
let (white, black) = ([255, 255, 255], [0, 0, 0]);
let all = (0, 0, 96, 54);
assert_eq!(turns(3, white, black, all), None, "three a second is the limit, not past it");
let (swings, _, kind) = turns(4, white, black, all).expect("four a second");
assert_eq!((swings / 2, kind), (4, "general"));
// a small box: under a quarter of any window, and then over it
assert_eq!(turns(5, white, black, (40, 20, 10, 10)), None);
assert!(turns(5, white, black, (30, 18, 32, 18)).is_some());
// too small a change, and both ends too bright for WCAG to count it
assert_eq!(turns(5, [60, 60, 60], [30, 30, 30], all), None);
assert_eq!(turns(5, [255, 255, 255], [235, 235, 235], all), None);
// a dark saturated red: too dim to count as a general flash, past the limit as a red one
assert_eq!(turns(5, [150, 0, 0], black, all).map(|t| t.2), Some("red"));
}
#[test]
fn a_flash_of_single_frames_counts_at_any_frame_rate() {
// 120 fps with one white frame in every 30: four flashes a second, each gone within a sixtieth of a second
let found = flash_samples(360, 120.0, |f, _, _, _| if f % 30 == 1 { [255, 255, 255] } else { [0, 0, 0] });
assert_eq!(found.map(|(swings, _, kind)| (swings / 2, kind)), Some((4, "general")));
}
#[test]
fn a_flash_the_area_sample_averages_away_is_found_in_the_point_sample() {
let found = flash_samples(180, 60.0, |f, sample, _, _| {
if sample == 0 {
return [128, 128, 128];
}
if f * 5 * 2 / 60 % 2 == 0 { [255, 255, 255] } else { [0, 0, 0] }
});
assert!(found.is_some(), "the same flash in the point sample alone");
}
#[test]
fn a_frame_gets_its_exact_time_from_the_log() {
// lines FFmpeg 9.0.2 logged with -loglevel level+info
@@ -382,34 +316,99 @@ fn only_a_lines_own_severity_counts_as_an_error() {
assert_eq!(log_level("frame= 300 fps=0.0"), None);
}
/// A centred line in a left: 0; right: 0 box isn't in the left zone: its letters are tested where the render recorded
/// them (#89); a left-aligned one is, the finding naming the edge, and a manifest without ink is tested by the box.
#[test]
fn a_shape_sliding_past_and_ordinary_cuts_are_not_flashing() {
let (white, black) = ([255, 255, 255], [0, 0, 0]);
assert_eq!(flash_of(3, move |f, x, _| if x < f { white } else { black }), None, "one wipe across the frame");
assert_eq!(flash_of(4, move |f, _, _| if (f / 30) % 2 == 0 { white } else { black }), None, "a cut every half second");
fn safe_area_tests_the_letters_not_the_box() {
let safe_area = |ink: Value| {
let m = json!({"fps": 1.0, "frames": [{"frame": 0, "text": [{"text": "centred", "box": [0, 160, 640, 40], "ink": ink}]}]});
let (mut issues, mut passed) = (vec![], vec![]);
text_rules(&text_runs(&m), None, 640.0, 360.0, None, None, &mut issues, &mut passed);
issues.into_iter().filter(|i| i.rule == "safe-area").map(|i| i.says).collect::<String>()
};
assert_eq!(safe_area(json!([250, 160, 140, 40])), "");
let left = safe_area(json!([0, 160, 140, 40]));
assert!(left.contains("at the left") && left.contains("its letters 0,160 140x40"), "{left}");
assert!(safe_area(Value::Null).contains("its box 0,160 640x40"));
}
#[test]
fn a_patch_strobing_while_its_background_dims_is_still_found() {
// a third of a window: 0 then 124 on a 148 background, then the background settles at 124 and the patch cycles 124 and 160.
// The background's drop is under the 0.10 that counts, but it outweighs the patch in the window's mean.
let found = flash_samples(180, 60.0, |f, _, x, y| {
let patch = x < 16 && y < 12;
let level = match (patch, f) {
(true, 0) => 0,
(true, 1) => 124,
(true, _) => if (f - 2) * 5 * 2 / 60 % 2 == 0 { 160 } else { 124 },
(false, 0 | 1) => 148,
(false, _) => 124,
};
[level, level, level]
});
assert!(found.is_some(), "the patch flashes five times a second");
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 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![]);
// one word of three shared with the line, said 1.35 s before: not a caption of it (the film's false P1)
cues(&[run("Wirestock × OpenAI Sora", 39.55)], &words, &mut issues, &mut passed);
// one word of four, "campaign": the same
cues(&[run("Classroom of Tomorrow campaign", 39.55)], &words, &mut issues, &mut passed);
assert!(issues.is_empty(), "{:?}", issues.iter().map(|i| &i.says).collect::<Vec<_>>());
// a one-word card is held only to the word said right by it: "wirestock" 1.35 s earlier is another moment
cues(&[run("Wirestock", 39.55)], &words, &mut issues, &mut passed);
assert!(issues.is_empty(), "{:?}", issues.iter().map(|i| &i.says).collect::<Vec<_>>());
// a real caption late by 0.4 s is still found
cues(&[run("a Sora campaign", 39.7)], &words, &mut issues, &mut passed);
assert_eq!(issues.len(), 1, "{:?}", issues.iter().map(|i| &i.says).collect::<Vec<_>>());
}
#[test]
fn a_colour_crossing_the_saturation_line_is_not_a_red_flash() {
// one level of green moves the pixel across R/(R+G+B) = 0.8 and hardly changes its red at all
let found = flash_samples(180, 60.0, |f, _, _, _| if f * 5 * 2 / 60 % 2 == 0 { [100, 49, 0] } else { [100, 50, 0] });
assert_eq!(found, None);
fn clipping_is_found_and_a_loud_clean_tone_isnt() {
// a clean tone near full scale, then the same tone clamped (a limiter's flat tops), then pushed past full scale
let loud = tone(3.0, &[(0.0, 3.0, -1.0)]);
assert!(clipped(&loud).is_empty(), "{:?}", clipped(&loud));
let clamped: Vec<f32> = loud.iter().map(|v| (v * 10.0).clamp(-0.3, 0.3)).collect();
assert_eq!(clipped(&clamped).len(), 1);
let over: Vec<f32> = loud.iter().map(|v| (v * 2.0).clamp(-1.0, 1.0)).collect();
assert_eq!(clipped(&over).len(), 1);
// one transient hitting full scale once isn't clipping
let mut once = tone(3.0, &[(0.0, 3.0, -20.0)]);
once[SR] = 1.0;
assert!(clipped(&once).is_empty());
}
#[test]
fn a_dropout_is_found_and_a_faded_pause_isnt() {
// a bed at -20 dBFS with 0.6 s cut out of it, as the bootstrap's dropout does
let mut cut = tone(4.0, &[(0.0, 4.0, -20.0)]);
cut[(1.7 * SR as f64) as usize..(2.3 * SR as f64) as usize].iter_mut().for_each(|v| *v = 0.0);
let found = dropouts(&cut);
assert_eq!(found.len(), 1, "{found:?}");
assert!((found[0].0 - 1.7).abs() < 0.02, "{found:?}");
// a pause that fades out over 300 ms and back in isn't one, nor a sound that stops and stays stopped
let gain = |t: f32| ((1.7 - t) / 0.3).max((t - 2.3) / 0.3).clamp(0.0, 1.0);
let paused: Vec<f32> = tone(4.0, &[(0.0, 4.0, -20.0)]).into_iter().enumerate().map(|(i, v)| v * gain(i as f32 / SR as f32)).collect();
assert!(dropouts(&paused).is_empty(), "{:?}", dropouts(&paused));
assert!(dropouts(&tone(4.0, &[(0.0, 2.0, -20.0)])).is_empty());
}
#[test]
fn a_flash_frame_is_found_and_a_cut_or_a_fade_isnt() {
let mut shot = vec![0.5f32; 60];
shot[30] = 0.0;
assert_eq!(flash_frames(&shot, 30.0).len(), 1);
shot[31] = 0.0;
assert_eq!(flash_frames(&shot, 30.0).len(), 1, "two frames are one flash");
let cut: Vec<f32> = (0..60).map(|i| if i < 30 { 0.6 } else { 0.1 }).collect();
assert!(flash_frames(&cut, 30.0).is_empty());
let fade: Vec<f32> = (0..60).map(|i| 0.6 * (1.0 - i as f32 / 59.0)).collect();
assert!(flash_frames(&fade, 30.0).is_empty());
// a white frame, too
let mut white = vec![0.3f32; 20];
white[10] = 1.0;
assert_eq!(flash_frames(&white, 30.0)[0].0, 10.0 / 30.0);
}
#[test]
fn things_found_are_findings_and_an_unknown_rule_is_not() {
let p = std::env::temp_dir().join(format!("raea-check-things-{}.json", std::process::id()));
let found = r#"{"issues": [{"rule": "floating", "p": 2, "at": 1.5, "to": 3.0, "says": "cup floats"}, {"rule": "made-up", "p": 0, "at": 0.0, "says": "x"}]}"#;
std::fs::write(&p, found).unwrap();
let (mut issues, mut passed) = (Vec::new(), Vec::new());
things(p.to_str().unwrap(), &mut issues, &mut passed).unwrap();
assert_eq!(issues.iter().map(|i| (i.rule, i.p, i.at)).collect::<Vec<_>>(), [("floating", 2, Some(1.5))]);
std::fs::write(&p, r#"{"issues": []}"#).unwrap();
things(p.to_str().unwrap(), &mut Vec::new(), &mut passed).unwrap();
let _ = std::fs::remove_file(&p);
assert_eq!(passed.len(), 1, "nothing found is a pass");
}
+29 -63
View File
@@ -8,7 +8,8 @@ pub(crate) struct Run {
pub(crate) from: f64,
pub(crate) to: f64,
pub(crate) box_: [f64; 4],
/// its box on every frame it shows its whole text: a text the camera carries (a sign on a panning street) moves
/// where its letters are on every frame it shows its whole text (the manifest's `ink`, else its box: a centred line in
/// 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(crate) boxes: Vec<[f64; 4]>,
pub(crate) color: String,
@@ -61,7 +62,8 @@ pub(crate) fn text_runs(manifest: &Value) -> Vec<Run> {
let mut next = Vec::new();
for x in shown {
let text = x["text"].as_str().unwrap_or("").trim().to_string();
let b = x["box"].as_array().map(|b| [0, 1, 2, 3].map(|i| b.get(i).and_then(Value::as_f64).unwrap_or(0.0))).unwrap_or([0.0; 4]);
let quad = |k: &str| x[k].as_array().map(|b| [0, 1, 2, 3].map(|i| b.get(i).and_then(Value::as_f64).unwrap_or(0.0)));
let (b, ink) = (quad("box").unwrap_or([0.0; 4]), quad("ink"));
let k = key(&text);
let found = open.iter().position(|r| {
let rk = key(&r.text);
@@ -77,7 +79,7 @@ pub(crate) fn text_runs(manifest: &Value) -> Vec<Run> {
if text.len() >= r.text.len() {
r.text = text;
r.box_ = b;
r.boxes.push(b);
r.boxes.push(ink.unwrap_or(b));
}
r.to = t + 1.0 / fps;
r.color = x["color"].as_str().unwrap_or("rgb(255, 255, 255)").to_string();
@@ -169,7 +171,9 @@ pub(crate) fn text_rules(runs: &[Run], heard: Option<&[Word]>, w: f64, h: f64, s
issues.push(Issue { rule: "clipped", p: 0, at: Some(r.from), says: format!("{q} runs off the frame (box {x:.0},{y:.0} {bw:.0}x{bh:.0} in {w:.0}x{h:.0}); fit it or break the line") });
} else if r.boxes.iter().all(zoned) {
unsafe_ += 1;
issues.push(Issue { rule: "safe-area", p: 1, at: Some(r.from), says: format!("{q} sits in the app's UI zone (keep {zt:.0} px top, {zb:.0} bottom, {zl:.0} left, {zr:.0} right clear)") });
let [ix, iy, iw, ih] = *r.boxes.last().unwrap_or(&r.box_);
let edge = if iy < zt { format!("the top (keep {zt:.0} px clear)") } else if iy + ih > h - zb { format!("the bottom (keep {zb:.0} px clear)") } else if ix < zl { format!("the left (keep {zl:.0} px clear)") } else { format!("the right (keep {zr:.0} px clear)") };
issues.push(Issue { rule: "safe-area", p: 1, at: Some(r.from), says: format!("{q} sits in the app's UI zone at {edge}: its {} {ix:.0},{iy:.0} {iw:.0}x{ih:.0} in {w:.0}x{h:.0}", if r.boxes.last() == Some(&r.box_) { "box" } else { "letters" }) });
}
let words = r.text.split_whitespace().count() as f64;
let need = (0.3 * words).max(1.0);
@@ -195,20 +199,6 @@ pub(crate) fn quote(s: &str) -> String {
format!("\u{201c}{s}\u{201d}")
}
pub(crate) fn rgb_of(css: &str) -> [f64; 3] {
let n: Vec<f64> = css.split(|c: char| !(c.is_ascii_digit() || c == '.')).filter(|s| !s.is_empty()).filter_map(|s| s.parse().ok()).collect();
[n.first().copied().unwrap_or(255.0), n.get(1).copied().unwrap_or(255.0), n.get(2).copied().unwrap_or(255.0)]
}
/// relative luminance (WCAG) of an sRGB colour 0-255
pub(crate) fn lum([r, g, b]: [f64; 3]) -> f64 {
let c = |v: f64| {
let v = v / 255.0;
if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
};
0.2126 * c(r) + 0.7152 * c(g) + 0.0722 * c(b)
}
/// Caption contrast: at each text's middle frame, the pixels behind it against its colour, at least 3:1. The pixels
/// behind are the half of the box least like the text.
pub(crate) fn contrast(video: &str, runs: &[Run], w: f64, h: f64, probe: &Probe, issues: &mut Vec<Issue>, passed: &mut Vec<String>) {
@@ -217,29 +207,13 @@ pub(crate) fn contrast(video: &str, runs: &[Run], w: f64, h: f64, probe: &Probe,
let mut measured = 0;
for r in runs.iter().filter(|r| r.size >= 20.0).take(80) {
let [x, y, bw, bh] = r.box_;
// even sizes and offsets: the decoder's 4:2:0 frame crops to them
let (cx, cy, cw, ch) = ((x * sx).max(0.0) as u32 & !1, (y * sy).max(0.0) as u32 & !1, ((bw * sx) as u32).max(2) & !1, ((bh * sy) as u32).max(2) & !1);
if cx + cw > probe.w as u32 || cy + ch > probe.h as u32 {
let crop = [(x * sx).max(0.0) as u32, (y * sy).max(0.0) as u32, (bw * sx) as u32, (bh * sy) as u32];
if crop[0] + crop[2] > probe.w as u32 || crop[1] + crop[3] > probe.h as u32 {
continue;
}
let t = (r.from + r.to) / 2.0;
let Ok(out) = Command::new("ffmpeg")
.args(["-v", "error", "-ss", &format!("{t:.3}"), "-i", video, "-frames:v", "1", "-vf", &format!("crop={cw}:{ch}:{cx}:{cy}"), "-f", "rawvideo", "-pix_fmt", "rgb24", "-"])
.output()
else {
continue;
};
if out.stdout.len() < (cw * ch * 3) as usize {
continue;
}
let text = lum(rgb_of(&r.color));
let mut ls: Vec<f64> = out.stdout.chunks_exact(3).map(|p| lum([p[0] as f64, p[1] as f64, p[2] as f64])).collect();
ls.sort_by(|a, b| (b - text).abs().total_cmp(&(a - text).abs()));
let behind = &ls[..ls.len() / 2];
let mut sorted = behind.to_vec();
sorted.sort_by(f64::total_cmp);
let bg = sorted[sorted.len() / 2];
let ratio = (text.max(bg) + 0.05) / (text.min(bg) + 0.05);
// the same measure `raea world` joins to a text from its render (raea-sys-measure, DR2)
let Some(ratio) = raea_sys_measure::contrast(std::path::Path::new(video), t, crop, &r.color) else { continue };
measured += 1;
if ratio < 3.0 {
low += 1;
@@ -251,35 +225,18 @@ pub(crate) fn contrast(video: &str, runs: &[Run], w: f64, h: f64, probe: &Probe,
}
}
pub(crate) struct Word {
pub(crate) text: String,
pub(crate) start: f64,
/// when the word ends, in seconds (its start when the transcript doesn't say)
pub(crate) end: f64,
}
/// A transcript's word: its text, start and end in seconds (its end is its start when the transcript doesn't say).
pub(crate) use raea_core_facts::Word;
/// raea's transcript shape (an array of {text|word, start|from|start_ms, …}), or a flat array of {w, t}
/// A transcript's words: {text, start} in seconds (or t, or start_ms), or {text, from} in frames at `fps`, as the app's
/// words.json and `raea render --words` have them.
/// A transcript's words (raea_core_facts::transcript_words: {text, start} in seconds, or t, start_ms, or {text, from}
/// in frames at `fps`), as the app's words.json and `raea render --words` have them.
pub(crate) fn transcript(path: &str, fps: f64) -> R<Vec<Word>> {
let v: Value = serde_json::from_str(&std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"))?).map_err(|e| format!("{path}: {e}"))?;
let list = v.as_array().ok_or_else(|| format!("{path}: expected an array of words ({{text, start}} in seconds or {{text, from}} in frames)"))?;
Ok(list
.iter()
.filter_map(|w| {
let text = w.get("text").or_else(|| w.get("word")).or_else(|| w.get("w"))?.as_str()?.to_string();
// the time keys a transcript may use, each with what turns it into seconds
let secs = |keys: &[(&str, f64)]| keys.iter().find_map(|(k, to_s)| Some(w.get(*k)?.as_f64()? * to_s));
let start = secs(&[("start", 1.0), ("t", 1.0), ("a", 1.0), ("start_ms", 0.001), ("from", 1.0 / fps)])?;
let end = secs(&[("end", 1.0), ("b", 1.0), ("end_ms", 0.001), ("to", 1.0 / fps)]).unwrap_or(start);
Some(Word { text, start, end })
})
.collect())
v.as_array().ok_or_else(|| format!("{path}: expected an array of words ({{text, start}} in seconds or {{text, from}} in frames)"))?;
Ok(raea_core_facts::transcript_words(&v, fps))
}
pub(crate) fn norm(s: &str) -> String {
s.chars().filter(|c| c.is_alphanumeric()).collect::<String>().to_lowercase()
}
pub(crate) use raea_core_facts::word_key as norm;
pub(crate) const SMALL: [&str; 24] = ["the", "and", "you", "your", "for", "with", "that", "this", "its", "it's", "are", "was", "our", "out", "from", "into", "then", "than", "but", "not", "all", "can", "has", "have"];
@@ -291,12 +248,21 @@ pub(crate) fn cues(runs: &[Run], words: &[Word], issues: &mut Vec<Issue>, passed
for r in runs {
let shown: Vec<String> = r.text.split_whitespace().map(norm).filter(|t| !t.is_empty()).collect();
let Some((k, i)) = shown.iter().enumerate().filter(|(_, t)| t.len() >= 3 && !SMALL.contains(&t.as_str())).find_map(|(k, t)| {
words.iter().enumerate().filter(|(_, w)| norm(&w.text) == *t && (w.start - r.from).abs() <= 2.0).min_by(|(_, a), (_, b)| (a.start - r.from).abs().total_cmp(&(b.start - r.from).abs())).map(|(i, _)| (k, i))
// a one-word card matches only a word said right by it: the same word said 2 s earlier is another moment
let near = if shown.len() == 1 { 0.75 } else { 2.0 };
words.iter().enumerate().filter(|(_, w)| norm(&w.text) == *t && (w.start - r.from).abs() <= near).min_by(|(_, a), (_, b)| (a.start - r.from).abs().total_cmp(&(b.start - r.from).abs())).map(|(i, _)| (k, i))
}) else {
continue;
};
// back over the words the text shows before it, while the voice says them in the same order just before
let back = (1..=k.min(i)).take_while(|&n| norm(&words[i - n].text) == shown[k - n]).last().unwrap_or(0);
// a caption says what the voice says: at least half its words, in order, around the anchor. A card that only
// shares one word with another line ("Wirestock x OpenAI Sora" against "At Wirestock, I worked on...") isn't
// a caption of it, and holding it to that word's time was a false P1
let fwd = (1..).take_while(|&n| k + n < shown.len() && i + n < words.len() && norm(&words[i + n].text) == shown[k + n]).last().unwrap_or(0);
if (back + 1 + fwd) * 2 < shown.len() {
continue;
}
let w = &words[i - back];
let tok = norm(&w.text);
checked += 1;
+24
View File
@@ -0,0 +1,24 @@
[package]
name = "raea-app-direction"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "How raea takes direction (docs/direction.feature): `raea world`, a composition's frame as one world of facts, queried across media"
[dependencies]
raea-runtime-world = { path = "../../runtime/world" }
raea-runtime-bundle = { path = "../../runtime/bundle" }
raea-core-facts = { path = "../../core/facts" }
# a render's record named by when it was (UTC)
raea-io-trace = { path = "../../io/trace" }
serde_json = "1"
# `raea check PROJECT | EDIT.tsx` (DR4): taste and controllers' rules, the floor on a composition's newest render, the
# project's compositions
raea-core-brief = { path = "../../core/brief" }
raea-app-check = { path = "../check" }
raea-app-registry = { path = "../workspace/registry" }
# the project's notes, whose asks' checks raea check runs beside its rules (DR6)
raea-app-notes = { path = "../notes" }
# a TS check's run printing nothing to the terminal (its ECHO)
raea-runtime-react = { path = "../../runtime/react", default-features = false }
+378
View File
@@ -0,0 +1,378 @@
//! `raea check PROJECT|EDIT.tsx` (docs/direction.feature DR4): every check that applies, run over each
//! composition's worlds. The rules come from raea's floor, the person's taste (and the workspace's), and the
//! workspace's and the project's controllers; each is one of raea's named checks (systems.rs) or a project's TS check
//! (ts.rs), and where it was written changes nothing about how it runs. A check that needs a render runs on the
//! composition's newest render; with none, it waits, and the command says what for. `raea check VIDEO.mp4` is the
//! floor alone (apps/check).
use std::path::{Path, PathBuf};
use raea_core_brief::{controller, taste};
use raea_core_facts::{finding, record, Facts, Finding, Level, Rule, Shot};
use raea_runtime_bundle::flag;
use raea_runtime_world::{Ask, Render};
use serde_json::{json, Value};
use crate::systems::{self, Frames};
use crate::ts;
type R<T> = Result<T, String>;
pub const USAGE: &str = "raea check [PROJECT|EDIT.tsx] [--composition ID] [--only ID] [--taste T] [--render OUT | --no-render] [--json] (every check that applies to each composition, over its frames: raea's floor on its newest render, the person's taste, the workspace's and the project's rules (a controller's rule fields: one of raea's checks by name, or a project's .ts check); what needs a render and has none waits, and says so)";
/// The flags raea check takes with a value (its own, and the floor's on a video).
const TAKES: [&str; 10] = ["--composition", "--only", "--taste", "--render", "--manifest", "--words", "--perception", "--shape", "--platform", "-o"];
/// What the CLI lends `raea check`: its TS evaluator and headless run, and the taste kinds a mode needs (as `raea
/// context` reads the person's taste).
pub struct Host {
pub ts: ts::Host,
pub kinds: fn(&str) -> &'static [&'static str],
}
/// The person's taste folder: RAEA_TASTE, else ~/.raea/taste.
pub fn taste_dir() -> Option<PathBuf> {
std::env::var_os("RAEA_TASTE").map(PathBuf::from).or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".raea/taste")))
}
/// The .ts files `--taste` names: the file, or every .ts in the folder. A file named under the person's taste folder
/// that isn't there yet is a note, not a refusal: the skill prescribes --taste on that folder's own taste file, and a
/// machine with none yet should still check (#89); any other missing path is left to the reader to refuse.
pub fn taste_files(args: &[String]) -> Vec<PathBuf> {
let Some(t) = flag(args, "--taste").map(PathBuf::from) else { return vec![] };
if t.extension().is_some_and(|x| x == "ts") {
let home = taste_dir().map(std::path::absolute).and_then(Result::ok);
if !t.is_file() && t.parent().map(std::path::absolute).and_then(Result::ok) == home {
eprintln!("note: no taste yet ({} isn't there); checking without it", t.display());
return vec![];
}
return vec![t];
}
let mut v: Vec<PathBuf> = std::fs::read_dir(&t).into_iter().flatten().filter_map(|e| e.ok().map(|e| e.path())).filter(|f| f.extension().is_some_and(|x| x == "ts")).collect();
v.sort();
v
}
/// The taste files a project is held to: `--taste`'s when given, else the person's taste.ts (RAEA_TASTE, or
/// ~/.raea/taste) and the kinds its brief's modes need, then the workspace's house rules.
fn tastes(project: &Path, given: Vec<PathBuf>, host: &Host) -> Vec<PathBuf> {
if !given.is_empty() {
return given;
}
let mut out = Vec::new();
if let Some(dir) = taste_dir().filter(|d| d.join("taste.ts").is_file()) {
out.push(dir.join("taste.ts"));
let brief: Value = (host.ts.eval)(&project.join("brief.ts")).ok().and_then(|j| serde_json::from_str(&j).ok()).unwrap_or_default();
for m in brief["mode"].as_array().into_iter().flatten().filter_map(Value::as_str) {
for f in (host.kinds)(&m.trim().to_ascii_lowercase()).iter().map(|k| dir.join(format!("{k}.ts"))) {
if f.is_file() && !out.contains(&f) {
out.push(f);
}
}
}
}
out.extend(record::up(project, ".raea/workspace").map(|ws| ws.join("taste.ts")).filter(|f| f.is_file()));
out
}
/// One rule as it runs: a named check, or a project's check file's declaration.
enum How {
Named(systems::Named),
File(ts::Meta),
}
/// Every rule `project` is held to (`given`: `--taste`'s files) with its notes' asks (DR6), the notes, and a finding
/// for each file of rules or note raea couldn't read.
fn rules(project: &Path, given: Vec<PathBuf>, host: &Host) -> (Vec<Rule>, Vec<Finding>, Vec<raea_app_notes::Kept>) {
let (mut out, mut bad) = held(project, given, host);
let notes = raea_app_notes::read(project, host.ts.eval);
let (asks, unread) = raea_app_notes::check::rules(project, &notes);
out.extend(asks);
bad.extend(unread);
// a check's path made plain (no `..`), as its import will name it
for r in out.iter_mut() {
if let Some(p) = r.file() {
r.check = raea_runtime_bundle::normalize(p).display().to_string();
}
}
(out, bad, notes)
}
/// raea's floor, the person's taste and the workspace's and project's controllers' rules, and a finding for each file
/// of them raea couldn't read.
fn held(project: &Path, given: Vec<PathBuf>, host: &Host) -> (Vec<Rule>, Vec<Finding>) {
// raea's own: the floor, and the reading check (DR28: its findings keep their own levels, so no rule level)
let read = Rule { level: None, ..Rule::named("text-read", "text can be read for as long as it needs, and OCR reads it", Default::default(), Level::Warn, "raea") };
let mut out = vec![Rule::named("floor", "raea's floor", Default::default(), Level::Error, "raea"), read];
let mut bad = Vec::new();
let name = |f: &Path| f.strip_prefix(project).unwrap_or(f).display().to_string();
for f in tastes(project, given, host) {
match (host.ts.eval)(&f).and_then(|j| raea_core_brief::read::<taste::Taste>(&name(&f), &j)) {
Ok(t) => out.extend(t.sections.iter().flat_map(|s| &s.rules).filter_map(|r| Some(Rule::of_taste(&r.text, r.check?, &name(&f))))),
Err(e) => bad.push(Finding::new("taste", Level::Error, format!("raea can't read it: {e}"), "raea check").about(name(&f), None)),
}
}
let ws = record::up(project, ".raea/workspace");
for (dir, scope) in ws.iter().map(|w| (raea_app_registry::shared_dir(w, "controllers"), "workspace")).chain([(project.join("controllers"), "project")]) {
// a workspace's own folder is its project's too: read once
if scope == "project" && ws.as_deref() == Some(project) {
continue;
}
let mut files: Vec<PathBuf> = std::fs::read_dir(&dir).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "ts")).collect();
files.sort();
for f in files {
match (host.ts.eval)(&f).and_then(|j| controller::of_json(&j)) {
Ok(c) => out.extend(Rule::of_controller(&c, &dir, &format!("{scope} {}", name(&f)))),
Err(e) => bad.push(Finding::new("controller", Level::Error, format!("raea can't read it: {e}"), "raea check").about(name(&f), None)),
}
}
}
(out, bad)
}
/// The compositions `target` names: each (its file, its id when the file registers several).
fn compositions(target: &Path, args: &[String]) -> R<Vec<(PathBuf, Option<String>)>> {
let one = flag(args, "--composition");
let (dir, file) = if target.is_dir() { (target.to_path_buf(), None) } else { (target.parent().unwrap_or(Path::new(".")).to_path_buf(), Some(target.canonicalize().map_err(|e| format!("{}: {e}", target.display()))?)) };
let reg = raea_app_registry::scan(&dir, &[]);
let mut out: Vec<(PathBuf, Option<String>)> = Vec::new();
for c in &reg.compositions {
let path = reg.dir.join(&c.file);
let path = path.canonicalize().unwrap_or(path);
let id = (c.how == raea_app_registry::How::Registered).then(|| c.id.clone());
if file.as_ref().is_none_or(|f| *f == path) && one.as_ref().is_none_or(|o| Some(o) == id.as_ref()) {
out.push((path, id));
}
}
if out.is_empty() {
match (file, one) {
// a file the scan didn't register (outside a project): itself
(Some(f), one) => out.push((f, one)),
(None, one) => return Err(format!("no composition in {}{}", dir.display(), one.map(|o| format!(" named {o}")).unwrap_or_default())),
}
}
Ok(out)
}
/// What one composition's checks found, each check that waits with what for, and its newest render, its named shots
/// (each from its first frame to its end) and its rate, for a note's clip (DR6).
struct Checked {
file: PathBuf,
id: Option<String>,
found: Vec<Finding>,
waits: Vec<(String, String)>,
render: Option<raea_app_notes::check::Rendered>,
shots: Vec<(String, i64, Option<i64>)>,
fps: f64,
}
/// One composition checked against `rules` (`--only`'s already picked), every frame read when `whole` or a check
/// ranges over them.
fn check_one(tsx: &Path, id: Option<String>, rules: &[Rule], args: &[String], whole: bool, host: &Host) -> R<Checked> {
let named = systems::named();
let mut found = Vec::new();
let mut hows = Vec::new();
for r in rules {
match r.file() {
Some(f) => match ts::meta(f, &host.ts) {
Ok(m) => hows.push((r, How::File(m))),
Err(e) => found.push(Finding::new(&r.id, Level::Error, e, &r.by)),
},
None => match named.iter().find(|n| n.name == r.check) {
Some(n) => hows.push((r, How::Named(n.clone()))),
None => found.push(Finding::new(&r.id, Level::Error, format!("raea has no check named {} (its checks: {}, or a .ts check's path)", r.check, named.iter().map(|n| n.name).collect::<Vec<_>>().join(", ")), &r.by)),
},
}
}
let frames: Vec<&Frames> = hows.iter().map(|(_, h)| match h { How::Named(n) => &n.frames, How::File(m) => &m.frames }).collect();
// every frame when a check ranges over them (cuts and lines are found in them), else the frames named and the first
let whole = whole || frames.iter().any(|f| f.whole());
let mut asked: Vec<i64> = if whole { Vec::new() } else { frames.iter().flat_map(|f| if let Frames::At(v) = f { v.clone() } else { vec![] }).chain([0]).collect() };
asked.sort();
asked.dedup();
// the render joins the first frame (what it is, or that there is none) and where a TS check needs it
let join_all = hows.iter().any(|(_, h)| match h {
How::File(m) => m.render && m.frames.whole(),
How::Named(n) => n.render && n.frames.whole(),
});
let join_on = (!join_all).then(|| hows.iter().flat_map(|(_, h)| match h { How::File(m) if m.render => if let Frames::At(v) = &m.frames { v.clone() } else { vec![] }, _ => vec![] }).chain([0]).collect());
let render_how = match (flag(args, "--render"), args.iter().any(|a| a == "--no-render")) {
(Some(o), _) => Render::From(o.into()),
(None, true) => Render::Off,
(None, false) => Render::Newest,
};
let mut opts_args = vec![tsx.display().to_string()];
if let Some(i) = &id {
opts_args.extend(["--composition".to_string(), i.clone()]);
}
let opts = raea_runtime_bundle::comp_opts(&opts_args)?;
let worlds = raea_runtime_world::read(tsx, &opts, &Ask { frames: asked, layout: true, render: render_how, join_on })?;
let rendered = worlds.first().and_then(|w| w.resources.get("Rendered")).cloned();
let mut waits = Vec::new();
let needs = |w: &mut Vec<(String, String)>, r: &Rule| w.push((r.id.clone(), "a render (raea render EDIT.tsx)".into()));
if let Some(r) = rendered.as_ref().filter(|r| r["stale"] == true) {
found.push(Finding::new("render", Level::Note, "the newest render is older than the composition's last change: what it measured may have moved", "raea check").about(r["out"].as_str().unwrap_or("").to_string(), None));
}
// raea's named checks: the text forms over every frame; the floor (and the loudness and stillness it measures) on the render
// the forms the floor measures on the video (each its form, value and line), and where each was written
let (mut held, mut bys) = (Vec::new(), Vec::new());
let mut floor = false;
for (r, h) in &hows {
let How::Named(n) = h else { continue };
match n.name {
"floor" => floor = true,
"loudness" | "still-max" => {
held.push((n.name, r.number("value").unwrap_or(if n.name == "loudness" { -14.0 } else { 3.0 }), r.text.clone()));
bys.push(r.by.clone());
}
"text-read" if rendered.is_none() => needs(&mut waits, r),
"text-read" => found.extend(crate::read::read(r, &worlds)),
_ => found.extend(systems::text(r, &worlds)),
}
}
if floor || !held.is_empty() {
match &rendered {
Some(r) if is_video(r["out"].as_str().unwrap_or("")) => {
let a = [r["out"].as_str().unwrap_or("").to_string(), "--manifest".into(), r["manifest"].as_str().unwrap_or("").to_string()];
// where text-read runs, the floor's own reading rule (held against when a text is on) is its
let without: &[&str] = if hows.iter().any(|(_, h)| matches!(h, How::Named(n) if n.name == "text-read")) { &["reading"] } else { &[] };
for mut f in raea_app_check::floor(&a, &held, without)? {
match held.iter().position(|h| h.0 == f.check) {
Some(k) => f.by = bys[k].clone(),
None if !floor => continue,
None => f.by = "raea".into(),
}
found.push(f);
}
}
Some(_) => waits.extend(hows.iter().filter(|(_, h)| matches!(h, How::Named(n) if n.render && n.name != "text-read")).map(|(r, _)| (r.id.clone(), "a video render (its render is stills)".to_string()))),
None => hows.iter().filter(|(_, h)| matches!(h, How::Named(n) if n.render && n.name != "text-read")).for_each(|(r, _)| needs(&mut waits, r)),
}
}
// the project's own checks, in one run
let mut files: Vec<PathBuf> = Vec::new();
let mut plan = Vec::new();
for (r, h) in &hows {
let How::File(m) = h else { continue };
if m.render && rendered.is_none() {
needs(&mut waits, r);
continue;
}
let k = files.iter().position(|f| *f == m.file).unwrap_or_else(|| {
files.push(m.file.clone());
files.len() - 1
});
let mut on = m.frames.pick(&worlds);
if let (true, Some(j)) = (m.render, &join_on_of(&worlds)) {
on.retain(|f| j.contains(f));
}
plan.push(ts::Planned { check: k, frames: on, values: r.values.clone(), level: r.level, by: r.by.clone() });
}
found.extend(ts::run(&files, &plan, &worlds, &host.ts)?);
let render = rendered.map(|r| {
// how many frames it drew, as its manifest lists them
let m: Value = std::fs::read(r["manifest"].as_str().unwrap_or("")).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default();
raea_app_notes::check::Rendered { out: PathBuf::from(r["out"].as_str().unwrap_or("")), stale: r["stale"] == true, frames: m["frames"].as_array().map_or(0, |f| f.len() as i64) }
});
let mut shots: Vec<(String, i64, Option<i64>)> = worlds.iter().flat_map(|w| w.find(&["Shot"]).into_iter().filter_map(|e| w.get::<Shot>(e.id)).filter_map(|s| Some((s.name?, s.from, s.to)))).collect();
shots.sort();
shots.dedup();
let fps = worlds.first().map_or(30.0, |w| w.fps);
Ok(Checked { file: tsx.to_path_buf(), id, found: finding::ranked(found), waits, render, shots, fps })
}
/// Whether `r` runs on the composition `tsx` (`id` where its file registers several) of `project`: a rule a note's ask
/// scopes to one (`of`) runs there alone.
fn applies(r: &Rule, project: &Path, tsx: &Path, id: Option<&str>) -> bool {
r.of.as_ref().is_none_or(|of| raea_app_notes::check::is_of(of, &named_as(project, tsx, id)))
}
/// A composition as a note's ask names it: its file from the project, `#ID` after it where the file registers several.
fn named_as(project: &Path, tsx: &Path, id: Option<&str>) -> String {
format!("{}{}", record::rel(project, tsx), id.map(|i| format!("#{i}")).unwrap_or_default())
}
/// `rules` run on `project`'s compositions (`--composition` picks one), each where it applies, as `raea check` runs
/// its own: what `raea notes check` runs a project's asks through (DR6).
pub fn run(project: &Path, rules: &[Rule], args: &[String], whole: bool, host: &Host) -> R<Vec<raea_app_notes::check::Ran>> {
let mut out = Vec::new();
for (tsx, id) in compositions(project, args)? {
let mine: Vec<Rule> = rules.iter().filter(|r| applies(r, project, &tsx, id.as_deref())).cloned().collect();
let c = check_one(&tsx, id, &mine, args, whole, host)?;
out.push(raea_app_notes::check::Ran { of: named_as(project, &c.file, c.id.as_deref()), found: c.found, waits: c.waits, render: c.render, shots: c.shots, fps: c.fps });
}
Ok(out)
}
/// The frames the render joined (each with what it rendered, or says it waits), or None when it joined none.
fn join_on_of(worlds: &[Facts]) -> Option<Vec<i64>> {
let on: Vec<i64> = worlds.iter().filter(|w| w.resources.contains_key("Rendered")).map(|w| w.frame).collect();
(!on.is_empty()).then_some(on)
}
/// Whether `raea check`'s arguments name a file that isn't a composition (a video, a still: the floor alone, apps/check)
/// rather than a project, a folder or an EDIT.tsx.
pub fn of_video(args: &[String]) -> bool {
raea_app_check::words(args, &TAKES).first().is_some_and(|a| !a.ends_with(".tsx") && !Path::new(a).is_dir())
}
fn is_video(out: &str) -> bool {
Path::new(out).extension().and_then(|x| x.to_str()).is_some_and(|x| matches!(x.to_ascii_lowercase().as_str(), "mp4" | "mov"))
}
/// `raea check PROJECT|EDIT.tsx ...`: the report, and whether an error is among what it found.
pub fn check(args: &[String], host: &Host) -> R<(String, bool)> {
let target = raea_app_check::words(args, &TAKES).first().map_or_else(|| PathBuf::from("."), PathBuf::from);
// the folder it is in, made whole (`lyric.tsx`'s is the empty path): a rule's check is a path from it
let here = if target.is_dir() { target.clone() } else { target.parent().filter(|p| !p.as_os_str().is_empty()).map_or_else(|| PathBuf::from("."), Path::to_path_buf) };
let here = here.canonicalize().map_err(|e| format!("{}: {e}", here.display()))?;
let project = record::up(&here, ".raea/project").unwrap_or(here);
let (mut rules, unread, notes) = rules(&project, taste_files(args), host);
if let Some(only) = flag(args, "--only") {
rules.retain(|r| r.id == only);
if rules.is_empty() {
return Err(format!("--only {only}: no rule here has that id"));
}
}
let mut all = Vec::new();
for (tsx, id) in compositions(&target, args)? {
let mine: Vec<Rule> = rules.iter().filter(|r| applies(r, &project, &tsx, id.as_deref())).cloned().collect();
all.push(check_one(&tsx, id, &mine, args, false, host)?);
}
let stamp = raea_io_trace::utc(std::time::SystemTime::now()).1;
// what the notes' asks found, kept with what each has been through (DR6): an ask's first run that passes is refused
let ran: Vec<raea_app_notes::check::Ran> = all.iter().map(|c| raea_app_notes::check::Ran { of: named_as(&project, &c.file, c.id.as_deref()), found: c.found.clone(), waits: c.waits.clone(), render: None, shots: Vec::new(), fps: c.fps }).collect();
let mut kept = raea_app_notes::state::read(&project);
let (asks, _) = raea_app_notes::check::settle(&project, &notes, &rules, &ran, &stamp, &mut kept);
if !asks.is_empty() {
raea_app_notes::state::write(&project, &kept)?;
}
let mut bad = unread.iter().any(|f| f.level == Level::Error);
if args.iter().any(|a| a == "--json") {
let v: Vec<Value> = all.iter().map(|c| json!({"file": c.file, "composition": c.id, "findings": c.found, "waits": c.waits.iter().map(|(r, w)| json!({"rule": r, "for": w})).collect::<Vec<_>>()})).collect();
bad |= all.iter().any(|c| c.found.iter().any(|f| f.level == Level::Error));
return Ok((serde_json::to_string_pretty(&json!({"unread": unread, "compositions": v, "asks": asks})).unwrap_or_default(), bad));
}
let mut out: Vec<String> = unread.iter().map(Finding::line).collect();
let mut every = unread.clone();
for c in &all {
out.push(format!("raea check {}{}", c.file.display(), c.id.as_ref().map(|i| format!(" ({i})")).unwrap_or_default()));
// a note's ask's finding says which ask, as two asks can run one check
out.extend(c.found.iter().map(|f| if f.by.starts_with("note ") { format!("{} [{}]", f.line(), f.by) } else { f.line() }));
out.extend(c.waits.iter().map(|(r, w)| format!("waits {r}: needs {w}")));
// kept in its project's record (DR3), what raea findings and raea next read
if let Some(e) = record::keep("raea check", &c.file, None, &c.found, vec![], &stamp) {
out.push(format!("raea check: kept in the project's record as {} (raea findings reads it)", e.id));
}
bad |= c.found.iter().any(|f| f.level == Level::Error);
every.extend(c.found.iter().cloned());
}
out.extend(asks.iter().map(|a| format!("raea check: note {a}")));
out.push(format!("raea check: {}", finding::count(&every)));
Ok((out.join("\n"), bad))
}
/// `raea check ...`: its exit code (1 on an error found, 2 when it couldn't check).
pub fn cli(args: &[String], host: &Host) -> i32 {
raea_app_check::said(check(args, host), "raea check: ")
}
+155
View File
@@ -0,0 +1,155 @@
//! `raea findings` (docs/direction.feature DR3): what renders and checks found, read from the project's record
//! (core/facts record.rs). For each thing rendered or checked, its latest entry against the one before (or the one
//! `--since` names): what was fixed, what is new and what is carried, and since which render.
use std::path::{Path, PathBuf};
use raea_core_facts::record::{self, Entry};
use raea_core_facts::{Finding, finding};
use raea_runtime_bundle::flag;
use serde_json::{Value, json};
pub const USAGE: &str = "raea findings [PROJECT|EDIT.tsx] [--about NAME] [--check ID] [--open] [--since RENDER] [--json] (what each render and raea check found, from the project's record: fixed, new and carried since the one before, or since RENDER; --open: only what stands)";
/// The oldest entry of the unbroken run up to the latest that all found `f`.
fn carried_since(entries: &[&Entry], f: &Finding) -> String {
let key = record::same(f);
let run = entries.iter().rev().take_while(|e| e.findings.iter().any(|g| record::same(g) == key));
run.last().map(|e| e.id.clone()).unwrap_or_default()
}
/// One thing's latest entry against the one before it (or `since`), each list filtered by `keep`.
fn compare(entries: &[&Entry], since: Option<&str>, keep: &dyn Fn(&Finding) -> bool, open: bool) -> Option<Value> {
let (now, earlier) = entries.split_last()?;
let before = match since {
Some(id) => earlier.iter().rev().find(|e| e.id.starts_with(id)),
None => earlier.last(),
};
let none = Vec::new();
let ch = record::changes(before.map_or(&none, |b| &b.findings), &now.findings);
let list = |fs: Vec<&Finding>| fs.into_iter().filter(|f| keep(f)).cloned().collect::<Vec<Finding>>();
let carried: Vec<Value> = list(ch.carried).into_iter().map(|f| json!({"since": carried_since(entries, &f), "finding": f})).collect();
let renamed: Vec<Value> = ch.renamed.into_iter().filter(|(_, n)| keep(n)).map(|(was, f)| json!({"was": was.about.iter().map(|a| &a.name).collect::<Vec<_>>(), "finding": f})).collect();
let fixed = if open { Vec::new() } else { list(ch.fixed) };
Some(json!({"of": now.of, "kind": now.kind, "id": now.id, "by": now.by, "commit": now.commit, "out": now.out, "against": before.map(|b| &b.id),
"new": list(ch.new), "carried": carried, "renamed": renamed, "fixed": fixed, "despite": now.despite}))
}
/// One thing's lines: its entry, then what is new, carried and fixed.
fn lines(r: &Value) -> Vec<String> {
let read = Finding::read;
let mut t = vec![format!(
"{} {} ({} {}{}, against {})",
r["of"].as_str().unwrap_or(""),
r["kind"].as_str().filter(|k| !k.is_empty()).unwrap_or("run"),
r["by"].as_str().unwrap_or(""),
r["id"].as_str().unwrap_or(""),
r["commit"].as_str().map(|c| format!(" at {c}")).unwrap_or_default(),
r["against"].as_str().unwrap_or("nothing: its first")
)];
t.extend(r["new"].as_array().into_iter().flatten().filter_map(read).map(|f| format!(" new {}", f.line())));
for c in r["carried"].as_array().into_iter().flatten() {
if let Some(f) = read(&c["finding"]) {
t.push(format!(" carried {} (since {})", f.line(), c["since"].as_str().unwrap_or("")));
}
}
for c in r["renamed"].as_array().into_iter().flatten() {
if let Some(f) = read(&c["finding"]) {
let was: Vec<&str> = c["was"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
t.push(format!(" renamed {} (the same, about {} before: not fixed)", f.line(), was.join(", ")));
}
}
t.extend(r["fixed"].as_array().into_iter().flatten().filter_map(read).map(|f| format!(" fixed {}", f.line())));
// what was let through, and why: the error stands in the count all the same
for d in r["despite"].as_array().into_iter().flatten() {
t.push(format!(" despite {}: {}", d["check"].as_str().unwrap_or(""), d["why"].as_str().unwrap_or("")));
}
t
}
/// What stands across the reports: each one's new and carried.
fn standing(reports: &[Value]) -> Vec<Finding> {
let mut out = Vec::new();
for r in reports {
out.extend(r["new"].as_array().into_iter().flatten().filter_map(Finding::read));
out.extend(["carried", "renamed"].iter().flat_map(|k| r[*k].as_array().into_iter().flatten()).filter_map(|c| Finding::read(&c["finding"])));
}
out
}
/// `raea findings ...` (args from "findings").
pub fn cli(args: &[String]) -> Result<String, String> {
if args.iter().any(|a| a == "--help" || a == "-h") {
return Ok(USAGE.into());
}
let target = args.get(1).filter(|a| !a.starts_with("--")).map_or_else(|| PathBuf::from("."), PathBuf::from);
// made absolute first: a bare name's parent is "", which names no folder
let from = if target.is_file() { target.canonicalize().unwrap_or_else(|_| target.clone()).parent().map_or_else(|| PathBuf::from("."), Path::to_path_buf) } else { target.clone() };
let project = record::up(&from, ".raea/project").ok_or_else(|| format!("raea findings: {} isn't in a raea project (no .raea/project at or above it), so nothing is recorded\n{USAGE}", target.display()))?;
let (about, check, since) = (flag(args, "--about"), flag(args, "--check"), flag(args, "--since"));
let keep = |f: &Finding| about.as_deref().is_none_or(|n| f.about.iter().any(|a| a.name == n || a.key.as_deref() == Some(n))) && check.as_deref().is_none_or(|c| f.check == c);
let all = record::read(&project);
let only = target.is_file().then(|| record::rel(&project, &target));
// each thing by what kind of output it was (a video against the video before it, a review against a review)
let mut ofs: Vec<(&str, &str)> = all.iter().filter(|e| only.as_deref().is_none_or(|w| w == e.of)).map(|e| (&*e.of, &*e.kind)).collect();
ofs.sort();
ofs.dedup();
let open = args.iter().any(|a| a == "--open");
let reports: Vec<Value> = ofs.iter().filter_map(|(of, kind)| compare(&all.iter().filter(|e| e.of == *of && e.kind == *kind).collect::<Vec<_>>(), since.as_deref(), &keep, open)).collect();
let count = finding::count(&standing(&reports));
if args.iter().any(|a| a == "--json") {
return Ok(serde_json::to_string_pretty(&json!({"project": project, "entries": all.len(), "reports": reports, "standing": count})).unwrap_or_default());
}
let mut t = vec![format!("raea findings: {} ({} entries in .raea/record)", project.display(), all.len())];
if reports.is_empty() {
t.push(" nothing recorded yet: a render or raea check of a file in this project keeps what it found".into());
}
t.extend(reports.iter().flat_map(lines));
t.push(format!("raea findings: {count} standing"));
Ok(t.join("\n"))
}
#[cfg(test)]
mod tests {
use super::*;
use raea_core_facts::Level;
fn entry(id: &str, fs: Vec<Finding>) -> Entry {
Entry { id: id.into(), at: 0, by: "raea render".into(), of: "edit.tsx".into(), out: None, kind: "video".into(), commit: None, findings: fs, despite: vec![] }
}
#[test]
fn the_latest_render_against_the_one_before_says_fixed_new_and_carried_since_when() {
let clips = Finding::new("clips", Level::Error, "rider in seat", "raea render").about("rider", None);
let tilt = Finding::new("tilted", Level::Warn, "vase leans", "raea render").about("vase", None);
let float = Finding::new("floats", Level::Error, "lamp floats", "raea render").about("lamp", None);
let es = [entry("a", vec![clips.clone(), tilt.clone()]), entry("b", vec![clips.clone(), tilt]), entry("c", vec![clips, float])];
let refs: Vec<&Entry> = es.iter().collect();
let all = |_: &Finding| true;
let r = compare(&refs, None, &all, false).unwrap();
assert_eq!((r["against"].as_str(), r["new"][0]["check"].as_str(), r["fixed"][0]["check"].as_str()), (Some("b"), Some("floats"), Some("tilted")));
assert_eq!((r["carried"][0]["finding"]["check"].as_str(), r["carried"][0]["since"].as_str()), (Some("clips"), Some("a")));
// against a named render, and only what stands
let r = compare(&refs, Some("a"), &all, true).unwrap();
assert_eq!((r["against"].as_str(), r["fixed"].as_array().map(Vec::len)), (Some("a"), Some(0)));
assert_eq!(finding::count(&standing(&[r])), "2 errors, 0 warns, 0 notes");
let lamp = |f: &Finding| f.about.iter().any(|a| a.name == "lamp");
assert_eq!(compare(&refs, None, &lamp, false).unwrap()["carried"].as_array().map(Vec::len), Some(0));
}
#[test]
fn a_renamed_part_or_an_error_let_through_is_never_read_as_fixed() {
let crate_ = Finding::new("clips", Level::Error, "crate in pillar", "raea render").about("crate", None).about("pillar", None).frames(0, 30).measure("depth", 0.241, "m", None);
let mut boxed = crate_.clone();
boxed.about[0].name = "box".into();
boxed.says = "box in pillar".into();
let mut let_through = entry("b", vec![boxed]);
let_through.despite = vec![record::Despite { check: "clips".into(), why: "posed through it".into() }];
let es = [entry("a", vec![crate_]), let_through];
let r = compare(&es.iter().collect::<Vec<_>>(), None, &|_: &Finding| true, false).unwrap();
assert_eq!((r["fixed"].as_array().map(Vec::len), r["new"].as_array().map(Vec::len), r["renamed"][0]["was"][0].as_str()), (Some(0), Some(0), Some("crate")));
let text = lines(&r).join("\n");
assert!(text.contains(" renamed error clips frames 0-29 box, pillar") && text.contains(" despite clips: posed through it"), "{text}");
assert_eq!(finding::count(&standing(&[r])), "1 error, 0 warns, 0 notes");
}
}
+19
View File
@@ -0,0 +1,19 @@
//! How raea takes direction (docs/direction.feature). `raea world` (world.rs): a composition's frame as one world of
//! facts, its 3D, page and timeline as entities with components, printed or queried across media.
mod world;
pub use world::{cli, find, Find, USAGE};
// how `raea render` ends: its findings counted last, and 1 on an error not let through (DR3)
mod rendered;
pub use rendered::rendered;
// `raea findings`: the project's record read back, fixed, new and carried (DR3)
pub mod findings;
// `raea check PROJECT | EDIT.tsx`: every rule's check, raea's named ones and a project's TS ones, over the worlds (DR4)
pub mod check;
pub mod systems;
pub mod ts;
// text-read: each text's reading time held to when it can be read, and what OCR reads of it (DR28)
pub mod read;
+243
View File
@@ -0,0 +1,243 @@
//! `text-read`, raea's reading check (docs/direction.feature DR28). Each text on screen is given three times: the
//! frames it is in the world (`on`), the frames it can be read on (`visible`: in the frame, at an opacity, size and
//! contrast against what is behind it that can be read, and covered by no other layer past a share), and the frames
//! OCR reads its words on (`read`, the render's Ocr). Its reading time is held against `visible`, not `on`: a text
//! faded in over half its time, or behind a part for some of it, has less time to be read than it is up, and the
//! finding says which frames were lost and why. A text that can be read where OCR doesn't read it is broken. raea
//! check runs it on every composition's newest render with no rule asking for it, as raea's own, beside the floor.
use std::collections::BTreeMap;
use raea_core_facts::{Contrast, Covers, Facts, Finding, Layer, Level, Line, Ocr, Rule, Text, word_key as norm};
use crate::systems::{ident, quote};
/// Frames OCR may miss inside what it reads before that's a fault (a word dropped for a frame or two, as textread's
/// GAP allows).
const GAP: usize = 3;
/// What the check holds a text to, each a value its rule may change: seconds a word (`word`) and at least (`least`),
/// as the floor's reading rule; the least opacity, letter height (px at 1080 on the short side) and contrast that can
/// be read; the most of it another layer may cover; the share of its words OCR must read.
struct Limits {
word: f64,
least: f64,
opacity: f64,
size: f64,
contrast: f64,
covered: f64,
share: f64,
}
impl Limits {
fn of(rule: &Rule) -> Limits {
let v = |n: &str, d: f64| rule.number(n).unwrap_or(d);
Limits { word: v("word", 0.3), least: v("least", 1.0), opacity: v("opacity", 0.5), size: v("size", 24.0), contrast: v("contrast", 3.0), covered: v("covered", 0.5), share: v("share", 0.5) }
}
}
/// One frame a text is on: why it can't be read there (None: it can), whether OCR read it (None: OCR didn't run),
/// and what OCR read.
struct Seen {
frame: i64,
lost: Option<String>,
read: Option<bool>,
ocr: String,
}
/// A text across the frames: its words, its layer key, the largest it's set, and each frame it's on.
struct Track {
words: String,
key: Option<String>,
size: f64,
seen: Vec<Seen>,
}
/// An entity's opacity: its own layer's, else its nearest parent's.
fn opacity(w: &Facts, mut e: u32) -> f64 {
loop {
if let Some(l) = w.get::<Layer>(e) {
return l.opacity;
}
match w.entities.get(e as usize).and_then(|x| x.parent) {
Some(p) => e = p,
None => return 1.0,
}
}
}
/// Why a text can't be read on this frame (`covered`: the most of it one layer covers), or None.
fn lost(w: &Facts, e: u32, t: &Text, l: &Limits, covered: f64) -> Option<String> {
if let Some(b) = t.box_ {
let inside = |a: f64, z: f64| (z.min(1.0) - a.max(0.0)).max(0.0);
let area = ((b[2] - b[0]) * (b[3] - b[1])).max(1e-9);
if inside(b[0], b[2]) * inside(b[1], b[3]) / area < 0.9 {
return Some("partly off the frame".into());
}
}
let o = opacity(w, e);
if o < l.opacity {
return Some(format!("at {:.0}% opacity", o * 100.0));
}
if let Some(s) = t.size.filter(|s| *s < l.size) {
return Some(format!("{s:.0} px high"));
}
// covered before contrast: what covers it is what its pixels then measure against
if covered > l.covered {
return Some(format!("{:.0}% covered", covered * 100.0));
}
w.get::<Contrast>(e).filter(|c| c.ratio < l.contrast).map(|c| format!("{:.1}:1 against what's behind it", c.ratio))
}
/// The words said or sung over the piece, each with its start in seconds.
fn said(worlds: &[Facts]) -> Vec<(String, f64)> {
let Some(w) = worlds.iter().find(|w| !w.find(&["Line"]).is_empty()) else { return Vec::new() };
w.find(&["Line"]).iter().filter_map(|e| w.get::<Line>(e.id)).flat_map(|l| l.words).map(|x| (norm(&x.text), x.start)).collect()
}
/// Runs of frames one after another in `frames` (sorted), each [first, the frame after its last).
fn runs(frames: impl IntoIterator<Item = i64>) -> Vec<[i64; 2]> {
let mut out: Vec<[i64; 2]> = Vec::new();
for f in frames {
match out.last_mut() {
Some(r) if r[1] == f => r[1] = f + 1,
_ => out.push([f, f + 1]),
}
}
out
}
/// Runs closer than `gap` frames to the one before, joined.
fn joined(runs: Vec<[i64; 2]>, gap: i64) -> Vec<[i64; 2]> {
let mut out: Vec<[i64; 2]> = Vec::new();
for r in runs {
match out.last_mut() {
Some(p) if r[0] - p[1] < gap => p[1] = r[1],
_ => out.push(r),
}
}
out
}
/// A number of frames as a person reads it: "2 frames" under a tenth of a second, else seconds.
fn span(frames: i64, fps: f64) -> String {
match frames {
1 => "1 frame".into(),
n if (n as f64) < 0.1 * fps => format!("{n} frames"),
n => format!("{:.1} s", n as f64 / fps),
}
}
/// "frames 10-22 at 20% opacity; frames 30-41 60% covered": the frames of [from, to) lost, grouped by why (three
/// groups at most); a frame it isn't drawn on is "not shown".
fn why_lost(from: i64, to: i64, seen: &[&Seen]) -> String {
let mut groups: Vec<([i64; 2], &str)> = Vec::new();
for f in from..to {
let why = match seen.iter().find(|s| s.frame == f) {
Some(s) => match s.lost.as_deref() {
Some(w) => w,
None => continue,
},
None => "not shown",
};
match groups.last_mut() {
Some((r, w)) if r[1] == f && *w == why => r[1] = f + 1,
_ => groups.push(([f, f + 1], why)),
}
}
let shown: Vec<String> = groups.iter().take(3).map(|([a, b], w)| if b - a == 1 { format!("frame {a} {w}") } else { format!("frames {a}-{} {w}", b - 1) }).collect();
let more = groups.len().saturating_sub(3);
format!("{}{}", shown.join("; "), if more > 0 { format!("; and {more} more") } else { String::new() })
}
/// The check's findings over `worlds` (every frame of the composition, in order, with its render joined).
pub fn read(rule: &Rule, worlds: &[Facts]) -> Vec<Finding> {
let l = Limits::of(rule);
let Some(fps) = worlds.first().map(|w| w.fps) else { return Vec::new() };
let lvl = |d: Level| rule.level.unwrap_or(d);
let mut tracks: BTreeMap<String, Track> = BTreeMap::new();
// what wasn't measured, and what it waits for
let mut waits: BTreeMap<String, String> = BTreeMap::new();
for w in worlds {
for c in ["Ocr", "Covers"] {
if let Some(why) = w.resources.get("Waits").and_then(|v| v.get(c)).and_then(|v| v.as_str()) {
waits.entry(c.to_string()).or_insert_with(|| why.to_string());
}
}
// the most of each layer one other layer covers
let mut covered: BTreeMap<u32, f64> = BTreeMap::new();
for e in w.find(&["Covers"]) {
for c in w.get::<Covers>(e.id).map(|c| c.0).unwrap_or_default() {
let s = covered.entry(c.layer).or_default();
*s = s.max(c.share);
}
}
for e in w.find(&["Text"]) {
let Some(t) = w.get::<Text>(e.id) else { continue };
let (id, key) = ident(w, e.id, &t);
let lost = lost(w, e.id, &t, &l, covered.get(&e.id).copied().unwrap_or(0.0));
let ocr = w.get::<Ocr>(e.id);
let tr = tracks.entry(id).or_insert_with(|| Track { words: t.words.clone(), key, size: 0.0, seen: Vec::new() });
// a text laid out with no size known is held as a caption
tr.size = tr.size.max(t.size.unwrap_or(f64::INFINITY));
tr.seen.push(Seen { frame: w.frame, lost, read: ocr.as_ref().map(|o| o.share >= l.share), ocr: ocr.map(|o| o.words).unwrap_or_default() });
}
}
let said = said(worlds);
let mut out = Vec::new();
// a text that leaves and comes back within half a second is one text that blinks, not two
let blink = (0.5 * fps).round() as i64;
for tr in tracks.values().filter(|t| t.size >= l.size) {
for [from, to] in joined(runs(tr.seen.iter().map(|s| s.frame)), blink) {
let seen: Vec<&Seen> = tr.seen.iter().filter(|s| (from..to).contains(&s.frame)).collect();
let at = |f: Finding| f.about(tr.words.clone(), tr.key.clone());
let q = quote(&tr.words);
// the time it needs to be read, against the time it can be: a caption the voice says as it shows needs none
let n = tr.words.split_whitespace().count();
let need = (l.word * n as f64).max(l.least);
let can_frames = seen.iter().filter(|s| s.lost.is_none()).count() as i64;
let can = can_frames as f64 / fps;
let (a, b) = (from as f64 / fps, to as f64 / fps);
let tokens: Vec<String> = tr.words.split_whitespace().map(norm).filter(|t| !t.is_empty()).collect();
let spoken = !tokens.is_empty() && tokens.iter().all(|t| said.iter().any(|(w, s)| w == t && *s >= a - 0.3 && *s <= b + 0.1));
if can + 0.05 < need && !spoken {
let says = if can_frames == 0 {
format!("{q} is up {} but can't be read on any frame of it ({}); {n} words need {need:.1} s", span(to - from, fps), why_lost(from, to, &seen))
} else if can_frames < to - from {
format!("{q} is up {} but can be read for {} ({}); {n} words need {need:.1} s", span(to - from, fps), span(can_frames, fps), why_lost(from, to, &seen))
} else {
format!("{q} is on for {}; {n} words need {need:.1} s", span(to - from, fps))
};
out.push(at(Finding::new(&rule.id, lvl(Level::Warn), says, &rule.by)).frames(from, to).measure("readable", (can * 10.0).round() / 10.0, "s", Some((need * 10.0).round() / 10.0)));
}
// what can be read and OCR doesn't read is broken; a word with fewer than two letters or digits isn't held
if norm(&tr.words).chars().count() < 2 {
continue;
}
let judged: Vec<&&Seen> = seen.iter().filter(|s| s.lost.is_none() && s.read.is_some()).collect();
let unread: Vec<[i64; 2]> = runs(judged.iter().filter(|s| s.read == Some(false)).map(|s| s.frame)).into_iter().filter(|[a, b]| (b - a) as usize > GAP).collect();
for [ua, ub] in &unread {
let got = judged.iter().find(|s| s.frame == *ua).map_or("", |s| s.ocr.as_str());
let heard = if got.trim().is_empty() { "OCR reads nothing in its box".to_string() } else { format!("OCR reads {} in its box", quote(got)) };
let says = format!("{q} can be read on frames {ua}-{} and OCR doesn't read it there ({heard}): it's broken", ub - 1);
out.push(at(Finding::new(&rule.id, lvl(Level::Error), says, &rule.by)).frames(*ua, *ub).fix("set it so it reads: a face, weight, size or treatment OCR reads, and nothing drawn through it"));
}
let read = judged.iter().filter(|s| s.read == Some(true)).count();
if unread.is_empty() && !judged.is_empty() && read * 2 < judged.len() {
let says = format!("{q} is read by OCR on {read} of the {} frames it can be read on", judged.len());
out.push(at(Finding::new(&rule.id, lvl(Level::Warn), says, &rule.by)).frames(from, to).measure("read", read as f64, "frames", Some(judged.len() as f64 / 2.0)));
}
}
}
// what it didn't see, said
if let Some(why) = waits.get("Ocr") {
out.push(Finding::new(&rule.id, Level::Note, format!("no text was held to what OCR reads: OCR waits for {why}"), &rule.by));
}
if let Some(why) = waits.get("Covers") {
out.push(Finding::new(&rule.id, Level::Note, format!("what covers each text wasn't counted: it waits for {why}"), &rule.by));
}
out
}
#[cfg(test)]
mod tests;
+98
View File
@@ -0,0 +1,98 @@
use super::*;
use raea_core_facts::{Medium, Waits, Word};
/// A caption of `words` on 60 frames at 30 fps: frame f at `opacity(f)`, read by OCR at `share(f)` (None: OCR
/// didn't run), 40 px high in the middle of the frame, 7:1 against its ground.
fn caption(words: &str, opacity: impl Fn(i64) -> f64, share: impl Fn(i64) -> Option<f64>) -> Vec<Facts> {
(0..60)
.map(|f| {
let mut w = Facts::new(f, 1080, 1920, 30.0);
let e = w.spawn(None);
w.put(e, &Text { words: words.into(), font: None, size: Some(40.0), box_: Some([0.1, 0.45, 0.9, 0.5]), extruded: 0.0, lines: Some(1), needs: None });
w.put(e, &Layer { medium: Medium::Type2d, order: 1, opacity: opacity(f), blend: None });
w.put(e, &Contrast { ratio: 7.0 });
match share(f) {
Some(s) => w.put(e, &Ocr { words: if s > 0.0 { words.into() } else { String::new() }, share: s }),
None => w.set(&Waits([("Ocr".to_string(), "OCR (on the Mac)".to_string())].into())),
}
w
})
.collect()
}
fn rule() -> Rule {
Rule { level: None, ..Rule::named("text-read", "", Default::default(), Level::Warn, "raea") }
}
#[test]
fn a_caption_up_long_enough_that_ocr_reads_holds() {
assert!(read(&rule(), &caption("Fresh bread every morning", |_| 1.0, |_| Some(1.0))).is_empty());
// OCR dropping it for a frame or two isn't a fault
let found = read(&rule(), &caption("Fresh bread every morning", |_| 1.0, |f| Some(if f == 20 || f == 21 { 0.0 } else { 1.0 })));
assert!(found.is_empty(), "{found:?}");
}
#[test]
fn reading_time_is_held_to_the_frames_it_can_be_read_on() {
// up 2 s, but under half opacity for its first 40 frames: 0.7 s to read seven words
let found = read(&rule(), &caption("one two three four five six seven", |f| if f < 40 { 0.2 } else { 1.0 }, |_| Some(1.0)));
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!((found[0].level, found[0].frames), (Level::Warn, Some([0, 60])));
assert!(found[0].says.contains("is up 2.0 s but can be read for 0.7 s (frames 0-39 at 20% opacity); 7 words need 2.1 s"), "{}", found[0].says);
// the frames it couldn't be read on aren't held to OCR
let found = read(&rule(), &caption("one two three four five six seven", |f| if f < 40 { 0.2 } else { 1.0 }, |f| Some(if f < 40 { 0.0 } else { 1.0 })));
assert_eq!(found.len(), 1, "{found:?}");
}
#[test]
fn a_caption_said_as_it_shows_needs_no_reading_time() {
let mut worlds = caption("one two three four five six seven", |f| if f < 40 { 0.2 } else { 1.0 }, |_| Some(1.0));
for w in &mut worlds {
let l = w.spawn(None);
let words = "one two three four five six seven".split(' ').enumerate().map(|(i, t)| Word { text: t.into(), start: 0.2 * i as f64, end: 0.2 * i as f64 + 0.15 }).collect();
w.put(l, &Line { text: "one two three four five six seven".into(), from: 0.0, to: Some(2.0), words, needs: None });
}
assert!(read(&rule(), &worlds).is_empty());
}
#[test]
fn text_that_can_be_read_and_that_ocr_doesnt_read_is_broken() {
let found = read(&rule(), &caption("Fresh bread every morning", |_| 1.0, |_| Some(0.0)));
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!((found[0].level, found[0].frames), (Level::Error, Some([0, 60])));
assert!(found[0].says.contains("can be read on frames 0-59 and OCR doesn't read it there (OCR reads nothing in its box): it's broken"), "{}", found[0].says);
// read on a frame here and there, never long enough to be a broken run: a warn
let found = read(&rule(), &caption("Fresh bread every morning", |_| 1.0, |f| Some(if f % 3 == 0 { 1.0 } else { 0.0 })));
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(found[0].level, Level::Warn);
assert!(found[0].says.contains("is read by OCR on 20 of the 60 frames it can be read on"), "{}", found[0].says);
}
#[test]
fn what_it_did_not_measure_it_says() {
let found = read(&rule(), &caption("Fresh bread every morning", |_| 1.0, |_| None));
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(found[0].level, Level::Note);
assert!(found[0].says.contains("OCR waits for OCR (on the Mac)"), "{}", found[0].says);
}
#[test]
fn small_type_and_a_lone_mark_arent_held() {
let mut worlds = caption("x", |_| 1.0, |_| Some(0.0));
assert!(read(&rule(), &worlds).is_empty(), "one letter: nothing for OCR to read, and a second is enough");
for w in &mut worlds {
w.put(0, &Text { words: "a label in the corner".into(), font: None, size: Some(12.0), box_: Some([0.0, 0.0, 0.2, 0.02]), extruded: 0.0, lines: Some(1), needs: None });
}
assert!(read(&rule(), &worlds).is_empty(), "under 24 px: not a caption");
}
#[test]
fn a_text_that_blinks_is_one_text_up_the_whole_time() {
// drawn on one frame in ten: one finding over all of it, its frames off said as not shown
let worlds: Vec<Facts> = caption("Fresh bread every morning", |_| 1.0, |_| Some(1.0)).into_iter().map(|w| if w.frame % 10 == 0 { w } else { Facts::new(w.frame, 1080, 1920, 30.0) }).collect();
let found = read(&rule(), &worlds);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(found[0].frames, Some([0, 51]));
let says = "is up 1.7 s but can be read for 0.2 s (frames 1-9 not shown; frames 11-19 not shown; frames 21-29 not shown; and 2 more); 4 words need 1.2 s";
assert!(found[0].says.contains(says), "{}", found[0].says);
}
+86
View File
@@ -0,0 +1,86 @@
//! How `raea render` ends (docs/direction.feature DR3): what the render found, counted on the last line it prints
//! whatever its output is piped through, and its exit: 1 while an error stands that nothing lets through. An error is
//! let through by `--despite CHECK WHY` (a check's name, or `all`), or for a harness that renders many pieces and
//! compares pixels, not scenes, by RAEA_DESPITE="CHECK: why" (which a raea before this ignores, as it would refuse the
//! flag). What was let through, and why, is written into the render's manifest.
use std::path::PathBuf;
use std::time::SystemTime;
use raea_core_facts::record::{self, Despite};
use raea_core_facts::{Finding, Level, finding};
use serde_json::{Value, json};
/// Each `--despite CHECK WHY`, then RAEA_DESPITE's.
fn despite(args: &[String], env: Option<String>) -> Vec<(String, String)> {
let mut out: Vec<(String, String)> = args.windows(3).filter(|w| w[0] == "--despite").map(|w| (w[1].clone(), w[2].clone())).collect();
if let Some((check, why)) = env.as_deref().and_then(|e| e.split_once(':')) {
out.push((check.trim().to_string(), why.trim().to_string()));
}
out
}
/// The last line and the exit, for `found` with `through` letting errors past.
fn ending(found: &[Finding], through: &[(String, String)]) -> (String, i32) {
let excused = |f: &Finding| through.iter().any(|(c, _)| c == "all" || *c == f.check);
let errors = |past: bool| found.iter().filter(|f| f.level == Level::Error && excused(f) == past).count();
let mut line = format!("raea render: {}", finding::count(found));
if errors(true) > 0 {
let why: Vec<String> = through.iter().map(|(c, w)| format!("--despite {c} {w:?}")).collect();
line.push_str(&format!("; {} let through by {}", errors(true), why.join(", ")));
}
(line, i32::from(errors(false) > 0))
}
/// `raea render`'s exit, once its findings' count is printed; 0 for any other command. Its findings (the clipping
/// check's, its exposure's) go into its manifest, with what was let through and why, and into its project's record.
pub fn rendered(args: &[String]) -> i32 {
if args.first().map(String::as_str) != Some("render") {
return 0;
}
let found = finding::taken();
let through = despite(args, std::env::var("RAEA_DESPITE").ok());
let excused: Vec<Despite> = through.iter().map(|(c, w)| Despite { check: c.clone(), why: w.clone() }).collect();
let out = raea_runtime_bundle::flag(args, "-o").or_else(|| raea_runtime_bundle::flag(args, "--review")).map(PathBuf::from);
// the manifest every render writes beside its output (DR2), or where --manifest put it
let manifest = raea_runtime_bundle::flag(args, "--manifest").map(PathBuf::from).or_else(|| Some(raea_runtime_world::manifest_for(out.as_deref()?, std::path::Path::new(args.get(1)?))));
if let Some(m) = manifest {
if let Some(mut v) = std::fs::read(&m).ok().and_then(|b| serde_json::from_slice::<Value>(&b).ok()) {
v["findings"] = json!(found);
if !excused.is_empty() {
v["despite"] = json!(excused);
}
let _ = std::fs::write(&m, v.to_string());
}
}
// a render that is part of another (a review's tiles, a quick check's stills) leaves the entry to that one
let file = args.get(1).filter(|a| !a.starts_with('-') && std::env::var("RAEA_RECORD").as_deref() != Ok("off")).map(PathBuf::from);
if let Some(e) = file.and_then(|f| record::keep("raea render", &f, out.as_deref(), &found, excused, &raea_io_trace::utc(SystemTime::now()).1)) {
println!("raea render: kept in the project's record as {} (raea findings reads it)", e.id);
}
let (line, code) = ending(&found, &through);
println!("{line}");
code
}
#[cfg(test)]
mod tests {
use super::*;
fn s(v: &[&str]) -> Vec<String> {
v.iter().map(|a| a.to_string()).collect()
}
#[test]
fn an_error_fails_the_render_unless_it_is_let_through_and_says_by_what() {
let found = vec![Finding::new("clips", Level::Error, "rider in seat", "raea render"), Finding::new("tilted", Level::Warn, "vase leans", "raea render")];
assert_eq!(ending(&found, &[]), ("raea render: 1 error, 1 warn, 0 notes".into(), 1));
let through = despite(&s(&["render", "a.tsx", "--despite", "clips", "the rider is posed through it"]), None);
assert_eq!(ending(&found, &through), ("raea render: 1 error, 1 warn, 0 notes; 1 let through by --despite clips \"the rider is posed through it\"".into(), 0));
// another check's despite lets nothing through
assert_eq!(ending(&found, &despite(&s(&["render", "--despite", "floats", "x"]), None)).1, 1);
// a harness's
assert_eq!(ending(&found, &despite(&s(&["render"]), Some("all: P26 compares pixels".into()))).1, 0);
assert_eq!(ending(&[], &[]), ("raea render: 0 errors, 0 warns, 0 notes".into(), 0));
}
}
+179
View File
@@ -0,0 +1,179 @@
//! raea's own checks by name (docs/direction.feature DR4): each a system over a composition's worlds, held to its
//! rule's values, as a project's TS check is (sdk/raea/src/check.ts). Taste's six forms are six of them, with the same
//! names and values: the four text forms run over every frame's Text with no render; loudness and still-max are
//! measured on the newest render itself, in the floor's pass (`floor`: raea check's floor on that render).
use std::collections::BTreeMap;
use raea_core_facts::{Facts, Finding, Rule, Source, Text};
/// Where a check runs: every frame; the frame before each cut and the cut's first frame; every frame a line is
/// said or sung on; once, on the first frame; or these.
#[derive(Debug, Clone, PartialEq)]
pub enum Frames {
All,
Cuts,
Lines,
Once,
At(Vec<i64>),
}
impl Frames {
/// As a check file declares it ("all", "cuts", "lines", "once" or a list of frames).
pub fn of(v: &serde_json::Value) -> Result<Frames, String> {
match v {
serde_json::Value::Null => Ok(Frames::All),
serde_json::Value::String(s) => match s.as_str() {
"all" => Ok(Frames::All),
"cuts" => Ok(Frames::Cuts),
"lines" => Ok(Frames::Lines),
"once" => Ok(Frames::Once),
o => Err(format!("frames is \"all\", \"cuts\", \"lines\", \"once\" or a list of frames, not \"{o}\"")),
},
serde_json::Value::Array(a) => a.iter().map(|f| f.as_i64().ok_or("frames lists frame numbers")).collect::<Result<_, _>>().map(Frames::At).map_err(str::to_string),
o => Err(format!("frames is \"all\", \"cuts\", \"lines\", \"once\" or a list of frames, not {o}")),
}
}
/// Whether running here needs the frames of the whole piece read (cuts and lines are found in them).
pub fn whole(&self) -> bool {
matches!(self, Frames::All | Frames::Cuts | Frames::Lines)
}
/// The frames of `worlds` (every frame read, in order) it runs on.
pub fn pick(&self, worlds: &[Facts]) -> Vec<i64> {
let first = worlds.first().map_or(0, |w| w.frame);
match self {
Frames::All => worlds.iter().map(|w| w.frame).collect(),
Frames::Once => vec![first],
Frames::At(v) => v.clone(),
Frames::Lines => worlds.iter().filter(|w| !w.find(&["Line"]).is_empty()).map(|w| w.frame).collect(),
Frames::Cuts => {
let mut cuts: Vec<i64> = worlds.iter().flat_map(|w| w.find(&["Shot"]).into_iter().filter_map(|e| e.components["Shot"]["from"].as_i64())).filter(|f| *f > first).collect();
cuts.sort();
cuts.dedup();
cuts.into_iter().flat_map(|c| [c - 1, c]).collect()
}
}
}
}
/// One of raea's checks: its name, whether it needs a render, where it runs, and its line when no rule gives one.
#[derive(Debug, Clone)]
pub struct Named {
pub name: &'static str,
pub render: bool,
pub frames: Frames,
pub text: &'static str,
}
/// raea's named checks.
pub fn named() -> Vec<Named> {
let n = |name, render, frames, text| Named { name, render, frames, text };
vec![
n("text-hold", false, Frames::All, "text holds long enough to read"),
n("text-above", false, Frames::All, "text sits above a line down the frame"),
n("text-below", false, Frames::All, "text sits below a line down the frame"),
n("text-margin", false, Frames::All, "text keeps a margin from the frame's edges"),
n("loudness", true, Frames::Once, "the mix is at its loudness"),
n("still-max", true, Frames::Once, "the picture is never still for too long"),
n("floor", true, Frames::Once, "raea's floor: what every finished piece must meet"),
n("text-read", true, Frames::All, "text on screen can be read for as long as it needs, and OCR reads what can be read (read.rs)"),
]
}
/// A text's identity across frames: its layer key, else its words.
pub(crate) fn ident(f: &Facts, e: u32, t: &Text) -> (String, Option<String>) {
let key = f.get::<Source>(e).and_then(|s| s.key);
(key.clone().unwrap_or_else(|| t.words.clone()), key)
}
/// A run of frames on which one text measures past its rule: the text, its key, the frames (end exclusive) and the
/// worst measure in the run.
#[derive(Debug, Clone, PartialEq)]
pub struct Run {
pub words: String,
pub key: Option<String>,
pub from: i64,
pub to: i64,
pub value: f64,
}
/// Each text's runs of frames on which `bad` gives a measure, the worst of each run by `worse`.
fn runs(worlds: &[Facts], bad: impl Fn(&Facts, &Text) -> Option<f64>, worse: fn(f64, f64) -> bool) -> Vec<Run> {
let mut open: BTreeMap<String, Run> = BTreeMap::new();
let mut done = Vec::new();
for w in worlds {
for e in w.find(&["Text"]) {
let Some(t) = w.get::<Text>(e.id) else { continue };
let Some(v) = bad(w, &t) else { continue };
let (id, key) = ident(w, e.id, &t);
match open.get_mut(&id) {
Some(r) if r.to == w.frame => {
r.to = w.frame + 1;
if worse(v, r.value) {
r.value = v;
}
}
_ => {
if let Some(r) = open.insert(id, Run { words: t.words.clone(), key, from: w.frame, to: w.frame + 1, value: v }) {
done.push(r);
}
}
}
}
}
done.extend(open.into_values());
done.sort_by_key(|r| (r.from, r.words.clone()));
done
}
pub(crate) fn quote(s: &str) -> String {
let s: String = s.split_whitespace().collect::<Vec<_>>().join(" ");
if s.chars().count() > 40 { format!("\"{}…\"", s.chars().take(39).collect::<String>()) } else { format!("\"{s}\"") }
}
/// A text form's findings over `worlds` (every frame of the composition, in order), held to `rule`'s `value`.
pub fn text(rule: &Rule, worlds: &[Facts]) -> Vec<Finding> {
let level = rule.level.unwrap_or(raea_core_facts::Level::Error);
let Some(v) = rule.number("value") else {
return vec![Finding::new(&rule.id, level, format!("{} needs a value (values: {{ value: N }})", rule.check), &rule.by)];
};
let Some(first) = worlds.first() else { return Vec::new() };
let (w, h, fps) = (first.width as f64, first.height as f64, first.fps);
// the runs of text past the line across the frame at `v`%: by its edge `k` (1 its top, 3 its bottom), below the
// line (`down`) or above it
let past = |k: usize, down: bool| {
let worse: fn(f64, f64) -> bool = if down { |a, b| a > b } else { |a, b| a < b };
// a pixel past it, so text that only touches the line holds it
let line = v + (if down { 100.0 } else { -100.0 }) / h;
runs(worlds, move |_, t| t.box_.map(|b| b[k] * 100.0).filter(|y| worse(*y, line)), worse)
};
// the runs that break the form, each with its measure as its value; what's said of one ({n} its measure, {v} the
// rule's); and the unit
let (got, says, unit): (Vec<Run>, &str, &str) = match rule.check.as_str() {
"text-hold" => {
let on = runs(worlds, |_, _| Some(0.0), |_, _| false).into_iter().map(|r| Run { value: (r.to - r.from) as f64 / fps, ..r });
(on.filter(|r| r.value + 0.05 < v).collect(), "is on for {n} s, under {v} s", "s")
}
"text-above" => (past(3, true), "reaches {n}% down the frame, below {v}%", "%"),
"text-below" => (past(1, false), "starts {n}% down the frame, above {v}%", "%"),
"text-margin" => {
let s = w.min(h) / 1080.0;
let margin = move |b: [f64; 4]| (b[0] * w).min(b[1] * h).min(w - b[2] * w).min(h - b[3] * h) / s;
(runs(worlds, |_, t| t.box_.map(margin).filter(|m| m + 1.0 < v), |a, b| a < b), "is {n} px from the edge, inside {v}", "px")
}
other => return vec![Finding::new(&rule.id, level, format!("{other} isn't a text check"), &rule.by)],
};
let shown = |x: f64| if unit == "s" { format!("{x:.1}") } else { format!("{x:.0}") };
got.iter()
.map(|r| {
let said = format!("{} {}", quote(&r.words), says.replace("{n}", &shown(r.value)).replace("{v}", &shown(v)));
let said = if rule.text.is_empty() { said } else { format!("{said} (\"{}\")", rule.text) };
Finding::new(&rule.id, level, said, &rule.by).about(r.words.clone(), r.key.clone()).frames(r.from, r.to).measure(&rule.check, (r.value * 10.0).round() / 10.0, unit, Some(v))
})
.collect()
}
#[cfg(test)]
mod tests;
+75
View File
@@ -0,0 +1,75 @@
use super::*;
use raea_core_facts::{Level, Shot};
use serde_json::{json, Map, Value};
/// Frames 0..n of a 1080x1920 piece at 30 fps, each holding the texts `on(frame)` gives (words, box).
fn piece(n: i64, on: impl Fn(i64) -> Vec<(&'static str, [f64; 4])>) -> Vec<Facts> {
(0..n)
.map(|f| {
let mut w = Facts::new(f, 1080, 1920, 30.0);
for (words, b) in on(f) {
let e = w.spawn(None);
w.put(e, &Text { words: words.into(), font: None, size: Some(64.0), box_: Some(b), extruded: 0.0, lines: Some(1), needs: None });
}
w
})
.collect()
}
fn rule(check: &str, v: f64) -> Rule {
Rule::named(check, "", Map::from_iter([("value".to_string(), Value::from(v))]), Level::Error, "taste taste.ts")
}
#[test]
fn a_text_on_too_briefly_is_found_once_over_its_frames() {
// "GO" is on frames 10 to 24 (half a second), "STAY" all 90
let w = piece(90, |f| {
let mut v = vec![("STAY", [0.1, 0.1, 0.9, 0.2])];
if (10..25).contains(&f) {
v.push(("GO", [0.1, 0.5, 0.9, 0.6]));
}
v
});
let got = text(&rule("text-hold", 2.0), &w);
assert_eq!(got.len(), 1, "{got:?}");
assert_eq!((got[0].frames, got[0].about[0].name.as_str()), (Some([10, 25]), "GO"));
assert!(got[0].says.starts_with("\"GO\" is on for 0.5 s, under 2.0 s"), "{}", got[0].says);
assert_eq!(got[0].measure.as_ref().map(|m| (m.value, m.limit)), Some((0.5, Some(2.0))));
}
#[test]
fn placement_and_margin_name_the_worst_frame_of_a_run() {
// a caption whose bottom slides down from 70% to 85% over frames 0 to 30
let w = piece(31, |f| vec![("SALE", [0.2, 0.6, 0.8, 0.70 + 0.005 * f as f64])]);
let above = text(&rule("text-above", 80.0), &w);
assert_eq!(above.len(), 1);
assert_eq!(above[0].frames, Some([21, 31]), "past 80% from frame 21: {above:?}");
assert!(above[0].says.contains("reaches 85% down the frame, below 80%"), "{}", above[0].says);
assert!(text(&rule("text-below", 50.0), &w).is_empty(), "it starts at 60%, below 50%");
// 0.2 of 1080 is 216 px from the left and right; the bottom is 0.15 of 1920 = 288 px at its lowest
assert!(text(&rule("text-margin", 200.0), &w).is_empty());
assert_eq!(text(&rule("text-margin", 250.0), &w).len(), 1);
}
#[test]
fn a_rule_with_no_value_says_so() {
let r = Rule { level: Some(Level::Warn), ..Rule::named("text-hold", "", Map::new(), Level::Error, "project controllers/rules.ts") };
let got = text(&r, &piece(3, |_| vec![]));
assert_eq!((got.len(), got[0].level), (1, Level::Warn));
assert!(got[0].says.contains("needs a value"));
}
#[test]
fn cuts_are_the_frame_before_and_the_first_frame_of_each_shot_after_the_first() {
let mut w = piece(60, |_| vec![]);
for f in &mut w {
let (from, to) = if f.frame < 20 { (0, Some(20)) } else { (20, None) };
let e = f.spawn(None);
f.put(e, &Shot { name: None, from, to });
}
assert_eq!(Frames::Cuts.pick(&w), vec![19, 20]);
assert_eq!(Frames::Once.pick(&w), vec![0]);
assert_eq!(Frames::of(&json!("lines")).unwrap(), Frames::Lines);
assert_eq!(Frames::of(&json!([3, 4])).unwrap(), Frames::At(vec![3, 4]));
assert!(Frames::of(&json!("every")).unwrap_err().contains("not \"every\""));
}
+105
View File
@@ -0,0 +1,105 @@
//! A project's own checks in TypeScript (sdk/raea/src/check.ts, DR4): each file's declaration read first (its id,
//! line, what it needs and where it runs), then one run of every planned check over the worlds it ranges over, in the
//! engine's V8 with nothing drawn. raea/check's `runChecks` runs them; what they found comes back as Findings.
use std::path::{Path, PathBuf};
use raea_core_facts::{Facts, Finding, Level};
use serde_json::{json, Value};
use crate::systems::Frames;
type R<T> = Result<T, String>;
/// What the CLI lends a check: its evaluator of a .ts module's default export (as JSON), and its headless run of a
/// bundle (exit code and what it printed).
pub struct Host {
pub eval: fn(&Path) -> R<String>,
pub run: fn(&Path, f64) -> R<(i32, String)>,
}
/// A check file's declaration.
#[derive(Debug, Clone)]
pub struct Meta {
pub file: PathBuf,
pub id: String,
pub text: String,
pub render: bool,
pub level: Level,
pub frames: Frames,
}
/// The declaration of the check `file`'s default export is.
pub fn meta(file: &Path, host: &Host) -> R<Meta> {
let name = file.display();
let v: Value = serde_json::from_str(&(host.eval)(file)?).map_err(|e| format!("{name}: {e}"))?;
let s = |k: &str| v[k].as_str().map(str::to_string);
let id = s("id").ok_or_else(|| format!("{name}: its default export isn't a check({{ id, text }}, system) from \"raea/check\""))?;
let render = match v["needs"].as_str() {
None => false,
Some("render") => true,
Some(o) => return Err(format!("{name}: a check needs \"render\" or nothing, not \"{o}\"")),
};
let level = match s("level").as_deref() {
None => Level::Error,
Some(w @ ("error" | "warn" | "note")) => Level::of_word(w),
Some(o) => return Err(format!("{name}: a check's level is error, warn or note, not \"{o}\"")),
};
let frames = Frames::of(&v["frames"]).map_err(|e| format!("{name}: {e}"))?;
Ok(Meta { file: file.to_path_buf(), id, text: s("text").unwrap_or_default(), render, level, frames })
}
/// One planned run: the check (its index in `files`), its frames, and its rule's values, level (None: the check's
/// own) and `by`.
pub struct Planned {
pub check: usize,
pub frames: Vec<i64>,
pub values: serde_json::Map<String, Value>,
pub level: Option<Level>,
pub by: String,
}
/// Every planned check run on its frames of `worlds`, in one bundle: what each found (its rule's level where the
/// finding names none, its `by` the rule's), and a finding for each check that threw.
pub fn run(files: &[PathBuf], plan: &[Planned], worlds: &[Facts], host: &Host) -> R<Vec<Finding>> {
if plan.is_empty() {
return Ok(Vec::new());
}
let work = std::env::temp_dir().join(format!("raea-check-{}", std::process::id()));
std::fs::create_dir_all(&work).map_err(|e| e.to_string())?;
let data = work.join("worlds.json");
std::fs::write(&data, serde_json::to_string(worlds).map_err(|e| e.to_string())?).map_err(|e| e.to_string())?;
let imports: String = files.iter().enumerate().map(|(i, f)| format!("import c{i} from {:?};\n", f.canonicalize().unwrap_or_else(|_| f.clone()).display().to_string())).collect();
let checks = (0..files.len()).map(|i| format!("c{i}")).collect::<Vec<_>>().join(", ");
let planned: Vec<Value> = plan.iter().map(|p| json!({"check": p.check, "frames": p.frames, "values": p.values, "level": p.level, "by": p.by})).collect();
let entry = format!(
"import {{ declared, runChecks }} from \"raea/check\";\n{imports}import worlds from {data:?};\nconst call = (globalThis as any).__raea_call;\n\
try {{ const checks = [{checks}]; declared(checks); const r = runChecks(checks, {plan}, worlds as any); call(\"print\", JSON.stringify({{ text: JSON.stringify(r) }})); call(\"done\", JSON.stringify({{ code: 0 }})); }}\n\
catch (e: any) {{ call(\"print\", JSON.stringify({{ text: \"error: \" + (e && e.message ? e.message : String(e)) }})); call(\"done\", JSON.stringify({{ code: 1 }})); }}\n",
data = data.display().to_string(),
plan = Value::Array(planned),
);
let js = work.join("checks.js");
let ran = raea_runtime_bundle::bundle_entry(&entry, &js, &[]).and_then(|_| {
// what the checks print is raea's to read: nothing reaches the terminal
let echo = raea_runtime_react::native::ECHO.swap(false, std::sync::atomic::Ordering::Relaxed);
let ran = (host.run)(&js, 120.0);
raea_runtime_react::native::ECHO.store(echo, std::sync::atomic::Ordering::Relaxed);
ran
});
let _ = std::fs::remove_dir_all(&work);
let (code, printed) = ran?;
let last = printed.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("");
if code != 0 {
return Err(format!("the project's checks: {}", last.strip_prefix("error: ").unwrap_or(last)));
}
let got: Value = serde_json::from_str(last).map_err(|e| format!("the project's checks printed {last:?}: {e}"))?;
// a finding that doesn't read is said as it came, never dropped
let unread = |f: &Value| Finding::new(f["check"].as_str().unwrap_or("check"), Level::Error, format!("a finding raea couldn't read: {f}"), "raea check");
let mut out: Vec<Finding> = got["findings"].as_array().into_iter().flatten().map(|f| Finding::read(f).unwrap_or_else(|| unread(f))).collect();
for t in got["threw"].as_array().into_iter().flatten() {
let id = t["check"].as_str().unwrap_or("check");
out.push(Finding::new(id, Level::Error, format!("the check threw {}", t["says"].as_str().unwrap_or("")), "raea check").fix("fix the check: it ran on none of the frames after this one"));
}
Ok(out)
}
+229
View File
@@ -0,0 +1,229 @@
//! `raea world EDIT.tsx`: a composition's frame as one world (docs/direction.feature DR1), read with React stepped and
//! nothing drawn; the page laid out unless `--no-layout`. `--find` is one query of it, raea/ecs's find: the entities
//! with every component `with` names, none `without` names, and each `where` field equal (`"Layer.medium": "2d-type"`).
use raea_runtime_world::{Ask, Entity, Facts, Render};
use raea_runtime_bundle::flag;
use serde_json::{json, Value};
pub const USAGE: &str = "raea world EDIT.tsx [--composition ID] [--frame N | --at A-B|A,B] [--find JSON] [--no-layout] [--render OUT | --no-render] [--json] (a frame as one world: its layers, text, parts, camera, shots, clips, cues and lines as entities with components, each measured, with what its newest render measured (contrast, light and movement, loudness, onsets, covers) or what waits for one; --find '{\"with\": [\"Text\", \"Layer\"], \"where\": {\"Layer.medium\": \"2d-type\"}}' is one query across media)";
/// A query: the components an entity has, those it hasn't, and fields (Component.field.field) equal to a value.
#[derive(Debug, Default, PartialEq)]
pub struct Find {
pub with: Vec<String>,
pub without: Vec<String>,
pub fields: Vec<(String, Value)>,
}
impl Find {
pub fn parse(s: &str) -> Result<Find, String> {
let v: Value = serde_json::from_str(s).map_err(|e| format!("--find takes JSON ({{\"with\": [...], \"without\": [...], \"where\": {{\"Comp.field\": value}}}}): {e}"))?;
let names = |k: &str| -> Result<Vec<String>, String> {
match &v[k] {
Value::Null => Ok(Vec::new()),
Value::Array(a) => a.iter().map(|n| n.as_str().map(str::to_string).ok_or_else(|| format!("--find's {k} lists component names"))).collect(),
_ => Err(format!("--find's {k} is a list of component names")),
}
};
let fields = match &v["where"] {
Value::Null => Vec::new(),
Value::Object(m) => m.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
_ => return Err("--find's where is an object of \"Component.field\": value".into()),
};
let known = ["with", "without", "where"];
if let Some(k) = v.as_object().and_then(|o| o.keys().find(|k| !known.contains(&k.as_str()))) {
return Err(format!("--find has no \"{k}\" (it takes with, without and where)"));
}
Ok(Find { with: names("with")?, without: names("without")?, fields })
}
fn holds(&self, e: &Entity) -> bool {
let at = |path: &str| -> Option<&Value> {
let mut keys = path.split('.');
let mut v = e.components.get(keys.next()?)?;
for k in keys {
v = v.get(k)?;
}
Some(v)
};
self.with.iter().all(|c| e.components.contains_key(c)) && !self.without.iter().any(|c| e.components.contains_key(c)) && self.fields.iter().all(|(p, v)| at(p) == Some(v))
}
}
/// The entities of `w` that `q` finds, in id order.
pub fn find<'a>(w: &'a Facts, q: &Find) -> Vec<&'a Entity> {
w.entities.iter().filter(|e| q.holds(e)).collect()
}
fn frames(args: &[String]) -> Result<Vec<i64>, String> {
let n = |s: &str, k: &str| s.trim().parse::<i64>().map_err(|_| format!("{k} takes frame numbers, got \"{s}\""));
match (flag(args, "--frame").as_deref(), flag(args, "--at").as_deref()) {
(Some(_), Some(_)) => Err("give --frame or --at, not both".into()),
(Some(f), None) => Ok(vec![n(f, "--frame")?]),
// as render's --at: a list (A,B,C), or a range (A-B), each frame its own world
(None, Some(r)) => match r.split_once('-') {
Some((a, b)) => {
let (a, b) = (n(a, "--at")?, n(b, "--at")?);
if b < a {
return Err(format!("--at {r} runs backwards"));
}
Ok((a..=b).collect())
}
None => r.split(',').map(|f| n(f, "--at")).collect(),
},
(None, None) => Ok(vec![0]),
}
}
/// One entity as a line: its id, parent and each component's gist.
fn line(e: &Entity) -> String {
let s = raea_runtime_world::text_of;
let r2 = |v: &Value| v.as_array().map(|a| a.iter().map(|x| format!("{:.2}", x.as_f64().unwrap_or(0.0))).collect::<Vec<_>>().join(", ")).unwrap_or_default();
let mut out = format!("#{}{}", e.id, e.parent.map(|p| format!(" in #{p}")).unwrap_or_default());
for (name, c) in &e.components {
let gist = match name.as_str() {
"Layer" => format!("{} at {}{}", s(&c["medium"]), c["order"], if c["opacity"].as_f64().unwrap_or(1.0) < 1.0 { format!(", opacity {}", c["opacity"]) } else { String::new() }),
"Text" => format!("\"{}\"{}{}{}", s(&c["words"]), c["size"].as_f64().map(|v| format!(" {v} px")).unwrap_or_default(), if c["box"].is_array() { format!(" box ({})", r2(&c["box"])) } else { String::new() }, c["needs"].as_str().map(|n| format!(" (needs {n})")).unwrap_or_default()),
"Part" => format!("{} \"{}\"{}{}", s(&c["kind"]), s(&c["name"]), if c["min"].is_array() { format!(" box ({}) to ({})", r2(&c["min"]), r2(&c["max"])) } else { " (not measured)".into() }, c["triangles"].as_u64().map(|t| format!(", {t} triangles")).unwrap_or_default()),
"Camera" => format!("eye ({}) looking at ({}){}", r2(&c["eye"]), r2(&c["look"]), if c["velocity"].is_array() { format!(", moving ({}) m/s", r2(&c["velocity"])) } else { String::new() }),
"Shot" => format!("{} frames {} to {}", c["name"].as_str().unwrap_or("(unnamed)"), c["from"], c["to"].as_i64().map_or("the end".into(), |t| t.to_string())),
"Clip" => format!("{} at {}s of it, {} words", s(&c["source"]), c["time"].as_f64().map_or("?".into(), |t| format!("{t:.2}")), c["words"].as_array().map_or(0, Vec::len)),
"Cue" => format!("{} from {:.2}s{}", s(&c["source"]), c["at"].as_f64().unwrap_or(0.0), c["gain"].as_f64().map(|g| format!(" at {g} dB")).unwrap_or_default()),
"Line" => format!("\"{}\" from {:.2}s{}", s(&c["text"]), c["from"].as_f64().unwrap_or(0.0), c["needs"].as_str().map(|n| format!(" (needs {n})")).unwrap_or_default()),
"Source" => format!("{}:{}{}", s(&c["file"]), c["line"], c["component"].as_str().map(|n| format!(" <{n}>")).unwrap_or_default()),
"Contrast" => format!("{}:1 against its pixels", c["ratio"]),
"Picture" => picture(c),
"Onset" => c["at"].as_f64().map_or_else(|| "not heard where it starts".into(), |a| format!("heard at {a:.2}s ({:+} ms)", c["late_ms"].as_f64().unwrap_or(0.0))),
"Covers" => c.as_array().into_iter().flatten().map(|x| format!("#{} {:.0}%", x["layer"], x["share"].as_f64().unwrap_or(0.0) * 100.0)).collect::<Vec<_>>().join(", "),
_ => c.get("to").map_or_else(|| c.to_string(), |t| format!("#{t}")),
};
out.push_str(&format!(" {name} {gist}"));
}
out
}
/// A picture's light and movement as words.
fn picture(c: &Value) -> String {
let moved = c["motion"].as_f64().map(|m| format!(", motion {m:.3}")).unwrap_or_default();
format!("luma {:.3}{moved}{}", c["luma"].as_f64().unwrap_or(0.0), c["frames"].as_u64().map(|n| format!(" over {n} frames")).unwrap_or_default())
}
/// The frame's resources as lines: the render its facts came from, its mix and picture, what waits for one.
fn resources(w: &Facts) -> Vec<String> {
let r = &w.resources;
let mut out = Vec::new();
if let Some(x) = r.get("Rendered") {
let stale = if x["stale"] == true { " (made before the composition last changed: its measures are of that version)" } else { "" };
out.push(format!(" rendered: {}{}{stale}", raea_runtime_world::text_of(&x["out"]), x["record"].as_str().map(|i| format!(" ({i})")).unwrap_or_default()));
}
if let Some(m) = r.get("Mix") {
out.push(match m["lufs"].as_f64() {
Some(l) => format!(" mix: {l:.1} LUFS{}", m["peak"].as_f64().map(|p| format!(", true peak {p:.1} dBTP")).unwrap_or_default()),
None => " mix: no sound".into(),
});
}
if let Some(p) = r.get("Picture") {
out.push(format!(" picture: {}", picture(p)));
}
if let Some(Value::Object(ws)) = r.get("Waits") {
let mut by: Vec<(String, Vec<&str>)> = Vec::new();
for (c, on) in ws {
let on = raea_runtime_world::text_of(on);
match by.iter_mut().find(|(o, _)| *o == on) {
Some((_, cs)) => cs.push(c),
None => by.push((on, vec![c])),
}
}
out.extend(by.into_iter().map(|(on, cs)| format!(" waits for {on}: {}", cs.join(", "))));
}
out
}
/// Which render's facts join: `--render OUT`, none with `--no-render`, else the newest in the project's record.
fn render(args: &[String]) -> Result<Render, String> {
match (flag(args, "--render"), args.iter().any(|a| a == "--no-render")) {
(Some(_), true) => Err("give --render or --no-render, not both".into()),
(Some(o), false) => Ok(Render::From(o.into())),
(None, true) => Ok(Render::Off),
(None, false) => Ok(Render::Newest),
}
}
fn run(args: &[String]) -> Result<String, String> {
let edit = args.iter().find(|a| a.ends_with(".tsx")).ok_or(USAGE)?;
let q = flag(args, "--find").as_deref().map(Find::parse).transpose()?;
let ask = Ask { frames: frames(args)?, layout: !args.iter().any(|a| a == "--no-layout"), render: render(args)?, join_on: None };
let worlds = raea_runtime_world::read(std::path::Path::new(edit), &raea_runtime_bundle::comp_opts(args)?, &ask)?;
if args.iter().any(|a| a == "--json") {
let one = |w: &Facts| match &q {
Some(q) => json!({"frame": w.frame, "found": find(w, q)}),
None => serde_json::to_value(w).unwrap_or(Value::Null),
};
let v = if worlds.len() == 1 { one(&worlds[0]) } else { Value::Array(worlds.iter().map(one).collect()) };
return Ok(serde_json::to_string_pretty(&v).unwrap_or_default());
}
let mut out = Vec::new();
for w in &worlds {
let shown = q.as_ref().map_or_else(|| w.entities.iter().collect(), |q| find(w, q));
out.push(format!("frame {} ({}x{} at {} fps): {} of {} entities", w.frame, w.width, w.height, w.fps, shown.len(), w.entities.len()));
out.extend(resources(w));
out.extend(shown.into_iter().map(line));
}
Ok(out.join("\n"))
}
/// `raea world ...`: its exit code.
pub fn cli(args: &[String]) -> i32 {
let got = run(args);
match &got {
Ok(s) => println!("{s}"),
Err(e) => eprintln!("raea world: {e}"),
}
if got.is_ok() { 0 } else { 2 }
}
#[cfg(test)]
mod tests {
use super::*;
use raea_runtime_world::{Layer, Medium, Part, Text};
fn world() -> Facts {
let mut w = Facts::new(0, 1920, 1080, 30.0);
let lyric = w.spawn(None);
w.put(lyric, &Layer { medium: Medium::Type2d, order: 2, opacity: 1.0, blend: None });
w.put(lyric, &Text { words: "GIVE IT BACK".into(), font: None, size: Some(96.0), box_: Some([0.1, 0.1, 0.6, 0.2]), extruded: 0.0, lines: Some(1), needs: None });
let scene = w.spawn(None);
w.put(scene, &Layer { medium: Medium::Scene3d, order: 0, opacity: 1.0, blend: None });
let sign = w.spawn(Some(scene));
w.put(sign, &Text { words: "OPEN".into(), font: None, size: None, box_: None, extruded: 0.2, lines: Some(1), needs: None });
w.put(sign, &Part { kind: "text3d".into(), name: "sign".into(), tags: vec![], at: [0.0; 3], rotation: [0.0, 0.0, 0.0, 1.0], scale: [1.0; 3], min: None, max: None, own: None, triangles: None, src: None, material: None, color: None });
let hidden = w.spawn(None);
w.put(hidden, &Layer { medium: Medium::Type2d, order: 3, opacity: 1.0, blend: None });
w.put(hidden, &Text { words: "UNDER".into(), font: None, size: None, box_: None, extruded: 0.0, lines: None, needs: None });
w.relate(hidden, "MaskedBy", sign);
w
}
#[test]
fn one_find_spans_media() {
let w = world();
let flat = Find::parse(r#"{"with": ["Text", "Layer"], "where": {"Layer.medium": "2d-type"}, "without": ["MaskedBy"]}"#).unwrap();
let got: Vec<u32> = find(&w, &flat).iter().map(|e| e.id).collect();
assert_eq!(got, vec![0], "the 2D lyric no part masks, not the 3D sign or the masked line");
let words_in_3d = Find::parse(r#"{"with": ["Text", "Part"], "where": {"Text.extruded": 0.2}}"#).unwrap();
assert_eq!(find(&w, &words_in_3d).len(), 1);
assert!(line(&w.entities[0]).contains("\"GIVE IT BACK\" 96 px box (0.10, 0.10, 0.60, 0.20)"), "{}", line(&w.entities[0]));
}
#[test]
fn a_bad_query_or_range_says_what_it_takes() {
assert!(Find::parse(r#"{"has": ["Text"]}"#).unwrap_err().contains("no \"has\""));
assert!(Find::parse("Text").is_err());
let a = |s: &[&str]| s.iter().map(|x| x.to_string()).collect::<Vec<_>>();
assert_eq!(frames(&a(&["e.tsx", "--at", "3-5"])).unwrap(), vec![3, 4, 5]);
assert!(frames(&a(&["--at", "5-3"])).unwrap_err().contains("backwards"));
assert_eq!(frames(&a(&["--at", "3,7"])).unwrap(), vec![3, 7], "a list, as render's --at");
assert_eq!(frames(&a(&["e.tsx"])).unwrap(), vec![0]);
}
}
+23
View File
@@ -0,0 +1,23 @@
[package]
name = "raea-app-engines"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "The `raea` verbs that script other engines from TypeScript: Blender (`setup blender`, `blender run`) and Godot with GodotJS (`setup godot`, `godot run|types|open`)"
[dependencies]
# Blender found or downloaded, its scripts in Python, and the helpers Godot's setup shares (apps/tools/src/blender.rs)
raea-app-tools = { path = "../tools" }
raea-io-home = { path = "../../io/home" }
# a TypeScript script bundled and run on raea's engine, posting raea/blender's batches to the bridge (blender.post)
raea-runtime-bundle = { path = "../../runtime/bundle" }
raea-runtime-export = { path = "../../runtime/export" }
raea-runtime-calls = { path = "../../runtime/calls" }
# a composition's 3D as scene.json, a Godot project from it, and changes read back (raea scene export, raea godot export|back,
# raea blender open|back)
raea-app-interchange = { path = "../interchange" }
serde_json = "1"
# Godot with GodotJS, unpacked from its release zip (`raea setup godot`), and the script path the bundler imports
zip = { version = "9", default-features = false, features = ["deflate-flate2"] }
dunce = "1"
+142
View File
@@ -0,0 +1,142 @@
//! The Blender a TypeScript script drives (`raea blender run SCRIPT.ts`, sdk/blender): a headless Blender started with
//! raea's bridge (sdk/blender/python/headless.py), which serves raea/blender's batches on 127.0.0.1 behind a token,
//! and ends with this process. The CLI runs the script on raea's engine, posting each batch (the native call
//! blender.post, runtime/calls/src/blender.rs); Node and Bun start their own (sdk/blender/src/launch.ts).
use std::hash::{BuildHasher, Hasher};
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};
type R<T> = Result<T, String>;
/// A script raea runs as TypeScript (against raea/blender) rather than as Python.
pub fn is_ts(script: &str) -> bool {
[".ts", ".tsx", ".mts", ".js", ".mjs"].iter().any(|e| script.ends_with(e))
}
/// The bridge script in the SDK raea ships (its home's sdk/, else this checkout's).
pub fn bridge_script() -> R<PathBuf> {
let shipped = raea_io_home::home().join("sdk/blender/python/headless.py");
if shipped.is_file() {
return Ok(shipped);
}
let here = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../sdk/blender/python/headless.py");
if here.is_file() {
return Ok(here);
}
Err(format!("raea/blender's bridge isn't here ({}): reinstall raea", shipped.display()))
}
/// 128 bits from the OS's random keys (each RandomState is seeded from them), as hex.
fn token() -> String {
let word = || {
let mut h = std::collections::hash_map::RandomState::new().build_hasher();
h.write_u128(Instant::now().elapsed().as_nanos() ^ u128::from(std::process::id()));
h.finish()
};
format!("{:016x}{:016x}", word(), word())
}
pub struct Bridge {
pub port: u16,
pub token: String,
child: Child,
}
/// Blender's own lines nobody needs from a script's run: its banner and its goodbye.
fn banner(l: &str) -> bool {
let t = l.trim();
t.starts_with("Blender quit") || (t.starts_with("Blender ") && t.as_bytes().get(8).is_some_and(u8::is_ascii_digit))
}
/// A headless Blender serving raea/blender: `file` (a .blend) opened, `args` after `--` (Python's sys.argv). Its
/// output after the bridge starts goes to stderr, as the script's prints.
pub fn start(blender: &Path, file: Option<&Path>, args: &[String]) -> R<Bridge> {
let script = bridge_script()?;
let token = token();
let mut cmd = Command::new(blender);
cmd.args(["--background", "--factory-startup"]);
if let Some(f) = file {
cmd.arg(f);
}
cmd.args(["--python-exit-code", "1", "--python"]).arg(&script).arg("--").args(args);
cmd.env("RAEA_BLENDER_TOKEN", &token).env("RAEA_BLENDER_PORT", "0").env("RAEA_BLENDER_PARENT", std::process::id().to_string());
let mut child = cmd.stdout(Stdio::piped()).stderr(Stdio::inherit()).spawn().map_err(|e| format!("{}: {e}", blender.display()))?;
let mut lines = BufReader::new(child.stdout.take().ok_or("Blender's output")?).lines();
let mut early = Vec::new();
let port = loop {
match lines.next() {
Some(Ok(l)) => match l.trim().strip_prefix("RAEA_BLENDER_READY ") {
Some(ready) => {
let v: serde_json::Value = serde_json::from_str(ready).map_err(|e| format!("the bridge's ready line {ready}: {e}"))?;
break v.get("port").and_then(serde_json::Value::as_u64).ok_or("the bridge's port")? as u16;
}
None => early.push(l),
},
_ => {
let st = child.wait().map_err(|e| e.to_string())?;
let tail = early[early.len().saturating_sub(30)..].join("\n");
return Err(format!("Blender exited ({st}) before raea's bridge started:\n{tail}"));
}
}
};
std::thread::spawn(move || {
for l in lines.map_while(Result::ok) {
if !banner(&l) {
eprintln!("{l}");
}
}
});
Ok(Bridge { port, token, child })
}
impl Bridge {
/// Waits for Blender to exit (after the bridge was asked to quit), killing it after 10 s.
pub fn wait(mut self) {
let t0 = Instant::now();
while t0.elapsed() < Duration::from_secs(10) {
if let Ok(Some(_)) = self.child.try_wait() {
return;
}
std::thread::sleep(Duration::from_millis(20));
}
let _ = self.child.kill();
let _ = self.child.wait();
}
}
impl Drop for Bridge {
/// A run that ends early (an error, a panic) leaves no Blender behind.
fn drop(&mut self) {
if let Ok(None) = self.child.try_wait() {
let _ = self.child.kill();
let _ = self.child.wait();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn typescript_scripts_by_extension() {
assert!(is_ts("scene.ts") && is_ts("a/b.tsx") && is_ts("x.mjs"));
assert!(!is_ts("convert.py") && !is_ts("blender/repair.py"));
}
#[test]
fn tokens_differ_and_are_128_bits() {
let (a, b) = (token(), token());
assert_eq!(a.len(), 32);
assert_ne!(a, b);
}
#[test]
fn the_banner_is_dropped_and_prints_kept() {
assert!(banner("Blender 5.2.1 LTS (hash 1a2b3c built 2026-10-01)") && banner("Blender quit"));
assert!(!banner("Blender found 3 objects") && !banner("made Cube"));
}
}
+61
View File
@@ -0,0 +1,61 @@
//! `raea blender run SCRIPT.ts [FILE.blend] [ARGS...]`: a headless Blender with raea's bridge (FILE.blend opened, ARGS
//! its sys.argv after --), the script on raea's engine with each batch posted to it (blender.post), Blender quit after.
use std::path::{Path, PathBuf};
use raea_runtime_calls::blender::{BRIDGE, post};
use serde_json::json;
use crate::{R, blender_bridge};
/// What an entry does once its work is a promise: the session closed (sdk/blender/src/blender.ts's
/// __raea_blender_end), so a failure in Blender the script never awaited fails the run, as an uncaught Python exception
/// would; then the run's exit.
pub(crate) const CLOSE: &str = ".then(() => (globalThis as any).__raea_blender_end?.()).then(() => call(\"done\", JSON.stringify({ code: 0 })), (e: any) => { call(\"print\", JSON.stringify({ text: \"error: \" + String(e) + (e && e.name === \"BlenderError\" ? (e.pythonTrace ? \"\\n\" + e.pythonTrace : \"\") : e && e.stack ? \"\\n\" + e.stack : \"\") })); call(\"done\", JSON.stringify({ code: 1 })); });";
/// The script's default export, called and awaited.
pub(crate) const DEFAULT: &str = "Promise.resolve().then(() => (typeof (M as any).default === \"function\" ? (M as any).default() : undefined))";
/// `--timeout SECS` taken out of ARGS (Blender's sys.argv), and its seconds.
pub(crate) fn timeout(rest: &mut Vec<String>) -> f64 {
let mut secs = 3600.0;
if let Some(i) = rest.iter().position(|a| a == "--timeout") {
secs = rest.get(i + 1).and_then(|t| t.parse().ok()).unwrap_or(secs);
rest.drain(i..(i + 2).min(rest.len()));
}
secs
}
/// An entry's bundle run against a headless Blender started with the bridge (`file` opened, `rest` its sys.argv):
/// the bundle's exit code. Blender is quit after, and killed if the run ends any other way.
pub(crate) fn session(entry: &str, file: Option<&Path>, rest: &[String], secs: f64) -> R<i32> {
let (bin, _) = raea_app_tools::blender::find().ok_or("no Blender: raea setup blender finds or downloads one")?;
let bridge = blender_bridge::start(&bin, file, rest)?;
*BRIDGE.lock().map_err(|e| e.to_string())? = Some((bridge.port, bridge.token.clone()));
let out = std::env::temp_dir().join(format!("raea-blender-{}.js", std::process::id()));
let ran = raea_runtime_bundle::bundle_entry(entry, &out, &[]).and_then(|_| raea_runtime_export::run_bundle(&out, secs));
let _ = std::fs::remove_file(&out);
let _ = post(&json!({ "sid": "raea", "ops": [{ "o": "quit" }] }));
*BRIDGE.lock().map_err(|e| e.to_string())? = None;
bridge.wait();
Ok(ran?.0)
}
/// A path as an entry's import specifier (Windows' verbatim prefix dropped, as raea-runtime-bundle does).
pub(crate) fn spec(p: &Path) -> String {
format!("{:?}", dunce::simplified(p).display().to_string())
}
pub fn run(args: &[String]) -> R<String> {
let ts = PathBuf::from(&args[2]).canonicalize().map_err(|e| format!("{}: {e}", args[2]))?;
let file = args.get(3).filter(|a| a.ends_with(".blend")).map(PathBuf::from);
// ARGS for Blender's sys.argv, without raea's own --timeout SECS
let mut rest = args[if file.is_some() { 4 } else { 3 }..].to_vec();
let secs = timeout(&mut rest);
let entry = format!("import * as M from {};\nconst call = (globalThis as any).__raea_call;\n{DEFAULT}{CLOSE}\n", spec(&ts));
let code = session(&entry, file.as_deref(), &rest, secs)?;
if code != 0 {
return Err(format!("{} ended with exit {code}", args[2]));
}
Ok(String::new())
}
+305
View File
@@ -0,0 +1,305 @@
//! `raea setup godot`, `raea godot types` and `raea godot open`; `raea godot run` is godot_run.rs. raea's Godot is
//! Godot 4.6.1 with GodotJS (github.com/godotjs/GodotJS, MIT): Godot's whole API from TypeScript, on Godot's own
//! JavaScript engine, JavaScriptCore on the Mac and QuickJS-ng on Windows and Linux (no V8). Godot without GodotJS
//! can't run a script, so raea uses an editor build with GodotJS in it (the editor, headless or not, runs scripts and
//! projects): raea's own (GD9, sdk/godot/build), from raea's release, else GodotJS's, from its GitHub release, into
//! ~/.raea/tools/godot and checked against the sha256 pinned here.
use std::path::{Path, PathBuf};
use std::process::Command;
use raea_app_tools::blender::own_dir;
type R<T> = Result<T, String>;
pub const USAGE: &str = "raea setup godot [--check] (download Godot 4.6.1 with GodotJS, its TypeScript bindings (MIT), into ~/.raea/tools/godot: JavaScriptCore on the Mac, QuickJS on Windows and Linux; raea's own build (the Mac's notarized), else GodotJS's, each checked against its pinned sha256)\n raea godot run [SCRIPT.ts] [--project DIR] [--window] [--movie FILE [--fps N] [--frames N]] [--scene res://X.tscn] [--size WxH] [--timeout S] [ARGS...] (a TypeScript script against Godot's whole API through raea/godot: its default export gets the SceneTree and ARGS, headless unless --window; --movie writes every frame Godot draws (NAME.png numbered, or .avi) at a fixed --fps, 30 unless given; the project is DIR, else the nearest project.godot above the script, else an empty one; Godot quits when it returns, or after --frames N; --scene plays a scene of the project under it, with no script needed; a scene in --window plays until the window is closed)\n raea godot types [DIR] (the project's own TypeScript types from GodotJS: Godot's API with its scenes, resources and input actions, into DIR/typings)\n raea godot open [DIR] (the Godot editor on the project, GodotJS's, to edit its scenes)";
/// The GodotJS release raea downloads (github.com/godotjs/GodotJS/releases); sdk/godot/tools/gen.sh writes
/// raea/godot's types from it, so the two move together.
pub const RELEASE: &str = "v1.1.0.beta1-4.6.1";
/// raea's own builds of the same editors (GD9: sdk/godot/build's macos.sh, linux.py and windows.py, zipped by
/// package.sh; the Mac's signed with raea's Developer ID and notarized), files of raea's release of this tag.
pub const RAEA_RELEASE: &str = "v0.1.1";
/// Where raea's builds are downloaded from; RAEA_GODOT_FROM points elsewhere (a folder as file:///..., to rehearse).
fn raea_base() -> String {
std::env::var("RAEA_GODOT_FROM").unwrap_or_else(|_| format!("https://github.com/shinyobjectz/raea/releases/download/{RAEA_RELEASE}"))
}
/// One platform's download: who built it, the asset, its sha256 and size, and the program inside its one top folder.
#[derive(Clone, Copy)]
struct Pin {
by: &'static str,
asset: &'static str,
sha256: &'static str,
size: u64,
program: &'static str,
}
impl Pin {
fn url(&self) -> String {
match self.by {
"raea" => format!("{}/{}", raea_base(), self.asset),
_ => format!("https://github.com/godotjs/GodotJS/releases/download/{RELEASE}/{}", self.asset),
}
}
}
// raea's Mac build is arm64 and notarized; GodotJS's a universal app, ad-hoc signed
const MAC_RAEA: Pin = Pin { by: "raea", asset: "godot-4.6.1-raea-macos-arm64.zip", sha256: "17e66b8f99134a67db29ce82b88ace7f4c2e4ae651c80a3876ac6bd5e68a8a75", size: 69_132_728, program: "Godot.app/Contents/MacOS/Godot" };
const MAC_GODOTJS: Pin = Pin { by: "GodotJS", asset: "macos-editor-app-4.6.1-jsc.zip", sha256: "8a3022cb07c9740b2acc4a0b6bba6be78fb2fe46ba172b13abd51e6829cdca95", size: 143_940_673, program: "Godot.app/Contents/MacOS/Godot" };
const LINUX_RAEA: Pin = Pin { by: "raea", asset: "godot-4.6.1-raea-linux-x86_64.zip", sha256: "9c86b3e6af0f8cc8a7158685103ccbe15d10aaf246067ec47509909647726b54", size: 78_737_822, program: "godot.linuxbsd.editor.x86_64" };
const LINUX_GODOTJS: Pin = Pin { by: "GodotJS", asset: "linux-editor-4.6.1-qjs-ng.zip", sha256: "daa91d6cff5862ed9e0b3776694fbe4ea0ebb474d244f46ffb3aa5af0318989d", size: 78_737_089, program: "godot.linuxbsd.editor.x86_64" };
const WINDOWS_RAEA: Pin = Pin { by: "raea", asset: "godot-4.6.1-raea-windows-x86_64.zip", sha256: "cf360e7a350f04a1cdb8d1ac475ebfc81518b5b49831ab2ed693f5d8127265e5", size: 73_171_472, program: "godot.windows.editor.x86_64.exe" };
const WINDOWS_GODOTJS: Pin = Pin { by: "GodotJS", asset: "windows-editor-4.6.1-qjs-ng.zip", sha256: "041b761a945b6a34d40f508dbd1accca462d943d2941c3a1a4568f84dd29c1d4", size: 83_915_786, program: "godot.windows.editor.x86_64.exe" };
fn pins() -> R<Vec<Pin>> {
pins_for(std::env::consts::OS, std::env::consts::ARCH)
}
/// This platform's downloads in the order they're tried: raea's build, then GodotJS's (a release made before raea's
/// builds are among its files still installs). Both hold the program at the same path. A platform GodotJS doesn't
/// build for is told how to bring its own build (GD2), never given a stock Godot.
fn pins_for(os: &str, arch: &str) -> R<Vec<Pin>> {
match (os, arch) {
("macos", "aarch64") => Ok(vec![MAC_RAEA, MAC_GODOTJS]),
("macos", _) => Ok(vec![MAC_GODOTJS]),
("linux", "x86_64") => Ok(vec![LINUX_RAEA, LINUX_GODOTJS]),
("windows", "x86_64") => Ok(vec![WINDOWS_RAEA, WINDOWS_GODOTJS]),
(os, arch) => Err(format!("GodotJS has no build for {os} {arch}: build it (github.com/godotjs/GodotJS) and `git config --global raea.godot PATH`")),
}
}
/// Whether the download in own_dir is one this raea pins (raea.json beside it names its sha256), so a moved pin
/// downloads again.
fn own_is_pinned() -> bool {
let Some(text) = own_dir("godot").ok().and_then(|d| std::fs::read_to_string(d.join("raea.json")).ok()) else { return false };
let Ok(had) = serde_json::from_str::<serde_json::Value>(&text) else { return false };
pins().is_ok_and(|ps| ps.iter().any(|p| had["sha256"] == p.sha256))
}
/// The Godot to use and where it came from: `git config --global raea.godot` (a GodotJS build of your own), else
/// raea's download. A Godot without GodotJS isn't looked for: it can't run raea/godot's scripts.
pub fn find() -> Option<(PathBuf, &'static str)> {
let configured = raea_app_tools::blender::run(Command::new("git").args(["config", "--global", "raea.godot"]), "git config").ok().map(|out| PathBuf::from(out.trim()));
if let Some(p) = configured.filter(|p| p.is_file()) {
return Some((p, "raea.godot in git config"));
}
let own = own_dir("godot").ok()?.join(pins().ok()?.first()?.program);
own.is_file().then_some((own, "raea's download"))
}
/// The binary, or what to run to get one.
pub fn binary() -> R<PathBuf> {
find().map(|(p, _)| p).ok_or_else(|| "no Godot with GodotJS: raea setup godot downloads it".to_string())
}
/// `godot --version`'s line ("4.6.1.stable.gh.14d19694e").
fn version(bin: &Path) -> R<String> {
let o = Command::new(bin).args(["--headless", "--version"]).output().map_err(|e| format!("{}: {e}", bin.display()))?;
let out = String::from_utf8_lossy(&o.stdout);
out.lines().map(str::trim).find(|l| l.chars().next().is_some_and(|c| c.is_ascii_digit())).map(str::to_string).ok_or_else(|| format!("{} --version printed no version", bin.display()))
}
/// Downloads the first pinned editor that comes and matches (raea's, then GodotJS's) into ~/.raea/tools/godot and
/// returns its program, and which it was.
fn download() -> R<(PathBuf, String)> {
let mut not = Vec::new();
for p in pins()? {
match download_one(&p) {
Ok(program) => return Ok((program, downloaded(&p, &not))),
Err(e) => not.push(format!("{}'s build: {e}", p.by)),
}
}
Err(format!("no Godot downloaded: {}", not.join("; ")))
}
/// What `raea setup godot` says it downloaded: whose build, and why any tried before it wasn't.
fn downloaded(p: &Pin, not: &[String]) -> String {
let by = if p.by == "raea" { format!("raea's build ({}, from raea's {RAEA_RELEASE} release)", p.asset) } else { format!("GodotJS's build ({}, from GodotJS {RELEASE})", p.asset) };
let before = if not.is_empty() { String::new() } else { format!("; {}", not.join("; ")) };
format!("downloaded Godot 4.6.1 with GodotJS, {by}{before}")
}
/// One pinned download, checked and unpacked into ~/.raea/tools/godot: its program.
fn download_one(p: &Pin) -> R<PathBuf> {
let dir = own_dir("godot")?;
let tmp = dir.with_file_name("godot.download");
let _ = std::fs::remove_dir_all(&tmp);
std::fs::create_dir_all(&tmp).map_err(|e| format!("{}: {e}", tmp.display()))?;
let file = tmp.join(p.asset);
let url = p.url();
if raea_app_tools::blender::run(Command::new("curl").args(["-fsSL", "--retry", "3", "-o"]).arg(&file).arg(&url), "downloading Godot with GodotJS").is_err() {
return Err(format!("{url} didn't download"));
}
let size = std::fs::metadata(&file).map_err(|e| e.to_string())?.len();
if size != p.size || raea_app_tools::blender::sha256(&file)? != p.sha256 {
return Err(format!("{} doesn't match the sha256 raea pins ({size} bytes); nothing installed (it's in {})", p.asset, tmp.display()));
}
let unpacked = tmp.join("unpacked");
unzip(&file, &unpacked)?;
let program = unpacked.join(p.program);
if !program.is_file() {
return Err(format!("{} holds no {}", p.asset, p.program));
}
// the zips keep no executable bits
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o755)).map_err(|e| e.to_string())?;
}
let release = if p.by == "raea" { RAEA_RELEASE } else { RELEASE };
std::fs::write(unpacked.join("raea.json"), serde_json::json!({ "by": p.by, "release": release, "asset": p.asset, "sha256": p.sha256 }).to_string()).map_err(|e| e.to_string())?;
let _ = std::fs::remove_dir_all(&dir);
std::fs::rename(&unpacked, &dir).map_err(|e| format!("{}: {e}", dir.display()))?;
let _ = std::fs::remove_dir_all(&tmp);
Ok(dir.join(p.program))
}
/// A zip's files into `to`, without its one top folder (every GodotJS zip has one).
fn unzip(file: &Path, to: &Path) -> R<()> {
let f = std::fs::File::open(file).map_err(|e| format!("{}: {e}", file.display()))?;
let mut z = zip::ZipArchive::new(f).map_err(|e| format!("{}: {e}", file.display()))?;
for i in 0..z.len() {
let mut e = z.by_index(i).map_err(|e| e.to_string())?;
let Some(path) = e.enclosed_name() else { return Err(format!("{} has an entry outside its folder: {}", file.display(), String::from_utf8_lossy(e.name_raw()))) };
let rel: PathBuf = path.components().skip(1).collect();
if rel.as_os_str().is_empty() {
continue;
}
let out = to.join(rel);
if e.is_dir() {
std::fs::create_dir_all(&out).map_err(|e| e.to_string())?;
continue;
}
if let Some(d) = out.parent() {
std::fs::create_dir_all(d).map_err(|e| e.to_string())?;
}
let mut w = std::fs::File::create(&out).map_err(|e| format!("{}: {e}", out.display()))?;
std::io::copy(&mut e, &mut w).map_err(|e| format!("{}: {e}", out.display()))?;
}
Ok(())
}
/// `raea setup godot [--check]`.
pub fn setup(args: &[String]) -> R<String> {
let check = args.iter().any(|a| a == "--check");
let current = own_is_pinned();
let (bin, from) = match find() {
Some((p, from)) if from != "raea's download" || current => (p, from.to_string()),
_ if check => return Err("no Godot with GodotJS that this raea pins: raea setup godot downloads it".into()),
_ => download()?,
};
let v = version(&bin)?;
Ok(format!("APPLIED Godot {v} with GodotJS at {} ({from}); raea godot run SCRIPT.ts runs a script against it", bin.display()))
}
/// The project folder: DIR, else the current folder; it needs its project.godot.
fn project(arg: Option<&String>) -> R<PathBuf> {
let dir = arg.map(PathBuf::from).unwrap_or_else(|| PathBuf::from("."));
let dir = dir.canonicalize().map_err(|e| format!("{}: {e}", dir.display()))?;
if !dir.join("project.godot").is_file() {
return Err(format!("{} has no project.godot", dir.display()));
}
Ok(dir)
}
/// `raea godot types [DIR]`: GodotJS's codegen on the project, headless (--generate-types), into DIR/typings.
fn types(args: &[String]) -> R<String> {
let dir = project(args.get(2))?;
let o = Command::new(binary()?).args(["--headless", "--editor", "--path"]).arg(&dir).arg("--generate-types").output().map_err(|e| e.to_string())?;
let log = format!("{}{}", String::from_utf8_lossy(&o.stdout), String::from_utf8_lossy(&o.stderr));
if !o.status.success() || !log.contains("Type generation complete") {
let tail: Vec<&str> = log.lines().rev().take(12).collect::<Vec<_>>().into_iter().rev().collect();
return Err(format!("GodotJS's codegen failed on {}:\n{}", dir.display(), tail.join("\n")));
}
let mut n = 0;
for e in std::fs::read_dir(dir.join("typings")).into_iter().flatten().flatten() {
n += e.file_name().to_string_lossy().ends_with(".d.ts") as usize;
}
Ok(format!("APPLIED {n} typings files in {} (Godot's API with the project's scenes, resources and input actions); a tsconfig that includes them types `import ... from \"godot\"`", dir.join("typings").display()))
}
/// `raea godot open [DIR]`: the editor on the project, left running.
fn open(args: &[String]) -> R<String> {
let dir = project(args.get(2))?;
// its output isn't raea's: a caller reading raea's (the app) would otherwise wait until the editor is closed
let null = std::process::Stdio::null;
Command::new(binary()?).args(["--editor", "--path"]).arg(&dir).stdin(null()).stdout(null()).stderr(null()).spawn().map_err(|e| e.to_string())?;
Ok(format!("APPLIED the Godot editor (GodotJS) is opening {}", dir.display()))
}
/// `raea godot types|open ...` (run is godot_run::run).
pub fn godot(args: &[String]) -> R<String> {
match args.get(1).map(String::as_str) {
Some("types") => types(args),
Some("open") => open(args),
Some("run") => crate::godot_run::run(args),
_ => Err(format!("usage: {USAGE}")),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_pin_has_a_full_digest() {
for (os, arch) in [("macos", "aarch64"), ("macos", "x86_64"), ("linux", "x86_64"), ("windows", "x86_64")] {
for p in pins_for(os, arch).unwrap() {
assert_eq!(p.sha256.len(), 64);
assert!(p.sha256.chars().all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase()));
assert!(p.asset.ends_with(".zip") && p.size > 50_000_000);
}
}
}
#[test]
fn raeas_build_is_tried_first_and_godotjss_after() {
for (os, arch) in [("macos", "aarch64"), ("linux", "x86_64"), ("windows", "x86_64")] {
let ps = pins_for(os, arch).unwrap();
assert_eq!(ps.iter().map(|p| p.by).collect::<Vec<_>>(), ["raea", "GodotJS"], "{os}");
assert_eq!(ps[0].program, ps[1].program, "{os}: both hold the program at one path");
assert!(ps[1].url().starts_with("https://github.com/godotjs/GodotJS/releases/download/v1.1.0.beta1-4.6.1/"));
}
let mac = pins_for("macos", "aarch64").unwrap();
if std::env::var_os("RAEA_GODOT_FROM").is_none() {
assert_eq!(mac[0].url(), "https://github.com/shinyobjectz/raea/releases/download/v0.1.1/godot-4.6.1-raea-macos-arm64.zip");
}
// raea builds the Mac editor for arm64 only: an Intel Mac gets GodotJS's universal app
assert_eq!(pins_for("macos", "x86_64").unwrap().iter().map(|p| p.by).collect::<Vec<_>>(), ["GodotJS"]);
}
#[test]
fn setup_says_whose_build_and_why_not_the_one_before() {
let ps = pins_for("linux", "x86_64").unwrap();
assert_eq!(downloaded(&ps[0], &[]), "downloaded Godot 4.6.1 with GodotJS, raea's build (godot-4.6.1-raea-linux-x86_64.zip, from raea's v0.1.1 release)");
let not = ["raea's build: https://x/godot-4.6.1-raea-linux-x86_64.zip didn't download".to_string()];
assert_eq!(downloaded(&ps[1], &not), "downloaded Godot 4.6.1 with GodotJS, GodotJS's build (linux-editor-4.6.1-qjs-ng.zip, from GodotJS v1.1.0.beta1-4.6.1); raea's build: https://x/godot-4.6.1-raea-linux-x86_64.zip didn't download");
}
#[test]
fn a_platform_godotjs_doesnt_build_for_is_told_to_bring_its_own() {
for (os, arch) in [("linux", "aarch64"), ("windows", "aarch64"), ("freebsd", "x86_64")] {
let e = pins_for(os, arch).err().unwrap_or_default();
assert!(e.contains("github.com/godotjs/GodotJS") && e.contains("git config --global raea.godot PATH"), "{os} {arch}: {e}");
}
}
#[test]
fn unzip_drops_the_top_folder() {
let base = std::env::temp_dir().join(format!("raea-godot-unzip-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
std::fs::create_dir_all(&base).unwrap();
let zf = base.join("a.zip");
let mut w = zip::ZipWriter::new(std::fs::File::create(&zf).unwrap());
let o = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
w.add_directory("top/", o).unwrap();
w.start_file("top/Godot.app/Contents/MacOS/Godot", o).unwrap();
std::io::Write::write_all(&mut w, b"binary").unwrap();
w.finish().unwrap();
unzip(&zf, &base.join("out")).unwrap();
assert_eq!(std::fs::read(base.join("out/Godot.app/Contents/MacOS/Godot")).unwrap(), b"binary");
let _ = std::fs::remove_dir_all(&base);
}
}
+358
View File
@@ -0,0 +1,358 @@
//! `raea godot run SCRIPT.ts [--project DIR] [--window] [--movie FILE [--fps N] [--frames N]] [--scene res://X.tscn] [--size WxH]
//! [--timeout S] [ARGS...]`:
//! a TypeScript script against Godot's whole API (raea/godot, sdk/godot). raea's bundler makes one CommonJS file of the
//! script, with GodotJS's modules ("godot", "godot.annotations", ...) aliased to sdk/godot/src/shim's stand-ins, which
//! read GodotJS's own when the script runs. It goes into the project's .godot/raea/<pid>/ as run.js, beside
//! sdk/godot/src/host/main.js, which Godot loads as its main loop (--script): main.js calls the script's default export
//! with the SceneTree and ARGS, then quits. The script runs in Godot, on GodotJS's engine (JavaScriptCore on the Mac,
//! QuickJS elsewhere). --movie is Godot's Movie Maker: each frame drawn and written at a fixed rate, offline, in a window.
use std::io::{BufRead, BufReader, Read};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
type R<T> = Result<T, String>;
/// GodotJS's modules a script may import, each with its stand-in in sdk/godot/src/shim.
const MODULES: [(&str, &str); 5] = [("godot", "godot.js"), ("godot.annotations", "annotations.js"), ("godot-jsb", "jsb.js"), ("godot.lib.api", "lib-api.js"), ("godot.worker", "worker.js")];
struct Opts {
script: PathBuf,
project: Option<PathBuf>,
window: bool,
timeout: f64,
/// Godot's Movie Maker: every frame written to this file (NAME.png numbered, or .avi), at a fixed frame rate
movie: Option<PathBuf>,
fps: u32,
size: Option<String>,
/// Godot quits after this many frames (--quit-after), not when the script returns: a shot's length (GD11)
frames: Option<u32>,
/// a scene of the project added to the tree before the script runs, playing as it would in the game (GD11)
scene: Option<String>,
rest: Vec<String>,
}
fn opts(args: &[String]) -> R<Opts> {
let script = args.get(2).ok_or("raea godot run SCRIPT.ts [--project DIR] [--window] [--movie FILE [--fps N] [--frames N]] [--scene res://X.tscn] [--size WxH] [--timeout S] [ARGS...]")?;
// no script, only flags: the project's --scene plays with nothing of yours added (sdk/godot/src/host/none.ts)
let bare = script.starts_with("--");
let script = if bare { raea_io_home::home().join("sdk/godot/src/host/none.ts") } else { PathBuf::from(script).canonicalize().map_err(|e| format!("{script}: {e}"))? };
let mut o = Opts { script, project: None, window: false, timeout: 3600.0, movie: None, fps: 30, size: None, frames: None, scene: None, rest: Vec::new() };
let mut it = args[if bare { 2 } else { 3 }..].iter();
while let Some(a) = it.next() {
match a.as_str() {
"--project" => o.project = Some(PathBuf::from(it.next().ok_or("--project needs a folder")?)),
"--window" => o.window = true,
"--timeout" => o.timeout = it.next().and_then(|s| s.parse().ok()).ok_or("--timeout needs seconds")?,
"--movie" => o.movie = Some(std::path::absolute(it.next().ok_or("--movie needs a file (frames.png or film.avi)")?).map_err(|e| e.to_string())?),
"--fps" => o.fps = it.next().and_then(|s| s.parse().ok()).filter(|n| *n > 0).ok_or("--fps needs frames a second")?,
"--frames" => o.frames = Some(it.next().and_then(|s| s.parse().ok()).filter(|n| *n > 0).ok_or("--frames needs a number of frames")?),
"--scene" => o.scene = Some(it.next().filter(|s| s.starts_with("res://")).ok_or("--scene needs a scene of the project, res://PATH.tscn")?.clone()),
"--size" => {
let s = it.next().filter(|s| s.split_once('x').is_some_and(|(w, h)| w.parse::<u32>().is_ok() && h.parse::<u32>().is_ok()));
o.size = Some(s.ok_or("--size needs WxH")?.clone());
}
// everything after -- is the script's, flags too
"--" => o.rest.extend(it.by_ref().cloned()),
_ => o.rest.push(a.clone()),
}
}
if bare && o.scene.is_none() {
return Err("raea godot run without a script plays a scene: give --scene res://PATH.tscn (and --project DIR)".into());
}
Ok(o)
}
/// The nearest folder at or above `from` with a project.godot.
fn nearest_project(from: &Path) -> Option<PathBuf> {
from.ancestors().find(|d| d.join("project.godot").is_file()).map(Path::to_path_buf)
}
/// The script's bundle at `out`: its module as M on globalThis.__raea_godot_main, GodotJS's modules aliased.
fn bundle(script: &Path, out: &Path) -> R<()> {
let shim = raea_io_home::home().join("sdk/godot/src/shim");
let entry = format!("import * as M from {:?};\n(globalThis as any).__raea_godot_main = M;\n", dunce::simplified(script).display().to_string());
let aliases: Vec<String> = MODULES.iter().map(|(m, f)| format!("{m}={}", shim.join(f).display())).collect();
let mut extra: Vec<&str> = Vec::new();
for a in &aliases {
extra.extend(["--alias", a.as_str()]);
}
raea_runtime_bundle::bundle_entry(&entry, out, &extra)
}
/// One line of Godot's output as raea prints it: GodotJS's console prefix gone, and what every run prints dropped:
/// Godot's banner and the blank line after it, the JavaScriptCore build's note that it has no promise-rejection hook,
/// and the leaks reported at exit (GodotJS 1.1's values, Godot's RIDs and objects the script left: harmless once it
/// has quit; each with its "at:" line). It also notes when a callback of the script threw: GodotJS prints the
/// exception, its stack and an "at: _call" line, and Godot carries on, so the run is stopped (`threw`).
pub(crate) struct Clean {
skip_at: bool,
skip_blank: bool,
in_throw: bool,
pub(crate) threw: bool,
}
impl Clean {
pub(crate) fn new() -> Self {
Clean { skip_at: false, skip_blank: false, in_throw: false, threw: false }
}
pub(crate) fn line(&mut self, l: &str) -> Option<String> {
let t = l.trim_start();
if t.contains("[jsb][Error] exception thrown in function") {
self.in_throw = true;
} else if self.in_throw && t.starts_with("at: _call (modules/GodotJS/") {
self.in_throw = false;
self.threw = true;
}
let (at, blank) = (std::mem::take(&mut self.skip_at), std::mem::take(&mut self.skip_blank));
if (at && t.starts_with("at: ")) || (blank && t.is_empty()) {
return None;
}
let exit_leak = t.contains(" leaked") && (t.contains("RID") || t.contains("ObjectDB"));
if t.contains("variant pool leaked") || t.contains("Pages in use exist at exit in PagedAllocator") || exit_leak {
self.skip_at = true;
return None;
}
if t.starts_with("Godot Engine v") && t.contains("godotengine.org") {
self.skip_blank = true;
return None;
}
if t.contains("SetPromiseRejectCallback is not supported") {
return None;
}
Some(l.strip_prefix("[JS] ").unwrap_or(l).to_string())
}
}
fn forward(from: impl Read + Send + 'static, err: bool, threw: Arc<AtomicBool>) -> std::thread::JoinHandle<()> {
std::thread::spawn(move || {
let mut c = Clean::new();
for l in BufReader::new(from).lines().map_while(Result::ok) {
if let Some(l) = c.line(&l) {
if err { eprintln!("{l}") } else { println!("{l}") }
}
if c.threw {
threw.store(true, Ordering::SeqCst);
}
}
})
}
/// The window size Godot's Movie Maker records: the project's display/window/size/viewport_width and _height
/// (Godot's own --resolution sizes the window, not the movie), 1152x648 when it sets none.
fn project_size(project_godot: &str) -> (u32, u32) {
let mut size = (1152, 648);
let mut display = false;
for l in project_godot.lines().map(str::trim) {
if l.starts_with('[') {
display = l == "[display]";
} else if display {
let Some((key, v)) = l.split_once('=') else { continue };
match (key.trim(), v.trim().parse::<u32>()) {
("window/size/viewport_width", Ok(w)) => size.0 = w,
("window/size/viewport_height", Ok(h)) => size.1 = h,
_ => {}
}
}
}
size
}
fn parse_size(s: &str) -> Option<(u32, u32)> {
let (w, h) = s.split_once('x')?;
Some((w.parse().ok()?, h.parse().ok()?))
}
/// `raea godot run ...`.
pub fn run(args: &[String]) -> R<String> {
let o = opts(args)?;
let bin = crate::godot::binary()?;
let home = raea_io_home::home();
let host = home.join("sdk/godot/src/host/main.js");
if !host.is_file() {
return Err(format!("{} is missing: this raea's install has no sdk/godot", host.display()));
}
// the project: --project, the nearest project.godot above the script, else an empty one for this run
let found = match &o.project {
Some(p) => Some(p.canonicalize().map_err(|e| format!("{}: {e}", p.display()))?),
None => nearest_project(o.script.parent().unwrap_or(Path::new("."))),
};
let temp = std::env::temp_dir().join(format!("raea-godot-{}", std::process::id()));
let project = match found {
Some(p) if p.join("project.godot").is_file() => p,
Some(p) => return Err(format!("{} has no project.godot", p.display())),
None => {
std::fs::create_dir_all(&temp).map_err(|e| e.to_string())?;
// --size is the window's size, which is what Movie Maker records
let display = match o.size.as_deref().and_then(parse_size) {
Some((w, h)) => format!("\n[display]\nwindow/size/viewport_width={w}\nwindow/size/viewport_height={h}\n"),
None => String::new(),
};
let text = format!("config_version=5\n\n[application]\nconfig/name=\"raea godot run\"\n{display}");
std::fs::write(temp.join("project.godot"), text).map_err(|e| e.to_string())?;
temp.clone()
}
};
// a project's own movie is its window's size: say so rather than record another one
if let (Some(_), Some(want), true) = (&o.movie, o.size.as_deref().and_then(parse_size), project != temp) {
let has = project_size(&std::fs::read_to_string(project.join("project.godot")).unwrap_or_default());
if has != want {
return Err(format!(
"Godot's Movie Maker records {}'s window, {}x{}, not --size {}x{}: set display/window/size/viewport_width and _height in its project.godot",
project.display(), has.0, has.1, want.0, want.1
));
}
}
// a project Godot never opened has its assets unimported, so its scenes wouldn't load: import them first
if project != temp && !project.join(".godot").is_dir() {
let s = Command::new(&bin).args(["--headless", "--path"]).arg(&project).arg("--import").stdout(Stdio::null()).stderr(Stdio::null()).status().map_err(|e| e.to_string())?;
if !s.success() {
return Err(format!("Godot couldn't import {}'s assets (godot --headless --import)", project.display()));
}
}
let pid = std::process::id();
let work = project.join(format!(".godot/raea/{pid}"));
std::fs::create_dir_all(&work).map_err(|e| format!("{}: {e}", work.display()))?;
let ran = (|| {
std::fs::copy(&host, work.join("main.js")).map_err(|e| format!("{}: {e}", host.display()))?;
bundle(&o.script, &work.join("run.js"))?;
let mut cmd = Command::new(&bin);
// a movie is drawn, so it needs the window; headless Godot draws nothing
if let Some(m) = &o.movie {
if let Some(d) = m.parent() {
std::fs::create_dir_all(d).map_err(|e| format!("{}: {e}", d.display()))?;
}
// on top: macOS stops drawing a window other windows cover, and Movie Maker then writes its last frame again
cmd.arg("--write-movie").arg(m).arg("--fixed-fps").arg(o.fps.to_string()).arg("--always-on-top");
} else if !o.window {
cmd.arg("--headless");
}
if let Some(s) = &o.size {
cmd.arg("--resolution").arg(s);
}
// a set length: Godot stops after it, and main.js doesn't quit when the script returns
if let Some(n) = o.frames {
cmd.arg("--quit-after").arg(n.to_string()).env("RAEA_GODOT_HOLD", "1");
}
if let Some(sc) = &o.scene {
cmd.env("RAEA_GODOT_SCENE", sc);
}
cmd.arg("--path").arg(&project).arg("--script").arg(format!("res://.godot/raea/{pid}/main.js")).arg("--").args(&o.rest);
cmd.env("RAEA_GODOT_LOADED", work.join("loaded"));
// Godot runs in the project's folder: raea/godot's cwd() and resolve() read where raea was run from
if let Ok(here) = std::env::current_dir() {
cmd.env("RAEA_CWD", here);
}
let mut child = cmd.stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().map_err(|e| format!("{}: {e}", bin.display()))?;
let threw = Arc::new(AtomicBool::new(false));
let outs = [forward(child.stdout.take().unwrap(), false, threw.clone()), forward(child.stderr.take().unwrap(), true, threw.clone())];
let deadline = Instant::now() + Duration::from_secs_f64(o.timeout);
let status = loop {
if let Some(s) = child.try_wait().map_err(|e| e.to_string())? {
break Ok(s);
}
// a callback that threw leaves Godot running on a broken script: stop it, as main.js does when main() throws
if threw.load(Ordering::SeqCst) {
let _ = child.kill();
let _ = child.wait();
break Err(format!("{} threw (above); Godot was stopped", o.script.display()));
}
if Instant::now() >= deadline {
let _ = child.kill();
let _ = child.wait();
break Err(format!("{} didn't finish in {} s (--timeout); Godot was stopped", o.script.display(), o.timeout));
}
std::thread::sleep(Duration::from_millis(20));
};
for t in outs {
let _ = t.join();
}
status
})();
// main.js writes it once the script has loaded: Godot exits 0 when it couldn't load the script at all
let loaded = work.join("loaded").is_file();
let _ = std::fs::remove_dir_all(&work);
if project == temp {
let _ = std::fs::remove_dir_all(&temp);
}
let status = ran?;
if !loaded {
return Err(format!("Godot couldn't load {} (GodotJS's errors above)", o.script.display()));
}
match status.code() {
Some(0) => Ok(String::new()),
Some(c) => Err(format!("{} ended with exit {c}", o.script.display())),
None => Err(format!("Godot stopped running {} ({status})", o.script.display())),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn clean_keeps_the_script_and_drops_the_exit_noise() {
let mut c = Clean::new();
let lines = [
"Godot Engine v4.6.1.stable.gh.14d19694e - https://godotengine.org",
"",
"[jsc][Log] SetPromiseRejectCallback is not supported",
"[JS] PASS 3",
"",
"WARNING: [jsb][Warning] variant pool leaked",
" at: ~VariantAllocator (modules/GodotJS/bridge/../impl/jsc/../../internal/jsb_variant_allocator.h:43)",
"ERROR: Pages in use exist at exit in PagedAllocator: 7Variant",
" at: ~PagedAllocator (./core/templates/paged_allocator.h:169)",
"ERROR: a real error",
" at: somewhere (file.cpp:1)",
];
let kept: Vec<String> = lines.iter().filter_map(|l| c.line(l)).collect();
assert_eq!(kept, ["PASS 3", "", "ERROR: a real error", " at: somewhere (file.cpp:1)"]);
for l in [
"WARNING: 3 RIDs of type \"CanvasItem\" were leaked.",
" at: _free_rids (servers/rendering/renderer_canvas_cull.cpp:2678)",
"WARNING: ObjectDB instances leaked at exit (run with --verbose for details).",
" at: cleanup (core/object/object.cpp:2378)",
] {
assert_eq!(c.line(l), None, "{l}");
}
assert!(!c.threw);
}
#[test]
fn a_callback_that_threw_is_noted_once_its_stack_is_out() {
let mut c = Clean::new();
let lines = [
"ERROR: [jsb][Error] exception thrown in function:",
"undefined is not an object (evaluating 'this.logo.position')",
"_process@/tmp/p/.godot/raea/1/run.js:1575:14",
];
for l in lines {
assert!(c.line(l).is_some());
assert!(!c.threw);
}
assert!(c.line(" at: _call (modules/GodotJS/bridge/jsb_environment.cpp:1737)").is_some());
assert!(c.threw);
}
#[test]
fn movie_size_is_the_projects_window() {
assert_eq!(project_size("config_version=5\n"), (1152, 648));
let p = "[application]\nconfig/name=\"x\"\n\n[display]\nwindow/size/viewport_width=1920\nwindow/size/viewport_height=1080\n";
assert_eq!(project_size(p), (1920, 1080));
assert_eq!(project_size("[rendering]\nwindow/size/viewport_width=10\n"), (1152, 648));
assert_eq!(parse_size("960x540"), Some((960, 540)));
assert_eq!(parse_size("960"), None);
}
#[test]
fn the_nearest_project_is_above_the_script() {
let base = std::env::temp_dir().join(format!("raea-godot-near-{}", std::process::id()));
std::fs::create_dir_all(base.join("scripts/deep")).unwrap();
std::fs::write(base.join("project.godot"), "").unwrap();
assert_eq!(nearest_project(&base.join("scripts/deep")), Some(base.clone()));
let _ = std::fs::remove_dir_all(&base);
}
}
+58
View File
@@ -0,0 +1,58 @@
//! The verbs that script other engines from TypeScript: Blender (`raea setup blender`, `raea blender run SCRIPT.py|.ts`;
//! finding and setting Blender up is apps/tools/src/blender.rs) and Godot with GodotJS (`raea setup godot`,
//! `raea godot run|types|open`; sdk/blender and sdk/godot are their TypeScript sides).
/// the Blender a TypeScript script drives (`raea blender run SCRIPT.ts`, sdk/blender)
pub mod blender_bridge;
/// `raea blender run SCRIPT.ts`: the script on raea's engine, its batches posted to the bridge's Blender
pub mod blender_ts;
/// `raea setup godot`, `raea godot types` and `raea godot open`: Godot with GodotJS (sdk/godot)
pub mod godot;
/// `raea godot run SCRIPT.ts`: a TypeScript script in Godot through GodotJS
pub mod godot_run;
/// `raea blender shot`, `raea godot shot`: a shot's frames drawn by Blender or Godot (<BlenderShot>, <GodotShot>)
pub mod shot;
/// `raea scene export`, `raea godot export|back`, `raea blender open|back`: a raea scene sent to Blender or Godot and back
pub mod round;
use raea_app_tools::blender;
type R<T> = Result<T, String>;
/// The CLI's verbs here, or None for any other: `setup blender|godot`, `blender ...` and `godot ...`.
pub fn cli(args: &[String]) -> Option<R<String>> {
let second = args.get(1).map(String::as_str);
Some(match (args.first()?.as_str(), second) {
("setup", Some("blender")) => blender::setup(&args[2..]),
("setup", Some("godot")) => godot::setup(&args[2..]),
("blender", Some("run")) if args.get(2).is_some_and(|s| blender_bridge::is_ts(s)) => blender_ts::run(args),
("blender", Some("shot")) => shot::blender(args),
("godot", Some("shot")) => shot::godot(args),
("scene", Some("export")) => round::scene_export(args),
("godot", Some("export")) => round::godot_export(args),
("godot", Some("back")) => round::godot_back(args),
("blender", Some("open")) => round::blender_open(args),
("blender", Some("back")) => round::blender_back(args),
("blender", _) => blender::blender(args),
("godot", _) => godot::godot(args),
_ => return None,
})
}
#[cfg(test)]
mod tests {
use super::*;
fn args(s: &str) -> Vec<String> {
s.split_whitespace().map(str::to_string).collect()
}
// other verbs pass through untouched, and a bare `godot` or `blender` gets its usage, not a run
#[test]
fn takes_only_its_verbs() {
assert!(cli(&args("setup audio")).is_none());
assert!(cli(&args("render edit.tsx")).is_none());
assert!(cli(&[]).is_none());
assert!(cli(&args("godot")).unwrap().unwrap_err().contains(godot::USAGE));
}
}
+146
View File
@@ -0,0 +1,146 @@
//! A raea scene sent to Blender or Godot and its changes read back (docs/blender.feature BL37-BL39, docs/godot.feature
//! GD12-GD13): the verbs, running Blender (sdk/blender/src/scene.ts) and Godot (sdk/godot/src/host/back.ts) on what
//! raea-app-interchange writes and compares.
//! raea scene export EDIT.tsx -o DIR [--composition ID] [--frame N | --at A-B]
//! raea godot export EDIT.tsx -o DIR [--composition ID] [--frame N | --at A-B]
//! raea godot back DIR [--json]
//! raea blender open EDIT.tsx [--frame N | --at A-B] [-o DIR] [--no-window] | FILE.blend|.glb|.gltf|.obj|.fbx
//! raea blender back FILE.blend [--json]
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use raea_app_interchange::{back, export, godot};
use serde_json::Value;
use crate::{R, blender_ts};
pub const USAGE: &str = "raea scene export EDIT.tsx -o DIR [--composition ID] [--frame N | --at A-B] (the composition's 3D as data other tools build: DIR/scene.json, each part placed (y up, metres) with its shape, material or light, and the camera; meshes/ and models/ beside it)\n raea godot export EDIT.tsx -o DIR [--frame N | --at A-B] (the composition's 3D as a Godot project that runs: project.godot and main.tscn, each part Godot's own node, --at's frames an AnimationPlayer)\n raea godot back DIR (what changed in Godot's main.tscn since the export, as edits to the TSX at their lines; nodes added there written as media/NAME.glb; --json)\n raea blender open EDIT.tsx [--frame N | --at A-B] [-o DIR] [--no-window] | FILE.blend|.glb (the composition's 3D built in Blender, saved as DIR/NAME.blend (out/blender/NAME/ unless -o) and opened in a Blender window; a model or .blend opened as it is)\n raea blender back FILE.blend (what changed in Blender since raea blender open, as edits to the TSX at their lines; meshes made there written as media/NAME.glb; --json)";
fn flag<'a>(args: &'a [String], k: &str) -> Option<&'a String> {
args.iter().position(|a| a == k).and_then(|i| args.get(i + 1))
}
fn read_json(p: &Path) -> R<Value> {
serde_json::from_slice(&std::fs::read(p).map_err(|e| format!("{}: {e}", p.display()))?).map_err(|e| format!("{}: {e}", p.display()))
}
/// The scene export's folder for an edit: -o DIR, else out/blender/NAME/ beside it.
fn export_to(args: &[String], default_sub: &str) -> R<(PathBuf, Value)> {
let mut a = args.to_vec();
if flag(args, "-o").is_none() {
let edit = PathBuf::from(args.get(2).ok_or(USAGE)?);
let stem = edit.file_stem().and_then(|s| s.to_str()).unwrap_or("scene").to_string();
let dir = edit.parent().unwrap_or(Path::new(".")).join("out").join(default_sub).join(&stem);
a.extend(["-o".into(), dir.to_string_lossy().into_owned()]);
}
export::export(&a)
}
/// The edits from scene.json in `dir` to what `now` holds, said (or as JSON).
fn compared(dir: &Path, now: &Path, json: bool) -> R<String> {
let sent = read_json(&dir.join("scene.json"))?;
let held = read_json(now)?;
let _ = std::fs::remove_file(now);
let edits = back::compare(&sent, &held);
let tsx = PathBuf::from(sent["from"].as_str().unwrap_or(""));
Ok(if json { serde_json::to_string_pretty(&edits).unwrap_or_default() } else { back::said(&edits, &tsx) })
}
/// The project's media folder for models made in Blender or Godot: beside the edit the scene came from.
fn media_of(dir: &Path) -> R<PathBuf> {
let sent = read_json(&dir.join("scene.json"))?;
let tsx = PathBuf::from(sent["from"].as_str().ok_or("scene.json names no edit")?);
Ok(tsx.parent().unwrap_or(Path::new(".")).join("media"))
}
pub fn scene_export(args: &[String]) -> R<String> {
let (out, v) = export::export(args)?;
Ok(export::said(&out, &v))
}
pub fn godot_export(args: &[String]) -> R<String> {
let (out, v) = export_to(args, "godot")?;
let name = Path::new(&args[2]).file_stem().and_then(|s| s.to_str()).unwrap_or("raea").to_string();
let said = godot::project(&out, &v, &name)?;
let left = export::said(&out, &v);
let left = left.split_once("; ").map(|(_, l)| format!("; {l}")).unwrap_or_default();
Ok(format!("a Godot project in {}: {said}{left}\nrun it: raea godot run SCRIPT.ts --project {0} (or --movie); edit it: raea godot open {0}; then raea godot back {0}", out.display()))
}
pub fn godot_back(args: &[String]) -> R<String> {
let dir = PathBuf::from(args.get(2).ok_or(USAGE)?).canonicalize().map_err(|e| format!("{}: {e}", args[2]))?;
let media = media_of(&dir)?;
let now = dir.join(".raea-now.json");
let script = raea_io_home::home().join("sdk/godot/src/host/back.ts");
let run: Vec<String> = ["godot", "run"].iter().map(|s| s.to_string())
.chain([script.to_string_lossy().into_owned(), "--project".into(), dir.to_string_lossy().into_owned(), "--".into(), now.to_string_lossy().into_owned(), media.to_string_lossy().into_owned()])
.collect();
crate::godot_run::run(&run)?;
compared(&dir, &now, args.iter().any(|a| a == "--json"))
}
/// A Blender window on `file`, left running as the person's.
fn window(file: &Path, python: Option<String>) -> R<()> {
let (bin, _) = raea_app_tools::blender::find().ok_or("no Blender: raea setup blender finds or downloads one")?;
let mut cmd = Command::new(&bin);
match python {
Some(code) => cmd.arg("--python-expr").arg(code),
None => cmd.arg(file),
};
cmd.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).spawn().map_err(|e| format!("{}: {e}", bin.display()))?;
Ok(())
}
pub fn blender_open(args: &[String]) -> R<String> {
let src = args.get(2).ok_or(USAGE)?;
let path = std::path::absolute(src).map_err(|e| e.to_string())?;
let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase();
match ext.as_str() {
"blend" => {
window(&path, None)?;
return Ok(format!("APPLIED Blender is opening {}", path.display()));
}
"glb" | "gltf" | "obj" | "fbx" => {
let op = match ext.as_str() {
"obj" => "bpy.ops.wm.obj_import",
"fbx" => "bpy.ops.import_scene.fbx",
_ => "bpy.ops.import_scene.gltf",
};
let code = format!("import bpy\nbpy.ops.wm.read_homefile(use_empty=True)\n{op}(filepath={:?})", path.to_string_lossy());
window(&path, Some(code))?;
return Ok(format!("APPLIED Blender is opening {}", path.display()));
}
_ => {}
}
let (dir, v) = export_to(args, "blender")?;
let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("scene");
let blend = dir.join(format!("{stem}.blend"));
let call = format!("build({:?}, {:?})", dir.to_string_lossy(), blend.to_string_lossy());
let entry = format!("import {{ build }} from \"@raea/blender/scene\";\nconst call = (globalThis as any).__raea_call;\nPromise.resolve().then(() => {call}){}\n", blender_ts::CLOSE);
let code = blender_ts::session(&entry, None, &[], 900.0)?;
if code != 0 || !blend.is_file() {
return Err(format!("Blender couldn't build {} (above)", dir.join("scene.json").display()));
}
if !args.iter().any(|a| a == "--no-window") {
window(&blend, None)?;
}
Ok(format!("{}\nbuilt in Blender: {}; after changing it there, save and run: raea blender back {}", export::said(&dir, &v), blend.display(), blend.display()))
}
pub fn blender_back(args: &[String]) -> R<String> {
let blend = PathBuf::from(args.get(2).filter(|a| a.ends_with(".blend")).ok_or(USAGE)?).canonicalize().map_err(|e| format!("{}: {e}", args[2]))?;
let dir = blend.parent().ok_or("the .blend's folder")?.to_path_buf();
if !dir.join("scene.json").is_file() {
return Err(format!("{} has no scene.json beside it: raea blender back reads a .blend raea blender open made", blend.display()));
}
let media = media_of(&dir)?;
let now = dir.join(".raea-now.json");
let call = format!("readBack({:?}, {:?})", now.to_string_lossy(), media.to_string_lossy());
let entry = format!("import {{ readBack }} from \"@raea/blender/scene\";\nconst call = (globalThis as any).__raea_call;\nPromise.resolve().then(() => {call}){}\n", blender_ts::CLOSE);
let code = blender_ts::session(&entry, Some(&blend), &[], 900.0)?;
if code != 0 {
return Err(format!("Blender couldn't read {} (above)", blend.display()));
}
compared(&dir, &now, args.iter().any(|a| a == "--json"))
}
+231
View File
@@ -0,0 +1,231 @@
//! A shot's frames made by another engine, numbered from DIR/0000.png (docs/blender.feature BL36, docs/godot.feature
//! GD11): what <BlenderShot> and <GodotShot> show, made through their native calls (runtime/react's scene/shots.rs).
//! raea blender shot SCRIPT.ts|FILE.blend -o DIR --frames N [--fps F] [--size WxH] [--file FILE.blend]
//! [--engine eevee|cycles|workbench] [--samples S] [--transparent] [--timeout S] [-- ARGS]
//! raea godot shot SCRIPT.ts|res://SCENE.tscn [--project DIR] -o DIR --frames N [--fps F] [--size WxH] [--scene res://X]
//! [--timeout S] [-- ARGS]
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use serde_json::json;
use crate::{R, blender_ts};
pub const BLENDER_USAGE: &str = "raea blender shot SCRIPT.ts|FILE.blend -o DIR --frames N [--fps F] [--size WxH] [--file FILE.blend] [--engine eevee|cycles|workbench] [--samples S] [--transparent] [--timeout S] [-- ARGS]";
/// Both, as raea's help says them.
pub const USAGE: &str = "raea blender shot SCRIPT.ts|FILE.blend -o DIR --frames N [--fps F] [--size WxH] [--engine eevee|cycles|workbench] [--samples S] [--transparent] (a shot's frames rendered by Blender, DIR/0000.png on: a raea/blender script's scene or a .blend's animation; what <BlenderShot> shows, from raea/blender/shot)\n raea godot shot SCRIPT.ts|res://SCENE.tscn [--project DIR] -o DIR --frames N [--fps F] [--size WxH] (a shot's frames recorded by Godot's Movie Maker, DIR/0000.png on, its sound as sound.wav; what <GodotShot> shows, from raea/godot/shot)";
pub const GODOT_USAGE: &str = "raea godot shot SCRIPT.ts|res://SCENE.tscn [--project DIR] -o DIR --frames N [--fps F] [--size WxH] [--scene res://X.tscn] [--timeout S] [-- ARGS]";
#[derive(Debug)]
struct Shot {
src: String,
out: PathBuf,
frames: u32,
fps: f64,
size: (u32, u32),
transparent: bool,
/// the flags that take a value, by name
flags: BTreeMap<String, String>,
rest: Vec<String>,
}
/// args[2] the source, then the flags (each taking a value but --transparent), then -- and the script's own.
fn parse(args: &[String], usage: &str) -> R<Shot> {
let src = args.get(2).filter(|a| !a.starts_with('-')).ok_or(usage)?.clone();
let (mut flags, mut rest, mut transparent) = (BTreeMap::new(), Vec::new(), false);
let mut it = args[3..].iter();
while let Some(a) = it.next() {
match a.as_str() {
"--" => rest.extend(it.by_ref().cloned()),
"--transparent" => transparent = true,
f if f.starts_with('-') => _ = flags.insert(a.clone(), it.next().ok_or_else(|| format!("{a} needs a value: {usage}"))?.clone()),
_ => return Err(format!("{a}: not a flag of this verb: {usage}")),
}
}
let out = std::path::absolute(flags.get("-o").ok_or(usage)?).map_err(|e| e.to_string())?;
let frames = flags.get("--frames").and_then(|n| n.parse().ok()).filter(|n| *n > 0).ok_or("--frames needs a number of frames over 0")?;
let fps: f64 = match flags.get("--fps") {
Some(f) => f.parse().ok().filter(|f: &f64| *f > 0.0).ok_or("--fps needs frames a second")?,
None => 30.0,
};
let size = match flags.get("--size") {
Some(s) => s.split_once('x').and_then(|(w, h)| Some((w.parse().ok()?, h.parse().ok()?))).ok_or("--size needs WxH")?,
None => (1920, 1080),
};
Ok(Shot { src, out, frames, fps, size, transparent, flags, rest })
}
/// The frames a run wrote in `dir` (Blender's 0001.png on, Godot's f00000000.png on), by their number: the first
/// `n` renamed 0000.png on, any past them removed. Too few is the run's failure.
pub(crate) fn renumber(dir: &Path, n: u32) -> R<()> {
let number = |p: &Path| p.file_stem()?.to_str()?.trim_start_matches(|c: char| !c.is_ascii_digit()).parse::<u64>().ok();
let mut made: Vec<(u64, PathBuf)> = std::fs::read_dir(dir).map_err(|e| format!("{}: {e}", dir.display()))?
.flatten()
.map(|e| e.path())
.filter(|p| p.extension().is_some_and(|e| e == "png"))
.filter_map(|p| Some((number(&p)?, p)))
.collect();
made.sort();
if made.len() < n as usize {
return Err(format!("{} frames were made of the {n} asked for ({})", made.len(), dir.display()));
}
// through a name of their own first, so 0001.png -> 0000.png never meets a frame not yet moved
let mut moved = Vec::new();
for (i, (_, p)) in made.iter().enumerate() {
if i < n as usize {
let tmp = dir.join(format!("raea-{i:06}.tmp"));
std::fs::rename(p, &tmp).map_err(|e| format!("{}: {e}", p.display()))?;
moved.push((i, tmp));
} else {
let _ = std::fs::remove_file(p);
}
}
for (i, tmp) in moved {
std::fs::rename(&tmp, dir.join(format!("{i:04}.png"))).map_err(|e| e.to_string())?;
}
Ok(())
}
fn fresh(out: &Path) -> R<()> {
let _ = std::fs::remove_dir_all(out);
std::fs::create_dir_all(out).map_err(|e| format!("{}: {e}", out.display()))
}
/// `raea blender shot ...`: the script's default export run (or the .blend opened), then sdk/blender's shoot().
pub fn blender(args: &[String]) -> R<String> {
let s = parse(args, BLENDER_USAGE)?;
let src = std::path::absolute(&s.src).map_err(|e| e.to_string())?;
let is_blend = s.src.ends_with(".blend");
let file = if is_blend { Some(src.clone()) } else { s.flags.get("--file").map(PathBuf::from) };
if let Some(f) = file.as_ref().filter(|f| !f.is_file()) {
return Err(format!("{}: no such .blend", f.display()));
}
fresh(&s.out)?;
let mut opts = json!({ "out": s.out.to_string_lossy(), "frames": s.frames, "fps": s.fps, "width": s.size.0, "height": s.size.1, "transparent": s.transparent });
if let Some(e) = s.flags.get("--engine").map(String::as_str) {
opts["engine"] = json!(e);
}
if let Some(n) = s.flags.get("--samples").map(String::as_str) {
opts["samples"] = json!(n.parse::<u32>().map_err(|_| "--samples needs a whole number")?);
}
let shoot = "import { shoot } from \"@raea/blender/shoot\";\nconst call = (globalThis as any).__raea_call;\n";
let entry = if is_blend {
format!("{shoot}Promise.resolve().then(() => shoot({opts})){}\n", blender_ts::CLOSE)
} else {
let ts = src.canonicalize().map_err(|e| format!("{}: {e}", s.src))?;
format!("import * as M from {};\n{shoot}{}.then(() => shoot({opts})){}\n", blender_ts::spec(&ts), blender_ts::DEFAULT, blender_ts::CLOSE)
};
let mut rest = s.rest.clone();
let secs = s.flags.get("--timeout").map(String::as_str).and_then(|t| t.parse().ok()).unwrap_or_else(|| blender_ts::timeout(&mut rest));
let code = blender_ts::session(&entry, file.as_deref(), &rest, secs)?;
if code != 0 {
return Err(format!("{} ended with exit {code}", s.src));
}
renumber(&s.out, s.frames)?;
Ok(format!("{} frames by Blender in {}", s.frames, s.out.display()))
}
/// Godot's window size for the shot: an override.cfg in the project (Godot reads it over project.godot) for the
/// length of the run, since Movie Maker records the window the project opens; put back as it was after.
struct Override {
path: PathBuf,
before: Option<Vec<u8>>,
}
impl Override {
fn set(project: &Path, (w, h): (u32, u32)) -> R<Override> {
let path = project.join("override.cfg");
let before = std::fs::read(&path).ok();
let mut text = before.as_deref().map(String::from_utf8_lossy).unwrap_or_default().into_owned();
text.push_str(&format!("\n[display]\nwindow/size/viewport_width={w}\nwindow/size/viewport_height={h}\n"));
std::fs::write(&path, text).map_err(|e| format!("{}: {e}", path.display()))?;
Ok(Override { path, before })
}
}
impl Drop for Override {
fn drop(&mut self) {
let _ = match &self.before {
Some(b) => std::fs::write(&self.path, b),
None => std::fs::remove_file(&self.path),
};
}
}
/// `raea godot shot ...`: `raea godot run` with --movie, --frames and --scene, its frames renumbered; the sound Movie
/// Maker writes beside them kept as sound.wav.
pub fn godot(args: &[String]) -> R<String> {
let s = parse(args, GODOT_USAGE)?;
let none = raea_io_home::home().join("sdk/godot/src/host/none.ts");
let (script, scene) = match s.src.strip_prefix("res://") {
Some(_) => (none.to_string_lossy().into_owned(), Some(s.src.clone())),
None => (s.src.clone(), s.flags.get("--scene").cloned()),
};
fresh(&s.out)?;
let mut run = vec!["godot".to_string(), "run".into(), script, "--movie".into(), s.out.join("f.png").to_string_lossy().into_owned()];
run.extend(["--fps".into(), s.fps.round().to_string(), "--frames".into(), s.frames.to_string()]);
let _over = match s.flags.get("--project").map(String::as_str) {
Some(p) => {
run.extend(["--project".into(), p.to_string()]);
Some(Override::set(Path::new(p), s.size)?)
}
None => {
run.extend(["--size".into(), format!("{}x{}", s.size.0, s.size.1)]);
None
}
};
if let Some(sc) = scene {
run.extend(["--scene".into(), sc]);
}
if let Some(t) = s.flags.get("--timeout").map(String::as_str) {
run.extend(["--timeout".into(), t.to_string()]);
}
if !s.rest.is_empty() {
run.push("--".into());
run.extend(s.rest.iter().cloned());
}
crate::godot_run::run(&run)?;
let wav = s.out.join("f.wav");
if wav.is_file() {
let _ = std::fs::rename(&wav, s.out.join("sound.wav"));
}
renumber(&s.out, s.frames)?;
Ok(format!("{} frames by Godot in {}", s.frames, s.out.display()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn frames_are_numbered_from_zero_by_their_own_numbers() {
let d = std::env::temp_dir().join(format!("raea-shot-renumber-{}", std::process::id()));
fresh(&d).unwrap();
for f in ["0001.png", "0002.png", "0003.png", "10000.png", "notes.txt"] {
std::fs::write(d.join(f), f).unwrap();
}
renumber(&d, 3).unwrap();
assert_eq!(std::fs::read_to_string(d.join("0000.png")).unwrap(), "0001.png");
assert_eq!(std::fs::read_to_string(d.join("0002.png")).unwrap(), "0003.png");
assert!(!d.join("10000.png").exists() && !d.join("0003.png").exists() && d.join("notes.txt").exists());
// Godot's names, and too few
fresh(&d).unwrap();
for f in ["f00000000.png", "f00000001.png"] {
std::fs::write(d.join(f), f).unwrap();
}
assert!(renumber(&d, 3).unwrap_err().contains("2 frames were made of the 3"));
renumber(&d, 2).unwrap();
assert_eq!(std::fs::read_to_string(d.join("0001.png")).unwrap(), "f00000001.png");
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn a_shot_needs_its_out_and_length() {
let a = |s: &str| s.split_whitespace().map(String::from).collect::<Vec<_>>();
assert!(parse(&a("blender shot x.ts --frames 3"), BLENDER_USAGE).is_err());
assert!(parse(&a("blender shot x.ts -o d"), BLENDER_USAGE).unwrap_err().contains("--frames"));
let s = parse(&a("godot shot res://m.tscn -o d --frames 4 --size 640x360 --project p -- go"), GODOT_USAGE).unwrap();
assert_eq!((s.frames, s.size, s.flags.get("--project").map(String::as_str), s.rest.clone()), (4, (640, 360), Some("p"), vec!["go".to_string()]));
}
}
+23
View File
@@ -0,0 +1,23 @@
[package]
name = "raea-app-fingerprint"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "`raea fingerprint` (docs/fingerprint.feature FP3a): new, bootstrap, teach, score and report, run by a resident service on localhost that keeps the encoders loaded"
[dependencies]
# the taxonomy, evidence and heads
raea-sys-fingerprint = { path = "../../systems/fingerprint" }
# scoring and the sheet, which one judges a piece, diff and profiles
raea-sys-fingerprint-use = { path = "../../systems/fingerprint-use" }
raea-sys-fingerprint-things = { path = "../../systems/fingerprint-things" }
# the encoders and the columns they make
raea-sys-columns = { path = "../../systems/columns" }
# raea check's floor on the file: its findings go in the summary, and a check wins over a head (FP4c)
raea-app-check = { path = "../check" }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
anyhow = "1"
# the draws of FP0b's few-shot curves, seeded (bootstrap.rs)
fastrand = "2"
+86
View File
@@ -0,0 +1,86 @@
//! Approvals are positives (docs/fingerprint.feature FP6a): an approved cut, a picture lock, a publish or a golden
//! reference says every moment of it is clean on every axis, except where the person left a note. `raea fingerprint
//! approve FILE... [--project P]` adds a clean row on every axis ("*") for each 2 s window of each file, skipping the
//! windows within 2 s of a pinned note on that file in its project's feed (.raea/feed/*.json), since a note there may
//! name a defect. Notes aren't read into labels here; that is FP5a.
use crate::bootstrap::WIN;
use crate::flag;
use anyhow::{Result, anyhow};
use raea_sys_columns::Encoders;
use raea_sys_fingerprint::evidence::{Row, features};
use raea_sys_fingerprint::folder::Folder;
use raea_sys_fingerprint::taxonomy::Fingerprint;
use std::path::Path;
/// The seconds a note was pinned at on `file`, from every post in its project's feed that shows a file of that name
pub(crate) fn noted(file: &Path) -> Vec<f64> {
let Some(name) = file.file_name().and_then(|n| n.to_str()) else { return Vec::new() };
let Some(feed) = file.ancestors().map(|d| d.join(".raea/feed")).find(|d| d.is_dir()) else { return Vec::new() };
let mut at = Vec::new();
for e in std::fs::read_dir(feed).into_iter().flatten().flatten() {
let Ok(text) = std::fs::read_to_string(e.path()) else { continue };
let Ok(post) = serde_json::from_str::<serde_json::Value>(&text) else { continue };
let shows = post["media"].as_array().into_iter().flatten().any(|m| m["path"].as_str().is_some_and(|p| p.ends_with(name)));
if shows {
at.extend(post["notes"].as_array().into_iter().flatten().filter_map(|n| n["pin"]["t"].as_f64()));
}
}
at
}
/// The windows an approval labels clean: every WIN seconds of the piece, away from its notes
pub(crate) fn windows(dur: f64, notes: &[f64]) -> Vec<(f64, f64)> {
let n = (dur / WIN).floor() as usize;
(0..n).map(|i| (i as f64 * WIN, (i + 1) as f64 * WIN)).filter(|(a, b)| !notes.iter().any(|t| *t > a - WIN && *t < b + WIN)).collect()
}
pub(crate) fn approve(enc: &mut Encoders, dir: &Folder, fp: &Fingerprint, args: &[String], cwd: &Path, project: impl Fn(&Path) -> String) -> Result<(String, usize)> {
let files = crate::named(args, cwd)?;
if files.is_empty() {
return Err(anyhow!("which approved work? raea fingerprint approve FILE..."));
}
let mut l = dir.ledger()?;
let mut out = String::new();
let mut added = 0;
for file in &files {
let c = enc.columns(file)?;
// an approval given again replaces the last one for that media
l.retain(|r| !(r.source == "approval" && r.media == c.media));
let notes = noted(file);
let w = windows(c.dur, &notes);
for (a, b) in &w {
let row = Row {
media: c.media.clone(),
a: *a,
b: *b,
axis: "*".into(),
bad: false,
weight: 1.0,
who: fp.who.clone().unwrap_or_else(|| "me".into()),
source: "approval".into(),
project: flag(args, "--project").map_or_else(|| project(file), str::to_string),
kind: None,
region: None,
words: None,
at: 0,
pin: None,
};
l.push(row, &features(&c, *a, *b));
}
added += w.len();
out += &format!("approved {}: {} clean windows on every axis{}\n", file.display(), w.len(), if notes.is_empty() { String::new() } else { format!(", {} noted moments left out", notes.len()) });
}
dir.write_ledger(&l)?;
Ok((out, added))
}
#[cfg(test)]
mod tests {
#[test]
fn an_approval_leaves_out_the_windows_near_a_note() {
assert_eq!(super::windows(9.0, &[]), vec![(0.0, 2.0), (2.0, 4.0), (4.0, 6.0), (6.0, 8.0)]);
// a note at 5 s: the windows within 2 s of it go
assert_eq!(super::windows(12.0, &[5.0]), vec![(0.0, 2.0), (8.0, 10.0), (10.0, 12.0)]);
}
}
+280
View File
@@ -0,0 +1,280 @@
//! The bootstrap (FP4a, FP4b): known defects put into windows of the person's own real work, so the mechanical axes
//! learn from labels by construction, and the cheats each must still catch. Each source gives `per` 2 s windows
//! from 0.5 s to its end less 2.5 s (FP0b's protocol); each window gives a clean row ("*"), a row per picture and
//! sound defect, and a row per cheat. Only what the damage changed is embedded again: a freeze reuses the first
//! frame's vector, a flash re-embeds one frame, a sound defect leaves the picture alone.
//!
//! Then it measures what FP0b measured, in Rust: each axis's AUC from k = 4, 16 and 32 labelled windows a class, held
//! out by source (5 folds x 5 draws, the scaler fit on every plain row of the training sources), on its own
//! modality and on the one FP0b used; and each word head's AUC and catch rate with no labels (FP0g).
use raea_sys_fingerprint::evidence::{Ledger, Row, features, slice};
use raea_sys_fingerprint::head::{Logistic, Scaler, auc, quantile, share_over};
use raea_sys_fingerprint::taxonomy::Fingerprint;
use raea_sys_fingerprint::train::{C, folds};
use raea_sys_fingerprint::words::Words;
use anyhow::Result;
use raea_sys_columns::damage::{self, CHEATS, Noise, PICTURE, SOUND};
use raea_sys_columns::media::{self, Rgb};
use raea_sys_columns::window::Modality;
use raea_sys_columns::{Columns, Encoders, FPS};
use serde::Serialize;
use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;
/// The window, seconds
pub const WIN: f64 = 2.0;
/// Sources shorter than this are skipped (FP0b's)
pub const SHORTEST: f64 = 6.0;
pub const KS: [usize; 3] = [4, 16, 32];
/// FP0b's AUC at k = 32 for each axis, on the modality it was measured on (docs/fingerprint.md FP0b, FP0g)
pub const FP0B: [(&str, Modality, f64); 11] = [
("blur", Modality::Picture, 1.00),
("dark", Modality::Picture, 0.95),
("glow", Modality::Picture, 0.80),
("flash", Modality::Change, 0.97),
("freeze", Modality::Change, 1.00),
("noise", Modality::Events, 1.00),
("dropout", Modality::Events, 0.97),
("clip", Modality::Events, 0.98),
("noise", Modality::Sound, 1.00),
("dropout", Modality::Sound, 0.99),
("clip", Modality::Sound, 1.00),
];
#[derive(Debug, Default, Serialize)]
pub struct Made {
pub sources: usize,
pub windows: usize,
pub rows: usize,
/// windows too quiet for a gap or clipping to change them, which get only the noise damage
pub quiet: usize,
pub skipped: Vec<String>,
}
/// The rows a bootstrap makes, which the next bootstrap replaces
fn made_here(r: &Row) -> bool {
matches!(r.source.as_str(), "damage" | "cheat")
}
/// A plain damage row on `axis` ("*" for the clean windows)
fn damage_on(r: &Row, axis: &str) -> bool {
r.source == "damage" && r.axis == axis
}
/// The plain damage rows on `axis`
fn damage_rows(l: &Ledger, axis: &str) -> Vec<usize> {
(0..l.rows.len()).filter(|&i| damage_on(&l.rows[i], axis)).collect()
}
/// Each defect of a sense as (kind, axis, source): the plain ones, then their disguises
fn damages(sense: &[&'static str]) -> Vec<(&'static str, &'static str, &'static str)> {
sense.iter().map(|k| (*k, *k, "damage")).chain(CHEATS.iter().filter(|c| sense.contains(&c.1)).map(|c| (c.0, c.1, "cheat"))).collect()
}
/// Below this a window is near silence: a gap or clipping changes nothing, and a row saying it does teaches noise
const QUIET_DB: f32 = -45.0;
/// The window's loudness in dB over all of it
fn loudness(pcm: &[f32]) -> f32 {
if pcm.is_empty() {
return -100.0;
}
(10.0 * (pcm.iter().map(|x| x * x).sum::<f32>() / pcm.len() as f32).max(1e-10).log10()).max(-100.0)
}
fn zeros_to(mut v: Vec<f32>, n: usize) -> Vec<f32> {
v.resize(n, 0.0);
v
}
/// The picture columns of damaged frames, embedding only frames the damage changed
fn picture_of(enc: &mut Encoders, clean: &[Rgb], sig: &[f32], look: &[f32], d: &[Rgb]) -> Result<(Vec<f32>, Vec<f32>)> {
let (sd, ld) = (sig.len() / clean.len().max(1), look.len() / clean.len().max(1));
let mut fresh: Vec<Rgb> = Vec::new();
let mut from: Vec<Result<usize, usize>> = Vec::new();
for f in d {
match clean.iter().position(|c| c == f) {
Some(j) => from.push(Ok(j)),
None => {
fresh.push(f.clone());
from.push(Err(fresh.len() - 1));
}
}
}
let (fs, fl) = if fresh.is_empty() { (Vec::new(), Vec::new()) } else { enc.picture(&fresh)? };
let (mut s, mut l) = (Vec::with_capacity(sig.len()), Vec::with_capacity(look.len()));
for f in from {
let (ss, ll, j) = match f {
Ok(j) => (sig, look, j),
Err(k) => (&fs[..], &fl[..], k),
};
s.extend_from_slice(&ss[j * sd..(j + 1) * sd]);
l.extend_from_slice(&ll[j * ld..(j + 1) * ld]);
}
Ok((s, l))
}
/// The bootstrap's rows for `files` into the ledger, replacing any it made before. `say` hears each source's progress.
pub fn rows(enc: &mut Encoders, who: &str, files: &[PathBuf], per: usize, l: &mut Ledger, say: &mut dyn FnMut(String)) -> Result<Made> {
l.retain(|r| !made_here(r));
let mut made = Made::default();
let mut noise = Noise::new(0);
for (n, file) in files.iter().enumerate() {
let dur = media::duration(file).unwrap_or(0.0);
if dur < SHORTEST {
made.skipped.push(format!("{} ({dur:.1} s, under {SHORTEST} s)", file.display()));
continue;
}
let sha = media::sha256(file)?;
let frames = media::frames(file, FPS, 0.0, dur)?;
let (p16, p48) = (media::sound(file, 16_000)?, media::sound(file, 48_000)?);
made.sources += 1;
for w in 0..per {
let t = 0.5 + (dur - 3.0) * w as f64 / (per - 1).max(1) as f64;
let i0 = (t * FPS).round() as usize;
let Some(fr) = frames.get(i0..i0 + (WIN * FPS) as usize) else { continue };
let cut = |p: &[f32], rate: f64| zeros_to(p.get((t * rate) as usize..).unwrap_or(&[]).iter().take((WIN * rate) as usize).copied().collect(), (WIN * rate) as usize);
let (w16, w48) = (cut(&p16, 16_000.0), cut(&p48, 48_000.0));
let (sig, look) = enc.picture(fr)?;
let (clap, yam) = enc.sound(&w16, &w48)?;
let clean = Columns { media: sha.clone(), dur: WIN, sig, look, clap, yam, level: media::levels(&w16, 16_000), text: Vec::new() };
let push = |l: &mut Ledger, c: &Columns, axis: &str, kind: &str, source: &str| {
let r = Row {
media: sha.clone(),
a: t,
b: t + WIN,
axis: axis.into(),
bad: axis != "*",
weight: 1.0,
who: who.into(),
source: source.into(),
project: sha[..12].to_string(),
kind: Some(kind.into()),
region: None,
words: None,
at: 0,
pin: None,
};
l.push(r, &features(c, 0.0, WIN));
};
push(l, &clean, "*", "clean", "damage");
for (kind, axis, source) in damages(&PICTURE) {
let (sig, look) = picture_of(enc, fr, &clean.sig, &clean.look, &damage::picture(fr, kind))?;
push(l, &Columns { sig, look, ..clean.clone() }, axis, kind, source);
}
let quiet = loudness(&w16) < QUIET_DB;
made.quiet += quiet as usize;
for (kind, axis, source) in damages(&SOUND).into_iter().filter(|s| !quiet || s.1 == "noise") {
let (d16, d48) = (damage::sound(&w16, kind, 16_000, &mut noise), damage::sound(&w48, kind, 48_000, &mut noise));
let (clap, yam) = enc.sound(&d16, &d48)?;
push(l, &Columns { clap, yam, level: media::levels(&d16, 16_000), ..clean.clone() }, axis, kind, source);
}
made.windows += 1;
}
say(format!("source {}/{} {}: {} windows so far", n + 1, files.len(), file.display(), made.windows));
}
made.rows = l.rows.iter().filter(|r| made_here(r)).count();
Ok(made)
}
#[derive(Debug, Serialize)]
pub struct Curve {
pub axis: String,
pub modality: Modality,
/// AUC at each k
pub k: BTreeMap<usize, f64>,
/// FP0b's at k = 32 on this modality, and whether this run came within 0.03 of it or beat it
pub fp0b: Option<f64>,
pub holds: Option<bool>,
}
fn sample(rng: &mut fastrand::Rng, from: &[usize], k: usize) -> Vec<usize> {
let mut v = from.to_vec();
rng.shuffle(&mut v);
v.truncate(k);
v
}
/// FP0b's few-shot curve for one axis on one modality, from the bootstrap's rows
pub fn curve(l: &Ledger, axis: &str, m: Modality, rng: &mut fastrand::Rng) -> Curve {
let s = slice(m);
let row = |i: usize| &l.features(i)[s.clone()];
let plain = |i: &usize| l.rows[*i].source == "damage";
let (clean, bad) = (damage_rows(l, "*"), damage_rows(l, axis));
let projects = l.projects(&clean);
let mut k_auc = BTreeMap::new();
for k in KS {
let mut aucs = Vec::new();
for fold in folds(&projects) {
let held = |i: &usize| fold.contains(&l.rows[*i].project);
let base: Vec<&[f32]> = (0..l.rows.len()).filter(|i| plain(i) && !held(i)).map(row).collect();
let sc = Scaler::fit(&base);
let (tc, tb): (Vec<usize>, Vec<usize>) = (clean.iter().copied().filter(|i| !held(i)).collect(), bad.iter().copied().filter(|i| !held(i)).collect());
if tc.len() < k || tb.len() < k {
continue;
}
for _ in 0..5 {
let (a, b) = (sample(rng, &tc, k), sample(rng, &tb, k));
let x: Vec<&[f32]> = a.iter().chain(&b).map(|&i| row(i)).collect();
let y: Vec<bool> = (0..2 * k).map(|i| i >= k).collect();
let f = Logistic::fit(sc.clone(), &x, &y, None, C, true);
let score = |v: &Vec<usize>| -> Vec<f32> { v.iter().filter(|i| held(i)).map(|&i| f.score(row(i))).collect() };
aucs.push(auc(&score(&bad), &score(&clean)));
}
}
let ok: Vec<f64> = aucs.into_iter().filter(|a| a.is_finite()).collect();
if !ok.is_empty() {
k_auc.insert(k, ok.iter().sum::<f64>() / ok.len() as f64);
}
}
let fp0b = FP0B.iter().find(|(a, mm, _)| *a == axis && *mm == m).map(|x| x.2);
let holds = fp0b.zip(k_auc.get(&32)).map(|(want, got)| *got >= want - 0.03);
Curve { axis: axis.into(), modality: m, k: k_auc, fp0b, holds }
}
/// Every mechanical axis's curve on its own modality and on FP0b's
pub fn curves(fp: &Fingerprint, l: &Ledger) -> Vec<Curve> {
let mut rng = fastrand::Rng::with_seed(1);
let mut out = Vec::new();
for axis in PICTURE.iter().chain(&SOUND) {
let own = fp.axis(axis).map(|a| a.modality);
let mut ms: Vec<Modality> = own.into_iter().chain(FP0B.iter().filter(|x| x.0 == *axis).map(|x| x.1)).collect();
ms.dedup();
for m in ms.into_iter().collect::<BTreeSet<_>>() {
out.push(curve(l, axis, m, &mut rng));
}
}
out
}
#[derive(Debug, Serialize)]
pub struct WordScore {
pub axis: String,
/// AUC, damaged against clean windows, with no labels
pub auc: f64,
/// the share of damaged windows over the score that flags 10% of clean ones
pub caught: f64,
/// each cheat's share over that same score
pub cheats: BTreeMap<String, f64>,
}
/// Each word head on the bootstrap's windows (FP0g)
pub fn word_scores(l: &Ledger, words: &Words) -> Vec<WordScore> {
let z = |i: usize, axis: &str| words.z(axis, l.features(i));
let of = |axis: &str, pick: &dyn Fn(&Row) -> bool| -> Vec<f32> { l.rows.iter().enumerate().filter(|(_, r)| pick(r)).filter_map(|(i, _)| z(i, axis)).collect() };
let mut out = Vec::new();
for axis in PICTURE.iter().chain(&SOUND) {
if !words.axes.iter().any(|w| w.0 == *axis) {
continue;
}
let clean = of(axis, &|r| damage_on(r, "*"));
let bad = of(axis, &|r| damage_on(r, axis));
let thr = quantile(&clean, 0.9);
let share = |v: &[f32]| share_over(v, thr);
let cheats = CHEATS.iter().filter(|c| c.1 == *axis).map(|c| (c.0.to_string(), share(&of(axis, &|r| r.source == "cheat" && r.kind.as_deref() == Some(c.0))))).collect();
out.push(WordScore { axis: axis.to_string(), auc: auc(&bad, &clean), caught: share(&bad), cheats });
}
out
}
+160
View File
@@ -0,0 +1,160 @@
//! `raea fingerprint` (docs/fingerprint.feature FP3a): a person's fingerprint made, bootstrapped, taught and used to
//! score a piece. The encoders take seconds to load, so the verbs run in a resident service (`raea fingerprint
//! serve`, serve.rs) that keeps them loaded: the first verb starts it, on localhost, and later verbs reach it in
//! milliseconds (earshot's CLI reloads its models on every call, 20-40 s). It leaves after 30 idle minutes, or on
//! `raea fingerprint stop`. RAEA_FINGERPRINT_HERE=1 runs a verb in this process instead.
mod approve;
mod bootstrap;
mod moving;
mod notes;
mod pairing;
mod pick;
mod postmortem;
mod profiles;
mod reembed;
mod serve;
mod things;
mod verbs;
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] [--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); 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)";
/// 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] = [
("--fp", true),
("--was", true),
("--to", true),
("--source", true),
("--kinds", true),
("--tags", true),
("--who", true),
("--about", true),
("--extends", true),
("--from", true),
("--per", true),
("--axis", true),
("--at", true),
("--then", true),
("--span", true),
("--box", true),
("--words", true),
("--project", true),
("--sheet", true),
("--in", true),
("--as", true),
("--against", true),
("--profile", true),
("--by", true),
("--ask", true),
("--tally", false),
("--bad", false),
("--good", false),
("--json", false),
("--timeline", false),
("--here", false),
];
/// A flag's value
pub(crate) fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> {
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).map(String::as_str)
}
pub(crate) fn has(args: &[String], name: &str) -> bool {
args.iter().any(|a| a == name)
}
/// A path as given, against the folder the verb ran in (an absolute one stays itself)
pub(crate) fn at(cwd: &Path, p: &str) -> std::path::PathBuf {
cwd.join(p)
}
/// The files a verb names, against the folder it ran in
pub(crate) fn named(args: &[String], cwd: &Path) -> anyhow::Result<Vec<std::path::PathBuf>> {
Ok(words(args).map_err(anyhow::Error::msg)?.iter().map(|f| at(cwd, f)).collect())
}
/// The files a list names, one a line against the list's own folder; blank lines and # lines are skipped
pub(crate) fn listed(cwd: &Path, list: &str) -> anyhow::Result<Vec<std::path::PathBuf>> {
use anyhow::Context;
let list = at(cwd, list);
let text = std::fs::read_to_string(&list).with_context(|| list.display().to_string())?;
let base = list.parent().unwrap_or(cwd);
Ok(text.lines().map(str::trim).filter(|l| !(l.is_empty() || l.starts_with('#'))).map(|l| at(base, l)).collect())
}
/// The words that aren't flags or their values; an unknown flag is an error
pub(crate) fn words(args: &[String]) -> Result<Vec<&str>, String> {
let mut out = Vec::new();
let mut it = args.iter();
while let Some(a) = it.next() {
match FLAGS.iter().find(|(f, _)| f == a) {
Some((_, true)) => {
it.next().ok_or_else(|| format!("{a} takes a value"))?;
}
Some(_) => {}
None if a.starts_with("--") => return Err(format!("no flag {a}")),
None => out.push(a.as_str()),
}
}
Ok(out)
}
/// `raea fingerprint VERB ...`, printed; its exit code (1: the verb failed, 2: the command was wrong)
pub fn cli(args: &[String], eval: Eval) -> i32 {
let verb = match args.first().map(String::as_str) {
None | Some("--help" | "-h" | "help") => {
println!("{USAGE}");
return 0;
}
Some(v) => v,
};
if let Err(e) = words(&args[1..]) {
eprintln!("raea fingerprint: {e}\n{USAGE}");
return 2;
}
match verb {
"serve" => match serve(eval) {
Ok(()) => 0,
Err(e) => {
eprintln!("raea fingerprint serve: {e:#}");
1
}
},
"report" => verbs::report_here(args),
"which" => pick::which_here(&args[1..], &std::env::current_dir().unwrap_or_default()),
"diff" => pick::diff_here(&args[1..]),
"read" => notes::read_here(&args[1..], &std::env::current_dir().unwrap_or_default()),
"readings" => notes::readings_here(&args[1..], &std::env::current_dir().unwrap_or_default()),
"share" => pick::share_here(&args[1..], &std::env::current_dir().unwrap_or_default()),
"use" => pick::use_here(&args[1..], &std::env::current_dir().unwrap_or_default()),
"new" | "bootstrap" | "teach" | "approve" | "pair" | "versions" | "learn-notes" | "move" | "postmortem" | "things" | "reembed" | "profile" | "score" | "stop" => {
let cwd = std::env::current_dir().unwrap_or_default();
let here = has(args, "--here") || std::env::var_os("RAEA_FINGERPRINT_HERE").is_some();
let (out, code) = if here { serve::here(args, &cwd, eval) } else { serve::call(args, &cwd) };
if !out.is_empty() {
println!("{}", out.trim_end());
}
code
}
v => {
eprintln!("raea fingerprint: no verb {v}\n{USAGE}");
2
}
}
}
#[cfg(test)]
mod tests {
#[test]
fn the_usage_names_every_flag() {
let missing: Vec<_> = super::FLAGS.iter().filter(|(f, _)| *f != "--here" && !super::USAGE.contains(f)).collect();
assert!(missing.is_empty(), "raea fingerprint takes flags its usage doesn't name: {missing:?}");
}
}
+86
View File
@@ -0,0 +1,86 @@
//! `raea fingerprint move [--fp CHILD] [--to PARENT] [--axis A] [--source S] [--project P]` (docs/fingerprint.feature
//! FP14d). A note or mark teaches the fingerprint that judged the piece, and a parent never reads a child's evidence
//! (inherit.rs), so one client's taste doesn't move the person's own. Moving labels up is the person's call: the
//! child's own rows that match leave its ledger for a fingerprint it extends (its nearest unless --to names one). A
//! row on an axis the parent hasn't, or on one the child says otherwise, stays: in the parent it would mean something
//! else.
use crate::{Eval, flag};
use anyhow::{Result, anyhow, bail};
use raea_sys_fingerprint::evidence::{Ledger, Row};
use raea_sys_fingerprint::folder::Folder;
use raea_sys_fingerprint::inherit;
use raea_sys_fingerprint::taxonomy::Fingerprint;
use std::collections::BTreeSet;
/// The rows `pick` takes from `child` into `parent`; returns how many moved
pub fn rows(child: &mut Ledger, parent: &mut Ledger, pick: &dyn Fn(&Row) -> bool) -> usize {
let mut n = 0;
for i in 0..child.rows.len() {
if pick(&child.rows[i]) {
parent.push(child.rows[i].clone(), child.features(i));
n += 1;
}
}
child.retain(|r| !pick(r));
n
}
/// The axes a row may carry into `parent`: the parent's own and inherited ones, less those the child overrides
pub fn carried(parent: &Fingerprint, eval: Eval, over: &BTreeSet<String>) -> BTreeSet<String> {
let full = inherit::axes(parent, &inherit::parents(parent, Some(eval)));
full.axes.iter().map(|a| a.name.clone()).filter(|a| !over.contains(a)).chain(["*".to_string()]).collect()
}
/// Moves the child's matching rows up and writes both ledgers; returns the parent's name and what it did
pub(crate) fn up(dir: &Folder, child: &Fingerprint, args: &[String], eval: Eval) -> Result<(String, String)> {
let (axis, source, project) = (flag(args, "--axis"), flag(args, "--source"), flag(args, "--project"));
if axis.is_none() && source.is_none() && project.is_none() {
bail!("say which labels: --axis A, --source S (note, teach, approval, pair, damage) or --project P");
}
let parents = inherit::parents(child, Some(eval));
let (pdir, parent) = match flag(args, "--to") {
Some(n) => parents.iter().find(|(_, p)| p.name == n).ok_or_else(|| anyhow!("{} doesn't extend {n}: labels only move up", child.name))?,
None => parents.first().ok_or_else(|| anyhow!("{} extends nothing, so its labels have nowhere to move up to", child.name))?,
};
let keep = carried(parent, eval, &inherit::overrides(child, &parents));
let wanted = |r: &Row| axis.is_none_or(|a| r.axis == a) && source.is_none_or(|s| r.source == s) && project.is_none_or(|p| r.project == p);
let (mut lc, mut lp) = (dir.ledger()?, pdir.ledger()?);
let stay = lc.rows.iter().filter(|r| wanted(r) && !keep.contains(&r.axis)).count();
let n = rows(&mut lc, &mut lp, &|r| wanted(r) && keep.contains(&r.axis));
if n == 0 && stay == 0 {
bail!("none of {}'s own labels match", child.name);
}
pdir.write_ledger(&lp)?;
dir.write_ledger(&lc)?;
let mut out = format!("{n} labels moved from {} up to {}\n", child.name, parent.name);
if stay > 0 {
out += &format!("{stay} stay: their axes are {}'s own, and would mean something else in {}\n", child.name, parent.name);
}
Ok((parent.name.clone(), out))
}
#[cfg(test)]
mod tests {
use super::*;
fn row(axis: &str, source: &str) -> Row {
Row { media: "m".into(), a: 0.0, b: 2.0, axis: axis.into(), bad: true, weight: 1.0, who: "me".into(), source: source.into(), project: "p".into(), kind: None, region: None, words: None, at: 0, pin: None }
}
#[test]
fn only_picked_rows_move_and_keep_their_features() {
let w = raea_sys_fingerprint::evidence::width();
let (mut c, mut p) = (Ledger::default(), Ledger::default());
c.push(row("blur", "note"), &vec![1.0; w]);
c.push(row("glow", "note"), &vec![2.0; w]);
c.push(row("blur", "damage"), &vec![3.0; w]);
p.push(row("hiss", "teach"), &vec![4.0; w]);
let n = rows(&mut c, &mut p, &|r| r.source == "note" && r.axis == "blur");
assert_eq!(n, 1);
assert_eq!(c.rows.iter().map(|r| r.axis.as_str()).collect::<Vec<_>>(), ["glow", "blur"]);
assert_eq!((c.features(0)[0], c.features(1)[0]), (2.0, 3.0), "the child's rows keep their own features");
assert_eq!(p.rows.len(), 2);
assert_eq!(p.features(1)[0], 1.0, "a moved row carries its features");
}
}
+346
View File
@@ -0,0 +1,346 @@
//! 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
//! 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
//! once the kind is right 45 times in 50 and the axis 40 (FP5b) does `raea fingerprint learn-notes` make each defect
//! or praise an evidence row over its span (1.5 s before the pin to 0.5 s after). A direction goes to the brief and the
//! agent, never into a head. A note's marks (FP11b) make its row a region label: the box around its marks, boxes and
//! lassos; a span pin sets the row's time. On a render with a layer pass, a reading keeps the layers under its pin,
//! and the reader is told them.
use crate::{flag, has, words};
use raea_sys_fingerprint::folder::Folder;
use raea_sys_fingerprint::taxonomy::Fingerprint;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
/// FP5b's bar, out of every 50 checked
pub const KIND_BAR: f64 = 45.0 / 50.0;
pub const AXIS_BAR: f64 = 40.0 / 50.0;
pub const INBOX: &str = "fingerprint";
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct Reading {
pub note: String,
pub text: String,
pub who: String,
pub media: PathBuf,
pub t: f64,
pub project: String,
/// defect, direction, praise or both
pub kind: String,
pub axis: Option<String>,
/// how it was read: kimi or claude
pub by: String,
/// the person's check: Some(true) agreed, Some(false) not; None until asked
#[serde(default)]
pub kind_ok: Option<bool>,
#[serde(default)]
pub axis_ok: Option<bool>,
/// a span pin's end: the label covers t..to (FP11b)
#[serde(default, skip_serializing_if = "Option::is_none")]
pub to: Option<f64>,
/// where in the frame the note's marks say the thing is, x0,y0,x1,y1 in 0-1 (FP11b)
#[serde(default, skip_serializing_if = "Option::is_none")]
pub region: Option<[f32; 4]>,
/// the layers under the pin's x,y in the layer pass, on a render with one (FP5a)
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub layers: Vec<String>,
}
/// A post's video on this machine: the renders library, else the project's own folder
fn media(project: &Path, m: &Value) -> Option<PathBuf> {
let p = m["path"].as_str()?;
let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());
[home.join(".raea/feed/media").join(p), project.join(p)].into_iter().find(|f| f.is_file())
}
/// Every video in the project's feed, each version's, found on this machine (FP7a's postmortem looks back on them)
pub fn videos(project: &Path) -> Vec<PathBuf> {
let mut out: Vec<PathBuf> = Vec::new();
for e in std::fs::read_dir(project.join(".raea/feed")).into_iter().flatten().flatten() {
let Some(post) = std::fs::read_to_string(e.path()).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok()) else { continue };
for m in post["media"].as_array().into_iter().flatten().filter(|m| m["kind"] == "video") {
if let Some(v) = media(project, m).filter(|v| !out.contains(v)) {
out.push(v);
}
}
}
out.sort();
out
}
/// Every person's pinned note on a video in the project's feed
pub fn pinned(project: &Path) -> Vec<Reading> {
let name = project.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let mut out = Vec::new();
for e in std::fs::read_dir(project.join(".raea/feed")).into_iter().flatten().flatten() {
let Ok(post) = std::fs::read_to_string(e.path()).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok()).ok_or(()) else { continue };
let Some(video) = post["media"].as_array().into_iter().flatten().find(|m| m["kind"] == "video").and_then(|m| media(project, m)) else { continue };
for n in post["notes"].as_array().into_iter().flatten() {
let (Some(t), Some(text)) = (n["pin"]["t"].as_f64(), n["text"].as_str()) else { continue };
if n["author"]["kind"] != "person" {
continue;
}
let to = n["pin"]["to"].as_f64().filter(|&to| to > t);
let at = n["pin"]["x"].as_f64().zip(n["pin"]["y"].as_f64()).map(|(x, y)| [x - 0.01, y - 0.01, x + 0.01, y + 0.01].map(|v| v.clamp(0.0, 1.0)));
let layers = at.map(|b| raea_sys_fingerprint_things::located::layers(&video, t, b)).unwrap_or_default();
out.push(Reading { note: n["id"].as_str().unwrap_or("").into(), text: text.into(), who: n["author"]["name"].as_str().unwrap_or("me").into(), media: video.clone(), t, project: name.clone(), to, region: raea_sys_fingerprint_use::grow::marked(&n["pin"]), layers, ..Default::default() });
}
}
out
}
/// The reading prompt: the axes with their words, then the notes, and the JSON to answer
pub fn prompt(fp: &Fingerprint, notes: &[Reading]) -> String {
let axes = fp.axes.iter().map(|a| format!("- {}: {}", a.name, a.words.join("; "))).collect::<Vec<_>>().join("\n");
let on = |n: &Reading| if n.layers.is_empty() { String::new() } else { format!(" (pinned on {})", n.layers.join(", ")) };
let list = notes.iter().map(|n| format!("{}: {}{}", n.note, n.text.replace('\n', " "), on(n))).collect::<Vec<_>>().join("\n");
format!(
"You read a person's review notes on their videos. Read each note only; open no file and change nothing.\n\
For each note say its kind: \"defect\" (it names something wrong at that moment), \"direction\" (it asks for a creative change, \
not a fault), \"praise\" (it says something is good) or \"both\" (a defect and a direction). Then the axis it is about, from \
these and only these, or null when none fits:\n{axes}\n\nThe notes, one a line, id first:\n{list}\n\n\
End with only this JSON, nothing after it: [{{\"id\": \"\", \"kind\": \"defect|direction|praise|both\", \"axis\": \"name or null\"}}]"
)
}
/// The JSON array an answer ends with
pub fn answer(text: &str) -> Option<Vec<Value>> {
let end = text.rfind(']')?;
let start = text[..end].rfind("[{").or_else(|| text[..end].rfind('['))?;
serde_json::from_str(&text[start..=end]).ok()
}
/// Fold an answer into the notes: a kind it doesn't know or an axis not in the fingerprint is dropped
pub fn fold(notes: &mut [Reading], fp: &Fingerprint, ans: &[Value], by: &str) {
for a in ans {
let Some(id) = a["id"].as_str() else { continue };
let Some(n) = notes.iter_mut().find(|n| n.note == id) else { continue };
let kind = a["kind"].as_str().unwrap_or("");
if !matches!(kind, "defect" | "direction" | "praise" | "both") {
continue;
}
n.kind = kind.into();
n.axis = a["axis"].as_str().filter(|x| fp.axis(x).is_some()).map(str::to_string);
n.by = by.into();
}
}
/// 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)
}
pub fn readings_of(dir: &Folder) -> Vec<Reading> {
std::fs::read_to_string(dir.dir.join("readings.jsonl")).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).collect()
}
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]`
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 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);
let mut kept = readings_of(&dir);
notes.retain(|n| !kept.iter().any(|k| k.note == n.note && k.media == n.media));
if notes.is_empty() {
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"))?;
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()))
};
match run() {
Ok(o) => {
println!("{o}");
0
}
Err(e) => {
eprintln!("raea fingerprint read: {e}");
1
}
}
}
/// The share of checked readings the person agreed with, for kind and for axis, and how many were checked
pub fn agreement(r: &[Reading]) -> (Option<f64>, Option<f64>, usize) {
let share = |v: Vec<bool>| (!v.is_empty()).then(|| v.iter().filter(|x| **x).count() as f64 / v.len() as f64);
let checked = r.iter().filter(|x| x.kind_ok.is_some()).count();
(share(r.iter().filter_map(|x| x.kind_ok).collect()), share(r.iter().filter_map(|x| x.axis_ok).collect()), checked)
}
/// Whether the readings have earned training (FP5b): 50 checked, the kind right 45 times and the axis 40
pub fn earned(r: &[Reading]) -> bool {
matches!(agreement(r), (Some(k), Some(a), n) if n >= 50 && k >= KIND_BAR && a >= AXIS_BAR)
}
/// The choices a reading is checked with, and what each says about kind and axis
pub const CHOICES: [(&str, bool, bool); 4] = [("Right", true, true), ("Right kind, wrong axis", true, false), ("Wrong kind", false, false), ("Right axis, wrong kind", false, true)];
/// `raea fingerprint readings [PROJECT] [--ask N] [--tally]`: the readings kept in the fingerprint that judges PROJECT
pub(crate) fn readings_here(args: &[String], cwd: &Path) -> i32 {
let dir = crate::pick::chosen(args, Some(&crate::pick::piece_in(args, cwd))).0;
let mut r = readings_of(&dir);
if let Some(n) = flag(args, "--ask").and_then(|n| n.parse::<usize>().ok()) {
let todo: Vec<usize> = r.iter().enumerate().filter(|(_, x)| x.kind_ok.is_none()).map(|(i, _)| i).take(n).collect();
let mut cmd = std::process::Command::new(std::env::current_exe().unwrap_or_else(|_| "raea".into()));
cmd.args(["show", "--title", "Check how raea read your notes", "--inbox", INBOX]);
for &i in &todo {
let x = &r[i];
let q = format!("[{}] \"{}\" read as {} on {}", x.note, x.text.replace('\n', " "), x.kind, x.axis.as_deref().unwrap_or("no axis"));
cmd.args(["--question", &q, "--preview", &x.media.display().to_string()]);
for (c, _, _) in CHOICES {
cmd.args(["--choice", c]);
}
}
if todo.is_empty() {
println!("every reading is checked");
return 0;
}
let Ok(out) = cmd.output() else { return 1 };
let said = String::from_utf8_lossy(&out.stdout).into_owned();
// the item raea show made, so the answers can be matched to the notes asked, in order
let Some(item) = said.split(|c: char| c.is_whitespace() || c == '(' || c == ')' || c == ',').find(|w| w.starts_with("i-show-")) else {
eprintln!("raea fingerprint readings: raea show didn't say its item: {said}{}", String::from_utf8_lossy(&out.stderr));
return 1;
};
let mut asked: serde_json::Map<String, Value> = std::fs::read(dir.dir.join("asked.json")).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default();
asked.insert(item.to_string(), json!(todo.iter().map(|&i| [r[i].note.clone(), r[i].media.display().to_string()]).collect::<Vec<_>>()));
let _ = std::fs::write(dir.dir.join("asked.json"), serde_json::to_vec_pretty(&asked).unwrap_or_default());
println!("{} readings put to you in the app ({item}); `raea fingerprint readings --tally` counts your answers", todo.len());
return 0;
}
if has(args, "--tally") {
let asked: serde_json::Map<String, Value> = std::fs::read(dir.dir.join("asked.json")).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default();
let inbox = PathBuf::from(std::env::var("HOME").unwrap_or_default()).join(format!(".raea/inbox/{INBOX}.jsonl"));
for line in std::fs::read_to_string(inbox).unwrap_or_default().lines() {
let Ok(v) = serde_json::from_str::<Value>(line) else { continue };
let Some(batch) = v["item"].as_str().and_then(|i| asked.get(i)).and_then(Value::as_array) else { continue };
for (k, who) in batch.iter().enumerate() {
let Some(a) = v["answers"][format!("q{}", k + 1)].as_str() else { continue };
let Some((_, ok_kind, ok_axis)) = CHOICES.iter().find(|c| c.0 == a) else { continue };
if let Some(x) = r.iter_mut().find(|x| who[0].as_str() == Some(x.note.as_str()) && who[1].as_str() == Some(&x.media.display().to_string())) {
(x.kind_ok, x.axis_ok) = (Some(*ok_kind), Some(*ok_axis));
}
}
}
let _ = write_readings(&dir, &r);
}
let (k, a, n) = agreement(&r);
let f = |x: Option<f64>| x.map_or("-".into(), |v| format!("{:.0}%", v * 100.0));
println!("{} readings, {n} checked: kind right {}, axis right {} (FP5b needs 50 checked, 90% and 80%): {}", r.len(), f(k), f(a), if earned(&r) { "notes may train" } else { "notes don't train yet" });
println!("{}", json!({"readings": r.len(), "checked": n, "kind": k, "axis": a, "earned": earned(&r)}));
0
}
/// `learn-notes`: each checked-off reading's defect or praise as an evidence row over its span, once the readings
/// have earned it; a reading already learned is replaced, so learning again is safe
pub(crate) fn learn(enc: &mut raea_sys_columns::Encoders, dir: &Folder, l: &mut raea_sys_fingerprint::evidence::Ledger) -> anyhow::Result<String> {
let r = readings_of(dir);
if !earned(&r) {
let (k, a, n) = agreement(&r);
anyhow::bail!("notes don't train yet: {n} readings checked, kind right {:?}, axis right {:?} (FP5b needs 50 checked, 90% and 80%: raea fingerprint readings --ask 50)", k, a);
}
// only these readings' rows are remade: notes another fingerprint's person moved up here (FP14d) stay
let ids: std::collections::BTreeSet<&str> = r.iter().map(|x| x.note.as_str()).collect();
l.retain(|x| x.source != "note" || !x.kind.as_deref().is_some_and(|k| ids.contains(k)));
let mut made = 0;
for x in r.iter().filter(|x| x.kind_ok != Some(false) && x.axis_ok != Some(false)) {
let bad = match x.kind.as_str() {
"defect" | "both" => true,
"praise" => false,
_ => continue,
};
let axis = match (&x.axis, bad) {
(Some(a), _) => a.clone(),
(None, false) => "*".into(),
(None, true) => continue,
};
let c = enc.columns(&x.media)?;
// a span is the label's time; a moment, 1.5 s before the pin to 0.5 s after (FP11b)
let (a, b) = x.to.map_or(((x.t - 1.5).max(0.0), (x.t + 0.5).min(c.dur)), |to| (x.t.max(0.0), to.min(c.dur)));
if b - a < 0.5 {
continue;
}
// a defect's marks, grown into the thing by EdgeTAM and followed through its shot: a row for each 2 s it stays
// in, with its box there (grow.rs through); else the mark's own box over the label
let seed = x.region.filter(|_| bad);
let shot = seed.and_then(|s| raea_sys_fingerprint_use::grow::through(&x.media, x.t, c.dur, s, 2.0).ok().flatten()).filter(|w| !w.is_empty());
for (a, b, region) in shot.map_or_else(|| vec![(a, b, seed)], |w| w.into_iter().map(|(a, b, r)| (a, b, Some(r))).collect()) {
let (media, axis, who, project, kind, words) = (c.media.clone(), axis.clone(), x.who.clone(), x.project.clone(), Some(x.note.clone()), Some(x.text.clone()));
let row = raea_sys_fingerprint::evidence::Row { media, a, b, axis, bad, weight: 1.0, who, source: "note".into(), project, kind, region, words, at: 0, pin: None };
l.push(row, &raea_sys_fingerprint::evidence::features(&c, a, b));
}
made += 1;
}
Ok(format!("{made} notes are evidence now (defects and praise; directions stay with the brief)\n"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_reading_keeps_only_kinds_and_axes_it_knows() {
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");
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");
n[0].layers = vec!["Floor".into()];
assert!(prompt(&fp, &n).contains("n1: ") && prompt(&fp, &n).contains("(pinned on Floor)"), "the reader is told the layer");
}
#[test]
fn notes_train_only_once_the_person_agrees_enough() {
let r = |k: bool, a: bool| Reading { kind_ok: Some(k), axis_ok: Some(a), ..Default::default() };
let mut v: Vec<Reading> = (0..45).map(|_| r(true, true)).collect();
v.extend((0..5).map(|_| r(false, false)));
assert!(earned(&v), "45 and 45 of 50");
v[0] = r(false, true);
assert!(!earned(&v), "44 kinds of 50 is under the bar");
assert!(!earned(&v[..40]), "fewer than 50 checked");
}
}
+91
View File
@@ -0,0 +1,91 @@
//! Pairs from what the person already does (docs/fingerprint.feature FP6b, FP6c). `raea fingerprint pair WORSE BETTER
//! --axis A [--at T] [--then T2]` records a pick between real options or a hand edit's before and after: the better
//! window against the worse on that axis. `raea fingerprint versions V1 V2...` (the files in version order) makes a
//! weak pair (weight 0.5, every axis) of each noted moment whose picture or sound changed in the next version (cosine
//! distance 0.01 or more) and wasn't noted again within 1 s there.
use crate::approve::noted;
use crate::flag;
use anyhow::{Context, Result, anyhow, bail};
use raea_sys_columns::Encoders;
use raea_sys_columns::window::Modality;
use raea_sys_fingerprint::evidence::{Ledger, Row, features, slice};
use raea_sys_fingerprint::pairs::difference;
use std::path::Path;
fn row(media: &str, a: f64, b: f64, axis: &str, weight: f32, who: &str, project: String, words: Option<String>) -> Row {
Row { media: media.into(), a, b, axis: axis.into(), bad: true, weight, who: who.into(), source: "pair".into(), project, kind: None, region: None, words, at: 0, pin: None }
}
/// `pair`: one row, the worse window's features minus the better one's
pub(crate) fn pair(enc: &mut Encoders, l: &mut Ledger, who: &str, args: &[String], cwd: &Path, project: impl Fn(&Path) -> String) -> Result<String> {
let f = crate::named(args, cwd)?;
let [worse, better] = f.as_slice() else { bail!("raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2]") };
let axis = flag(args, "--axis").ok_or_else(|| anyhow!("--axis A: the axis the better one is better on"))?;
let span: f64 = flag(args, "--span").map_or(Ok(2.0), str::parse).context("--span takes seconds")?;
let t: f64 = flag(args, "--at").map_or(Ok(span / 2.0), str::parse).context("--at takes seconds")?;
let t2: f64 = flag(args, "--then").map_or(Ok(t), str::parse).context("--then takes seconds")?;
let (cw, cb) = (enc.columns(worse)?, enc.columns(better)?);
let win = |dur: f64, t: f64| {
let a = (t - span / 2.0).clamp(0.0, (dur - span).max(0.0));
(a, (a + span).min(dur))
};
let ((a, b), (a2, b2)) = (win(cw.dur, t), win(cb.dur, t2));
let d = difference(&features(&cw, a, b), &features(&cb, a2, b2));
l.push(row(&cw.media, a, b, axis, 1.0, who, flag(args, "--project").map_or_else(|| project(worse), str::to_string), flag(args, "--words").map(str::to_string)), &d);
Ok(format!("paired on {axis}: {} at {a:.1} s is worse than {} at {a2:.1} s\n", worse.display(), better.display()))
}
fn distance(x: &[f32], y: &[f32]) -> f32 {
let d: f32 = x.iter().zip(y).map(|(a, b)| a * b).sum();
1.0 - d / (x.iter().map(|a| a * a).sum::<f32>().sqrt() * y.iter().map(|b| b * b).sum::<f32>().sqrt()).max(1e-9)
}
/// Whether a noted moment changed in the next version and wasn't noted there again
pub(crate) fn weak(before: &[f32], after: &[f32], t: f64, next_notes: &[f64]) -> bool {
let changed = [Modality::Picture, Modality::Sound].iter().any(|&m| distance(&before[slice(m)], &after[slice(m)]) >= 0.01);
changed && !next_notes.iter().any(|n| (n - t).abs() <= 1.0)
}
/// `versions`: weak pairs along a chain of versions
pub(crate) fn versions(enc: &mut Encoders, l: &mut Ledger, who: &str, args: &[String], cwd: &Path, project: impl Fn(&Path) -> String) -> Result<String> {
let f = crate::named(args, cwd)?;
if f.len() < 2 {
bail!("raea fingerprint versions V1 V2... takes the versions in order");
}
let mut made = 0;
for w in f.windows(2) {
let (now, next) = (&w[0], &w[1]);
let (cn, cx) = (enc.columns(now)?, enc.columns(next)?);
let next_notes = noted(next);
for t in noted(now) {
let (a, b) = ((t - 1.5).max(0.0), (t + 0.5).min(cn.dur.min(cx.dur)));
if b - a < 1.0 {
continue;
}
let (fb, fa) = (features(&cn, a, b), features(&cx, a, b));
if weak(&fb, &fa, t, &next_notes) {
l.push(row(&cn.media, a, b, "*", 0.5, who, flag(args, "--project").map_or_else(|| project(now), str::to_string), None), &difference(&fb, &fa));
made += 1;
}
}
}
Ok(format!("{made} weak pairs from {} versions: noted moments the next version changed and nobody noted again\n", f.len()))
}
#[cfg(test)]
mod tests {
use raea_sys_fingerprint::evidence::width;
#[test]
fn a_changed_moment_not_noted_again_is_a_weak_pair() {
let a = vec![1.0; width()];
let mut b = a.clone();
assert!(!super::weak(&a, &b, 5.0, &[]), "unchanged: no pair");
b.iter_mut().enumerate().for_each(|(i, x)| *x = if i % 2 == 0 { 1.0 } else { -1.0 });
assert!(super::weak(&a, &b, 5.0, &[]));
assert!(!super::weak(&a, &b, 5.0, &[5.6]), "noted again within 1 s: no pair");
assert!(super::weak(&a, &b, 5.0, &[7.0]));
}
}
+151
View File
@@ -0,0 +1,151 @@
//! Which fingerprint judges a piece (docs/fingerprint.feature FP14c): `raea fingerprint which PATH` says the one
//! chosen, what it's for and why; `raea fingerprint use NAME [--in project|workspace] [PATH]` pins one by writing that
//! level's `default`. score and teach use the chosen one unless --fp names another. No encoders are needed.
use crate::{flag, has, words};
use raea_sys_fingerprint::folder::{Folder, root};
use raea_sys_fingerprint_use::which::{Choice, default_file, levels, piece, which};
use std::path::{Path, PathBuf};
/// The fingerprint a verb uses: --fp, else the one that judges `file`, else the account's default, else "me"
pub(crate) fn chosen(args: &[String], file: Option<&Path>) -> (Folder, Option<Choice>) {
if let Some(n) = flag(args, "--fp") {
return (Folder::named(n), None);
}
if let Some(c) = file.and_then(which) {
return (Folder { dir: c.dir.clone() }, Some(c));
}
let n = std::fs::read_to_string(root().join("default")).ok().map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).unwrap_or_else(|| "me".into());
(Folder::named(&n), None)
}
/// A piece in the project a verb names (its first word, else the current folder), so `read`, `readings` and
/// `learn-notes` keep a project's notes in the fingerprint that judges it (FP14d)
pub(crate) fn piece_in(args: &[String], cwd: &Path) -> PathBuf {
here(cwd, args, 0).join("piece.mp4")
}
fn here(cwd: &Path, args: &[String], at: usize) -> PathBuf {
let w = words(args).unwrap_or_default();
w.get(at).map_or_else(|| cwd.to_path_buf(), |p| cwd.join(p))
}
pub(crate) fn which_here(args: &[String], cwd: &Path) -> i32 {
let path = here(cwd, args, 0);
let Some(c) = which(&path) else {
eprintln!("raea fingerprint which: you have no fingerprint yet (`raea fingerprint new me` makes one)");
return 1;
};
if has(args, "--json") {
let p = piece(&path);
println!("{}", serde_json::json!({"chosen": c, "piece": p, "looked_in": levels(&p).iter().map(|(l, d)| serde_json::json!({"level": l, "dir": d})).collect::<Vec<_>>()}));
} else {
println!("{} {}", c.name, c.about.as_deref().unwrap_or(""));
println!(" why: {}", c.why);
println!(" at: {}", c.dir.display());
}
0
}
pub(crate) fn use_here(args: &[String], cwd: &Path) -> i32 {
let Some(name) = words(args).ok().and_then(|w| w.first().map(|s| s.to_string())) else {
eprintln!("raea fingerprint use: which one? raea fingerprint use NAME [--in project|workspace] [PATH]");
return 2;
};
let level = flag(args, "--in").unwrap_or("account");
if !matches!(level, "project" | "workspace" | "account") {
eprintln!("raea fingerprint use: --in takes project or workspace, not {level}");
return 2;
}
let path = here(cwd, args, 1);
let Some(file) = default_file(&path, level) else {
eprintln!("raea fingerprint use: {} isn't in a {level} (no .raea/{level} above it)", path.display());
return 1;
};
let p = piece(&path);
let all = levels(&p);
let from = all.iter().position(|(l, _)| *l == level).unwrap_or(0);
if !all[from..].iter().any(|(_, d)| Folder { dir: d.join(&name) }.exists()) {
eprintln!("raea fingerprint use: no fingerprint {name} at the {level} or above it");
return 1;
}
let wrote = std::fs::create_dir_all(file.parent().unwrap_or(cwd)).and(std::fs::write(&file, &name));
if let Err(e) = wrote {
eprintln!("raea fingerprint use: {}: {e}", file.display());
return 1;
}
println!("{name} judges this {level}'s pieces now ({})", file.display());
0
}
/// `raea fingerprint diff A B [--json]` (FP8b): the axes two fingerprints rank the same evidence most differently on
pub(crate) fn diff_here(args: &[String]) -> i32 {
let w = words(args).unwrap_or_default();
let [a, b] = w.as_slice() else {
eprintln!("raea fingerprint diff: which two? raea fingerprint diff A B");
return 2;
};
match raea_sys_fingerprint_use::diff::diff(&Folder::named(a), &Folder::named(b), 3) {
Ok(d) if has(args, "--json") => {
println!("{}", serde_json::to_string_pretty(&d).unwrap_or_default());
0
}
Ok(d) => {
println!("where {a} and {b} differ, most apart first (0 agree, 1 unrelated, 2 opposed):");
for x in &d {
println!(" {:16} {:.2} over {} windows", x.axis, x.apart, x.windows);
for m in &x.moments {
println!(" {} {:.1}-{:.1}s: {a} ranks it {:.0}%, {b} {:.0}%", &m.media[..m.media.len().min(12)], m.a, m.b, m.rank_a * 100.0, m.rank_b * 100.0);
}
}
0
}
Err(e) => {
eprintln!("raea fingerprint diff: {e:#}");
1
}
}
}
/// `raea fingerprint share NAME --in project|workspace [PATH]` (FP8a): the fingerprint's taxonomy, words and evidence
/// copied into that level's .raea/fingerprints, to travel with its repo; never its heads (each machine retrains them)
/// and never media (the rows hold embeddings, spans and labels)
pub(crate) fn share_here(args: &[String], cwd: &Path) -> i32 {
let Some(name) = words(args).ok().and_then(|w| w.first().map(|s| s.to_string())) else {
eprintln!("raea fingerprint share: which one? raea fingerprint share NAME --in project|workspace [PATH]");
return 2;
};
let level = flag(args, "--in").unwrap_or("project");
let path = here(cwd, args, 1);
let Some(to) = default_file(&path, level).and_then(|f| f.parent().map(|d| d.join(&name))) else {
eprintln!("raea fingerprint share: {} isn't in a {level} (no .raea/{level} above it)", path.display());
return 1;
};
let from = Folder::named(&name);
let run = || -> anyhow::Result<usize> {
from.read(None)?;
let dest = Folder { dir: to.clone() };
if dest.exists() {
anyhow::bail!("{} has a fingerprint {name} already", to.display());
}
std::fs::create_dir_all(&to)?;
for f in ["fingerprint.ts", "fingerprint.json", "words.json", "words.f16"] {
if from.dir.join(f).is_file() {
std::fs::copy(from.dir.join(f), to.join(f))?;
}
}
let l = from.ledger()?;
dest.write_ledger(&l)?;
Ok(l.rows.len())
};
match run() {
Ok(n) => {
println!("shared {name} into {} with {n} evidence rows, no heads and no media; commit it with the {level}", to.display());
0
}
Err(e) => {
eprintln!("raea fingerprint share: {e:#}");
1
}
}
}
+58
View File
@@ -0,0 +1,58 @@
//! `raea fingerprint postmortem [PROJECT] [--ask N] [--tally]` (docs/fingerprint.feature FP7a; the picking, the clips
//! and the questions are raea-sys-fingerprint-use's postmortem.rs). It scores every version of the project's pieces with
//! the fingerprint that judges the project and asks at most ten yes/no questions in the app; `--tally` makes each answer
//! an evidence row, retrains, and says how each head's held-out score moved.
use crate::{Eval, flag, has};
use anyhow::{Result, anyhow, bail};
use raea_sys_columns::Encoders;
use raea_sys_fingerprint::evidence::{Row, features};
use raea_sys_fingerprint::retrain;
use raea_sys_fingerprint_use::postmortem::{self as pm, MOST};
use raea_sys_fingerprint_use::score::{Scored, score};
use std::path::{Path, PathBuf};
pub(crate) fn run(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result<(String, i32)> {
let project = crate::pick::piece_in(args, cwd).parent().map(Path::to_path_buf).unwrap_or_else(|| cwd.to_path_buf());
let name = project.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let (dir, fp, w) = crate::verbs::open(enc, args, eval, Some(&crate::pick::piece_in(args, cwd)))?;
let before = dir.trained()?.map(|t| t.0).ok_or_else(|| anyhow!("{} has no trained heads yet: `raea fingerprint bootstrap` or teach it first", fp.name))?;
if has(args, "--tally") {
let inbox = std::fs::read_to_string(PathBuf::from(std::env::var("HOME").unwrap_or_default()).join(format!(".raea/inbox/{}.jsonl", pm::INBOX))).unwrap_or_default();
let answers = pm::answered(&dir.dir, &inbox);
let mut l = dir.ledger()?;
// every tally adds every answer again, so tallying twice is safe
l.retain(|r| r.source != "postmortem");
for (x, yes) in &answers {
let c = enc.columns(&x.file)?;
let (a, b) = (x.a.min(c.dur), x.b.min(c.dur));
if b - a < 0.5 {
continue;
}
let who = fp.who.clone().unwrap_or_else(|| "me".into());
let row = Row { media: c.media.clone(), a, b, axis: x.axis.clone(), bad: *yes, weight: 1.0, who, source: "postmortem".into(), project: name.clone(), kind: None, region: None, words: Some(x.words.clone()), at: 0, pin: None };
l.push(row, &features(&c, a, b));
}
dir.write_ledger(&l)?;
let after = retrain(&dir, &fp, &w, &l, None)?;
let f = |v: Option<f64>| v.map_or("-".into(), |v| format!("{v:.2}"));
let mut out = format!("{} answers are evidence now\n", answers.len());
for (axis, was, now) in pm::moved(&before, &after) {
out += &format!(" {axis}: held out {} -> {}\n", f(was), f(now));
}
return Ok((out, 0));
}
let n = flag(args, "--ask").map_or(Ok(MOST), str::parse).map_err(|_| anyhow!("--ask takes a count"))?.min(MOST);
let files = crate::notes::videos(&project);
if files.is_empty() {
bail!("{} has no videos in its feed to look back on", project.display());
}
let scored = files.iter().map(|f| -> Result<Scored> { Ok(score(&fp, Some(&w), Some(&before), &enc.columns(f)?, &f.display().to_string())) }).collect::<Result<Vec<_>>>()?;
let asks = pm::picks(&scored, &before, &fp, &dir.ledger()?, n);
if asks.is_empty() {
return Ok((format!("nothing to ask: on {} versions, no head disagrees with you or sits near its flag\n", files.len()), 0));
}
let item = pm::ask(&std::env::current_exe()?, &dir.dir, &name, &asks)?;
let against = asks.iter().filter(|x| x.why == "disagrees with you").count();
Ok((format!("{} questions on {} versions put to you in the app ({item}): {against} where it disagrees with you, the rest where it's least sure; `raea fingerprint postmortem --tally` adds your answers\n", asks.len(), files.len()), 0))
}
+80
View File
@@ -0,0 +1,80 @@
//! `raea fingerprint profile REFS... --as NAME [--against LIST]` and `score FILE --profile NAME` (docs/fingerprint.feature
//! FP6e): a profile's measures taken from work the person admires, kept in the fingerprint's profiles/NAME.json, and a
//! piece critiqued against it, measure by measure, with where and which way to move.
use crate::{flag, listed, named};
use anyhow::{Context, Result, anyhow, bail};
use raea_sys_columns::{Encoders, media};
use raea_sys_fingerprint::folder::Folder;
use raea_sys_fingerprint_use::profile::{Measures, NAMES, Out, Profile, critique, measures, profile};
use raea_sys_fingerprint_use::score::clock;
use std::path::{Path, PathBuf};
const BINS: usize = 12;
/// The windows the critique says "where" with, seconds
const WIN: f64 = 4.0;
/// A piece's measures, whole and in windows
pub(crate) fn measured(enc: &mut Encoders, file: &Path) -> Result<(Measures, Vec<((f64, f64), Measures)>)> {
let c = enc.columns(file)?;
let pcm = media::sound(file, 16_000).unwrap_or_default();
let cols = ((c.dur * 10.0) as usize).max(1);
let spec = media::spectrogram(&pcm, 16_000, cols, BINS);
let whole = measures(&c, &spec, BINS, 0.0, c.dur);
let n = (c.dur / WIN).ceil() as usize;
let windows = (0..n).map(|i| {
let (a, b) = (i as f64 * WIN, ((i + 1) as f64 * WIN).min(c.dur));
((a, b), measures(&c, &spec, BINS, a, b))
}).collect();
Ok((whole, windows))
}
fn path(dir: &Folder, name: &str) -> PathBuf {
dir.dir.join("profiles").join(format!("{name}.json"))
}
pub(crate) fn make(enc: &mut Encoders, dir: &Folder, args: &[String], cwd: &Path) -> Result<String> {
let name = flag(args, "--as").ok_or_else(|| anyhow!("name it: raea fingerprint profile REFS... --as NAME"))?;
let refs = named(args, cwd)?;
if refs.len() < 2 {
bail!("a profile needs two references or more (three for its leave-one-out check)");
}
let mut r = Vec::new();
for f in &refs {
r.push((f.display().to_string(), measured(enc, f)?.0));
}
let mut other = Vec::new();
if let Some(list) = flag(args, "--against") {
for f in listed(cwd, list)? {
other.push(measured(enc, &f)?.0);
}
}
let p = profile(name, r, &other);
std::fs::create_dir_all(dir.dir.join("profiles"))?;
std::fs::write(path(dir, name), serde_json::to_vec_pretty(&p)?)?;
let mut out = format!("profile {name} from {} references:\n", p.refs.len());
for (k, words) in NAMES {
if let Some((lo, hi)) = p.ranges.get(k) {
out += &format!(" {words:40} {lo:.2} to {hi:.2}\n");
}
}
out += &match (p.inside_own, p.inside_other) {
(Some(o), Some(x)) => format!("leave-one-out: a reference falls in the others' ranges {:.0}% of the time, unrelated work {:.0}%: {}\n", o * 100.0, x * 100.0, if p.tells == Some(true) { "it tells this taste apart" } else { "it does NOT tell this taste apart" }),
(Some(o), None) => format!("leave-one-out: a reference falls in the others' ranges {:.0}% of the time (give --against LIST to compare with unrelated work)\n", o * 100.0),
_ => "leave-one-out needs three references\n".into(),
};
Ok(out)
}
/// The critique of a piece against a saved profile, as lines
pub(crate) fn against(enc: &mut Encoders, dir: &Folder, name: &str, file: &Path) -> Result<(String, Vec<Out>)> {
let p: Profile = serde_json::from_slice(&std::fs::read(path(dir, name)).with_context(|| format!("no profile {name} (raea fingerprint profile REFS... --as {name})"))?)?;
let (whole, windows) = measured(enc, file)?;
let out = critique(&p, &whole, &windows);
let words = |k: &str| NAMES.iter().find(|n| n.0 == k).map_or(k.to_string(), |n| n.1.to_string());
let mut t = format!("against the {name} profile: {}\n", if out.is_empty() { "every measure in range".to_string() } else { format!("{} out of range", out.len()) });
for o in &out {
t += &format!(" {} {:.2} is outside {:.2} to {:.2}: {} it{}\n", words(&o.measure), o.value, o.range.0, o.range.1, o.move_, o.at.map_or(String::new(), |(a, _)| format!(", most at {}", clock(a))));
}
Ok((t, out))
}
+90
View File
@@ -0,0 +1,90 @@
//! Encoder upgrades keep the evidence (docs/fingerprint.feature FP8c). When this machine's encoders aren't the ones a
//! fingerprint was trained on, `raea fingerprint reembed PLACE...` re-embeds every row whose media it finds under
//! those files and folders (matched by content hash), moves the fingerprint to the new encoders and retrains. A row
//! whose media isn't found keeps its old pin and trains no head until it's re-embedded or labelled again; a bootstrap's
//! damaged rows are remade by running the bootstrap again.
use crate::words;
use anyhow::{Result, anyhow};
use raea_sys_columns::{Encoders, media};
use raea_sys_fingerprint::evidence::features;
use raea_sys_fingerprint::folder::Folder;
use raea_sys_fingerprint::taxonomy::Fingerprint;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
const MEDIA: [&str; 9] = ["mp4", "mov", "m4v", "webm", "mkv", "wav", "mp3", "m4a", "flac"];
/// An encoder set's short name, as a row's pin
pub(crate) fn pin_of(p: &BTreeMap<String, String>) -> String {
p.iter().map(|(k, v)| format!("{k}:{}", &v[..v.len().min(8)])).collect::<Vec<_>>().join(",")
}
/// The media files under each place, two folders deep
fn files(places: &[PathBuf]) -> Vec<PathBuf> {
fn walk(d: &Path, depth: usize, out: &mut Vec<PathBuf>) {
for e in std::fs::read_dir(d).into_iter().flatten().flatten() {
let p = e.path();
if p.is_dir() && depth > 0 {
walk(&p, depth - 1, out);
} else if MEDIA.iter().any(|m| p.extension().is_some_and(|x| x.eq_ignore_ascii_case(m))) {
out.push(p);
}
}
}
let mut out = Vec::new();
for p in places {
if p.is_dir() { walk(p, 2, &mut out) } else { out.push(p.clone()) }
}
out
}
/// Rows moved to `here`'s encoders where their media is found; returns the fingerprint as it is now and what happened
pub(crate) fn reembed(enc: &mut Encoders, dir: &Folder, mut fp: Fingerprint, here: BTreeMap<String, String>, args: &[String], cwd: &Path) -> Result<(Fingerprint, String)> {
let places: Vec<PathBuf> = words(args).map_err(|e| anyhow!(e))?.iter().map(|f| cwd.join(f)).collect();
let mut l = dir.ledger()?;
if fp.encoders != here {
let old = pin_of(&fp.encoders);
l.rows.iter_mut().filter(|r| r.pin.is_none()).for_each(|r| r.pin = Some(old.clone()));
fp.encoders = here;
dir.rewrite(&fp)?;
}
let waiting: std::collections::BTreeSet<String> = l.rows.iter().filter(|r| r.pin.is_some() && !matches!(r.source.as_str(), "damage" | "cheat")).map(|r| r.media.clone()).collect();
let mut done = 0;
for f in files(&places) {
if waiting.is_empty() {
break;
}
let Ok(sha) = media::sha256(&f) else { continue };
if !waiting.contains(&sha) {
continue;
}
let c = enc.columns(&f)?;
for i in 0..l.rows.len() {
let r = &l.rows[i];
if r.media == sha && r.pin.is_some() && !matches!(r.source.as_str(), "damage" | "cheat") {
let x = features(&c, r.a, r.b);
l.set_features(i, &x);
l.rows[i].pin = None;
done += 1;
}
}
}
dir.write_ledger(&l)?;
let left = l.rows.iter().filter(|r| r.pin.is_some()).count();
let damage = l.rows.iter().filter(|r| r.pin.is_some() && matches!(r.source.as_str(), "damage" | "cheat")).count();
let mut out = format!("re-embedded {done} rows on this machine's encoders; {left} wait on their old ones");
if damage > 0 {
out += &format!(" ({damage} from a bootstrap: run raea fingerprint bootstrap again to remake them)");
}
Ok((fp, out + "\n"))
}
#[cfg(test)]
mod tests {
#[test]
fn a_pin_names_each_encoder_and_its_hash() {
let p = std::collections::BTreeMap::from([("clap".to_string(), "0123456789abcdef".to_string()), ("siglip".to_string(), "fedcba".to_string())]);
assert_eq!(super::pin_of(&p), "clap:01234567,siglip:fedcba");
}
}
+141
View File
@@ -0,0 +1,141 @@
//! The resident service: the encoders loaded once, on 127.0.0.1 at a port the host file names
//! (~/.raea/fingerprints/.serve.json). A request is one JSON line, {"args": [...], "cwd": "..."}; the answer is
//! progress lines, {"say": "..."}, then {"out": "...", "code": N}. One request at a time, in order.
use crate::{Eval, verbs};
use anyhow::{Context, Result};
use raea_sys_columns::Encoders;
use raea_sys_fingerprint::folder::root;
use serde_json::{Value, json};
use std::io::{BufRead, BufReader, Write};
use std::net::{TcpListener, TcpStream};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
/// The service leaves after this long with no request
const IDLE: Duration = Duration::from_secs(30 * 60);
/// How long a verb waits for a service it started to come up (the first run fetches the models)
const UP: Duration = Duration::from_secs(900);
fn host() -> PathBuf {
root().join(".serve.json")
}
fn now() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
}
/// `raea fingerprint serve`: load the encoders, listen, answer until idle or stopped
pub fn serve(eval: Eval) -> Result<()> {
let started = Instant::now();
let mut enc = Encoders::load().context("loading the encoders")?;
let listener = TcpListener::bind("127.0.0.1:0")?;
let port = listener.local_addr()?.port();
std::fs::create_dir_all(root())?;
std::fs::write(host(), json!({"port": port, "pid": std::process::id()}).to_string())?;
eprintln!("raea fingerprint serve: encoders loaded in {:.1} s, on 127.0.0.1:{port}", started.elapsed().as_secs_f64());
let last = Arc::new(AtomicU64::new(now()));
let seen = last.clone();
std::thread::spawn(move || {
loop {
std::thread::sleep(Duration::from_secs(60));
if now().saturating_sub(seen.load(Ordering::Relaxed)) > IDLE.as_secs() {
let _ = std::fs::remove_file(host());
eprintln!("raea fingerprint serve: idle for {} min, leaving", IDLE.as_secs() / 60);
std::process::exit(0);
}
}
});
for stream in listener.incoming() {
let Ok(mut s) = stream else { continue };
last.store(now(), Ordering::Relaxed);
let mut line = String::new();
if BufReader::new(&s).read_line(&mut line).is_err() {
continue;
}
let req: Value = serde_json::from_str(&line).unwrap_or_default();
let args: Vec<String> = serde_json::from_value(req["args"].clone()).unwrap_or_default();
let cwd = PathBuf::from(req["cwd"].as_str().unwrap_or("."));
if args.first().is_some_and(|v| v == "stop") {
let _ = writeln!(s, "{}", json!({"out": "raea fingerprint serve: stopped", "code": 0}));
let _ = std::fs::remove_file(host());
return Ok(());
}
let mut say = |m: String| {
let _ = writeln!(s, "{}", json!({ "say": m }));
};
let (out, code) = verbs::run(&mut enc, &args, &cwd, eval, &mut say);
let _ = writeln!(s, "{}", json!({"out": out, "code": code}));
last.store(now(), Ordering::Relaxed);
}
Ok(())
}
/// A verb run in this process, with the encoders loaded for it
pub(crate) fn here(args: &[String], cwd: &Path, eval: Eval) -> (String, i32) {
match Encoders::load() {
Ok(mut enc) => verbs::run(&mut enc, args, cwd, eval, &mut |m| eprintln!("{m}")),
Err(e) => (format!("raea fingerprint: loading the encoders: {e:#}"), 1),
}
}
fn reach() -> Option<TcpStream> {
let h: Value = serde_json::from_slice(&std::fs::read(host()).ok()?).ok()?;
TcpStream::connect(("127.0.0.1", h["port"].as_u64()? as u16)).ok()
}
/// The service started in the background, its output in ~/.raea/fingerprints/.serve.log; its stream once it's up
fn start() -> Result<TcpStream, String> {
let _ = std::fs::remove_file(host());
std::fs::create_dir_all(root()).map_err(|e| e.to_string())?;
let log = root().join(".serve.log");
let file = std::fs::File::create(&log).map_err(|e| e.to_string())?;
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let mut cmd = std::process::Command::new(exe);
cmd.args(["fingerprint", "serve"]).stdin(std::process::Stdio::null()).stdout(file.try_clone().map_err(|e| e.to_string())?).stderr(file);
#[cfg(unix)]
std::os::unix::process::CommandExt::process_group(&mut cmd, 0);
let mut child = cmd.spawn().map_err(|e| format!("starting the service: {e}"))?;
eprintln!("raea fingerprint: starting the service (loading the encoders once; its log is {})", log.display());
let t = Instant::now();
while t.elapsed() < UP {
if let Some(s) = reach() {
return Ok(s);
}
if let Ok(Some(status)) = child.try_wait() {
let tail = std::fs::read_to_string(&log).unwrap_or_default();
return Err(format!("the service stopped ({status}):\n{}", tail.lines().rev().take(12).collect::<Vec<_>>().into_iter().rev().collect::<Vec<_>>().join("\n")));
}
std::thread::sleep(Duration::from_millis(200));
}
let _ = child.kill();
Err(format!("the service didn't come up in {} s (see {})", UP.as_secs(), log.display()))
}
/// A verb sent to the service, started if it isn't running; its progress printed as it comes
pub(crate) fn call(args: &[String], cwd: &Path) -> (String, i32) {
let stream = match reach() {
Some(s) => Ok(s),
None if args.first().is_some_and(|v| v == "stop") => return ("raea fingerprint: no service running".into(), 0),
None => start(),
};
let mut s = match stream {
Ok(s) => s,
Err(e) => return (format!("raea fingerprint: {e}"), 1),
};
if writeln!(s, "{}", json!({"args": args, "cwd": cwd})).is_err() {
return ("raea fingerprint: the service closed the connection".into(), 1);
}
for line in BufReader::new(s).lines() {
let Ok(line) = line else { break };
let v: Value = serde_json::from_str(&line).unwrap_or_default();
if let Some(m) = v["say"].as_str() {
eprintln!("{m}");
} else if v.get("code").is_some() {
return (v["out"].as_str().unwrap_or("").to_string(), v["code"].as_i64().unwrap_or(1) as i32);
}
}
("raea fingerprint: the service ended without an answer (see ~/.raea/fingerprints/.serve.log)".into(), 1)
}
+31
View File
@@ -0,0 +1,31 @@
//! `raea fingerprint things FILE [--project P] [--json]` (docs/fingerprint.feature FP13a, FP13c): a piece's shots,
//! their things (a render's layers, and every mark a person drew on a note of it in P's feed, P the folder it runs in
//! by default) and the camera's path, with what floats, passes through, lurches or is empty
//! (raea-sys-fingerprint-things). `--json` prints it all for `raea check --things`.
use crate::{flag, has};
use anyhow::Result;
use raea_sys_columns::Encoders;
use raea_sys_fingerprint_things::things::{Mark, things};
use std::path::{Path, PathBuf};
pub(crate) fn run(enc: &mut Encoders, args: &[String], cwd: &Path) -> Result<(String, i32)> {
let file = cwd.join(args.first().filter(|a| !a.starts_with("--")).ok_or_else(|| anyhow::anyhow!("things FILE"))?);
let project = flag(args, "--project").map_or_else(|| cwd.to_path_buf(), |p| cwd.join(p));
let me = file.canonicalize().ok();
let marks: Vec<Mark> = crate::notes::pinned(&project)
.into_iter()
.filter(|r| r.media.canonicalize().ok() == me)
.filter_map(|r| Some(Mark { name: r.text.chars().take(40).collect(), t: r.t, a: (r.t - 1.0).max(0.0), b: r.to.unwrap_or(r.t + 1.0), region: r.region? }))
.collect();
let t = things(enc, &file, &marks)?;
if has(args, "--json") {
return Ok((serde_json::to_string_pretty(&t)?, 0));
}
let n: usize = t.shots.iter().map(|s| s.things.len()).sum();
let mut out = format!("{}: {} shots, {n} things seen ({} marked), {} findings\n", PathBuf::from(&t.file).display(), t.shots.len(), marks.len(), t.issues.len());
for i in &t.issues {
out += &format!(" {:>6.1} s {} {}\n", i.at, i.rule, i.says);
}
Ok((out, 0))
}
+397
View File
@@ -0,0 +1,397 @@
//! The verbs, run with the encoders loaded: new, bootstrap, teach and score; and report, which needs no encoders.
use crate::{Eval, at, flag, has, listed, named, words};
use anyhow::{Context, Result, anyhow, bail};
use raea_sys_columns::{Encoders, FPS, media};
use raea_sys_fingerprint::evidence::{Ledger, Row, features};
use raea_sys_fingerprint::folder::{Folder, root};
use raea_sys_fingerprint::inherit;
use raea_sys_fingerprint_use::score::{Scored, clock, score, summary, timeline};
use raea_sys_fingerprint_use::sheet::{Tick, sheet};
use raea_sys_fingerprint::taxonomy::{Applies, Fingerprint, base, words_of};
use raea_sys_fingerprint::words::Words;
use crate::bootstrap;
use raea_sys_fingerprint::{report_text, retrain};
use serde_json::json;
use std::path::Path;
/// The fingerprint a verb is about: --fp, else the one `new` made first, else "me"
/// A verb's answer and exit code
pub(crate) fn run(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval, say: &mut dyn FnMut(String)) -> (String, i32) {
let rest = &args[1..];
let ran = match args[0].as_str() {
"new" => new(enc, rest),
"bootstrap" => boot(enc, rest, cwd, eval, say),
"teach" => teach(enc, rest, cwd, eval),
"approve" => approved(enc, rest, cwd, eval),
"reembed" => reembedded(enc, rest, cwd, eval),
"pair" | "versions" => paired(enc, args[0].as_str(), rest, cwd, eval),
"learn-notes" => learned(enc, rest, cwd, eval),
"move" => moved(enc, rest, eval),
"postmortem" => crate::postmortem::run(enc, rest, cwd, eval),
"things" => crate::things::run(enc, rest, cwd),
"profile" => {
let dir = crate::pick::chosen(rest, None).0;
crate::profiles::make(enc, &dir, rest, cwd).map(|o| (o, 0))
}
"score" => scored(enc, rest, cwd, eval),
v => Err(anyhow!("no verb {v}")),
};
ran.unwrap_or_else(|e| (format!("raea fingerprint {}: {e:#}", args[0]), 1))
}
/// A new fingerprint as `new` makes it: raea's base axes, or the axes of the one it --extends, with --who and --about,
/// and the kinds of piece and project tags it judges (--kinds, --tags, each comma-separated)
pub(crate) fn shaped(short: &str, args: &[String], parent: Option<Fingerprint>) -> Fingerprint {
let mut fp = base(short);
if let Some(p) = parent {
fp.axes = p.axes;
fp.extends = Some(p.name);
}
fp.who = flag(args, "--who").map(str::to_string).or_else(|| std::env::var("USER").ok());
fp.about = flag(args, "--about").map(str::trim).filter(|a| !a.is_empty()).map(str::to_string);
let (kinds, tags) = (flag(args, "--kinds").map(words_of).unwrap_or_default(), flag(args, "--tags").map(words_of).unwrap_or_default());
if !kinds.is_empty() || !tags.is_empty() {
fp.applies = Some(Applies { kinds, tags });
}
fp
}
fn new(enc: &mut Encoders, args: &[String]) -> Result<(String, i32)> {
let n = *words(args).map_err(|e| anyhow!(e))?.first().ok_or_else(|| anyhow!("name it: raea fingerprint new NAME"))?;
let dir = Folder::named(n);
let short = dir.dir.file_name().map(|s| s.to_string_lossy().into_owned()).unwrap_or_else(|| n.into());
let parent = match flag(args, "--extends") {
Some(p) => Some(Folder::named(p).read(None).with_context(|| format!("--extends {p}"))?),
None => None,
};
let from = parent.as_ref().map(|p| format!("{}'s axes", p.name)).unwrap_or_else(|| "raea's base taxonomy".into());
let mut fp = shaped(&short, args, parent);
fp.encoders = enc.pins();
dir.create(&fp)?;
let w = Words::build(enc, &fp)?;
dir.write_words(&w)?;
retrain(&dir, &fp, &w, &Ledger::default(), None)?;
if !root().join("default").exists() && dir.dir.parent() == Some(root().as_path()) {
std::fs::write(root().join("default"), &short)?;
}
Ok((
format!(
"made {}: {} axes from {from}, {} scoring from their words today (advice until they earn a gate)\n edit {} to add, remove or reword axes\n next: raea fingerprint bootstrap FILE... with your own finished work trains the mechanical axes",
dir.dir.display(),
fp.axes.len(),
w.axes.len(),
dir.ts().display()
),
0,
))
}
/// The fingerprint, its encoders checked against this machine's, and its words, made again when they changed
/// The fingerprint a verb uses (pick.rs: --fp, else the one that judges the file), its axes with its parents', and its
/// words
pub(crate) fn open(enc: &mut Encoders, args: &[String], eval: Eval, file: Option<&Path>) -> Result<(Folder, Fingerprint, Words)> {
let dir = crate::pick::chosen(args, file).0;
let mut raw = dir.read(Some(eval))?;
let here = enc.pins();
if raw.encoders.is_empty() {
raw.encoders = here;
dir.rewrite(&raw)?;
} else if here.iter().filter(|(k, v)| raw.encoders.get(*k) == Some(*v)).count() == raw.encoders.len() && raw.encoders != here {
// an encoder added since (EmbeddingGemma 2, FP1b) doesn't change the ones it was trained on
raw.encoders = here;
dir.rewrite(&raw)?;
} else if raw.encoders != here {
bail!(
"{} was trained on other encoders ({:?}) than this machine has ({:?}); its heads refuse these columns. `raea fingerprint reembed FOLDER...` moves its evidence to these, re-embedding the rows whose media it finds",
dir.ts().display(),
raw.encoders,
here
);
}
// a fingerprint that extends another judges with its parents' axes too (FP14b)
let fp = inherit::axes(&raw, &inherit::parents(&raw, Some(eval)));
let w = match dir.words().filter(|w| !w.stale(&fp)) {
Some(w) => w,
None => {
let w = Words::build(enc, &fp)?;
dir.write_words(&w)?;
w
}
};
// a shared fingerprint arrives with evidence and no heads: this machine trains its own (FP8a)
if !dir.dir.join("heads.safetensors").is_file() {
let l = dir.ledger()?;
if !l.rows.is_empty() {
retrain(&dir, &fp, &w, &l, None)?;
}
}
Ok((dir, fp, w))
}
fn boot(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval, say: &mut dyn FnMut(String)) -> Result<(String, i32)> {
let (dir, fp, w) = open(enc, args, eval, None)?;
let mut files = named(args, cwd)?;
if let Some(list) = flag(args, "--from") {
files.extend(listed(cwd, list)?);
}
if files.is_empty() {
bail!("give it real finished work: raea fingerprint bootstrap FILE... or --from LIST (no placeholder footage)");
}
let per: usize = flag(args, "--per").map_or(Ok(10), str::parse).context("--per takes a count")?;
let mut l = dir.ledger()?;
let who = fp.who.clone().unwrap_or_else(|| "me".into());
let made = bootstrap::rows(enc, &who, &files, per, &mut l, say)?;
dir.write_ledger(&l)?;
say(format!("{} windows from {} sources; measuring held out by source", made.windows, made.sources));
let curves = bootstrap::curves(&fp, &l);
let ws = bootstrap::word_scores(&l, &w);
let patches = raea_sys_fingerprint_things::located::bootstrap(enc, &dir.dir, &files, per, say)?;
let b = json!({"made": made, "per": per, "sources": files, "curves": curves, "words": ws, "patches": patches});
retrain(&dir, &fp, &w, &l, Some(b))?;
Ok((report_text(&dir.report().unwrap_or_default()), 0))
}
/// The project a file belongs to: the folder holding .raea/project above it, else the folder it's in
fn project_of(file: &Path) -> String {
let mut d = file.parent();
while let Some(p) = d {
if p.join(".raea/project").exists() {
return p.file_name().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
}
d = p.parent();
}
file.parent().and_then(|p| p.file_name()).map(|s| s.to_string_lossy().into_owned()).unwrap_or_default()
}
/// `approve`: approved work as clean rows on every axis (approve.rs, FP6a), then the heads retrained
fn approved(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result<(String, i32)> {
let first = words(args).map_err(|e| anyhow!(e))?.first().map(|f| at(cwd, f));
let (dir, fp, w) = open(enc, args, eval, first.as_deref())?;
let (mut out, _) = crate::approve::approve(enc, &dir, &fp, args, cwd, project_of)?;
let tr = retrain(&dir, &fp, &w, &dir.ledger()?, None)?;
out += &format!("{} axes gating\n", tr.heads.iter().filter(|h| h.state == "gating").count());
Ok((out, 0))
}
/// `reembed`: the evidence moved to this machine's encoders (reembed.rs, FP8c), the words remade and the heads retrained
fn reembedded(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result<(String, i32)> {
let dir = crate::pick::chosen(args, None).0;
let raw = dir.read(Some(eval))?;
let (fp, out) = crate::reembed::reembed(enc, &dir, raw, enc.pins(), args, cwd)?;
let fp = inherit::axes(&fp, &inherit::parents(&fp, Some(eval)));
let w = Words::build(enc, &fp)?;
dir.write_words(&w)?;
retrain(&dir, &fp, &w, &dir.ledger()?, None)?;
Ok((out, 0))
}
/// `pair` and `versions` (pairing.rs, FP6b, FP6c), then the heads retrained
fn paired(enc: &mut Encoders, verb: &str, args: &[String], cwd: &Path, eval: Eval) -> Result<(String, i32)> {
let first = words(args).map_err(|e| anyhow!(e))?.first().map(|f| at(cwd, f));
let (dir, fp, w) = open(enc, args, eval, first.as_deref())?;
let who = fp.who.clone().unwrap_or_else(|| "me".into());
let mut l = dir.ledger()?;
let out = if verb == "pair" { crate::pairing::pair(enc, &mut l, &who, args, cwd, project_of)? } else { crate::pairing::versions(enc, &mut l, &who, args, cwd, project_of)? };
dir.write_ledger(&l)?;
retrain(&dir, &fp, &w, &l, None)?;
Ok((out, 0))
}
/// `learn-notes [PROJECT]` (notes.rs, FP5a): checked readings as evidence in the fingerprint that judges the project
/// (FP14d), then its heads retrained
fn learned(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result<(String, i32)> {
let (dir, fp, w) = open(enc, args, eval, Some(&crate::pick::piece_in(args, cwd)))?;
let mut l = dir.ledger()?;
let out = crate::notes::learn(enc, &dir, &mut l)?;
dir.write_ledger(&l)?;
retrain(&dir, &fp, &w, &l, None)?;
Ok((out, 0))
}
/// `move` (moving.rs, FP14d): a child's own labels up into a fingerprint it extends, then both retrained
fn moved(enc: &mut Encoders, args: &[String], eval: Eval) -> Result<(String, i32)> {
let (dir, fp, w) = open(enc, args, eval, None)?;
let (to, out) = crate::moving::up(&dir, &dir.read(Some(eval))?, args, eval)?;
retrain(&dir, &fp, &w, &dir.ledger()?, None)?;
let (pd, pfp, pw) = open(enc, &["--fp".into(), to], eval, None)?;
retrain(&pd, &pfp, &pw, &pd.ledger()?, None)?;
Ok((out, 0))
}
fn teach(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result<(String, i32)> {
let file = at(cwd, words(args).map_err(|e| anyhow!(e))?.first().ok_or_else(|| anyhow!("which file?"))?);
let (dir, fp, w) = open(enc, args, eval, Some(&file))?;
let axis = flag(args, "--axis").ok_or_else(|| anyhow!("--axis A (or \"*\" for every axis)"))?;
if axis != "*" && fp.axis(axis).is_none() {
bail!("no axis {axis:?} in {}: its axes are {}", dir.ts().display(), fp.axes.iter().map(|a| a.name.as_str()).collect::<Vec<_>>().join(", "));
}
let t: f64 = flag(args, "--at").ok_or_else(|| anyhow!("--at SECONDS"))?.parse().context("--at takes seconds")?;
let span: f64 = flag(args, "--span").map_or(Ok(2.0), str::parse).context("--span takes seconds")?;
let region = flag(args, "--box").map(|b| -> Result<[f32; 4]> {
let v: Vec<f32> = b.split(',').map(str::parse).collect::<Result<_, _>>().context("--box takes x0,y0,x1,y1 in 0-1")?;
v.try_into().map_err(|_| anyhow!("--box takes four numbers"))
});
let c = enc.columns(&file)?;
let a = (t - span / 2.0).clamp(0.0, (c.dur - span).max(0.0));
let b = (a + span).min(c.dur);
let bad = !has(args, "--good");
let row = Row {
media: c.media.clone(),
a,
b,
axis: axis.into(),
bad,
weight: 1.0,
who: fp.who.clone().unwrap_or_else(|| "me".into()),
source: "teach".into(),
project: flag(args, "--project").map_or_else(|| project_of(&file), str::to_string),
kind: None,
region: region.transpose()?,
words: flag(args, "--words").map(str::to_string),
at: 0,
pin: None,
};
let mut l = dir.ledger()?;
l.push(row, &features(&c, a, b));
dir.write_ledger(&l)?;
let tr = retrain(&dir, &fp, &w, &l, None)?;
let h = tr.heads.iter().find(|h| h.axis == axis);
let (p, n) = l.for_axis(axis).iter().fold((0, 0), |(p, n), &i| if l.rows[i].bad { (p + 1, n) } else { (p, n + 1) });
Ok((
format!(
"taught {axis}: {} at {} in {}\n {axis} has {p} defect and {n} clean labels; its head: {}",
if bad { "the defect" } else { "clean" },
clock(t),
file.display(),
h.map_or("every axis's clean labels grew".to_string(), |h| format!("{} ({})", h.state, h.why))
),
0,
))
}
/// raea check's findings on the file, in seconds: (rule, from, to, what)
fn checks(file: &Path) -> Vec<(String, f64, f64, String)> {
let Ok(found) = raea_app_check::floor(&[file.display().to_string()], &[], &[]) else { return Vec::new() };
found.into_iter().map(|f| {
let (a, b) = f.frames.map_or((0.0, 0.0), |[a, b]| (a as f64 / 30.0, b as f64 / 30.0));
(f.check, a, b, f.says)
}).collect()
}
/// A check wins over a head (FP4c): a moment on an axis a check measures is no gate unless the check found it too
fn arbitrate(s: &mut Scored, fp: &Fingerprint, found: &[(String, f64, f64, String)]) {
for m in &mut s.moments {
let Some(rule) = fp.axis(&m.axis).and_then(|a| a.check.as_deref()) else { continue };
let agrees = found.iter().any(|(r, a, b, _)| r == rule && *a <= m.b + 1.0 && *b >= m.a - 1.0);
if !agrees {
m.gating = false;
m.state = format!("{}; the {rule} check found none", m.state);
}
}
}
fn scored(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result<(String, i32)> {
let file = at(cwd, words(args).map_err(|e| anyhow!(e))?.first().ok_or_else(|| anyhow!("which file?"))?);
let (dir, fp, w) = open(enc, args, eval, Some(&file))?;
let why = crate::pick::chosen(args, Some(&file)).1.map_or_else(|| "named with --fp, or the account's default".to_string(), |c| c.why);
let c = enc.columns(&file)?;
let trained = dir.trained()?.map(|(t, _)| t);
let mut s = score(&fp, Some(&w), trained.as_ref(), &c, &file.display().to_string());
let found = checks(&file);
arbitrate(&mut s, &fp, &found);
raea_sys_fingerprint_things::located::locate(enc, &file, &raea_sys_fingerprint_use::patch::load(&dir.dir), &mut s)?;
// FP9a: each gating flag on the cut before, judged on this one, and its axis's disguises rerun on the fix
let fixes = match flag(args, "--was") {
Some(old) => {
let was = at(cwd, old);
let mut ws = score(&fp, Some(&w), trained.as_ref(), &enc.columns(&was)?, &was.display().to_string());
arbitrate(&mut ws, &fp, &checks(&was));
Some(raea_sys_fingerprint_use::fixed::fixes(&ws, &s, &fp, &dir.ledger()?, &c))
}
None => None,
};
let mut out = if has(args, "--json") {
serde_json::to_string_pretty(&json!({"fingerprint": {"name": fp.name, "about": fp.about, "why": why}, "scored": s, "checks": found.iter().map(|(r, a, b, says)| json!({"check": r, "a": a, "b": b, "says": says})).collect::<Vec<_>>(), "fixes": fixes}))?
} else if let Some(f) = &fixes {
let mut t = format!("judged by {}: {why}\n", fp.name);
t += &raea_sys_fingerprint_use::fixed::said(f);
t += &summary(&s);
t
} else {
let mut t = format!("judged by {}: {why}\n", fp.name);
t += &summary(&s);
t += &format!("checks: {}\n", if found.is_empty() { "no findings".to_string() } else { format!("{} findings", found.len()) });
for (r, a, _, says) in &found {
t += &format!(" {} {r}: {says}\n", clock(*a));
}
t
};
if has(args, "--timeline") {
out += &timeline(&s);
}
if let Some(p) = flag(args, "--profile") {
out += &crate::profiles::against(enc, &dir, p, &file)?.0;
}
if let Some(png) = flag(args, "--sheet") {
let png = at(cwd, png);
let frames: Vec<media::Rgb> = (0..12).filter_map(|i| media::frames(&file, FPS, c.dur * (i as f64 + 0.5) / 12.0, 0.25).ok()?.into_iter().next()).collect();
let pcm = media::sound(&file, 16_000)?;
let ticks: Vec<Tick> = found.iter().map(|(r, a, b, _)| Tick { a: *a, b: *b, what: r.clone() }).collect();
sheet(&s, &frames, &pcm, &ticks, &|axis| fp.axis(axis).map(|a| a.modality), &png)?;
out += &format!("sheet: {}\n", png.display());
}
let unfixed = fixes.iter().flatten().any(|f| f.verdict != "fixed");
Ok((out, i32::from(unfixed || s.moments.iter().any(|m| m.gating))))
}
/// `raea fingerprint report`: report.json, read; no encoders needed
pub(crate) fn report_here(args: &[String]) -> i32 {
let dir = crate::pick::chosen(args, None).0;
match dir.report() {
Some(r) if has(args, "--json") => {
println!("{}", serde_json::to_string_pretty(&r).unwrap_or_default());
0
}
Some(r) => {
println!("{}", report_text(&r).trim_end());
0
}
None => {
eprintln!("raea fingerprint report: no report at {} (`raea fingerprint new NAME` makes one)", dir.dir.display());
1
}
}
}
#[cfg(test)]
mod tests {
use super::shaped;
use raea_sys_fingerprint::taxonomy::{Applies, base};
fn args(xs: &[&str]) -> Vec<String> {
xs.iter().map(|x| x.to_string()).collect()
}
/// FP14a: a new fingerprint says what it's for, and one that extends another starts from its axes
#[test]
fn a_new_fingerprint_says_what_its_for_and_what_it_builds_on() {
let own = shaped("me", &args(&["me", "--who", "w"]), None);
assert_eq!((own.about.as_deref(), own.extends.as_deref(), own.who.as_deref()), (None, None, Some("w")));
assert_eq!(own.axes, base("me").axes);
let mut parent = base("me");
parent.axes.truncate(2);
parent.axes[0].words = vec!["a soft picture".into()];
let ads = shaped("ads", &args(&["ads", "--about", " Short ads for one brand ", "--extends", "me"]), Some(parent.clone()));
assert_eq!(ads.name, "ads");
assert_eq!(ads.about.as_deref(), Some("Short ads for one brand"));
assert_eq!(ads.extends.as_deref(), Some("me"));
assert_eq!(ads.axes, parent.axes);
assert_eq!(shaped("x", &args(&["x", "--about", " "]), None).about, None);
assert_eq!(own.applies, None);
let judged = shaped("ads", &args(&["ads", "--kinds", "ad, Playable", "--tags", "brand,"]), None);
assert_eq!(judged.applies, Some(Applies { kinds: vec!["ad".into(), "playable".into()], tags: vec!["brand".into()] }));
}
}
+2
View File
@@ -23,6 +23,8 @@ raea-runtime-react = { path = "../../runtime/react", default-features = false }
raea-runtime-page = { path = "../../runtime/page" }
raea-runtime-export = { path = "../../runtime/export" }
raea-runtime-live = { path = "../../runtime/live" }
# its switches (env_on)
raea-io-home = { path = "../../io/home" }
serde_json = "1"
winit = "=0.30.13"
raea-gpu-device = { path = "../../gpu/device" }
+1 -1
View File
@@ -212,7 +212,7 @@ impl ApplicationHandler for Player {
}
pub(crate) fn probing() -> bool {
std::env::var("RAEA_PLAYER_PROBE").as_deref() == Ok("1")
raea_io_home::env_on("RAEA_PLAYER_PROBE")
}
pub(crate) fn windowed(game: Game) -> R<String> {
+17
View File
@@ -0,0 +1,17 @@
[package]
name = "raea-app-interchange"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "A composition's 3D as data another tool builds (`raea scene export`: scene.json, its meshes and models), a Godot project written from it, and what changed in Blender or Godot read back as edits to the TSX (docs/blender.feature BL37-BL39, docs/godot.feature GD12-GD13)"
[dependencies]
# the composition bundled and stepped to its frames' 3D (raea-runtime-export's scene_frames), walked into parts
raea-runtime-bundle = { path = "../../runtime/bundle" }
raea-runtime-export = { path = "../../runtime/export" }
raea-runtime-scene = { path = "../../runtime/scene" }
raea-core-scene = { path = "../../core/scene" }
# a mesh that isn't a primitive written as a .glb (Manifold's)
raea-core-shape = { path = "../../core/shape" }
serde_json = "1"
+209
View File
@@ -0,0 +1,209 @@
//! What changed in Blender or Godot, as edits to the TSX at their lines (docs/blender.feature BL39, docs/godot.feature
//! GD13). The scene went out as scene.json; Blender's or Godot's reader (sdk/blender/src/scene.ts's readBack,
//! sdk/godot/src/host/back.ts) writes what it holds now in the same terms (raea's axes, each object's raea_id), and this
//! compares the two at the first frame sent. Nothing in the TSX is changed here: the agent makes the edits.
use std::path::Path;
use serde_json::{Value, json};
/// A placement's numbers (x y z, qx qy qz qw, sx sy sz), or None.
fn nums(a: &Value) -> Option<Vec<f64>> {
let v: Vec<f64> = a.as_array()?.iter().filter_map(Value::as_f64).collect();
(v.len() >= 10).then_some(v)
}
fn r4(x: f64) -> f64 {
(x * 1e4).round() / 1e4
}
/// A quaternion (x y z w) as Euler angles X, Y, Z in radians, applied X then Y then Z (three.js' and raea's default
/// order for `rotation={[x, y, z]}`).
pub fn euler_xyz(q: &[f64]) -> [f64; 3] {
let (x, y, z, w) = (q[0], q[1], q[2], q[3]);
let m02 = 2.0 * (x * z + y * w);
let (m12, m22) = (2.0 * (y * z - x * w), 1.0 - 2.0 * (x * x + y * y));
let (m01, m00) = (2.0 * (x * y - z * w), 1.0 - 2.0 * (y * y + z * z));
let ey = m02.clamp(-1.0, 1.0).asin();
let (ex, ez) = if m02.abs() < 0.999_999 { ((-m12).atan2(m22), (-m01).atan2(m00)) } else { ((2.0 * (y * z + x * w)).atan2(1.0 - 2.0 * (x * x + z * z)), 0.0) };
[r4(ex), r4(ey), r4(ez)]
}
/// The angle between two rotations, in degrees.
fn turned(a: &[f64], b: &[f64]) -> f64 {
let d = (a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]).abs().min(1.0);
2.0 * d.acos().to_degrees()
}
/// One edit onto the list: the part, what changed, the prop with its old and new values, and the line said for it.
fn edit(out: &mut Vec<Value>, part: &Value, what: &str, prop: &str, from: Value, to: Value, said: String) {
out.push(json!({ "id": part["id"], "name": part["source"]["name"], "loc": part["source"]["loc"], "change": what, "prop": prop, "from": from, "to": to, "says": said }));
}
fn surface(p: &Value, sent: &Value, now: &Value, out: &mut Vec<Value>) {
if !now.is_object() {
return;
}
if let (Some(a), Some(b)) = (sent["color"].as_str(), now["color"].as_str())
&& !a.eq_ignore_ascii_case(b)
{
edit(out, p, "recoloured", "color", json!(a), json!(b), format!("color {a} -> {b}"));
}
for (k, prop) in [("roughness", "roughness"), ("metallic", "metalness"), ("intensity", "intensity")] {
if let (Some(a), Some(b)) = (sent[k].as_f64(), now[k].as_f64())
&& (a - b).abs() > 0.005 * a.abs().max(1.0)
{
edit(out, p, if k == "intensity" { "relit" } else { "resurfaced" }, prop, json!(r4(a)), json!(r4(b)), format!("{prop} {} -> {}", r4(a), r4(b)));
}
}
if now["emissive"].as_str().is_some() && sent["emissive"].as_str() != now["emissive"].as_str() {
edit(out, p, "glows", "emissive", sent["emissive"].clone(), now["emissive"].clone(), format!("emissive {} -> {}", sent["emissive"].as_str().unwrap_or("none"), now["emissive"].as_str().unwrap_or("none")));
}
}
fn placement(p: &Value, a: &[f64], b: &[f64], out: &mut Vec<Value>) {
let d = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
if d.iter().any(|x| x.abs() > 1e-3) {
let to = [r4(b[0]), r4(b[1]), r4(b[2])];
edit(out, p, "moved", "position", json!([r4(a[0]), r4(a[1]), r4(a[2])]), json!(to), format!("moved by [{}, {}, {}] to {to:?} (world)", r4(d[0]), r4(d[1]), r4(d[2])));
}
if turned(&a[3..7], &b[3..7]) > 0.05 {
let e = euler_xyz(&b[3..7]);
edit(out, p, "turned", "rotation", json!(euler_xyz(&a[3..7])), json!(e), format!("turned {:.1} degrees: rotation {e:?} (radians, X Y Z; world), quaternion [{}, {}, {}, {}]", turned(&a[3..7], &b[3..7]), r4(b[3]), r4(b[4]), r4(b[5]), r4(b[6])));
}
if (0..3).any(|k| (a[7 + k] - b[7 + k]).abs() > 1e-3 * a[7 + k].abs().max(1.0)) {
let to = [r4(b[7]), r4(b[8]), r4(b[9])];
edit(out, p, "scaled", "scale", json!([r4(a[7]), r4(a[8]), r4(a[9])]), json!(to), format!("scale {to:?}"));
}
}
/// The edits from `sent` (scene.json) to `now` (what Blender or Godot holds), at the first frame sent.
pub fn compare(sent: &Value, now: &Value) -> Vec<Value> {
let mut out = Vec::new();
let held: Vec<&Value> = now["parts"].as_array().into_iter().flatten().collect();
for p in sent["parts"].as_array().into_iter().flatten() {
let Some(n) = held.iter().find(|n| n["id"] == p["id"]) else {
edit(&mut out, p, "deleted", "", Value::Null, Value::Null, "deleted".into());
continue;
};
let first = p["at"].as_array().into_iter().flatten().find(|a| !a.is_null()).and_then(nums);
if let (Some(a), Some(b)) = (first, nums(&n["at"])) {
placement(p, &a, &b, &mut out);
}
surface(p, &p["material"], &n["material"], &mut out);
surface(p, &p["light"], &n["light"], &mut out);
}
let cam = sent["camera"].as_array().into_iter().flatten().find(|c| c.is_object());
if let (Some(c), Some(n)) = (cam, now["camera"].as_object()) {
let me = json!({ "id": "camera", "source": { "name": "camera" } });
if let (Some(a), Some(b)) = (nums(&c["at"]), n.get("at").and_then(nums)) {
placement(&me, &a, &b, &mut out);
}
if let (Some(a), Some(b)) = (c["fov"].as_f64(), n.get("fov").and_then(Value::as_f64))
&& (a - b).abs() > 0.05
{
edit(&mut out, &me, "lens", "fov", json!(r4(a)), json!(r4(b)), format!("fov {} -> {} (degrees, vertical)", r4(a), r4(b)));
}
}
for n in now["new"].as_array().into_iter().flatten() {
let file = n["file"].as_str().unwrap_or("");
let at = nums(&n["at"]).map(|v| format!(" at [{}, {}, {}]", r4(v[0]), r4(v[1]), r4(v[2]))).unwrap_or_default();
out.push(json!({ "id": Value::Null, "name": n["name"], "loc": Value::Null, "change": "added", "prop": "", "from": Value::Null, "to": n["at"],
"says": format!("added: <Model src={{staticFile(\"{}\")}} />{at}, written as {file} with its sidecar", file.trim_start_matches("media/")) }));
}
out
}
/// Where a part is written in the TSX: its stamp, else the line naming it (`name="crate"`), else for the camera and
/// a light that has no name the Nth line writing its element (the id's `#N`: `<DirectionalLight`), else None.
pub fn line_of(tsx: &Path, e: &Value) -> Option<String> {
if let Some(loc) = e["loc"].as_str() {
return Some(loc.to_string());
}
let text = std::fs::read_to_string(tsx).ok()?;
let file = tsx.file_name()?.to_string_lossy();
let at = |i: usize| format!("{file}:{}", i + 1);
if let Some(name) = e["name"].as_str().filter(|&n| n != "camera" || e["id"] != "camera") {
return text.lines().position(|l| l.contains(&format!("name=\"{name}\"")) || l.contains(&format!("name: \"{name}\""))).map(at);
}
let id = e["id"].as_str()?;
let (tag, n) = match id.split_once('|') {
None if id == "camera" => ("<Camera3d", 0),
Some((kind, rest)) => {
let tag = match kind {
"directional" => "<DirectionalLight",
"point" => "<PointLight",
"spot" => "<SpotLight",
"rect" => "<RectLight",
_ => return None,
};
(tag, rest.rsplit_once('#').and_then(|(_, n)| n.parse().ok()).unwrap_or(0))
}
None => return None,
};
text.lines().enumerate().filter(|(_, l)| l.contains(tag) && !l.contains(&format!("{tag}s"))).nth(n).map(|(i, _)| at(i))
}
/// The edits as lines, each with where it goes in the TSX.
pub fn said(edits: &[Value], tsx: &Path) -> String {
if edits.is_empty() {
return "nothing changed".into();
}
edits.iter().map(|e| {
// the part by its name in the TSX, else by its id
let who = match (e["name"].as_str(), e["id"].as_str()) {
(Some(n), _) => format!("\"{n}\""),
(None, id) => id.unwrap_or("").to_string(),
};
let at = line_of(tsx, e).map(|l| format!(" ({l})")).unwrap_or_default();
format!("{who}{at}: {}", e["says"].as_str().unwrap_or(""))
}).collect::<Vec<_>>().join("\n")
}
#[cfg(test)]
mod tests {
use super::*;
fn sent() -> Value {
json!({ "parts": [
{ "id": "mesh|a#0", "kind": "mesh", "source": { "name": "crate" }, "at": [[0, 0.5, 0, 0, 0, 0, 1, 1, 1, 1]], "material": { "color": "#ff0000", "roughness": 0.5, "metallic": 0 } },
{ "id": "point|#0", "kind": "light", "source": {}, "at": [[0, 3, 0, 0, 0, 0, 1, 1, 1, 1]], "light": { "color": "#ffffff", "intensity": 1 } }
], "camera": [{ "at": [0, 1, 5, 0, 0, 0, 1, 1, 1, 1], "fov": 40 }] })
}
#[test]
fn nothing_changed_says_so() {
let s = sent();
let now = json!({ "parts": [
{ "id": "mesh|a#0", "at": [0, 0.5, 0, 0, 0, 0, 1, 1, 1, 1], "material": { "color": "#FF0000", "roughness": 0.5, "metallic": 0 } },
{ "id": "point|#0", "at": [0, 3, 0, 0, 0, 0, 1, 1, 1, 1], "light": { "color": "#ffffff", "intensity": 1.0001 } }
], "camera": { "at": [0, 1, 5, 0, 0, 0, 1, 1, 1, 1], "fov": 40 } });
assert_eq!(compare(&s, &now), Vec::<Value>::new());
}
#[test]
fn each_change_is_one_edit() {
let h = std::f64::consts::FRAC_1_SQRT_2;
let now = json!({ "parts": [
{ "id": "mesh|a#0", "at": [1, 0.5, 0, 0, h, 0, h, 2, 2, 2], "material": { "color": "#00ff00", "roughness": 0.2, "metallic": 0 } }
], "camera": { "at": [0, 1, 5, 0, 0, 0, 1, 1, 1, 1], "fov": 30 }, "new": [{ "name": "Cube", "file": "media/cube.glb", "at": [2, 0, 0, 0, 0, 0, 1, 1, 1, 1] }] });
let e = compare(&sent(), &now);
let changes: Vec<&str> = e.iter().map(|x| x["change"].as_str().unwrap()).collect();
assert_eq!(changes, ["moved", "turned", "scaled", "recoloured", "resurfaced", "deleted", "lens", "added"]);
assert_eq!(e[1]["to"], json!([0.0, 1.5708, 0.0]));
assert!(e[7]["says"].as_str().unwrap().contains("staticFile(\"cube.glb\")"));
}
#[test]
fn a_part_is_found_by_its_name() {
let f = std::env::temp_dir().join(format!("raea-back-{}.tsx", std::process::id()));
std::fs::write(&f, "a\n <Cuboid name=\"crate\" size={[1, 1, 1]} />\n <Camera3d transform={t} />\n <PointLight intensity={1} />\n <PointLight intensity={2} />\n").unwrap();
let file = f.file_name().unwrap().to_string_lossy().to_string();
assert_eq!(line_of(&f, &json!({ "name": "crate" })).unwrap(), format!("{file}:2"));
assert_eq!(line_of(&f, &json!({ "id": "camera", "name": "camera" })).unwrap(), format!("{file}:3"));
assert_eq!(line_of(&f, &json!({ "id": "point|#1", "name": null })).unwrap(), format!("{file}:5"));
assert_eq!(line_of(&f, &json!({ "id": "spot|#0", "name": null })), None);
assert_eq!(line_of(&f, &json!({ "name": "lamp", "loc": "edit.tsx:9:3" })).unwrap(), "edit.tsx:9:3");
let _ = std::fs::remove_file(&f);
}
}
+315
View File
@@ -0,0 +1,315 @@
//! `raea scene export EDIT.tsx -o DIR [--composition ID] [--frame N | --at A-B]` (docs/blender.feature BL37): the
//! composition's 3D at a frame, or on every frame of a span, as DIR/scene.json, with each mesh that isn't a primitive in
//! DIR/meshes/ and each model's file in DIR/models/. Every part is placed in the world (y up, metres; a quaternion
//! x y z w), so Blender (sdk/blender/src/scene.ts) and Godot (godot.rs) each build it with their own parts.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use raea_core_scene::{Item, hex, light_power, n, num, tracks_of, vec3};
use serde_json::{Value, json};
use crate::R;
pub const USAGE: &str = "raea scene export EDIT.tsx -o DIR [--composition ID] [--frame N | --at A-B]";
/// The frames asked for: --frame N, every frame of --at A-B, else 0.
fn frames_of(args: &[String]) -> R<Vec<i64>> {
let fl = |k: &str| args.iter().position(|a| a == k).and_then(|i| args.get(i + 1));
if let Some(span) = fl("--at") {
let (a, b) = span.split_once('-').ok_or("--at takes A-B, the first and last frame")?;
let (a, b): (i64, i64) = (a.trim().parse().map_err(|_| "--at A-B: A is a frame")?, b.trim().parse().map_err(|_| "--at A-B: B is a frame")?);
if b < a || b - a > 10_000 {
return Err("--at A-B: B at or after A, at most 10 000 frames".into());
}
return Ok((a..=b).collect());
}
Ok(vec![fl("--frame").map(|f| f.parse().map_err(|_| "--frame takes a frame number")).transpose()?.unwrap_or(0)])
}
fn r6(x: f32) -> f64 {
(x as f64 * 1e6).round() / 1e6
}
/// A rotation turning -Z (the way a camera and a light face, in glTF, Blender and Godot alike) to `dir`, +Y towards
/// `up`: x y z w.
pub fn look_quat(dir: [f64; 3], up: [f64; 3]) -> [f64; 4] {
let norm = |v: [f64; 3]| {
let l = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
if l < 1e-12 { None } else { Some([v[0] / l, v[1] / l, v[2] / l]) }
};
let cross = |a: [f64; 3], b: [f64; 3]| [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
let Some(f) = norm(dir) else { return [0.0, 0.0, 0.0, 1.0] };
let z = [-f[0], -f[1], -f[2]];
let x = norm(cross(up, z)).or_else(|| norm(cross([0.0, 0.0, 1.0], z))).unwrap_or([1.0, 0.0, 0.0]);
let y = cross(z, x);
// the rotation matrix's columns x, y, z as a quaternion
let (m00, m11, m22) = (x[0], y[1], z[2]);
let t = m00 + m11 + m22;
let q = if t > 0.0 {
let s = (t + 1.0).sqrt() * 2.0;
[(y[2] - z[1]) / s, (z[0] - x[2]) / s, (x[1] - y[0]) / s, 0.25 * s]
} else if m00 > m11 && m00 > m22 {
let s = (1.0 + m00 - m11 - m22).sqrt() * 2.0;
[0.25 * s, (y[0] + x[1]) / s, (z[0] + x[2]) / s, (y[2] - z[1]) / s]
} else if m11 > m22 {
let s = (1.0 + m11 - m00 - m22).sqrt() * 2.0;
[(y[0] + x[1]) / s, 0.25 * s, (z[1] + y[2]) / s, (z[0] - x[2]) / s]
} else {
let s = (1.0 + m22 - m00 - m11).sqrt() * 2.0;
[(z[0] + x[2]) / s, (z[1] + y[2]) / s, 0.25 * s, (x[1] - y[0]) / s]
};
q.map(|v| (v * 1e6).round() / 1e6)
}
/// A mesh or model's placement: position, rotation (x y z w), scale.
fn placed(it: &Item) -> Value {
let (s, q, t) = it.world.to_scale_rotation_translation();
let q = if q.is_finite() { [q.x, q.y, q.z, q.w] } else { [0.0, 0.0, 0.0, 1.0] };
json!([r6(t.x), r6(t.y), r6(t.z), r6(q[0]), r6(q[1]), r6(q[2]), r6(q[3]), r6(s.x), r6(s.y), r6(s.z)])
}
/// A light's placement: where it is, turned to face its target (a sun's from its position to its target too).
fn light_placed(it: &Item) -> Value {
let p = vec3(&it.props, "position", if it.kind == "directional" { [0.0, 1.0, 0.0] } else { [0.0; 3] });
let w = it.world.transform_point3([p[0] as f32, p[1] as f32, p[2] as f32].into());
let t = vec3(&it.props, "target", [0.0; 3]);
let w = [w.x as f64, w.y as f64, w.z as f64];
let q = look_quat([t[0] - w[0], t[1] - w[1], t[2] - w[2]], [0.0, 1.0, 0.0]);
let r = |x: f64| (x * 1e6).round() / 1e6;
json!([r(w[0]), r(w[1]), r(w[2]), q[0], q[1], q[2], q[3], 1, 1, 1])
}
/// What a mesh is made of, as the parts another tool has: a primitive with its sizes, else its Manifold mesh as a .glb.
fn shape(expr: &str, out: &Path, meshes: &mut BTreeMap<String, String>) -> R<Value> {
if let Some(s) = raea_core_shape::cuboid_of(expr) {
return Ok(json!({ "type": "cuboid", "size": s }));
}
if let Some(raea_core_shape::SphereOf::Ico { radius, .. } | raea_core_shape::SphereOf::Uv { radius, .. }) = raea_core_shape::sphere_of(expr) {
return Ok(json!({ "type": "sphere", "radius": radius }));
}
if let Some((radius, height)) = raea_core_shape::cylinder_of(expr) {
return Ok(json!({ "type": "cylinder", "radius": radius, "height": height }));
}
if let Some((_, size)) = raea_core_shape::plane_of(expr).filter(|(n, _)| *n == [0.0, 1.0, 0.0]) {
return Ok(json!({ "type": "plane", "size": size }));
}
let k = meshes.len();
let file = match meshes.get(expr) {
Some(f) => f.clone(),
None => {
let f = format!("meshes/mesh{k}.glb");
let m = raea_core_shape::solid(expr)?;
raea_core_shape::export(&m, &out.join(&f).to_string_lossy(), "glb")?;
// and as an .obj, which Godot imports as a mesh of its own (a .glb comes in as a scene)
raea_core_shape::export(&m, &out.join(f.replace(".glb", ".obj")).to_string_lossy(), "obj")?;
meshes.insert(expr.to_string(), f.clone());
f
}
};
Ok(json!({ "type": "mesh", "file": file, "obj": file.replace(".glb", ".obj") }))
}
/// A file the scene names (a model, a texture) copied into `sub` of the export with its licence sidecar: its path there.
fn copied(dir: &Path, src: &str, out: &Path, sub: &str, files: &mut BTreeMap<PathBuf, String>) -> R<String> {
let from = raea_core_scene::media_path(dir, if src.starts_with('/') || src.contains("://") { src.to_string() } else { format!("/media/{src}") }.as_str());
let from = if from.exists() { from } else { raea_core_scene::media_path(dir, src) };
if let Some(f) = files.get(&from) {
return Ok(f.clone());
}
let name = from.file_name().and_then(|n| n.to_str()).ok_or_else(|| format!("{src}: no file"))?;
let mut rel = format!("{sub}/{name}");
if files.values().any(|v| *v == rel) {
rel = format!("{sub}/{}-{name}", files.len());
}
std::fs::create_dir_all(out.join(sub)).map_err(|e| e.to_string())?;
std::fs::copy(&from, out.join(&rel)).map_err(|e| format!("{}: {e}", from.display()))?;
for side in [format!("{}.json", from.display()), format!("{}.json", from.with_extension("").display())] {
if Path::new(&side).is_file() {
let _ = std::fs::copy(&side, out.join(format!("{rel}.json")));
break;
}
}
files.insert(from, rel.clone());
Ok(rel)
}
/// A part's surface: three.js-style props as the renderer reads them (runtime/scene's meshes_rows).
fn material(it: &Item, dir: &Path, out: &Path, files: &mut BTreeMap<PathBuf, String>) -> Value {
let Some(m) = &it.material else { return json!({ "color": "#cccccc", "roughness": 0.5, "metallic": 0.0 }) };
let p = &m.props;
let mut v = json!({ "color": hex(p.get("color")).unwrap_or("#cccccc".into()), "roughness": n(p, "roughness", 0.5), "metallic": n(p, "metalness", 0.0) });
if let Some(e) = hex(p.get("emissive")).filter(|e| e != "#000000") {
v["emissive"] = json!(e);
v["emissive_strength"] = json!(raea_core_scene::emissive_power(p));
}
if let Some(o) = num(p, "opacity").filter(|o| *o < 1.0) {
v["opacity"] = json!(o);
}
if &*m.kind == "MeshBasicMaterial" || p.get("unlit") == Some(&Value::Bool(true)) {
v["unlit"] = json!(true);
}
for (prop, key) in [("map", "color_map"), ("normalMap", "normal_map"), ("roughnessMap", "roughness_map"), ("metalnessMap", "metallic_map"), ("emissiveMap", "emissive_map")] {
if let Some(src) = p.get(prop).and_then(Value::as_str)
&& let Ok(f) = copied(dir, src, out, "textures", files)
{
v[key] = json!(f);
}
}
v
}
/// The light another tool sets: its kind, colour, intensity as raea reads it (1 is a 3d.tsx light's default) and in
/// Bevy's units (lux for a sun, lumens else), reach and cone.
fn light(it: &Item) -> Value {
let p = &it.props;
let power = light_power(it.kind, p);
let unit = if it.kind == "directional" { raea_core_scene::LUX } else { raea_core_scene::LUMENS };
let mut v = json!({ "type": it.kind, "color": hex(p.get("color")).unwrap_or("#ffffff".into()), "intensity": power / unit });
v[if it.kind == "directional" { "lux" } else { "lumens" }] = json!(power);
if let Some(d) = num(p, "distance").filter(|d| *d > 0.0) {
v["range"] = json!(d);
}
if it.kind == "spot" {
v["angle"] = json!(n(p, "angle", std::f64::consts::FRAC_PI_3));
v["penumbra"] = json!(n(p, "penumbra", 0.0));
}
if it.kind == "rect" {
v["width"] = json!(n(p, "width", 1.0));
v["height"] = json!(n(p, "height", 1.0));
}
v
}
/// Where the part is written in the TSX, when the bundle stamped it, and its name.
fn source(it: &Item) -> Value {
let s = |k: &str| it.props.get(k).and_then(Value::as_str).map(str::to_string);
json!({ "name": s("name"), "loc": s("data-raea-loc"), "use": s("data-raea-use") })
}
/// The parts of every frame asked for (`all`, one list of items each), written into `out`: scene.json's value.
pub fn scene(all: &[Vec<Item>], frames: &[i64], dir: &Path, out: &Path) -> R<Value> {
let (mut meshes, mut files) = (BTreeMap::new(), BTreeMap::new());
let mut parts = Vec::new();
for (id, track) in tracks_of(all, &["mesh", "model", "directional", "point", "spot", "rect"]) {
let Some(first) = track.iter().flatten().next() else { continue };
let mut part = json!({ "id": id, "kind": if first.kind == "mesh" || first.kind == "model" { first.kind } else { "light" }, "source": source(first) });
match first.kind {
// an <Instances> set is many copies of one mesh: left out (counted in `left`)
"mesh" if first.at.is_some() => continue,
"mesh" => {
let Some(expr) = first.shape.as_deref() else { continue };
part["shape"] = shape(expr, out, &mut meshes)?;
part["material"] = material(first, dir, out, &mut files);
}
"model" => {
let src = first.props.get("src").and_then(Value::as_str).unwrap_or_default();
part["model"] = json!(copied(dir, src, out, "models", &mut files)?);
}
_ => part["light"] = light(first),
}
let at: Vec<Value> = track.iter().map(|t| t.as_ref().map_or(Value::Null, |it| if part["kind"] == "light" { light_placed(it) } else { placed(it) })).collect();
part["at"] = json!(at);
parts.push(part);
}
// the camera: the first drawing one each frame, from its position to what it looks at
let cam: Vec<Value> = all.iter().map(|its| {
its.iter().find(|i| i.kind == "camera").map_or(Value::Null, |c| {
let (p, l, up) = (vec3(&c.props, "position", [0.0, 0.0, 5.0]), vec3(&c.props, "lookAt", [0.0; 3]), vec3(&c.props, "up", [0.0, 1.0, 0.0]));
let q = look_quat([l[0] - p[0], l[1] - p[1], l[2] - p[2]], up);
json!({ "at": [p[0], p[1], p[2], q[0], q[1], q[2], q[3], 1, 1, 1], "look": l, "fov": n(&c.props, "fov", 50.0) })
})
}).collect();
let ambient = all[0].iter().find(|i| i.kind == "ambient").map(|a| json!({ "color": hex(a.props.get("color")).unwrap_or("#ffffff".into()), "nits": light_power("ambient", &a.props) }));
// what doesn't cross, by kind, counted on the first frame
let mut left: BTreeMap<&str, usize> = BTreeMap::new();
for i in &all[0] {
match i.kind {
// a mesh drawn at many places (<Instances>) crosses as its first copy only
"mesh" if i.at.is_some() => *left.entry("instances").or_default() += 1,
"mesh" | "model" | "directional" | "point" | "spot" | "rect" | "camera" | "ambient" => {}
k => *left.entry(k).or_default() += 1,
}
}
Ok(json!({ "raea": "scene/1", "frames": frames, "parts": parts, "camera": cam, "ambient": ambient, "left": left }))
}
/// `raea scene export ...`: scene.json written, and its value.
pub fn export(args: &[String]) -> R<(PathBuf, Value)> {
let edit = args.get(2).ok_or(USAGE)?;
let tsx = PathBuf::from(edit).canonicalize().map_err(|e| format!("{edit}: {e}"))?;
let dir = tsx.parent().ok_or("the edit's folder")?.to_path_buf();
let out = args.iter().position(|a| a == "-o").and_then(|i| args.get(i + 1)).ok_or(USAGE)?;
let out = std::path::absolute(out).map_err(|e| e.to_string())?;
let frames = frames_of(args)?;
let js = std::env::temp_dir().join(format!("raea-scene-export-{}.js", std::process::id()));
// each part's place in the TSX (data-raea-loc), which raea blender back and raea godot back say their edits at
// SAFETY: the CLI sets it before the bundle starts any thread that reads the environment
unsafe { std::env::set_var("RAEA_SOURCE_STAMPS", "1") };
raea_runtime_bundle::bundle_composition(&tsx, &js, &raea_runtime_bundle::comp_opts(args)?, None)?;
let got = raea_runtime_export::scene_frames(&js, &dir, frames[frames.len() - 1] + 1, false, &frames);
let _ = std::fs::remove_file(&js);
let (got, w, h, fps) = got?.ok_or("the composition has no 3D")?;
let all: Vec<Vec<Item>> = frames.iter().map(|f| got.iter().find(|(k, _)| k == f).map(|(_, fr)| raea_runtime_scene::items_of(&fr.scene)).unwrap_or_default()).collect();
if all.iter().all(Vec::is_empty) {
return Err(format!("{edit}: no 3D on frame {}", frames[0]));
}
let _ = std::fs::remove_dir_all(out.join("meshes"));
std::fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?;
let mut v = scene(&all, &frames, &dir, &out)?;
v["from"] = json!(tsx.to_string_lossy());
v["fps"] = json!(fps);
v["size"] = json!([w, h]);
std::fs::write(out.join("scene.json"), serde_json::to_string_pretty(&v).unwrap_or_default()).map_err(|e| e.to_string())?;
Ok((out, v))
}
/// The summary line of an export.
pub fn said(out: &Path, v: &Value) -> String {
let parts = v["parts"].as_array().map_or(0, Vec::len);
let frames = v["frames"].as_array().map_or(0, Vec::len);
let left: Vec<String> = v["left"].as_object().into_iter().flatten().map(|(k, n)| format!("{n} {k}")).collect();
let left = if left.is_empty() { String::new() } else { format!("; not carried: {}", left.join(", ")) };
format!("{parts} parts on {frames} frame{} in {}{left}", if frames == 1 { "" } else { "s" }, out.join("scene.json").display())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_rotation_faces_where_it_is_turned() {
// looking down -Z is no turn; looking down +X turns -90 degrees about Y
assert_eq!(look_quat([0.0, 0.0, -1.0], [0.0, 1.0, 0.0]), [0.0, 0.0, 0.0, 1.0]);
let q = look_quat([1.0, 0.0, 0.0], [0.0, 1.0, 0.0]);
assert!((q[1] + std::f64::consts::FRAC_1_SQRT_2).abs() < 1e-6 && (q[3] - std::f64::consts::FRAC_1_SQRT_2).abs() < 1e-6, "{q:?}");
// straight down still has a way up
let q = look_quat([0.0, -1.0, 0.0], [0.0, 1.0, 0.0]);
assert!(q.iter().all(|v| v.is_finite()) && (q.iter().map(|v| v * v).sum::<f64>() - 1.0).abs() < 1e-5);
}
#[test]
fn frames_are_one_or_a_span() {
let a = |s: &str| s.split_whitespace().map(String::from).collect::<Vec<_>>();
assert_eq!(frames_of(&a("scene export e.tsx")).unwrap(), vec![0]);
assert_eq!(frames_of(&a("scene export e.tsx --frame 12")).unwrap(), vec![12]);
assert_eq!(frames_of(&a("scene export e.tsx --at 3-5")).unwrap(), vec![3, 4, 5]);
assert!(frames_of(&a("scene export e.tsx --at 5-3")).is_err());
}
#[test]
fn primitives_cross_as_themselves_and_the_rest_as_a_mesh() {
let out = std::env::temp_dir().join(format!("raea-interchange-shape-{}", std::process::id()));
std::fs::create_dir_all(out.join("meshes")).unwrap();
let mut m = BTreeMap::new();
assert_eq!(shape("box(1, 2, 3)", &out, &mut m).unwrap(), json!({ "type": "cuboid", "size": [1.0, 2.0, 3.0] }));
assert_eq!(shape("sphere(0.5)", &out, &mut m).unwrap()["type"], "sphere");
assert_eq!(shape("rotate(cone(0.5, 0.5, 2), -90, 0, 0)", &out, &mut m).unwrap()["height"], 2.0);
let v = shape("difference(box(1, 1, 1), sphere(0.6))", &out, &mut m).unwrap();
assert_eq!(v["type"], "mesh");
assert!(out.join(v["file"].as_str().unwrap()).is_file());
// the same mesh twice is one file
assert_eq!(shape("difference(box(1, 1, 1), sphere(0.6))", &out, &mut m).unwrap(), v);
let _ = std::fs::remove_dir_all(&out);
}
}
+291
View File
@@ -0,0 +1,291 @@
//! A raea scene as a Godot project (docs/godot.feature GD12): scene export's folder made into project.godot and
//! main.tscn, each part Godot's own node (a primitive its own mesh with a StandardMaterial3D, any other mesh an imported
//! .obj, a model its .glb instanced, lights, the camera, a WorldEnvironment), named for the part and carrying its id;
//! a span's frames an AnimationPlayer that plays as the project runs.
use std::collections::BTreeSet;
use std::fmt::Write as _;
use std::path::Path;
use serde_json::Value;
use crate::R;
/// `#rrggbb` as Godot's Color (sRGB, as Godot's albedo and light colours are given).
fn color(hex: &str, a: f64) -> String {
let h = hex.trim_start_matches('#');
let c = |i: usize| u8::from_str_radix(h.get(i..i + 2).unwrap_or("cc"), 16).unwrap_or(204) as f64 / 255.0;
format!("Color({:.4}, {:.4}, {:.4}, {a})", c(0), c(2), c(4))
}
/// A placement (x y z, qx qy qz qw, sx sy sz) as Godot's Transform3D: the basis by rows, the rotation's columns scaled.
pub fn transform(at: &Value) -> String {
let v: Vec<f64> = at.as_array().into_iter().flatten().filter_map(Value::as_f64).collect();
if v.len() < 10 {
return "Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0)".into();
}
let (x, y, z, w) = (v[3], v[4], v[5], v[6]);
let r = [
[1.0 - 2.0 * (y * y + z * z), 2.0 * (x * y - z * w), 2.0 * (x * z + y * w)],
[2.0 * (x * y + z * w), 1.0 - 2.0 * (x * x + z * z), 2.0 * (y * z - x * w)],
[2.0 * (x * z - y * w), 2.0 * (y * z + x * w), 1.0 - 2.0 * (x * x + y * y)],
];
let s = [v[7], v[8], v[9]];
let b: Vec<String> = (0..3).flat_map(|i| (0..3).map(move |j| (i, j))).map(|(i, j)| num(r[i][j] * s[j])).collect();
format!("Transform3D({}, {}, {}, {})", b.join(", "), num(v[0]), num(v[1]), num(v[2]))
}
fn num(x: f64) -> String {
let r = (x * 1e6).round() / 1e6;
if r == 0.0 { "0".into() } else { format!("{r}") }
}
/// A node name Godot takes (no . : @ / " %), unique in the scene.
fn node_name(want: &str, taken: &mut BTreeSet<String>) -> String {
let base: String = want.chars().map(|c| if ".:@/\"%#|".contains(c) || c.is_control() { '_' } else { c }).collect();
let base = if base.trim().is_empty() { "Part".to_string() } else { base.trim().to_string() };
let mut name = base.clone();
let mut k = 2;
while !taken.insert(name.clone()) {
name = format!("{base}{k}");
k += 1;
}
name
}
/// A part's node name: its name in the TSX, else what it is ("Sun", "PointLight", "Cuboid", the model's file).
pub fn wanted(p: &Value) -> String {
if let Some(n) = p["source"]["name"].as_str() {
return n.to_string();
}
let what = match (p["kind"].as_str(), p["light"]["type"].as_str(), p["shape"]["type"].as_str()) {
(_, Some("directional"), _) => "Sun",
(_, Some("point"), _) => "PointLight",
(_, Some("spot"), _) => "SpotLight",
(_, Some("rect"), _) => "AreaLight",
(Some("model"), _, _) => return p["model"].as_str().and_then(|m| Path::new(m).file_stem()?.to_str()).unwrap_or("Model").to_string(),
(_, _, Some("cuboid")) => "Cuboid",
(_, _, Some("sphere")) => "Sphere",
(_, _, Some("cylinder")) => "Cylinder",
(_, _, Some("plane")) => "Plane",
_ => "Mesh",
};
what.to_string()
}
/// The tscn's resources and nodes, written in order: ext_resources, sub_resources, then nodes.
#[derive(Default)]
struct Tscn {
ext: String,
sub: String,
nodes: String,
n_ext: usize,
n_sub: usize,
}
impl Tscn {
fn ext(&mut self, kind: &str, path: &str) -> String {
self.n_ext += 1;
let _ = writeln!(self.ext, "[ext_resource type=\"{kind}\" path=\"res://{path}\" id=\"{}\"]", self.n_ext);
format!("ExtResource(\"{}\")", self.n_ext)
}
fn sub(&mut self, kind: &str, body: &str) -> String {
self.n_sub += 1;
let _ = write!(self.sub, "\n[sub_resource type=\"{kind}\" id=\"{kind}_{}\"]\n{body}", self.n_sub);
format!("SubResource(\"{kind}_{}\")", self.n_sub)
}
}
fn material(m: &Value) -> String {
// each number the material gives, else raea's default for it
let f = |k: &str| m[k].as_f64().unwrap_or(match k { "opacity" | "emissive_strength" => 1.0, "roughness" => 0.5, _ => 0.0 });
let mut s = format!("albedo_color = {}\nmetallic = {}\nroughness = {}\n", color(m["color"].as_str().unwrap_or("#cccccc"), f("opacity")), num(f("metallic")), num(f("roughness")));
if let Some(e) = m["emissive"].as_str() {
let _ = write!(s, "emission_enabled = true\nemission = {}\nemission_energy_multiplier = {}\n", color(e, 1.0), num(f("emissive_strength")));
}
if m["opacity"].as_f64().is_some_and(|o| o < 1.0) {
s.push_str("transparency = 1\n");
}
if m["unlit"] == true {
s.push_str("shading_mode = 0\n");
}
// its textures need their files' ext_resources: part() adds them
s
}
/// One part's node (and its resources); the first frame it's in places it.
fn part(t: &mut Tscn, p: &Value, name: &str) {
let first = p["at"].as_array().into_iter().flatten().find(|a| !a.is_null()).cloned().unwrap_or(Value::Null);
let meta = format!("metadata/raea_id = \"{}\"\n", p["id"].as_str().unwrap_or("").replace('"', "'"));
let tr = transform(&first);
match p["kind"].as_str() {
Some("mesh") => {
let sh = &p["shape"];
let mesh = match sh["type"].as_str() {
Some("cuboid") => {
let s = &sh["size"];
t.sub("BoxMesh", &format!("size = Vector3({}, {}, {})\n", num(s[0].as_f64().unwrap_or(1.0)), num(s[1].as_f64().unwrap_or(1.0)), num(s[2].as_f64().unwrap_or(1.0))))
}
Some("sphere") => {
let r = sh["radius"].as_f64().unwrap_or(0.5);
t.sub("SphereMesh", &format!("radius = {}\nheight = {}\n", num(r), num(2.0 * r)))
}
Some("cylinder") => {
let r = num(sh["radius"].as_f64().unwrap_or(0.5));
t.sub("CylinderMesh", &format!("top_radius = {r}\nbottom_radius = {r}\nheight = {}\n", num(sh["height"].as_f64().unwrap_or(1.0))))
}
Some("plane") => {
let s = &sh["size"];
t.sub("PlaneMesh", &format!("size = Vector2({}, {})\n", num(s[0].as_f64().unwrap_or(1.0)), num(s[1].as_f64().unwrap_or(1.0))))
}
_ => t.ext("ArrayMesh", sh["obj"].as_str().unwrap_or("")),
};
let mut mat = material(&p["material"]);
if let Some(f) = p["material"]["color_map"].as_str() {
let tex = t.ext("Texture2D", f);
let _ = writeln!(mat, "albedo_texture = {tex}");
}
if let Some(f) = p["material"]["normal_map"].as_str() {
let tex = t.ext("Texture2D", f);
let _ = writeln!(mat, "normal_enabled = true\nnormal_texture = {tex}");
}
let mat = t.sub("StandardMaterial3D", &mat);
let _ = write!(t.nodes, "\n[node name=\"{name}\" type=\"MeshInstance3D\" parent=\".\"]\ntransform = {tr}\nmesh = {mesh}\nsurface_material_override/0 = {mat}\n{meta}");
}
Some("model") => {
let scene = t.ext("PackedScene", p["model"].as_str().unwrap_or(""));
let _ = write!(t.nodes, "\n[node name=\"{name}\" parent=\".\" instance={scene}]\ntransform = {tr}\n{meta}");
}
_ => {
let l = &p["light"];
let kind = match l["type"].as_str() {
Some("directional") => "DirectionalLight3D",
Some("spot") => "SpotLight3D",
_ => "OmniLight3D",
};
let mut body = format!("transform = {tr}\nlight_color = {}\nlight_energy = {}\nshadow_enabled = true\n", color(l["color"].as_str().unwrap_or("#ffffff"), 1.0), num(l["intensity"].as_f64().unwrap_or(1.0)));
let range = num(l["range"].as_f64().unwrap_or(20.0));
match kind {
"SpotLight3D" => {
let _ = write!(body, "spot_range = {range}\nspot_angle = {}\n", num(l["angle"].as_f64().unwrap_or(std::f64::consts::FRAC_PI_3).to_degrees().min(89.0)));
}
"OmniLight3D" => {
let _ = writeln!(body, "omni_range = {range}");
}
_ => {}
}
let _ = write!(t.nodes, "\n[node name=\"{name}\" type=\"{kind}\" parent=\".\"]\n{body}{meta}");
}
}
}
/// A placement track of the animation: each frame the node is in, as (time, transition, values...).
fn tracks(anim: &mut String, k: &mut usize, path: &str, at: &[Value], fps: f64, f0: i64, frames: &[i64]) {
let keyed: Vec<(f64, Vec<f64>)> = at.iter().zip(frames).filter_map(|(a, f)| {
let v: Vec<f64> = a.as_array()?.iter().filter_map(Value::as_f64).collect();
(v.len() >= 10).then(|| ((f - f0) as f64 / fps, v))
}).collect();
for (kind, range) in [("position_3d", 0..3), ("rotation_3d", 3..7), ("scale_3d", 7..10)] {
// a channel that holds still isn't a track: a part that only turns keys its rotation alone
if keyed.windows(2).all(|w| w[0].1[range.clone()] == w[1].1[range.clone()]) {
continue;
}
let keys: Vec<String> = keyed.iter().flat_map(|(t, v)| [num(*t), "1".into()].into_iter().chain(v[range.clone()].iter().map(|x| num(*x)))).collect();
let _ = write!(anim, "tracks/{k}/type = \"{kind}\"\ntracks/{k}/imported = false\ntracks/{k}/enabled = true\ntracks/{k}/path = NodePath(\"{path}\")\ntracks/{k}/interp = 1\ntracks/{k}/loop_wrap = true\ntracks/{k}/keys = PackedFloat32Array({})\n", keys.join(", "));
*k += 1;
}
}
/// project.godot and main.tscn in `dir` (scene export's folder), from its scene.json `v`: the name of the project.
pub fn project(dir: &Path, v: &Value, name: &str) -> R<String> {
let fps = v["fps"].as_f64().unwrap_or(30.0);
let frames: Vec<i64> = v["frames"].as_array().into_iter().flatten().filter_map(Value::as_i64).collect();
let f0 = frames.first().copied().unwrap_or(0);
let (w, h) = (v["size"][0].as_u64().unwrap_or(1920), v["size"][1].as_u64().unwrap_or(1080));
let mut t = Tscn::default();
let mut taken = BTreeSet::from(["WorldEnvironment".to_string(), "Camera3D".to_string(), "AnimationPlayer".to_string()]);
let mut anim = String::new();
let mut k = 0;
for p in v["parts"].as_array().into_iter().flatten() {
let name = node_name(&wanted(p), &mut taken);
part(&mut t, p, &name);
if frames.len() > 1 {
tracks(&mut anim, &mut k, &name, p["at"].as_array().map(Vec::as_slice).unwrap_or(&[]), fps, f0, &frames);
}
}
// the ambient and a background: Bevy's own clear colour unless the scene says otherwise
let amb = &v["ambient"];
let mut env = "background_mode = 1\nbackground_color = Color(0.1686, 0.1725, 0.1843, 1)\ntonemap_mode = 3\n".to_string();
if amb.is_object() {
let _ = write!(env, "ambient_light_source = 2\nambient_light_color = {}\nambient_light_energy = {}\n", color(amb["color"].as_str().unwrap_or("#ffffff"), 1.0), num(amb["nits"].as_f64().unwrap_or(400.0) / 400.0));
}
let env = t.sub("Environment", &env);
let mut nodes = format!("\n[node name=\"WorldEnvironment\" type=\"WorldEnvironment\" parent=\".\"]\nenvironment = {env}\n");
nodes.push_str(&t.nodes);
let cams: Vec<Value> = v["camera"].as_array().into_iter().flatten().cloned().collect();
if let Some(c) = cams.iter().find(|c| c.is_object()) {
let _ = write!(nodes, "\n[node name=\"Camera3D\" type=\"Camera3D\" parent=\".\"]\ntransform = {}\nfov = {}\ncurrent = true\n", transform(&c["at"]), num(c["fov"].as_f64().unwrap_or(50.0)));
if frames.len() > 1 {
let at: Vec<Value> = cams.iter().map(|c| c["at"].clone()).collect();
tracks(&mut anim, &mut k, "Camera3D", &at, fps, f0, &frames);
}
}
if k > 0 {
let len = (frames.len().saturating_sub(1)) as f64 / fps;
let a = t.sub("Animation", &format!("resource_name = \"raea\"\nlength = {}\n{anim}", num(len.max(1.0 / fps))));
let lib = t.sub("AnimationLibrary", &format!("_data = {{\n&\"raea\": {a}\n}}\n"));
let _ = write!(nodes, "\n[node name=\"AnimationPlayer\" type=\"AnimationPlayer\" parent=\".\"]\nlibraries = {{\n&\"\": {lib}\n}}\nautoplay = &\"raea\"\n");
}
let tscn = format!("[gd_scene load_steps={} format=3]\n\n{}{}\n[node name=\"{}\" type=\"Node3D\"]\n{nodes}", t.n_ext + t.n_sub + 1, t.ext, t.sub, node_name(name, &mut BTreeSet::new()));
std::fs::write(dir.join("main.tscn"), tscn).map_err(|e| e.to_string())?;
let godot = format!(
"; written by raea godot export (docs/godot.feature GD12)\nconfig_version=5\n\n[application]\nconfig/name=\"{}\"\nrun/main_scene=\"res://main.tscn\"\nconfig/features=PackedStringArray(\"4.6\", \"Forward Plus\")\n\n[display]\nwindow/size/viewport_width={w}\nwindow/size/viewport_height={h}\n\n[rendering]\nrenderer/rendering_method=\"forward_plus\"\n",
name.replace('"', "'")
);
std::fs::write(dir.join("project.godot"), godot).map_err(|e| e.to_string())?;
Ok(format!("{} parts{}", v["parts"].as_array().map_or(0, Vec::len), if k > 0 { format!(", {k} animation track{} over {} frames", if k == 1 { "" } else { "s" }, frames.len()) } else { String::new() }))
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn a_placement_is_a_transform_by_rows() {
assert_eq!(transform(&json!([1, 2, 3, 0, 0, 0, 1, 1, 1, 1])), "Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 2, 3)");
// a quarter turn about Y, then scaled by 2 along x: the x column is twice as long
let h = std::f64::consts::FRAC_1_SQRT_2;
assert_eq!(transform(&json!([0, 0, 0, 0, h, 0, h, 2, 1, 1])), "Transform3D(0, 0, 1, 0, 1, 0, -2, 0, 0, 0, 0, 0)");
}
#[test]
fn names_are_godots_and_unique() {
let mut t = BTreeSet::new();
assert_eq!(node_name("crate", &mut t), "crate");
assert_eq!(node_name("crate", &mut t), "crate2");
assert_eq!(node_name("mesh|a.b#0", &mut t), "mesh_a_b_0");
}
#[test]
fn a_scene_becomes_a_project_that_moves() {
let dir = std::env::temp_dir().join(format!("raea-godot-project-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let v = json!({ "fps": 30, "size": [640, 360], "frames": [0, 1],
"parts": [
{ "id": "mesh|box(1, 1, 1)#0", "kind": "mesh", "source": { "name": "crate" }, "shape": { "type": "cuboid", "size": [1, 1, 1] }, "material": { "color": "#ff0000", "roughness": 0.4, "metallic": 0 }, "at": [[0, 0.5, 0, 0, 0, 0, 1, 1, 1, 1], [1, 0.5, 0, 0, 0, 0, 1, 1, 1, 1]] },
{ "id": "directional|#0", "kind": "light", "source": {}, "light": { "type": "directional", "color": "#ffffff", "intensity": 1 }, "at": [[0, 5, 0, 0, 0, 0, 1, 1, 1, 1], [0, 5, 0, 0, 0, 0, 1, 1, 1, 1]] }
],
"camera": [{ "at": [0, 1, 5, 0, 0, 0, 1, 1, 1, 1], "fov": 40 }, { "at": [0, 1, 5, 0, 0, 0, 1, 1, 1, 1], "fov": 40 }], "ambient": null });
let said = project(&dir, &v, "box test").unwrap();
// the crate only moves: its position is keyed, its rotation and scale aren't tracks
assert!(said.contains("1 animation track over 2 frames"), "{said}");
let tscn = std::fs::read_to_string(dir.join("main.tscn")).unwrap();
assert!(!tscn.contains("tracks/1/"), "{tscn}");
for want in ["[node name=\"crate\" type=\"MeshInstance3D\"", "size = Vector3(1, 1, 1)", "albedo_color = Color(1.0000, 0.0000, 0.0000, 1)", "[node name=\"Sun\" type=\"DirectionalLight3D\"", "fov = 40", "tracks/0/type = \"position_3d\"", "autoplay = &\"raea\"", "tracks/0/path = NodePath(\"crate\")", "metadata/raea_id = \"mesh|box(1, 1, 1)#0\""] {
assert!(tscn.contains(want), "{want} in\n{tscn}");
}
assert!(std::fs::read_to_string(dir.join("project.godot")).unwrap().contains("window/size/viewport_width=640"));
let _ = std::fs::remove_dir_all(&dir);
}
}
+13
View File
@@ -0,0 +1,13 @@
//! A composition's 3D for other tools, and back (docs/blender.feature BL37-BL39, docs/godot.feature GD12-GD13):
//! `raea scene export` writes the parts of a frame (or a span) as scene.json with their meshes and models; godot.rs
//! makes that folder a Godot project; back.rs compares scene.json with what Blender or Godot holds after a person
//! changed it there, as edits to the TSX at their lines. apps/engines runs Blender and Godot for these verbs.
/// `raea scene export`: scene.json, meshes/, models/
pub mod export;
/// scene export's folder as a Godot project: project.godot, main.tscn
pub mod godot;
/// what changed in Blender or Godot, as edits to the TSX
pub mod back;
type R<T> = Result<T, String>;
+2
View File
@@ -8,6 +8,8 @@ description = "raea judge: a review's sheets judged by clef-omni on a frozen rub
[dependencies]
raea-io-home = { path = "../../io/home" }
# what a judge saw, as raea's one Finding (docs/direction.feature DR3)
raea-core-facts = { path = "../../core/facts" }
serde_json = "1"
raea-runtime-bundle = { path = "../../runtime/bundle" }
ureq = { version = "2", features = ["json"] }
+32 -7
View File
@@ -18,6 +18,7 @@ pub use agent::BY;
use std::path::{Path, PathBuf};
use raea_core_facts::{Finding, Level, finding};
use raea_runtime_bundle::flag;
use serde_json::{Value, json};
@@ -125,6 +126,31 @@ pub fn cli(args: &[String]) -> Result<String, String> {
finish(args, &dir, scores, raw, defects, photo, cost, "clef", !gating, json!({"calibrated": cal.is_some()}))
}
/// The defects a judge saw, as raea's one Finding (docs/direction.feature DR3): a blocking one an error and a detail a
/// warn, each a level lower from a judge that only advises. A judge sees pictures, not parts: a finding names its
/// sheet in its words and is about no entity.
pub fn findings(defects: &[Value], by: &str, advice: bool) -> Vec<Finding> {
let found = defects.iter().filter(|d| d["present"] == true).map(|d| {
let blocking = d["level"] == "blocking";
let level = match (blocking, advice) {
(true, false) => Level::Error,
(true, true) | (false, false) => Level::Warn,
(false, true) => Level::Note,
};
let sheet = d["sheet"].as_str().unwrap_or("");
let check = format!("judge.{}", if by == "clef" { d["defect"].as_str().unwrap_or("defect") } else { sheet });
let mut f = Finding::new(&check, level, format!("{sheet} sheet: {}", d["asked"].as_str().unwrap_or("")), &format!("raea judge ({by})"));
if let Some(p) = d["p"].as_f64() {
f = f.measure("p", p, "", Some(0.5));
}
match d["fix"].as_str() {
Some(x) if !x.is_empty() => f.fix(x),
_ => f,
}
});
finding::ranked(found.collect())
}
/// The verdict decided in code, written (DIR/judge.json for clef, DIR/judge.BY.json for an agent; every round in the
/// log), and said. `advice` marks a judge not yet trusted to gate (clef before calibration).
#[allow(clippy::too_many_arguments)]
@@ -133,8 +159,9 @@ fn finish(args: &[String], dir: &Path, scores: serde_json::Map<String, Value>, r
let vals: Vec<f64> = scores.values().filter_map(Value::as_f64).collect();
let mean = if vals.is_empty() { 0.0 } else { (vals.iter().sum::<f64>() / vals.len() as f64 * 100.0).round() / 100.0 };
let model = if by == "clef" { "@cf/cloudflare/clef-omni".to_string() } else { format!("{by} cli") };
let found = findings(&defects, by, advice);
let mut verdict = json!({"dir": dir.display().to_string(), "by": by, "scores": scores, "raw": raw, "mean": mean, "defects": defects, "photo": photo,
"pass": pass, "why": why, "gating": !advice, "cost": cost, "model": model});
"pass": pass, "why": why, "gating": !advice, "cost": cost, "model": model, "findings": found, "count": finding::count(&found)});
if let (Some(v), Some(e)) = (verdict.as_object_mut(), extra.as_object()) {
v.extend(e.clone());
}
@@ -155,15 +182,13 @@ fn finish(args: &[String], dir: &Path, scores: serde_json::Map<String, Value>, r
let who = if by == "clef" { String::new() } else { format!("({by}) ") };
let mut t = vec![format!("{} {who}{}{}", if pass { "PASS" } else { "NOT YET" }, if advice { "(advice: the judge isn't calibrated against your eye yet) " } else { "" }, why.join("; "))];
t.push(format!("scores: {}", scores.iter().map(|(k, v)| format!("{k} {v}")).collect::<Vec<_>>().join(", ")));
for d in verdict["defects"].as_array().into_iter().flatten().filter(|d| d["present"] == true) {
if by == "clef" {
t.push(format!(" {:<8} {} (p {}, {} sheet): {}", d["level"].as_str().unwrap_or(""), d["defect"].as_str().unwrap_or(""), d["p"], d["sheet"].as_str().unwrap_or(""), d["asked"].as_str().unwrap_or("")));
} else {
t.push(format!(" {:<8} {} tile: {} (fix: {})", d["level"].as_str().unwrap_or(""), d["sheet"].as_str().unwrap_or(""), d["asked"].as_str().unwrap_or(""), d["fix"].as_str().unwrap_or("")));
}
for f in &found {
let p = f.measure.as_ref().map(|m| format!(" (p {})", m.value)).unwrap_or_default();
t.push(format!(" {}{p}", f.line()));
}
let p = &verdict["progress"];
t.push(format!("round {}: {} passes in a row{}{}; ${cost:.4}", p["rounds"], p["passesInARow"], if p["done"] == true { ", done" } else { "" }, if p["stall"] == true { ", stalled: change the approach for the part, not the dose" } else { "" }));
t.push(format!("raea judge: {}", finding::count(&found)));
Ok(t.join("\n"))
}
+5
View File
@@ -69,4 +69,9 @@ fn an_agent_verdict_is_read_from_the_end_of_its_thinking() {
let (pass, why) = crate::rubric::pass(&scores, &defects);
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)"));
assert!(f.says.starts_with("iso sheet: "), "{}", f.says);
assert_eq!(crate::findings(&defects, "kimi", true)[0].level, raea_core_facts::Level::Warn);
}
+2
View File
@@ -15,3 +15,5 @@ raea-runtime-encode = { path = "../../runtime/encode" }
raea-io-media = { path = "../../io/media", default-features = false }
raea-page = { path = "../../engine/page" }
serde_json = "1"
# a model's lower levels of detail (lod.rs): the simplifier Bevy's meshlets use
meshopt = "0.6.2"
+9 -3
View File
@@ -1,9 +1,9 @@
//! The media verbs' command line (`raea media|ffmpeg|ffprobe`, and raea's shell, in process): the agent's media
//! work on raea-media (lib.rs and its files), and an HTML composition's render (html.rs).
//!
//! media probe|still|sheet|audio|loudness|motion|cuts|freezes|proxy|trim|concat FILE ... media work, native (media help)
//! media probe|still|sheet|audio|loudness|motion|cuts|freezes|proxy|lod|trim|concat FILE ... media work, native (media help)
//! ffmpeg ARGS | ffprobe ARGS ffmpeg and ffprobe command lines read as the media verbs (no ffmpeg involved)
//! render PAGE.html -o OUT.mp4|DIR [--at F,F] [--codec apple|soft|av1|ffmpeg] [--kbps K | --quality Q]
//! render PAGE.html -o OUT.mp4|OUT.png|DIR [--at F,F] [--alpha] [--codec apple|soft|av1|ffmpeg] [--kbps K | --quality Q]
//! shots [--size WxH] [--root DIR] plain HTML pages' first frames as PNGs, over white: stdin lines `PAGE\tOUT.png`,
//! one `ok OUT` or `err OUT: why` line each (bench/wpt's reftests)
@@ -53,8 +53,14 @@ fn run(args: Vec<String>) {
"render" => {
let out = PathBuf::from(flag("-o").unwrap_or_else(|| fail("render needs -o OUT.mp4|DIR")));
let frames = flag("--at").map(|at| at.split(',').map(|f| f.trim().parse().unwrap_or_else(|_| fail(format!("bad frame {f}")))).collect());
let opts = raea_runtime_encode::RenderOpts { frames, codec: flag("--codec"), kbps: flag("--kbps").and_then(|k| k.parse().ok()), quality: flag("--quality").map(|q| raea_io_media::parse_quality(&q).unwrap_or_else(|e| fail(e))), ssim: flag_on("--ssim"), sound: None, ten_bit: flag_on("--10bit") };
let opts = raea_runtime_encode::RenderOpts { frames, codec: flag("--codec"), kbps: flag("--kbps").and_then(|k| k.parse().ok()), quality: flag("--quality").map(|q| raea_io_media::parse_quality(&q).unwrap_or_else(|e| fail(e))), ssim: flag_on("--ssim"), sound: None, ten_bit: flag_on("--10bit"), alpha: flag_on("--alpha") };
if opts.alpha && out.extension().is_some_and(|x| x != "png") {
fail("--alpha writes PNGs (OUT.png or a folder): video here is H.264 or HEVC, which hold no alpha");
}
raea_runtime_encode::render_file(&arg(1), &out, &opts).unwrap_or_else(|e| fail(e));
if let Some(note) = raea_page::not_applied::said() {
println!("{note}");
}
}
"shots" => {
let size = flag("--size").map(|s| s.split_once('x').and_then(|(w, h)| Some((w.parse().ok()?, h.parse().ok()?))).unwrap_or_else(|| fail(format!("bad --size {s} (WxH)"))));
+1 -1
View File
@@ -170,7 +170,7 @@ pub(crate) fn ffmpeg(args: &[String]) -> R<()> {
if vf.is_some() {
return Err(format!("-vf on a still isn't read here: take the still (raea media still), then crop or scale it in an edit; {VERBS_HINT}"));
}
still(&path, from.unwrap_or(0.0), Path::new(&out))?;
still(&path, from.unwrap_or(0.0), Path::new(&out), None)?;
return Ok(());
}
// video: concat, trim, scale
+11 -4
View File
@@ -2,7 +2,7 @@
//! What agents used ffmpeg and ffprobe for, on raea-media (the platform's decoders and encoders, Symphonia's audio):
//!
//! raea media probe FILE duration, size, fps, codec, audio (JSON)
//! raea media still FILE --at S -o OUT.png|.jpg the frame showing at S
//! raea media still FILE --at S [--width W] -o OUT.png|.jpg the frame showing at S (an image: itself), W px wide at most
//! raea media sheet FILE... [--n 12] [--width 240] -o OUT a contact sheet (n frames of one file, or each file's middle)
//! raea media audio FILE [--rate 16000] [--mono] [--from S --to S] -o OUT.wav|- (- is f32le on stdout)
//! raea media loudness FILE [--from S --to S] integrated LUFS, mean and peak dB, true peak
@@ -10,6 +10,7 @@
//! raea media cuts FILE [--threshold 0.08] shot changes (ffmpeg's scene score)
//! raea media freezes FILE [--noise 0.001] [--min 2] held pictures (ffmpeg's freezedetect)
//! raea media proxy FILE [--height 720] -o OUT.mp4 a smaller copy
//! raea media lod MODEL.glb [--level 1] [--texture 1024] -o OUT.glb a model at a lower level of detail (triangles halved a level)
//! raea media trim FILE --from S --to S -o OUT.mp4 a stretch, frame-exact (re-encoded)
//! raea media concat A B ... -o OUT.mp4 one after another (same aspect)
//! raea media encode --size WxH [--fps 60] [--quality Q] [--audio FILE] -o OUT.mp4 raw RGBA frames on stdin, signed
@@ -28,6 +29,8 @@ use serde_json::{Value, json};
// `raea media|ffmpeg|ffprobe|render|shots` as one in-process command line
mod command;
pub use command::command;
/// a model at a lower level of detail (docs/preview.feature PV3c)
mod lod;
mod probe;
use probe::*;
mod picture;
@@ -86,11 +89,11 @@ fn num(fl: &BTreeMap<String, String>, k: &str) -> R<Option<f64>> {
}
/// The verbs `raea media` answers here.
pub const VERBS: &[&str] = &["probe", "still", "sheet", "audio", "loudness", "motion", "cuts", "freezes", "proxy", "trim", "concat", "encode", "help"];
pub const VERBS: &[&str] = &["probe", "still", "sheet", "audio", "loudness", "motion", "cuts", "freezes", "proxy", "lod", "trim", "concat", "encode", "help"];
pub fn cli(args: &[String]) -> i32 {
let Some(verb) = args.first() else {
println!("usage: raea media <probe|still|sheet|audio|loudness|motion|cuts|proxy|trim|concat|encode> FILE ... (raea media help)");
println!("usage: raea media <probe|still|sheet|audio|loudness|motion|cuts|proxy|lod|trim|concat|encode> FILE ... (raea media help)");
return 2;
};
let (pos, fl) = parse(&args[1..]);
@@ -116,7 +119,7 @@ fn run(verb: &str, pos: &[String], fl: &BTreeMap<String, String>) -> R<Option<Va
"probe" => probe(&file()?).map(Some),
"still" => {
let at = num(fl, "at")?.unwrap_or(0.0);
still(&file()?, at, &out()?).map(Some)
still(&file()?, at, &out()?, fl.get("width").and_then(|n| n.parse().ok())).map(Some)
}
"sheet" => {
let files: Vec<PathBuf> = pos.iter().map(PathBuf::from).collect();
@@ -158,6 +161,10 @@ fn run(verb: &str, pos: &[String], fl: &BTreeMap<String, String>) -> R<Option<Va
let (from, to) = range()?;
cuts(&file()?, th, from, to).map(|(v, _)| Some(v))
}
"lod" => {
let level = fl.get("level").and_then(|v| v.parse().ok()).unwrap_or(1);
lod::lod(&file()?, level, fl.get("texture").and_then(|v| v.parse().ok()).unwrap_or(1024), &out()?).map(Some)
}
"proxy" => {
let h = fl.get("height").and_then(|h| h.parse().ok()).unwrap_or(720);
encode(&[(file()?, None, None)], Some(h), &out()?, fl.get("kbps").and_then(|k| k.parse().ok())).map(Some)
+314
View File
@@ -0,0 +1,314 @@
//! `raea media lod MODEL.glb [--level 1] [--texture 1024] -o OUT.glb`: a model at a lower level of detail
//! (docs/preview.feature PV3c). Each level halves the triangles of every mesh (meshoptimizer's simplifier, on the
//! mesh's own vertices, so skins, morph targets, UVs and materials are untouched: only the index lists are replaced)
//! and its embedded pictures are made at most `--texture` px on their longer side. What nothing uses any more leaves
//! the file. A .glb with its buffer inside it only: a .gltf's separate files are left to their own tools.
use std::path::Path;
use serde_json::json;
use super::*;
const GLB: u32 = 0x4654_6c67;
const JSON: u32 = 0x4e4f_534a;
const BIN: u32 = 0x004e_4942;
/// The file's JSON and its binary chunk.
fn read(path: &Path) -> R<(Value, Vec<u8>)> {
let b = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
let u32_at = |i: usize| b.get(i..i + 4).map(|s| u32::from_le_bytes(s.try_into().unwrap()));
if u32_at(0) != Some(GLB) {
return Err(format!("{}: not a .glb (raea media lod reads a binary glTF with its buffer inside it)", path.display()));
}
let (mut at, mut doc, mut bin) = (12usize, None, Vec::new());
while let (Some(len), Some(kind)) = (u32_at(at), u32_at(at + 4)) {
let body = b.get(at + 8..at + 8 + len as usize).ok_or("the glb's chunk runs past its end")?;
match kind {
JSON => doc = Some(serde_json::from_slice::<Value>(body).map_err(|e| format!("the glb's JSON: {e}"))?),
BIN if bin.is_empty() => bin = body.to_vec(),
_ => {}
}
at += 8 + len as usize;
}
Ok((doc.ok_or("the glb has no JSON chunk")?, bin))
}
fn write(path: &Path, doc: &Value, bin: &[u8]) -> R<()> {
let mut text = serde_json::to_vec(doc).map_err(|e| e.to_string())?;
while text.len() % 4 != 0 {
text.push(b' ');
}
let mut bin = bin.to_vec();
while bin.len() % 4 != 0 {
bin.push(0);
}
let mut out = Vec::with_capacity(28 + text.len() + bin.len());
for v in [GLB, 2, (28 + text.len() + bin.len()) as u32, text.len() as u32, JSON] {
out.extend_from_slice(&v.to_le_bytes());
}
out.extend_from_slice(&text);
out.extend_from_slice(&(bin.len() as u32).to_le_bytes());
out.extend_from_slice(&BIN.to_le_bytes());
out.extend_from_slice(&bin);
std::fs::write(path, out).map_err(|e| format!("{}: {e}", path.display()))
}
fn n(v: &Value, k: &str) -> Option<usize> {
Some(v.get(k)?.as_u64()? as usize)
}
/// An accessor's bytes in the buffer: where they start, the step between elements, how many.
fn span(doc: &Value, acc: usize) -> Option<(usize, usize, usize, u64)> {
let a = doc["accessors"].get(acc)?;
if a.get("sparse").is_some() {
return None;
}
let view = doc["bufferViews"].get(n(a, "bufferView")?)?;
if n(view, "buffer").unwrap_or(0) != 0 {
return None;
}
let ty = a["componentType"].as_u64()?;
let size = match ty { 5120 | 5121 => 1, 5122 | 5123 => 2, _ => 4 } * match a["type"].as_str()? { "SCALAR" => 1, "VEC2" => 2, "VEC3" => 3, _ => 4 };
Some((n(view, "byteOffset").unwrap_or(0) + n(a, "byteOffset").unwrap_or(0), n(view, "byteStride").filter(|s| *s > 0).unwrap_or(size), n(a, "count")?, ty))
}
/// A view of `bytes` added at the end of the buffer (aligned to 4), and its index.
fn push_view(doc: &mut Value, bin: &mut Vec<u8>, bytes: &[u8], target: Option<u64>) -> usize {
while bin.len() % 4 != 0 {
bin.push(0);
}
let mut view = json!({"buffer": 0, "byteOffset": bin.len(), "byteLength": bytes.len()});
if let Some(t) = target {
view["target"] = json!(t);
}
bin.extend_from_slice(bytes);
let views = doc["bufferViews"].as_array_mut().unwrap();
views.push(view);
views.len() - 1
}
/// Every triangle list's indices simplified to `keep` of its triangles (never under 12): the triangles before and after.
fn simplify(doc: &mut Value, bin: &mut Vec<u8>, keep: f32) -> (usize, usize) {
let (mut before, mut after) = (0, 0);
// an index list several primitives share is simplified once (against the first one's positions), in its own
// accessor, so the old indices are left with nothing using them and leave the file
let mut done: std::collections::HashSet<usize> = Default::default();
let prims: Vec<(usize, usize)> = doc["meshes"].as_array().into_iter().flatten().enumerate().flat_map(|(m, mesh)| (0..mesh["primitives"].as_array().map_or(0, Vec::len)).map(move |p| (m, p))).collect();
for (m, p) in prims {
let prim = &doc["meshes"][m]["primitives"][p];
if prim.get("mode").and_then(Value::as_u64).unwrap_or(4) != 4 {
continue;
}
let (Some(ia), Some(pa)) = (n(prim, "indices"), n(&prim["attributes"], "POSITION")) else { continue };
if done.contains(&ia) {
continue;
}
let (Some((io, is, ic, ity)), Some((po, ps, pc, 5126))) = (span(doc, ia), span(doc, pa)) else { continue };
before += ic / 3;
let read = |i: usize| -> u32 {
let at = io + i * is;
match ity {
5121 => bin[at] as u32,
5123 => u16::from_le_bytes([bin[at], bin[at + 1]]) as u32,
_ => u32::from_le_bytes([bin[at], bin[at + 1], bin[at + 2], bin[at + 3]]),
}
};
if io + ic.saturating_sub(1) * is + 1 > bin.len() || po + pc * ps > bin.len() + ps - 12 {
continue;
}
let indices: Vec<u32> = (0..ic).map(read).collect();
let target = (((ic / 3) as f32 * keep) as usize).max(12).min(ic / 3) * 3;
// the positions as meshoptimizer reads them: a stride of bytes, three floats at its start
let positions = &bin[po..(po + pc * ps).min(bin.len())];
let positions: Vec<u8> = if positions.len() % ps == 0 { positions.to_vec() } else { (0..pc).flat_map(|v| bin[po + v * ps..po + v * ps + 12].to_vec()).collect() };
let stride = if positions.len() == pc * 12 { 12 } else { ps };
let Ok(adapter) = meshopt::VertexDataAdapter::new(&positions, stride, 0) else { continue };
// a loose error bound: the count is what a level asks for, the shape is kept as far as it allows
let out = meshopt::simplify(&indices, &adapter, target, 0.05, meshopt::SimplifyOptions::None, None);
let out = if out.len() >= 3 && out.len() < indices.len() { out } else { indices };
after += out.len() / 3;
let bytes: Vec<u8> = out.iter().flat_map(|i| i.to_le_bytes()).collect();
let view = push_view(doc, bin, &bytes, Some(34963));
doc["accessors"][ia] = json!({"bufferView": view, "componentType": 5125, "count": out.len(), "type": "SCALAR"});
done.insert(ia);
}
(before, after)
}
/// Each embedded PNG or JPEG longer than `max` px made that long, in its own format: how many were.
fn shrink_pictures(doc: &mut Value, bin: &mut Vec<u8>, max: u32) -> usize {
let mut made = 0;
for i in 0..doc["images"].as_array().map_or(0, Vec::len) {
let img = &doc["images"][i];
let (Some(view), Some(mime)) = (n(img, "bufferView"), img["mimeType"].as_str().map(str::to_string)) else { continue };
let v = &doc["bufferViews"][view];
let (at, len) = (n(v, "byteOffset").unwrap_or(0), n(v, "byteLength").unwrap_or(0));
let Some(bytes) = bin.get(at..at + len) else { continue };
let Ok(pic) = image::load_from_memory(bytes) else { continue };
if pic.width().max(pic.height()) <= max {
continue;
}
let k = max as f64 / pic.width().max(pic.height()) as f64;
let small = pic.resize_exact(((pic.width() as f64 * k).round() as u32).max(1), ((pic.height() as f64 * k).round() as u32).max(1), image::imageops::FilterType::CatmullRom);
let mut out = std::io::Cursor::new(Vec::new());
let wrote = if mime == "image/jpeg" { image::DynamicImage::ImageRgb8(small.to_rgb8()).write_to(&mut out, image::ImageFormat::Jpeg) } else { small.write_to(&mut out, image::ImageFormat::Png) };
if wrote.is_err() || (mime != "image/jpeg" && mime != "image/png") {
continue;
}
let view = push_view(doc, bin, out.get_ref(), None);
doc["images"][i]["bufferView"] = json!(view);
made += 1;
}
made
}
/// The buffer with only the views something still uses, the views numbered again.
fn compact(doc: &mut Value, bin: &[u8]) -> Vec<u8> {
let views = doc["bufferViews"].as_array().cloned().unwrap_or_default();
let mut used = vec![false; views.len()];
let mut mark = |v: &Value| {
if let Some(i) = n(v, "bufferView").filter(|i| *i < used.len()) {
used[i] = true;
}
};
for a in doc["accessors"].as_array().into_iter().flatten() {
mark(a);
mark(&a["sparse"]["indices"]);
mark(&a["sparse"]["values"]);
}
for i in doc["images"].as_array().into_iter().flatten() {
mark(i);
}
// anything an extension points at by "bufferView" stays too
fn walk(v: &Value, mark: &mut dyn FnMut(&Value)) {
match v {
Value::Object(m) => {
mark(v);
m.values().for_each(|x| walk(x, mark));
}
Value::Array(a) => a.iter().for_each(|x| walk(x, mark)),
_ => {}
}
}
walk(&doc["extensions"].clone(), &mut mark);
for m in doc["meshes"].as_array().into_iter().flatten() {
walk(&m["primitives"], &mut |v| if v.get("extensions").is_some() { walk(&v["extensions"], &mut |x| if let Some(i) = n(x, "bufferView").filter(|i| *i < used.len()) { used[i] = true }) });
}
let mut out = Vec::new();
let mut to = vec![usize::MAX; views.len()];
let mut kept = Vec::new();
for (i, v) in views.iter().enumerate().filter(|(i, _)| used[*i]) {
while out.len() % 4 != 0 {
out.push(0);
}
let (at, len) = (n(v, "byteOffset").unwrap_or(0), n(v, "byteLength").unwrap_or(0));
let mut v = v.clone();
v["byteOffset"] = json!(out.len());
out.extend_from_slice(bin.get(at..at + len).unwrap_or(&[]));
to[i] = kept.len();
kept.push(v);
}
fn renumber(v: &mut Value, to: &[usize]) {
match v {
Value::Object(m) => {
if let Some(i) = m.get("bufferView").and_then(Value::as_u64).map(|i| i as usize).filter(|i| *i < to.len() && to[*i] != usize::MAX) {
m.insert("bufferView".into(), json!(to[i]));
}
m.values_mut().for_each(|x| renumber(x, to));
}
Value::Array(a) => a.iter_mut().for_each(|x| renumber(x, to)),
_ => {}
}
}
doc["bufferViews"] = Value::Array(kept);
for k in ["accessors", "images", "meshes", "extensions"] {
if doc.get(k).is_some() {
renumber(&mut doc[k], &to);
}
}
doc["buffers"] = json!([{"byteLength": out.len()}]);
out
}
pub fn lod(path: &Path, level: u32, texture: u32, out: &Path) -> R<Value> {
let (mut doc, mut bin) = read(path)?;
if doc["buffers"].as_array().is_some_and(|b| b.len() > 1 || b.iter().any(|x| x.get("uri").is_some())) {
return Err(format!("{}: its buffers are separate files; raea media lod reads a .glb with its buffer inside it", path.display()));
}
let (before, after) = simplify(&mut doc, &mut bin, 0.5f32.powi(level.max(1) as i32));
let pictures = shrink_pictures(&mut doc, &mut bin, texture.max(16));
let bin = compact(&mut doc, &bin);
write(out, &doc, &bin)?;
let bytes = |p: &Path| std::fs::metadata(p).map(|m| m.len()).unwrap_or(0);
Ok(json!({"wrote": out, "level": level.max(1), "triangles": [before, after], "pictures_made_smaller": pictures, "bytes": [bytes(path), bytes(out)]}))
}
#[cfg(test)]
mod tests {
use super::*;
/// A flat grid of `n` by `n` squares as a .glb: positions and u16 indices, and a picture nothing shrinks.
fn grid(n: u16) -> (Value, Vec<u8>) {
let mut bin = Vec::new();
for y in 0..=n {
for x in 0..=n {
for v in [x as f32, 0.0, y as f32] {
bin.extend_from_slice(&v.to_le_bytes());
}
}
}
let verts = (n as usize + 1) * (n as usize + 1);
let index_at = bin.len();
let mut count = 0;
for y in 0..n {
for x in 0..n {
let a = y * (n + 1) + x;
for i in [a, a + 1, a + n + 1, a + 1, a + n + 2, a + n + 1] {
bin.extend_from_slice(&i.to_le_bytes());
count += 1;
}
}
}
let doc = json!({
"asset": {"version": "2.0"},
"buffers": [{"byteLength": bin.len()}],
"bufferViews": [{"buffer": 0, "byteOffset": 0, "byteLength": verts * 12}, {"buffer": 0, "byteOffset": index_at, "byteLength": count * 2}],
"accessors": [{"bufferView": 0, "componentType": 5126, "count": verts, "type": "VEC3"}, {"bufferView": 1, "componentType": 5123, "count": count, "type": "SCALAR"}],
"meshes": [{"primitives": [{"attributes": {"POSITION": 0}, "indices": 1}]}],
"nodes": [{"mesh": 0}], "scenes": [{"nodes": [0]}], "scene": 0,
});
(doc, bin)
}
#[test]
fn a_level_halves_the_triangles_and_the_old_indices_leave_the_file() {
let dir = std::env::temp_dir().join(format!("raea-lod-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let (doc, bin) = grid(16);
let (src, out) = (dir.join("grid.glb"), dir.join("grid.lod1.glb"));
write(&src, &doc, &bin).unwrap();
let said = lod(&src, 1, 1024, &out).unwrap();
let (before, after) = (said["triangles"][0].as_u64().unwrap(), said["triangles"][1].as_u64().unwrap());
assert_eq!(before, 512);
assert!(after <= 256 && after >= 12, "{after} triangles");
// read back: one index view (the new one), the positions as they were, every index a vertex of the mesh
let (doc, bin) = read(&out).unwrap();
assert_eq!(doc["bufferViews"].as_array().unwrap().len(), 2);
let (io, _, ic, ty) = span(&doc, doc["meshes"][0]["primitives"][0]["indices"].as_u64().unwrap() as usize).unwrap();
assert_eq!((ic as u64, ty), (after * 3, 5125));
assert!((0..ic).all(|i| u32::from_le_bytes(bin[io + i * 4..io + i * 4 + 4].try_into().unwrap()) < 289));
assert_eq!(doc["accessors"][0]["count"], 289);
let two = lod(&src, 2, 1024, &dir.join("grid.lod2.glb")).unwrap();
assert!(two["triangles"][1].as_u64().unwrap() <= 128);
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn a_file_that_is_not_a_glb_is_refused() {
let p = std::env::temp_dir().join(format!("raea-lod-not-{}.glb", std::process::id()));
std::fs::write(&p, b"plain text").unwrap();
assert!(lod(&p, 1, 1024, &p.with_extension("out.glb")).unwrap_err().contains("not a .glb"));
std::fs::remove_file(&p).ok();
}
}
+6 -1
View File
@@ -25,12 +25,17 @@ pub(crate) fn frame(path: &Path, t: f64) -> R<image::RgbaImage> {
to_image(d.frame_at(t)?)
}
pub fn still(path: &Path, at: f64, out: &Path) -> R<Value> {
/// `width`: the still made that wide (its height in proportion) when the picture is wider; never made bigger.
pub fn still(path: &Path, at: f64, out: &Path, width: Option<u32>) -> R<Value> {
let img = if IMAGE_EXTS.contains(&ext(path).as_str()) {
image::open(path).map_err(|e| format!("{}: {e}", path.display()))?.to_rgba8()
} else {
frame(path, at)?
};
let img = match width.filter(|w| *w > 0 && *w < img.width()) {
Some(w) => image::imageops::resize(&img, w, ((img.height() as f64 * w as f64 / img.width() as f64).round() as u32).max(1), image::imageops::FilterType::CatmullRom),
None => img,
};
save(&img, out)?;
Ok(json!({"wrote": out, "at": at, "width": img.width(), "height": img.height()}))
}
+21
View File
@@ -0,0 +1,21 @@
[package]
name = "raea-app-notes"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "A person's notes on a project as files the work is held to (docs/direction.feature DR5, DR6): `raea notes take`, `check`, `ls` and `post`"
[dependencies]
# Note and Ask, the project found by its .raea/project, and the world a note is an entity in
raea-core-facts = { path = "../../core/facts" }
# when a run of an ask's check was (UTC), as raea check stamps its record
raea-io-trace = { path = "../../io/trace" }
# what each ask has been through, kept as JSON (state.rs)
serde = { version = "1", features = ["derive"] }
serde_json = "1"
# the render a clip to sign is cut from, by its SHA-256 (check.rs)
sha2 = "0.10"
[dev-dependencies]
tempfile = "3"
+235
View File
@@ -0,0 +1,235 @@
//! `raea notes check` (docs/direction.feature DR6): each ask's check run as a rule on the work as it stands, through
//! `raea check`'s run (apps/direction, which the CLI lends). An ask's check must fail first: one that passes on its
//! first run is refused, as it isn't measuring the ask, and the work may change only once it has failed. What each run
//! found is kept (state.rs); `raea check` keeps it too, when it runs the notes' checks beside its rules. An ask the
//! person signs gets its clip cut here, from its composition's newest render.
use std::path::{Path, PathBuf};
use raea_core_facts::{Finding, Level, record};
/// A rule as `raea check` runs one: an ask's is one, run through the CLI's Runner.
pub use raea_core_facts::Rule;
use crate::state::{self, Clip, Failed, Run, State};
use crate::{Eval, Kept, R, place, quoted, read};
/// One composition's run: its file from the project (`#ID` after it where the file registers several), what the
/// rules found and which waited and for what, its newest render, its shots (name, first frame, end) and its rate.
pub struct Ran {
pub of: String,
pub found: Vec<Finding>,
pub waits: Vec<(String, String)>,
pub render: Option<Rendered>,
pub shots: Vec<(String, i64, Option<i64>)>,
pub fps: f64,
}
/// A composition's newest render: its file, whether the composition changed after it, and how many frames it drew.
pub struct Rendered {
pub out: PathBuf,
pub stale: bool,
pub frames: i64,
}
/// Runs rules on a project's compositions as `raea check` runs its own (taking its --composition, --render and
/// --no-render), every frame read when `whole` (a clip's shot is found in them).
pub type Runner = fn(&Path, &[Rule], &[String], bool) -> R<Vec<Ran>>;
/// An ask's rule's `by`, which its findings carry, so two asks that run one check are told apart.
pub fn by(id: &str) -> String {
format!("note {id}")
}
/// Whether `of`, the composition an ask names (its file from the project, `#ID` after it where the file registers
/// several), is the one a run names `named` (its file, and `#ID` when it has one): a file alone is any composition
/// in it.
pub fn is_of(of: &str, named: &str) -> bool {
let (file, id) = named.split_once('#').map_or((named, None), |(f, i)| (f, Some(i)));
match of.split_once('#') {
Some((f, i)) => f == file && id == Some(i),
None => of == file,
}
}
/// What ask `id`'s check found in a run.
fn found_by<'a>(ran: &'a [Ran], id: &str) -> impl Iterator<Item = &'a Finding> {
let by = by(id);
ran.iter().flat_map(|r| &r.found).filter(move |f| f.by == by)
}
/// Each note's file number with the note, for those that read.
fn numbered<'a>(project: &Path, notes: &'a [Kept]) -> Vec<(u32, &'a Kept, &'a raea_core_facts::Note)> {
notes.iter().filter_map(|k| Some((place(project, &project.join(&k.file))?.1, k, k.note.as_ref().ok()?))).collect()
}
/// The notes' asks that have a check, each as a rule: the ask's id (n3.2) and words, its check (a .ts check's path
/// from the note's folder, as a controller's is from its own), its values, `by` the ask; and each note that can't be
/// read, as a finding.
pub fn rules(project: &Path, notes: &[Kept]) -> (Vec<Rule>, Vec<Finding>) {
let bad = notes.iter().filter_map(|k| k.note.as_ref().err().map(|e| Finding::new("note", Level::Error, format!("raea can't read it: {e}"), "raea notes").about(k.file.display().to_string(), None))).collect();
let mut out = Vec::new();
for (number, k, n) in numbered(project, notes) {
for (i, a) in n.asks.iter().enumerate() {
let Some(c) = &a.check else { continue };
let check = if c.ends_with(".ts") { project.join(k.file.parent().unwrap_or(Path::new(""))).join(c).display().to_string() } else { c.clone() };
let id = state::id(number, i + 1);
out.push(Rule { by: by(&id), id, text: a.text.clone(), check, values: a.values.clone().unwrap_or_default(), level: None, of: a.of.clone() });
}
}
(out, bad)
}
/// What a run of the notes' rules says of each ask whose rule was among `rules` (`--only` runs one), kept in `s`: a
/// line for each, and whether one was refused (its first run passed).
pub fn settle(project: &Path, notes: &[Kept], rules: &[Rule], ran: &[Ran], stamp: &str, s: &mut State) -> (Vec<String>, bool) {
let commit = record::commit(project, ".");
let (mut out, mut refused) = (Vec::new(), false);
for (number, k, n) in numbered(project, notes) {
for (i, a) in n.asks.iter().enumerate() {
let id = state::id(number, i + 1);
let Some(check) = a.check.as_ref().filter(|_| rules.iter().any(|r| r.id == id)) else { continue };
let found = found_by(ran, &id).count();
let waits = ran.iter().flat_map(|r| &r.waits).find(|(r, _)| *r == id).map(|(_, w)| w.clone());
let run = Run { at: stamp.into(), commit: commit.clone(), found, waits: waits.clone().filter(|_| found == 0) };
let kept = s.entry(id.clone()).or_default();
let first = kept.failed.as_ref().is_none_or(|f| !state::same_check(a, f));
let head = format!("{id} {}: {}", k.file.display(), quoted(&a.text, 70));
out.push(match (&run.waits, found, first) {
(Some(w), _, _) => format!("{head}: waits for {w}"),
(None, 0, true) => {
refused = true;
kept.refused = Some(run.clone());
format!("{head}: refused: its check passes on the work as it stands, so it isn't measuring the ask; write one that fails now, before the work changes")
}
(None, 0, false) => format!("{head}: passing"),
(None, n, true) => {
kept.failed = Some(Failed { check: check.clone(), values: a.values.clone().unwrap_or_default(), run: run.clone() });
kept.refused = None;
format!("{head}: fails on the work as it stands ({n} finding{}): its check measures the ask, and the work may change now", if n == 1 { "" } else { "s" })
}
(None, n, false) => format!("{head}: failing ({n} finding{})", if n == 1 { "" } else { "s" }),
});
kept.last = Some(run);
}
}
(out, refused)
}
/// A file's SHA-256.
fn sha256(p: &Path) -> R<String> {
use sha2::{Digest, Sha256};
let mut f = std::fs::File::open(p).map_err(|e| format!("{}: {e}", p.display()))?;
let mut d = Sha256::new();
std::io::copy(&mut f, &mut d).map_err(|e| format!("{}: {e}", p.display()))?;
Ok(format!("{:x}", d.finalize()))
}
/// Frames `a` to `b` (the frame after its last) of `out` at `fps`, cut to `to` with ffmpeg.
fn cut(out: &Path, [a, b]: [i64; 2], fps: f64, to: &Path) -> R<()> {
if let Some(d) = to.parent() {
std::fs::create_dir_all(d).map_err(|e| format!("{}: {e}", d.display()))?;
}
let (from, len) = (format!("{:.4}", a as f64 / fps), format!("{:.4}", (b - a) as f64 / fps));
let args = ["-hide_banner", "-loglevel", "error", "-y", "-ss", &from, "-i"];
let o = std::process::Command::new("ffmpeg").args(args).arg(out).args(["-t", &len, "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac"]).arg(to).output().map_err(|e| format!("ffmpeg: {e}"))?;
if !o.status.success() {
return Err(format!("ffmpeg: {}", String::from_utf8_lossy(&o.stderr).trim()));
}
Ok(())
}
/// Each ask the person signs, its clip cut from its composition's newest render (again only when the render or the
/// frames changed), kept in `s`: a line for each.
pub fn clips(project: &Path, notes: &[Kept], ran: &[Ran], s: &mut State) -> Vec<String> {
let mut out = Vec::new();
for (number, k, n) in numbered(project, notes) {
for (i, a) in n.asks.iter().enumerate() {
let Some(p) = a.proof.as_ref().filter(|p| p.sign) else { continue };
let id = state::id(number, i + 1);
let head = format!("{id} {}: its clip", k.file.display());
let comp = match &a.of {
Some(of) => ran.iter().find(|r| is_of(of, &r.of)),
None if ran.len() == 1 => ran.first(),
None => {
out.push(format!("{head}: which composition? the project has {}: name one in the ask's `of`", ran.iter().map(|r| r.of.as_str()).collect::<Vec<_>>().join(", ")));
continue;
}
};
let Some(r) = comp else {
out.push(format!("{head}: no composition {} was checked", a.of.as_deref().unwrap_or("")));
continue;
};
let Some(render) = &r.render else {
out.push(format!("{head} waits for a render of {}", r.of));
continue;
};
// a render the composition changed after isn't the work: nothing is cut from it, and the clip kept from it
// (what the person signed, if they did) is marked so, until it's rendered again
if render.stale {
if let Some(c) = s.get_mut(&id).and_then(|k| k.clip.as_mut()) {
c.stale = true;
}
out.push(format!("{head} waits for a render of {} as it stands: it changed after its newest render", r.of));
continue;
}
let frames = match (p.frames, &p.shot) {
(Some(f), _) => f,
(None, Some(shot)) => match r.shots.iter().find(|(name, ..)| name == shot) {
Some((_, from, to)) => [*from, to.unwrap_or(render.frames)],
None => {
out.push(format!("{head}: {} has no shot named {shot}", r.of));
continue;
}
},
(None, None) => [0, render.frames],
};
let hash = match sha256(&render.out) {
Ok(h) => h,
Err(e) => {
out.push(format!("{head}: {e}"));
continue;
}
};
let kept = s.entry(id.clone()).or_default();
let file = project.join(".raea/notes-clips").join(format!("{id}.mp4"));
let same = kept.clip.as_ref().is_some_and(|c| c.render == hash && c.frames == frames && c.file.is_file());
if !same {
if let Err(e) = cut(&render.out, frames, r.fps, &file) {
out.push(format!("{head}: {e}"));
continue;
}
}
kept.clip = Some(Clip { file: file.clone(), of: r.of.clone(), render: hash, frames, stale: false });
out.push(format!("{head}, frames {}-{} of {}, {} from its newest render", frames[0], frames[1] - 1, r.of, if same { "kept" } else { "cut" }));
}
}
out
}
/// `raea notes check`: each ask's check on the work as it stands, and each clip to sign cut; 1 when an ask was
/// refused or a note can't be read.
pub(crate) fn check(project: &Path, args: &[String], eval: Eval, run: Runner) -> R<(String, i32)> {
let notes = read(project, eval);
let (rules, bad) = rules(project, &notes);
let signs = notes.iter().filter_map(|k| k.note.as_ref().ok()).flat_map(|n| &n.asks).any(|a| a.proof.as_ref().is_some_and(|p| p.sign));
let mut out: Vec<String> = bad.iter().map(Finding::line).collect();
if rules.is_empty() && !signs {
out.push("no ask has a check or a clip to sign yet: restate the notes' asks with one each (raea notes ls)".into());
return Ok((out.join("\n"), i32::from(!bad.is_empty())));
}
let ran = run(project, &rules, args, signs)?;
let stamp = raea_io_trace::utc(std::time::SystemTime::now()).1;
let mut s = state::read(project);
let (lines, refused) = settle(project, &notes, &rules, &ran, &stamp, &mut s);
// each ask's line, then what its check found
for l in lines {
let id = l.split(' ').next().unwrap_or("").to_string();
out.push(l);
out.extend(found_by(&ran, &id).map(|f| format!(" {}", f.line())));
}
out.extend(clips(project, &notes, &ran, &mut s));
state::write(project, &s)?;
let tally = crate::tally(project, &notes, &s);
out.push(tally);
Ok((out.join("\n"), i32::from(refused || !bad.is_empty())))
}
+188
View File
@@ -0,0 +1,188 @@
//! A person's notes on a project (docs/direction.feature DR5, DR6). `raea notes take` writes each note the person
//! sends from the raea app (an edit comment with its pin, or a note on an item) or says in a session to a file,
//! notes/<round>/<id>.ts, with their words verbatim and no asks. The agent restates each as its asks before anything
//! in the work changes, each with a check, or a clip for the person to sign. `raea notes check` runs each ask's check
//! on the work as it stands, which must fail first, and `raea notes ls` says where each note and ask stands and what
//! its restatement still owes. `raea notes post` shows the asks and where they stand on the person's comments in the
//! app, and their corrections and signs come back with the next take. In a project's world each note is an entity
//! with a Note.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use raea_core_facts::{Facts, Note, record};
use serde_json::json;
pub mod check;
mod post;
pub mod state;
mod take;
pub const USAGE: &str = "raea notes take [PROJECT] [--inbox NAME] [--said WORDS]... | raea notes check [PROJECT] [--composition ID] [--render OUT | --no-render] | raea notes ls [PROJECT] [--json] | raea notes post [PROJECT] (a person's notes as files the work is held to: take writes each note sent from the raea app or said in a session to notes/ROUND/ID.ts, the words verbatim, to be restated as asks before anything changes, and writes in each correction and sign the person sent back; check runs each ask's check on the work as it stands, which must fail before the work changes (a check that passes first is refused), and cuts each clip the person is to sign from the newest render; ls says where each note and ask stands (to restate, to check, failing, to sign, passing, signed) and what its restatement still owes; post shows each note's asks and where they stand on its comment in the raea app, and each clip to sign)";
/// Evaluates a .ts file's default export to its JSON (the CLI's spec host).
pub type Eval = fn(&Path) -> Result<String, String>;
pub(crate) type R<T> = Result<T, String>;
/// The flags `raea notes` takes, and whether each takes a value.
const FLAGS: [(&str, bool); 6] = [("--inbox", true), ("--said", true), ("--json", false), ("--composition", true), ("--render", true), ("--no-render", false)];
/// One note file: where it is in the project, and the note, or why it can't be read.
pub struct Kept {
pub file: PathBuf,
pub note: R<Note>,
}
/// `raea notes VERB ...`, printed; its exit code (1: a note that can't be read, or an ask's check refused; 2: the
/// command was wrong). `run` is `raea check`'s run of rules on the project's compositions (apps/direction).
pub fn cli(args: &[String], eval: Eval, run: check::Runner) -> i32 {
match go(args, eval, run) {
Ok((out, code)) => {
println!("{out}");
code
}
Err(e) => {
eprintln!("raea notes: {e}");
2
}
}
}
fn go(args: &[String], eval: Eval, run: check::Runner) -> R<(String, i32)> {
let Some(verb) = args.first().map(String::as_str).filter(|v| !matches!(*v, "--help" | "-h" | "help")) else {
return Ok((USAGE.into(), 0));
};
let rest = &args[1..];
let mut target = None;
let mut it = rest.iter();
while let Some(a) = it.next() {
match FLAGS.iter().find(|(f, _)| f == a) {
Some((_, true)) => {
it.next().ok_or_else(|| format!("{a} takes a value\n{USAGE}"))?;
}
Some(_) => {}
None if a.starts_with("--") => return Err(format!("no flag {a}\n{USAGE}")),
None if target.is_none() => target = Some(a.as_str()),
None => return Err(format!("one project at a time ({a} is a second)\n{USAGE}")),
}
}
let target = target.unwrap_or(".");
let project = record::up(Path::new(target), ".raea/project").ok_or_else(|| format!("{target} isn't in a raea project (no .raea/project at or above it)\n{USAGE}"))?;
match verb {
"take" => take::take(&project, rest).map(|s| (s, 0)),
"ls" => Ok(ls(&project, rest.iter().any(|a| a == "--json"), eval)),
"check" => check::check(&project, rest, eval, run),
"post" => Ok(post::post(&project, eval, post::run_raea)),
v => Err(format!("no verb {v}\n{USAGE}")),
}
}
/// The values a flag was given, in order.
pub(crate) fn values<'a>(args: &'a [String], flag: &str) -> Vec<&'a str> {
args.iter().zip(args.iter().skip(1)).filter_map(|(f, v)| (f == flag).then_some(v.as_str())).collect()
}
/// A note file's round and number: notes/2/n7.ts is (2, 7); anything else under notes/ isn't a note.
pub(crate) fn place(project: &Path, f: &Path) -> Option<(u32, u32)> {
let rel = f.strip_prefix(project.join("notes")).ok()?;
let round = rel.parent()?.to_str()?.parse().ok()?;
let n = rel.file_name()?.to_str()?.strip_prefix('n')?.strip_suffix(".ts")?.parse().ok()?;
Some((round, n))
}
/// The project's note files, by round and number.
pub fn files(project: &Path) -> Vec<PathBuf> {
let dirs = std::fs::read_dir(project.join("notes")).into_iter().flatten().flatten().map(|e| e.path());
let mut out: Vec<((u32, u32), PathBuf)> = dirs.flat_map(|d| std::fs::read_dir(d).into_iter().flatten().flatten().map(|e| e.path())).filter_map(|f| Some((place(project, &f)?, f))).collect();
out.sort();
out.into_iter().map(|(_, f)| f).collect()
}
/// Every note in the project, read through its file's default export.
pub fn read(project: &Path, eval: Eval) -> Vec<Kept> {
let of = |f: &Path| eval(f).and_then(|j| serde_json::from_str::<Note>(&j).map_err(|e| format!("not a note ({e})")));
files(project).into_iter().map(|f| Kept { note: of(&f), file: f.strip_prefix(project).map(Path::to_path_buf).unwrap_or(f) }).collect()
}
/// The notes as entities in a world, one with a Note each.
pub fn spawn(world: &mut Facts, notes: &[Kept]) {
for n in notes.iter().filter_map(|k| k.note.as_ref().ok()) {
let e = world.spawn(None);
world.put(e, n);
}
}
/// A note's first line, quoted and cut to `n` characters.
pub(crate) fn quoted(words: &str, n: usize) -> String {
let line = words.lines().next().unwrap_or("").trim();
if line.chars().count() > n { format!("\"{}…\"", line.chars().take(n).collect::<String>().trim_end()) } else { format!("\"{line}\"") }
}
/// Each note's number (its file's: n7 is 7), where it stands and each of its asks'.
fn standings(project: &Path, n: &Note, file: &Path, s: &state::State) -> (u32, state::Standing, Vec<state::Standing>) {
let number = place(project, &project.join(file)).map_or(0, |p| p.1);
let (note, asks) = state::of_note(n, number, s);
(number, note, asks)
}
/// How many notes stand where: "5 notes: 2 failing, 1 to restate".
pub(crate) fn tally(project: &Path, notes: &[Kept], s: &state::State) -> String {
let mut t: BTreeMap<&str, usize> = BTreeMap::new();
for k in notes {
*t.entry(k.note.as_ref().map_or("can't be read", |n| standings(project, n, &k.file, s).1.word())).or_default() += 1;
}
let counts: Vec<String> = t.iter().map(|(s, c)| format!("{c} {s}")).collect();
format!("{} note{}: {}", notes.len(), if notes.len() == 1 { "" } else { "s" }, counts.join(", "))
}
/// `raea notes ls`: each note with where it stands, each ask with its id and where it stands, and what its
/// restatement still owes; 1 when a note can't be read.
fn ls(project: &Path, as_json: bool, eval: Eval) -> (String, i32) {
let notes = read(project, eval);
let s = state::read(project);
let code = i32::from(notes.iter().any(|k| k.note.is_err()));
if as_json {
let v: Vec<_> = notes
.iter()
.map(|k| match &k.note {
Ok(n) => {
let (number, note, asks) = standings(project, n, &k.file, &s);
let each: Vec<_> = asks.iter().enumerate().map(|(i, a)| json!({ "id": state::id(number, i + 1), "state": a.word(), "says": a.said() })).collect();
json!({ "file": k.file, "note": n, "state": note.word(), "asks": each, "flags": n.flags() })
}
Err(e) => json!({ "file": k.file, "error": e }),
})
.collect();
return (serde_json::to_string_pretty(&v).unwrap_or_default(), code);
}
if notes.is_empty() {
return ("no notes yet: `raea notes take` writes each one the person sends from the raea app or says".into(), 0);
}
let mut out = Vec::new();
let mut restate = false;
for k in &notes {
let file = k.file.display();
let Ok(n) = &k.note else {
out.push(format!("{file}: can't be read: {}", k.note.as_ref().err().map_or("", String::as_str)));
continue;
};
let (number, note, asks) = standings(project, n, &k.file, &s);
restate |= note == state::Standing::ToRestate;
out.push(format!("{file}: round {}, {}: {}", n.round, note.word(), quoted(n.words.first().map_or("", String::as_str), 90)));
for (i, (a, st)) in n.asks.iter().zip(&asks).enumerate() {
let medium = a.medium.as_deref().map(|m| format!(" [{m}]")).unwrap_or_default();
let not = if a.not.is_empty() { String::new() } else { format!("; not: {}", a.not.join(", ")) };
out.push(format!(" {} {}{medium}{not}: {}", state::id(number, i + 1), a.text, st.said()));
}
out.extend(n.flags().into_iter().map(|f| format!(" ! {f}")));
}
out.push(tally(project, &notes, &s));
if restate {
out.push(take::RESTATE.into());
}
(out.join("\n"), code)
}
#[cfg(test)]
mod tests;
+140
View File
@@ -0,0 +1,140 @@
//! `raea notes post`: each note sent from the raea app gets where it stands shown on its comment (DR5, DR6), through
//! `raea show --on ITEM --working COMMENT`: its asks once restated (`--ask TEXT...`), for the person to correct one in
//! a word, which `raea notes take` writes into the note to be restated again; the note's state for the comment's
//! badge and each ask's (`--status S --states S1,S2`: to restate, to check, failing, to sign, passing, signed); and
//! each clip the person is to sign, under its ask (`--sign N --clip FILE --render HASH`). "done" is never the agent's:
//! a note closes when the person retires it.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use crate::state::{self, Standing};
use crate::{Eval, R, place, read};
/// What was last shown for each note, by where it came from (`.raea/notes-shown.json`): its asks, its states and its
/// clips. A note shown so already isn't shown again, so a comment isn't marked working again for nothing.
fn shown_at(project: &Path) -> PathBuf {
project.join(".raea/notes-shown.json")
}
/// The note from `from` as not shown: the person corrected it, so its next restatement is shown even in the same words
/// (the app takes new asks as the answer to their correction).
pub(crate) fn forget(project: &Path, from: &str) -> R<()> {
let f = shown_at(project);
let Ok(t) = std::fs::read_to_string(&f) else { return Ok(()) };
let mut shown: BTreeMap<String, Vec<String>> = serde_json::from_str(&t).unwrap_or_default();
if shown.remove(from).is_some() {
let t = serde_json::to_string_pretty(&shown).map_err(|e| e.to_string())?;
std::fs::write(&f, t + "\n").map_err(|e| format!("{}: {e}", f.display()))?;
}
Ok(())
}
/// Runs raea with these arguments: what it printed, or why it failed.
pub type Run = fn(&[String]) -> R<String>;
/// This raea, run again with `args`.
pub fn run_raea(args: &[String]) -> R<String> {
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let out = std::process::Command::new(exe).args(args).output().map_err(|e| e.to_string())?;
let said = |b: &[u8]| String::from_utf8_lossy(b).trim().to_string();
if out.status.success() { Ok(said(&out.stdout)) } else { Err(said(&out.stderr).lines().last().unwrap_or("raea show failed").to_string()) }
}
/// The item and comment a note sent from the app came from ("app ITEM cm-N"); a note on an item as a whole has none.
pub(crate) fn comment_of(from: &str) -> Option<(&str, &str)> {
let mut it = from.strip_prefix("app ")?.split(' ');
let (item, comment) = (it.next()?, it.next()?);
(comment.starts_with("cm-") && it.next().is_none()).then_some((item, comment))
}
/// The arguments that show a note on its comment: its asks (none while it's to restate), its state and each ask's.
pub(crate) fn args(item: &str, comment: &str, asks: &[&str], status: &str, states: &[&str]) -> Vec<String> {
let mut a: Vec<String> = ["show", "--on", item, "--working", comment].map(String::from).to_vec();
a.extend(asks.iter().flat_map(|t| ["--ask".to_string(), t.to_string()]));
a.extend(["--status".to_string(), status.to_string()]);
if !states.is_empty() {
a.extend(["--states".to_string(), states.join(",")]);
}
a
}
/// `raea notes post`: what was shown where, and what wasn't and why; 1 when one couldn't be posted.
pub(crate) fn post(project: &Path, eval: Eval, run: Run) -> (String, i32) {
let mut out = Vec::new();
let mut code = 0;
let mut shown: BTreeMap<String, Vec<String>> = std::fs::read_to_string(shown_at(project)).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default();
let before = shown.clone();
let kept = state::read(project);
for k in read(project, eval) {
let file = k.file.display().to_string();
let n = match k.note {
Ok(n) => n,
Err(e) => {
out.push(format!("{file}: can't be read: {e}"));
code = 1;
continue;
}
};
let Some((item, comment)) = comment_of(&n.from) else {
if n.from.starts_with("app ") {
out.push(format!("{file}: a note on its item as a whole has no comment to show its asks on: say them to the person"));
}
continue;
};
let number = place(project, &project.join(&k.file)).map_or(0, |p| p.1);
let owed = n.flags();
let (standing, each) = state::of_note(&n, number, &kept);
// a restatement that still owes something isn't shown: the comment reads "to restate" until it's whole
let whole = n.state() != "to restate" && owed.is_empty();
let asks: Vec<&str> = if whole { n.asks.iter().map(|a| a.text.as_str()).collect() } else { Vec::new() };
let status = if whole { standing.word() } else { "to restate" };
let states: Vec<&str> = if whole { each.iter().map(Standing::word).collect() } else { Vec::new() };
// each clip the person is to sign, under its ask: (its number, file, render)
let clips: Vec<(usize, String, String)> = if whole {
each.iter().enumerate().filter(|(_, s)| matches!(s, Standing::ToSign(_))).filter_map(|(i, _)| {
let c = kept.get(&state::id(number, i + 1))?.clip.as_ref().filter(|c| !c.stale)?;
Some((i + 1, c.file.display().to_string(), c.render.clone()))
}).collect()
} else {
Vec::new()
};
let mut said: Vec<String> = asks.iter().map(|a| a.to_string()).collect();
said.push(format!("status {status} {}", states.join(",")));
said.extend(clips.iter().map(|(i, _, h)| format!("clip {i} {h}")));
if shown.get(&n.from) == Some(&said) {
out.push(format!("{file}: shown on {comment} of {item} as it stands already ({status})"));
continue;
}
let mut calls = vec![args(item, comment, &asks, status, &states)];
calls.extend(clips.iter().map(|(i, f, h)| ["show", "--on", item, "--working", comment, "--sign", &i.to_string(), "--clip", f, "--render", h].map(String::from).to_vec()));
match calls.iter().try_for_each(|a| run(a).map(|_| ())) {
Ok(()) => {
let what = match (asks.len(), whole) {
(_, false) if owed.is_empty() => "to restate".to_string(),
(_, false) => format!("to restate: its restatement still owes: {}", owed.join("; ")),
(1, true) => format!("its ask, {status}"),
(n, true) => format!("its {n} asks, {status}"),
};
let signs = if clips.is_empty() { String::new() } else { format!(", with {} clip{} to sign", clips.len(), if clips.len() == 1 { "" } else { "s" }) };
out.push(format!("{file}: shown on {comment} of {item}: {what}{signs}"));
shown.insert(n.from.clone(), said);
}
Err(e) => {
out.push(format!("{file}: not posted: {e}"));
code = 1;
}
}
}
if shown != before {
let written = serde_json::to_string_pretty(&shown).map_err(|e| e.to_string()).and_then(|t| std::fs::write(shown_at(project), t + "\n").map_err(|e| e.to_string()));
if let Err(e) = written {
out.push(format!("what was shown isn't kept ({}: {e}): the next post shows these again", shown_at(project).display()));
code = 1;
}
}
if out.is_empty() {
out.push("no notes from the raea app to post: `raea notes ls` lists them".into());
}
(out.join("\n"), code)
}
+191
View File
@@ -0,0 +1,191 @@
//! What each ask has been through (docs/direction.feature DR6), kept in the project's .raea/notes-checks.json by its
//! id (n3.2: note 3's second ask): its check and values as they first failed on the work, the run before that if it
//! passed (refused: it wasn't measuring the ask), its last run, the clip cut for the person to sign and their sign.
//! From these and the note, each ask reads to check, failing, to sign, passing or signed, and the note its worst.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use raea_core_facts::{Ask, Note};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use crate::R;
/// A run of an ask's check: when (UTC), the project's commit ("+" when not all of it was committed), what it found,
/// and what it waited for instead, when it did.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct Run {
pub at: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub commit: Option<String>,
pub found: usize,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub waits: Option<String>,
}
/// An ask's check as it first failed: the check, its values, and that run.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Failed {
pub check: String,
#[serde(default, skip_serializing_if = "Map::is_empty")]
pub values: Map<String, Value>,
pub run: Run,
}
/// The clip cut for an ask the person signs: its file, the composition, the render it was cut from (its SHA-256),
/// the frames, and whether the composition changed after that render.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Clip {
pub file: PathBuf,
pub of: String,
pub render: String,
pub frames: [i64; 2],
#[serde(default)]
pub stale: bool,
}
/// The person's sign on a clip: their name (none when the app had no account to name), the render they watched, and
/// when.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Sign {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
pub render: String,
pub at: String,
}
/// What one ask has been through.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct Kept {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub failed: Option<Failed>,
/// its check's first run, when it passed: refused, as it wasn't measuring the ask
#[serde(default, skip_serializing_if = "Option::is_none")]
pub refused: Option<Run>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last: Option<Run>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub clip: Option<Clip>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub signed: Option<Sign>,
}
/// Every ask's, by its id.
pub type State = BTreeMap<String, Kept>;
fn path(project: &Path) -> PathBuf {
project.join(".raea/notes-checks.json")
}
pub fn read(project: &Path) -> State {
std::fs::read_to_string(path(project)).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default()
}
pub fn write(project: &Path, s: &State) -> R<()> {
let f = path(project);
if let Some(d) = f.parent() {
std::fs::create_dir_all(d).map_err(|e| format!("{}: {e}", d.display()))?;
}
let t = serde_json::to_string_pretty(s).map_err(|e| e.to_string())?;
std::fs::write(&f, t + "\n").map_err(|e| format!("{}: {e}", f.display()))
}
/// An ask's id: the note's number and the ask's (1 is the first).
pub fn id(note: u32, ask: usize) -> String {
format!("n{note}.{ask}")
}
/// Where an ask stands, the word the app's badge shows, and why when that isn't plain.
#[derive(Debug, Clone, PartialEq)]
pub enum Standing {
ToRestate,
ToCheck(String),
Failing(usize),
ToSign(String),
Passing,
Signed(Option<String>),
}
impl Standing {
pub fn word(&self) -> &'static str {
match self {
Standing::ToRestate => "to restate",
Standing::ToCheck(_) => "to check",
Standing::Failing(_) => "failing",
Standing::ToSign(_) => "to sign",
Standing::Passing => "passing",
Standing::Signed(_) => "signed",
}
}
/// The word, and why or by whom.
pub fn said(&self) -> String {
match self {
Standing::ToCheck(why) | Standing::ToSign(why) => format!("{}: {why}", self.word()),
Standing::Failing(n) => format!("failing ({n} finding{})", if *n == 1 { "" } else { "s" }),
Standing::Signed(Some(name)) => format!("signed by {name}"),
Standing::Signed(None) => "signed (unnamed: the app had no account)".into(),
_ => self.word().into(),
}
}
/// How far it is from settled: the note reads its asks' worst.
fn rank(&self) -> u8 {
match self {
Standing::ToRestate => 5,
Standing::ToCheck(_) => 4,
Standing::Failing(_) => 3,
Standing::ToSign(_) => 2,
Standing::Passing => 1,
Standing::Signed(_) => 0,
}
}
}
/// Whether the check an ask names now is the one that failed first (its check and its values).
pub fn same_check(a: &Ask, f: &Failed) -> bool {
a.check.as_deref() == Some(f.check.as_str()) && a.values.clone().unwrap_or_default() == f.values
}
/// Where an ask stands, from the ask and what it has been through.
pub fn standing(a: &Ask, k: Option<&Kept>) -> Standing {
let sign = a.proof.as_ref().is_some_and(|p| p.sign);
if a.check.is_none() && !sign {
return Standing::ToCheck("no check, and no clip to sign".into());
}
if a.check.is_some() {
let failed = k.and_then(|k| k.failed.as_ref());
match (failed, k.and_then(|k| k.last.as_ref())) {
(Some(f), _) if !same_check(a, f) => return Standing::ToCheck("its check changed since it failed: show the new one failing (raea notes check)".into()),
(Some(_), Some(Run { waits: Some(w), .. })) => return Standing::ToCheck(format!("its check waits for {w}")),
(Some(_), Some(r)) if r.found > 0 => return Standing::Failing(r.found),
(Some(_), _) => {}
(None, _) if k.and_then(|k| k.refused.as_ref()).is_some() => return Standing::ToCheck("its check passed on its first run, so it isn't measuring the ask: write one that fails on the work as it stands".into()),
(None, Some(Run { waits: Some(w), .. })) => return Standing::ToCheck(format!("its check waits for {w}")),
(None, _) => return Standing::ToCheck("its check isn't shown failing on the work yet (raea notes check)".into()),
}
if !sign {
return Standing::Passing;
}
}
let clip = k.and_then(|k| k.clip.as_ref());
match (clip, k.and_then(|k| k.signed.as_ref())) {
// the agent's move until there's a clip of the work as it stands: to check, not the person's to sign
(None, _) => Standing::ToCheck("no clip yet: render, and raea notes check cuts it from the newest render".into()),
(Some(c), _) if c.stale => Standing::ToCheck(format!("{} changed after the render its clip is cut from: render it again", c.of)),
(Some(c), Some(s)) if s.render == c.render => Standing::Signed(s.name.clone()),
(Some(_), Some(s)) => Standing::ToSign(format!("{} signed an older render; its clip is new", s.name.as_deref().unwrap_or("the person"))),
(Some(_), None) => Standing::ToSign("its clip waits on the person (raea notes post shows it)".into()),
}
}
/// Each ask of a note with where it stands, and the note's: to restate, else its asks' worst.
pub fn of_note(n: &Note, number: u32, s: &State) -> (Standing, Vec<Standing>) {
let asks: Vec<Standing> = n.asks.iter().enumerate().map(|(i, a)| standing(a, s.get(&id(number, i + 1)))).collect();
if n.state() == "to restate" {
return (Standing::ToRestate, asks);
}
let worst = asks.iter().max_by_key(|a| a.rank()).cloned().unwrap_or(Standing::ToRestate);
(worst, asks)
}
+289
View File
@@ -0,0 +1,289 @@
//! `raea notes take`: what the person sent from the raea app to this project (the inbox lines it wrote: each edit
//! comment of a send, with its pin, or a note on an item) and what they said in a session (`--said`), each written
//! as a note file with their words verbatim and no asks, all in one new round. A note already taken isn't taken again.
//! What the person sends back on a restated note comes the same way: a correction, written into its note (DR5), and
//! a sign on an ask's clip, kept with what that ask has been through (state.rs, DR6).
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use raea_core_facts::{Pin, note};
use serde_json::Value;
use crate::{R, files, place, quoted, state, values};
/// What a note asks of the agent before anything changes, said where notes are taken and listed.
pub(crate) const RESTATE: &str = "restate each note before changing anything: one ask for each thing it asks for, the medium where its words name one (2D, 3D, flat, extruded, real, modelled, voxel), what it is about, and what it doesn't ask for (`not`), so a change keeps the rest";
/// A note to write: the person's words, where they came from, its pin, and where it was as the app said it.
pub(crate) struct New {
pub words: String,
pub from: String,
pub pin: Option<Pin>,
pub at: Option<String>,
}
/// Where the raea app writes what the person sends (the app's host, inbox.ts).
fn inbox_dir() -> PathBuf {
match std::env::var_os("RAEA_INBOX_DIR") {
Some(dir) => dir.into(),
None => Path::new(&std::env::var_os("HOME").unwrap_or_default()).join(".raea/inbox"),
}
}
/// The app's pin ({kind: "place", x, y, t, part} or {kind: "time", t}) as a note's.
fn pin_of(v: &Value) -> Option<Pin> {
v.is_object().then(|| Pin { t: v["t"].as_f64(), x: v["x"].as_f64(), y: v["y"].as_f64(), part: v["part"].as_str().map(Into::into) })
}
/// The notes in one inbox line sent to `project`: each comment of a send of edits, or a note on an item.
pub(crate) fn of_line(v: &Value, project: &str) -> Vec<New> {
if v["project"].as_str() != Some(project) {
return Vec::new();
}
let item = v["item"].as_str().unwrap_or("");
let said = |v: &Value| v.as_str().map(str::trim).filter(|s| !s.is_empty()).map(String::from);
match v["kind"].as_str() {
// a send's own text is its comments listed again
Some("edits") => v["comments"].as_array().into_iter().flatten().filter_map(|c| {
Some(New { words: said(&c["text"])?, from: format!("app {item} {}", c["id"].as_str()?), pin: pin_of(&c["pin"]), at: said(&c["at"]) })
}).collect(),
Some("note") => said(&v["text"]).map(|words| New { words, from: format!("app {item} {}", v["when"].as_str().unwrap_or("")), pin: pin_of(&v["pin"]), at: None }).into_iter().collect(),
_ => Vec::new(),
}
}
/// A correction the person made in the app to a restated note: the note (by where it came from), the ask (1 is the
/// first; none: the note as a whole), and their line.
pub(crate) struct Correction {
pub from: String,
pub ask: u32,
pub text: String,
}
/// The correction in one inbox line sent to `project`, if it is one.
pub(crate) fn correction_of(v: &Value, project: &str) -> Option<Correction> {
if v["project"].as_str() != Some(project) || v["kind"].as_str() != Some("correction") {
return None;
}
let text = v["text"].as_str().map(str::trim).filter(|t| !t.is_empty())?;
let ask = v["ask"].as_u64().and_then(|n| u32::try_from(n).ok()).unwrap_or(0);
Some(Correction { from: format!("app {} {}", v["item"].as_str()?, v["comment"].as_str()?), ask, text: text.into() })
}
/// Where the list that opens at `open` (its `[`) in `t` closes, past what is quoted in it.
fn close_of(t: &str, open: usize) -> Option<usize> {
let (mut depth, mut quote, mut escaped) = (0, None, false);
for (i, c) in t[open..].char_indices() {
match (quote, c) {
(Some(_), _) if escaped => escaped = false,
(Some(_), '\\') => escaped = true,
(Some(q), c) if c == q => quote = None,
(Some(_), _) => {}
(None, '"' | '\'' | '`') => quote = Some(c),
(None, '[') => depth += 1,
(None, ']') => {
depth -= 1;
if depth == 0 {
return Some(open + i);
}
}
_ => {}
}
}
None
}
/// A note file's text with the person's correction added: their line last in its words, and its ask in `corrected`.
/// None when the file has no words list or asks to add them beside.
pub(crate) fn corrected(t: &str, c: &Correction) -> Option<String> {
let line = if c.ask == 0 { c.text.clone() } else { format!("on ask {}: {}", c.ask, c.text) };
let open = t.find("words: [")? + "words: ".len();
let end = close_of(t, open)?;
let mut out = format!("{}, {}{}", t[..end].trim_end().trim_end_matches(','), serde_json::to_string(&line).ok()?, &t[end..]);
match out.find("corrected: [") {
Some(at) => {
let at = at + "corrected: [".len();
let sep = if out[at..].starts_with(']') { "" } else { ", " };
out.insert_str(at, &format!("{}{sep}", c.ask));
}
None => {
// `asks:` where it starts its line, so a word in a quote is never taken for it
let at = out.match_indices("asks:").map(|(i, _)| i).find(|&i| out[..i].rsplit('\n').next().is_some_and(|l| l.trim().is_empty()))?;
let start = out[..at].rfind('\n').map_or(0, |i| i + 1);
let indent = out[start..at].to_string();
out.insert_str(start, &format!("{indent}corrected: [{}],\n", c.ask));
}
}
Some(out)
}
/// The person's sign on an ask's clip in the app: the note (by where it came from), the ask (1 is the first), the
/// render they watched (its SHA-256), their name (none when the app had no account) and when.
pub(crate) struct Signed {
pub from: String,
pub ask: u32,
pub render: String,
pub name: Option<String>,
pub when: String,
}
/// The sign in one inbox line sent to `project`, if it is one.
pub(crate) fn sign_of(v: &Value, project: &str) -> Option<Signed> {
if v["project"].as_str() != Some(project) || v["kind"].as_str() != Some("sign") {
return None;
}
let ask = v["ask"].as_u64().and_then(|n| u32::try_from(n).ok()).filter(|n| *n > 0)?;
let name = v["name"].as_str().map(str::trim).filter(|n| !n.is_empty()).map(String::from);
Some(Signed { from: format!("app {} {}", v["item"].as_str()?, v["comment"].as_str()?), ask, render: v["render"].as_str()?.into(), name, when: v["when"].as_str().unwrap_or("").into() })
}
/// Each ask's last sign kept with what it has been through (state.rs), once: what was signed, or why it wasn't.
fn sign(project: &Path, kept: &[PathBuf], signs: Vec<Signed>) -> R<Vec<String>> {
// the last sign of each ask: a newer render's sign replaces an older one's
let mut last: BTreeMap<(String, u32), Signed> = BTreeMap::new();
for g in signs {
last.insert((g.from.clone(), g.ask), g);
}
let mut s = state::read(project);
let before = s.clone();
let mut out = Vec::new();
for g in last.into_values() {
let from = format!("from: {}", serde_json::to_string(&g.from).unwrap_or_default());
// the note whose file says it came from this comment
let note = kept.iter().find_map(|f| {
let said = std::fs::read_to_string(f).ok()?;
if said.contains(&from) { Some((f, place(project, f)?)) } else { None }
});
let Some((f, (_, number))) = note else {
out.push(format!("a sign for a note not in notes/ ({}, ask {})", g.from, g.ask));
continue;
};
let k = s.entry(state::id(number, g.ask as usize)).or_default();
let signed = state::Sign { name: g.name.clone(), render: g.render.clone(), at: g.when.clone() };
if k.signed.as_ref() == Some(&signed) {
continue;
}
let now = k.clip.as_ref().is_some_and(|c| c.render == g.render);
k.signed = Some(signed);
let rel = f.strip_prefix(project).unwrap_or(f).display();
let by = g.name.as_deref().unwrap_or("the person (unnamed: the app had no account)");
let short: String = g.render.chars().take(12).collect();
out.push(format!("{rel}: ask {} signed by {by}, on the render {short}…{}", g.ask, if now { "" } else { ", not the one its clip is cut from now: it is to sign again" }));
}
if s != before {
state::write(project, &s)?;
}
Ok(out)
}
/// Each correction applied to its note's file, once: what was done, or why it wasn't.
fn apply(project: &Path, kept: &[PathBuf], corrections: &[Correction]) -> R<Vec<String>> {
let s = |v: &str| serde_json::to_string(v).unwrap_or_default();
let mut out = Vec::new();
for c in corrections {
let line = if c.ask == 0 { c.text.clone() } else { format!("on ask {}: {}", c.ask, c.text) };
let Some(f) = kept.iter().find(|f| std::fs::read_to_string(f).is_ok_and(|t| t.contains(&format!("from: {}", s(&c.from))))) else {
out.push(format!("a correction for a note not in notes/ ({}): {}", c.from, quoted(&c.text, 90)));
continue;
};
let t = std::fs::read_to_string(f).map_err(|e| format!("{}: {e}", f.display()))?;
if t.contains(&s(&line)) {
continue;
}
let rel = f.strip_prefix(project).unwrap_or(f).display().to_string();
match corrected(&t, c) {
Some(new) => {
std::fs::write(f, new).map_err(|e| format!("{}: {e}", f.display()))?;
crate::post::forget(project, &c.from)?;
let which = if c.ask == 0 { "the note".to_string() } else { format!("ask {}", c.ask) };
out.push(format!("{rel}: the person corrected {which}: {}: restate it again", quoted(&c.text, 90)));
}
None => out.push(format!("{rel}: a correction can't be written in (no `words: [` and `asks:` to put it beside): {}", quoted(&c.text, 90))),
}
}
Ok(out)
}
/// A note's file: its words and where they came from, its round, its pin, and no asks.
pub(crate) fn file_text(n: &New, round: u32) -> String {
let s = |v: &str| serde_json::to_string(v).unwrap_or_default();
// what the pin doesn't say is left out, as the type has it (a key with no value isn't written as null)
let pin = n.pin.as_ref().and_then(|p| serde_json::to_value(p).ok()).map(|mut p| {
if let Some(o) = p.as_object_mut() {
o.retain(|_, v| !v.is_null());
}
format!(" pin: {p},\n")
});
let redesign = if note::redesign(&n.words) { " redesign: true,\n" } else { "" };
let words: Vec<String> = n.words.lines().map(s).collect();
format!(
"// A note from the person, as they wrote it (raea notes take). Keep its words; restate it as asks below, one for each\n// thing it asks for, before anything in the work changes.\nimport {{ note }} from \"raea/note\";\n\nexport default note({{\n words: [{}],\n from: {},\n round: {round},\n{pin}{redesign} asks: [],\n}});\n",
words.join(", "),
s(&n.from),
pin = pin.unwrap_or_default()
)
}
pub(crate) fn take(project: &Path, args: &[String]) -> R<String> {
take_from(&inbox_dir(), project, args)
}
/// `take`, reading the inbox files in `dir`.
pub(crate) fn take_from(dir: &Path, project: &Path, args: &[String]) -> R<String> {
let name = project.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let inboxes: Vec<PathBuf> = match values(args, "--inbox").first() {
Some(n) => vec![dir.join(format!("{}.jsonl", n.trim_end_matches(".jsonl")))],
None => {
let mut v: Vec<PathBuf> = std::fs::read_dir(dir).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "jsonl")).collect();
v.sort();
v
}
};
let (mut new, mut fixes, mut signs): (Vec<New>, Vec<Correction>, Vec<Signed>) = (Vec::new(), Vec::new(), Vec::new());
for f in &inboxes {
let text = std::fs::read_to_string(f).map_err(|e| format!("{}: {e}", f.display()))?;
for v in text.lines().filter_map(|l| serde_json::from_str::<Value>(l).ok()) {
new.extend(of_line(&v, &name));
fixes.extend(correction_of(&v, &name));
signs.extend(sign_of(&v, &name));
}
}
new.extend(values(args, "--said").into_iter().map(str::trim).filter(|w| !w.is_empty()).map(|w| New { words: w.into(), from: "session".into(), pin: None, at: None }));
// a note already in notes/ (by where it came from; one said in a session, by its words too) isn't taken again
let kept = files(project);
let texts: Vec<String> = kept.iter().filter_map(|f| std::fs::read_to_string(f).ok()).collect();
let s = |v: &str| serde_json::to_string(v).unwrap_or_default();
let mut seen: Vec<(String, String)> = Vec::new();
new.retain(|n| {
let had = texts.iter().any(|t| t.contains(&format!("from: {}", s(&n.from))) && (n.from != "session" || n.words.lines().all(|l| t.contains(&s(l)))));
let twice = seen.contains(&(n.from.clone(), n.words.clone()));
seen.push((n.from.clone(), n.words.clone()));
!had && !twice
});
let mut out = Vec::new();
if !new.is_empty() {
let at = kept.iter().filter_map(|f| place(project, f));
let (round, mut last) = at.fold((0, 0), |(r, n), (fr, fnum)| (r.max(fr), n.max(fnum)));
let round = round + 1;
let folder = project.join("notes").join(round.to_string());
std::fs::create_dir_all(&folder).map_err(|e| format!("{}: {e}", folder.display()))?;
for n in &new {
last += 1;
let file = folder.join(format!("n{last}.ts"));
std::fs::write(&file, file_text(n, round)).map_err(|e| format!("{}: {e}", file.display()))?;
let at = n.at.as_deref().map(|a| format!(" (at {a})")).unwrap_or_default();
let redesign = if note::redesign(&n.words) { ", a redesign" } else { "" };
out.push(format!("notes/{round}/n{last}.ts: to restate{redesign}: {}{at}", quoted(&n.words, 90)));
}
out.push(format!("round {round}: {} note{} taken. {RESTATE}", new.len(), if new.len() == 1 { "" } else { "s" }));
}
// corrections last, so one for a note taken just now finds its file
out.extend(apply(project, &files(project), &fixes)?);
out.extend(sign(project, &files(project), signs)?);
if out.is_empty() {
return Ok(format!("no new notes for {name}: what was sent to it from the raea app ({} inbox file{}) or said is in notes/ already (raea notes ls)", inboxes.len(), if inboxes.len() == 1 { "" } else { "s" }));
}
Ok(out.join("\n"))
}
+351
View File
@@ -0,0 +1,351 @@
use std::path::Path;
use raea_core_facts::Finding;
use super::*;
use crate::take::take_from;
/// A note file's object as JSON, for a test without raea's TS host: its keys quoted and a comma before a close
/// dropped (the files take writes are in that form).
fn eval(f: &Path) -> Result<String, String> {
let t = std::fs::read_to_string(f).map_err(|e| e.to_string())?;
let body = t.split_once("note(").ok_or("no note(")?.1.rsplit_once(");").ok_or("no );")?.0;
let line = |l: &str| match l.trim().split_once(':') {
Some((k, v)) if !k.is_empty() && k.chars().all(char::is_alphanumeric) => format!("\"{k}\":{v}"),
_ => l.trim().to_string(),
};
Ok(body.lines().map(line).collect::<String>().replace(",}", "}").replace(",]", "]"))
}
/// A project folder named `shop`, and an inbox folder beside it.
fn project() -> (tempfile::TempDir, PathBuf, PathBuf) {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path().join("shop");
std::fs::create_dir_all(p.join(".raea")).unwrap();
std::fs::write(p.join(".raea/project"), "").unwrap();
let inbox = tmp.path().join("inbox");
std::fs::create_dir_all(&inbox).unwrap();
(tmp, p, inbox)
}
fn args(a: &[&str]) -> Vec<String> {
a.iter().map(|s| s.to_string()).collect()
}
const SENT: &str = r#"{"item":"i-show-1","project":"shop","title":"Spring ad","kind":"edits","text":"1. [0:04.5] the lamp","when":"2026-11-10T10:00:00Z","comments":[{"id":"cm-1","text":"I want 2D text with occlusion, not 3D. Think of a lyric video.","kind":"edit","pin":{"kind":"place","x":0.57,"y":0.67,"t":4.5},"at":"0:04.5 · 57%, 67%"},{"id":"cm-2","text":"the \"jug\" isn't visible","kind":"edit"}]}
{"item":"i-show-9","project":"other","kind":"note","text":"not this project's","when":"2026-11-10T10:01:00Z"}"#;
#[test]
fn what_the_person_sends_or_says_is_taken_once_as_notes_to_restate() {
let (_tmp, p, inbox) = project();
std::fs::write(inbox.join("claude-code-1.jsonl"), SENT).unwrap();
let out = take_from(&inbox, &p, &args(&["--said", "redo the intro from scratch"])).unwrap();
assert!(out.contains("notes/1/n1.ts: to restate: \"I want 2D text with occlusion, not 3D. Think of a lyric video.\" (at 0:04.5 · 57%, 67%)"), "{out}");
assert!(out.contains("notes/1/n3.ts: to restate, a redesign: \"redo the intro from scratch\""), "{out}");
assert!(out.contains("round 1: 3 notes taken."), "{out}");
let notes = read(&p, eval);
let n: Vec<&Note> = notes.iter().map(|k| k.note.as_ref().unwrap()).collect();
assert_eq!(n[0].words, ["I want 2D text with occlusion, not 3D. Think of a lyric video."]);
assert_eq!((n[0].from.as_str(), n[0].round), ("app i-show-1 cm-1", 1));
assert_eq!(n[0].pin.as_ref().map(|p| (p.t, p.part.clone())), Some((Some(4.5), None)));
assert_eq!(n[1].words, ["the \"jug\" isn't visible"], "words kept as written");
assert_eq!((n[2].from.as_str(), n[2].redesign), ("session", Some(true)));
assert!(!std::fs::read_to_string(p.join("notes/1/n1.ts")).unwrap().contains("null"), "a pin's missing keys aren't written");
// taken again: nothing new; a later send is the next round
let again = take_from(&inbox, &p, &args(&["--said", "redo the intro from scratch"])).unwrap();
assert!(again.starts_with("no new notes for shop"), "{again}");
let later = r#"{"item":"i-show-2","project":"shop","kind":"note","text":"hold the end card longer","when":"2026-11-10T11:00:00Z","pin":{"kind":"time","t":28.0}}"#;
std::fs::write(inbox.join("claude-code-1.jsonl"), format!("{SENT}\n{later}")).unwrap();
let out = take_from(&inbox, &p, &[]).unwrap();
assert!(out.starts_with("notes/2/n4.ts: to restate: \"hold the end card longer\""), "{out}");
}
#[test]
fn ls_says_where_each_note_stands_and_what_it_owes() {
let (_tmp, p, inbox) = project();
std::fs::write(inbox.join("a.jsonl"), SENT).unwrap();
take_from(&inbox, &p, &[]).unwrap();
let (out, code) = ls(&p, false, eval);
assert_eq!(code, 0);
assert!(out.contains("notes/1/n1.ts: round 1, to restate: \"I want 2D text"), "{out}");
assert!(out.ends_with(take::RESTATE), "{out}");
assert!(out.contains("2 notes: 2 to restate"), "{out}");
// restated as one ask with no medium: read again, and its 2D said
let f = p.join("notes/1/n1.ts");
let t = std::fs::read_to_string(&f).unwrap().replace("asks: [],", "asks: [{ \"text\": \"the lyric is flat type behind the singer\", \"not\": [] }],");
std::fs::write(&f, t).unwrap();
std::fs::write(p.join("notes/1/n9.ts"), "export default 3;").unwrap();
let (out, code) = ls(&p, false, eval);
assert_eq!(code, 1, "a note that can't be read");
assert!(out.contains("notes/1/n1.ts: round 1, to check: ") && out.contains(" n1.1 the lyric is flat type behind the singer: to check: no check, and no clip to sign"), "{out}");
assert!(out.contains(" ! one ask from 2 sentences: read it again for what else it asks"), "{out}");
assert!(out.contains(" ! its words say 2D and no ask says it, as its medium or in its `not`") && out.contains(" ! its words say 3D and no ask says it"), "{out}");
assert!(out.contains("notes/1/n9.ts: can't be read"), "{out}");
}
#[test]
fn notes_are_found_in_round_and_number_order_and_nothing_else_is_one() {
let (_tmp, p, _) = project();
for f in ["notes/2/n10.ts", "notes/2/n9.ts", "notes/1/n1.ts", "notes/1/check.ts", "notes/x/n2.ts"] {
std::fs::create_dir_all(p.join(f).parent().unwrap()).unwrap();
std::fs::write(p.join(f), "").unwrap();
}
let got: Vec<String> = files(&p).iter().map(|f| f.strip_prefix(&p).unwrap().display().to_string()).collect();
assert_eq!(got, ["notes/1/n1.ts", "notes/2/n9.ts", "notes/2/n10.ts"]);
}
#[test]
fn a_note_is_an_entity_in_the_world() {
let (_tmp, p, inbox) = project();
std::fs::write(inbox.join("a.jsonl"), SENT).unwrap();
take_from(&inbox, &p, &[]).unwrap();
let mut w = Facts::new(0, 1920, 1080, 30.0);
spawn(&mut w, &read(&p, eval));
assert_eq!(w.find(&["Note"]).len(), 2);
}
/// n1 of SENT restated as two asks that owe nothing.
fn restate_n1(p: &Path, asks: &str) {
let f = p.join("notes/1/n1.ts");
let t = std::fs::read_to_string(&f).unwrap();
let at = t.find("asks: [").unwrap();
let end = at + t[at..].find("],\n").unwrap() + 2;
std::fs::write(&f, format!("{}asks: [{asks}],{}", &t[..at], &t[end..])).unwrap();
}
const TWO: &str = r#"{ "text": "the lyric is flat type the singer passes in front of", "medium": "2D", "not": ["3D text"] }, { "text": "the words arrive as a lyric video's do", "medium": "2D", "not": [] }"#;
#[test]
fn a_correction_from_the_app_is_written_into_its_note_once_and_it_is_restated_again() {
let (_tmp, p, inbox) = project();
std::fs::write(inbox.join("a.jsonl"), SENT).unwrap();
take_from(&inbox, &p, &[]).unwrap();
restate_n1(&p, TWO);
assert_eq!(read(&p, eval)[0].note.as_ref().unwrap().state(), "to check");
let fix = |ask: &str, text: &str, comment: &str| format!(r#"{{"kind":"correction","item":"i-show-1","project":"shop","title":"Spring ad","comment":"{comment}",{ask}"text":"{text}"}}"#);
let lines = [SENT.to_string(), fix(r#""ask":2,"#, "no, keep the font as it is", "cm-1"), fix("", "it's about the chorus only", "cm-1"), fix("", "lost", "cm-7")];
std::fs::write(inbox.join("a.jsonl"), lines.join("\n")).unwrap();
let out = take_from(&inbox, &p, &[]).unwrap();
assert!(out.contains("notes/1/n1.ts: the person corrected ask 2: \"no, keep the font as it is\": restate it again"), "{out}");
assert!(out.contains("notes/1/n1.ts: the person corrected the note: \"it's about the chorus only\": restate it again"), "{out}");
assert!(out.contains("a correction for a note not in notes/ (app i-show-1 cm-7): \"lost\""), "{out}");
assert!(!out.contains("no new notes"), "{out}");
let n = read(&p, eval).remove(0).note.unwrap();
assert_eq!(n.words, ["I want 2D text with occlusion, not 3D. Think of a lyric video.", "on ask 2: no, keep the font as it is", "it's about the chorus only"]);
assert_eq!(n.corrected, Some(vec![0, 2]));
assert_eq!(n.state(), "to restate");
assert_eq!(n.asks.len(), 2, "the asks are kept for the agent to restate again");
// taken again: each correction is in already
let again = take_from(&inbox, &p, &[]).unwrap();
assert!(!again.contains("corrected"), "{again}");
assert_eq!(read(&p, eval).remove(0).note.unwrap().words.len(), 3);
}
thread_local! {
static RAN: std::cell::RefCell<Vec<Vec<String>>> = const { std::cell::RefCell::new(Vec::new()) };
}
fn ran(a: &[String]) -> R<String> {
RAN.with(|r| r.borrow_mut().push(a.to_vec()));
Ok("Marked cm-1 working".into())
}
fn refused(_: &[String]) -> R<String> {
Err("the raea app isn't running".into())
}
fn calls() -> Vec<Vec<String>> {
RAN.with(|r| r.borrow().clone())
}
#[test]
fn post_shows_each_note_on_its_comment_as_it_stands_once() {
let (_tmp, p, inbox) = project();
let whole = r#"{"item":"i-show-2","project":"shop","kind":"note","text":"hold the end card longer","when":"2026-11-10T11:00:00Z"}"#;
std::fs::write(inbox.join("a.jsonl"), format!("{SENT}\n{whole}")).unwrap();
take_from(&inbox, &p, &[]).unwrap();
// taken and not restated: each comment's badge reads "to restate"
let (out, code) = post::post(&p, eval, refused);
assert_eq!((code, out.contains("notes/1/n1.ts: not posted: the raea app isn't running")), (1, true), "{out}");
assert!(out.contains("notes/1/n3.ts: a note on its item as a whole has no comment to show its asks on"), "{out}");
let (out, code) = post::post(&p, eval, ran);
assert_eq!(code, 0, "{out}");
assert!(out.contains("notes/1/n1.ts: shown on cm-1 of i-show-1: to restate"), "{out}");
assert_eq!(calls()[0], args(&["show", "--on", "i-show-1", "--working", "cm-1", "--status", "to restate"]));
assert_eq!(calls().len(), 2, "cm-1 and cm-2");
// one ask for two sentences still owes a reading: its asks aren't shown, and it still reads to restate
restate_n1(&p, r#"{ "text": "the lyric is flat type", "medium": "2D", "not": ["3D text"] }"#);
let (out, _) = post::post(&p, eval, ran);
assert!(out.contains("notes/1/n1.ts: shown on cm-1 of i-show-1 as it stands already (to restate)"), "{out}");
assert_eq!(calls().len(), 2);
// whole: its asks, the note to check (no check yet) and each ask's state
restate_n1(&p, TWO);
let (out, _) = post::post(&p, eval, ran);
assert!(out.contains("notes/1/n1.ts: shown on cm-1 of i-show-1: its 2 asks, to check"), "{out}");
let want = args(&["show", "--on", "i-show-1", "--working", "cm-1", "--ask", "the lyric is flat type the singer passes in front of", "--ask", "the words arrive as a lyric video's do", "--status", "to check", "--states", "to check,to check"]);
assert_eq!(calls()[2], want);
let (out, _) = post::post(&p, eval, ran);
assert!(out.contains("notes/1/n1.ts: shown on cm-1 of i-show-1 as it stands already (to check)"), "{out}");
assert_eq!(calls().len(), 3);
// the person corrects ask 1: back to restate; restated again in the same words, it's shown again, as the answer
let fix = r#"{"kind":"correction","item":"i-show-1","project":"shop","title":"Spring ad","comment":"cm-1","ask":1,"text":"yes, that"}"#;
std::fs::write(inbox.join("a.jsonl"), format!("{SENT}\n{whole}\n{fix}")).unwrap();
take_from(&inbox, &p, &[]).unwrap();
let (out, _) = post::post(&p, eval, ran);
assert!(out.contains("notes/1/n1.ts: shown on cm-1 of i-show-1: to restate: its restatement still owes: the person corrected ask 1"), "{out}");
let f = p.join("notes/1/n1.ts");
std::fs::write(&f, std::fs::read_to_string(&f).unwrap().replace(" corrected: [1],\n", "")).unwrap();
post::post(&p, eval, ran);
assert_eq!(calls().last().unwrap(), &want);
}
/// A finding of the ask `id`'s check, as a run gives it.
fn found(id: &str) -> Finding {
Finding::new("faces", raea_core_facts::Level::Error, "desk-3 is turned 180 degrees from facing chair-3", &check::by(id))
}
/// One composition's run that found `fs`.
fn run_of(fs: Vec<Finding>) -> Vec<check::Ran> {
vec![check::Ran { of: "office.tsx".into(), found: fs, waits: vec![], render: None, shots: vec![], fps: 30.0 }]
}
/// A project with n1 restated as two asks that run one check with different values, the second on one composition.
fn two_asks() -> (tempfile::TempDir, PathBuf) {
let (tmp, p, inbox) = project();
std::fs::write(inbox.join("a.jsonl"), SENT).unwrap();
take_from(&inbox, &p, &[]).unwrap();
restate_n1(&p, r#"{ "text": "every desk faces its chair", "medium": "2D", "not": ["3D"], "check": "../../checks/faces.ts", "values": { "what": "desk" } }, { "text": "every chair faces its desk", "medium": "2D", "not": [], "of": "office.tsx", "check": "../../checks/faces.ts", "values": { "what": "chair" } }"#);
(tmp, p)
}
#[test]
fn an_asks_check_must_fail_first_and_one_that_passes_first_is_refused() {
let (_tmp, p) = two_asks();
let notes = read(&p, eval);
let (rules, bad) = check::rules(&p, &notes);
assert!(bad.is_empty());
assert_eq!(rules.iter().map(|r| (r.id.as_str(), r.by.as_str(), r.of.as_deref())).collect::<Vec<_>>(), [("n1.1", "note n1.1", None), ("n1.2", "note n1.2", Some("office.tsx"))]);
assert_eq!(rules[0].check, p.join("notes/1/../../checks/faces.ts").display().to_string(), "a check's path is from the note's folder");
let ask = |s: &state::State, i: usize| state::of_note(notes[0].note.as_ref().unwrap(), 1, s).1[i].clone();
// the first run passes n1.1 (refused) and fails n1.2; each counts only its own findings
let mut s = state::State::new();
let (lines, refused) = check::settle(&p, &notes, &rules, &run_of(vec![found("n1.2"), found("n1.2")]), "20261110-120000", &mut s);
assert!(refused);
assert!(lines[0].contains("n1.1 notes/1/n1.ts: \"every desk faces its chair\": refused: its check passes on the work as it stands"), "{lines:?}");
assert!(lines[1].contains("n1.2 notes/1/n1.ts: \"every chair faces its desk\": fails on the work as it stands (2 findings)"), "{lines:?}");
assert!(matches!(ask(&s, 0), state::Standing::ToCheck(why) if why.contains("passed on its first run")));
assert_eq!(ask(&s, 1), state::Standing::Failing(2));
// n1.1 shown failing later counts; the work changes and both pass
check::settle(&p, &notes, &rules, &run_of(vec![found("n1.1")]), "20261110-120100", &mut s);
assert_eq!((ask(&s, 0), ask(&s, 1)), (state::Standing::Failing(1), state::Standing::Passing));
let (lines, refused) = check::settle(&p, &notes, &rules, &run_of(vec![]), "20261110-120200", &mut s);
assert!(!refused && lines.iter().all(|l| l.ends_with(": passing")), "{lines:?}");
// --only runs one: the other isn't judged on a run it wasn't in
let (lines, _) = check::settle(&p, &notes, &rules[1..], &run_of(vec![found("n1.2")]), "20261110-120300", &mut s);
assert_eq!(lines.len(), 1);
assert_eq!((ask(&s, 0), ask(&s, 1)), (state::Standing::Passing, state::Standing::Failing(1)));
// a check changed after it failed is to be shown failing again; kept as written, ls says each ask's state
let f = p.join("notes/1/n1.ts");
std::fs::write(&f, std::fs::read_to_string(&f).unwrap().replace(r#""what": "desk""#, r#""what": "desk", "within": 90"#)).unwrap();
let notes = read(&p, eval);
assert!(matches!(state::of_note(notes[0].note.as_ref().unwrap(), 1, &s).1[0].clone(), state::Standing::ToCheck(why) if why.contains("changed since it failed")));
state::write(&p, &s).unwrap();
let (out, _) = ls(&p, false, eval);
assert!(out.contains(" n1.2 every chair faces its desk [2D]: failing (1 finding)"), "{out}");
assert!(out.contains("notes/1/n1.ts: round 1, to check: "), "{out}");
}
#[test]
fn a_clip_is_signed_by_the_person_for_its_render_and_reopens_when_its_source_changes() {
let (_tmp, p, inbox) = project();
std::fs::write(inbox.join("a.jsonl"), SENT).unwrap();
take_from(&inbox, &p, &[]).unwrap();
restate_n1(&p, r#"{ "text": "the light turns on the cut", "medium": "2D", "not": ["3D"], "proof": { "shot": "reveal", "sign": true } }, { "text": "the lyric is flat type", "medium": "2D", "not": [] }"#);
let note = || read(&p, eval).remove(0).note.unwrap();
let ask = |s: &state::State| state::of_note(&note(), 1, s).1[0].clone();
let mut s = state::State::new();
assert!(matches!(ask(&s), state::Standing::ToCheck(why) if why.starts_with("no clip yet")), "the agent's move: render and cut it");
let clip = |render: &str, stale: bool| state::Clip { file: p.join(".raea/notes-clips/n1.1.mp4"), of: "edit.tsx".into(), render: render.into(), frames: [30, 150], stale };
s.insert("n1.1".into(), state::Kept { clip: Some(clip("aaa", false)), ..Default::default() });
state::write(&p, &s).unwrap();
assert!(matches!(ask(&s), state::Standing::ToSign(why) if why.contains("waits on the person")));
// posted under its ask, for the person to sign
let (out, _) = post::post(&p, eval, ran);
assert!(out.contains("notes/1/n1.ts: shown on cm-1 of i-show-1: its 2 asks, to check, with 1 clip to sign"), "{out}");
let file = p.join(".raea/notes-clips/n1.1.mp4").display().to_string();
assert_eq!(calls()[1], args(&["show", "--on", "i-show-1", "--working", "cm-1", "--sign", "1", "--clip", &file, "--render", "aaa"]), "after cm-1's asks, before cm-2");
// the person signs it in the app (a sign for a note not taken is said, not dropped); a second take changes nothing
let sign = |render: &str, name: &str| format!(r#"{{"kind":"sign","item":"i-show-1","project":"shop","comment":"cm-1","ask":1,"render":"{render}",{name}"when":"2026-11-10T12:00:00Z"}}"#);
let lost = r#"{"kind":"sign","item":"i-show-7","project":"shop","comment":"cm-1","ask":1,"render":"aaa","when":"x"}"#;
std::fs::write(inbox.join("a.jsonl"), [SENT.to_string(), sign("aaa", r#""name":"Sam","#), lost.to_string()].join("\n")).unwrap();
let out = take_from(&inbox, &p, &[]).unwrap();
assert!(out.contains("notes/1/n1.ts: ask 1 signed by Sam, on the render aaa…"), "{out}");
assert!(out.contains("a sign for a note not in notes/ (app i-show-7 cm-1, ask 1)"), "{out}");
let s = state::read(&p);
assert_eq!(ask(&s), state::Standing::Signed(Some("Sam".into())));
assert!(!take_from(&inbox, &p, &[]).unwrap().contains("signed"));
// its composition changed after the render: to sign again; a new render's clip: the old sign doesn't hold
let mut s = state::read(&p);
s.get_mut("n1.1").unwrap().clip = Some(clip("aaa", true));
assert!(matches!(ask(&s), state::Standing::ToCheck(why) if why.contains("changed after the render")), "the agent's move: render it again");
s.get_mut("n1.1").unwrap().clip = Some(clip("bbb", false));
assert!(matches!(ask(&s), state::Standing::ToSign(why) if why.starts_with("Sam signed an older render")));
state::write(&p, &s).unwrap();
// signed again for the new render, by a person the app had no account for: signed, unnamed
std::fs::write(inbox.join("a.jsonl"), [SENT.to_string(), sign("aaa", r#""name":"Sam","#), sign("bbb", "")].join("\n")).unwrap();
let out = take_from(&inbox, &p, &[]).unwrap();
assert!(out.contains("ask 1 signed by the person (unnamed: the app had no account), on the render bbb…"), "{out}");
assert_eq!(ask(&state::read(&p)), state::Standing::Signed(None));
}
#[test]
fn an_ask_names_its_composition_by_file_or_by_file_and_id() {
assert!(check::is_of("hold.tsx", "hold.tsx#hold"), "a file alone is any composition in it");
assert!(check::is_of("hold.tsx", "hold.tsx"));
assert!(check::is_of("cuts.tsx#b", "cuts.tsx#b"));
assert!(!check::is_of("cuts.tsx#b", "cuts.tsx#a"));
assert!(!check::is_of("cuts.tsx#b", "cuts.tsx"), "an id the run doesn't name");
assert!(!check::is_of("hold.tsx", "scenes/hold.tsx#hold"), "its file from the project, not its name");
}
#[test]
fn no_clip_is_cut_from_a_render_the_composition_changed_after() {
let (_tmp, p, inbox) = project();
std::fs::write(inbox.join("a.jsonl"), SENT).unwrap();
take_from(&inbox, &p, &[]).unwrap();
restate_n1(&p, r#"{ "text": "the light turns on the cut", "medium": "2D", "not": ["3D"], "of": "edit.tsx", "proof": { "shot": "reveal", "sign": true } }, { "text": "the lyric is flat type", "medium": "2D", "not": [] }"#);
let notes = read(&p, eval);
let mut s = state::State::new();
let clip = state::Clip { file: p.join(".raea/notes-clips/n1.1.mp4"), of: "edit.tsx#edit".into(), render: "aaa".into(), frames: [30, 150], stale: false };
s.insert("n1.1".into(), state::Kept { clip: Some(clip), ..Default::default() });
let run = |render: Option<check::Rendered>| vec![check::Ran { of: "edit.tsx#edit".into(), found: vec![], waits: vec![], render, shots: vec![("reveal".into(), 30, None)], fps: 30.0 }];
let stale = check::Rendered { out: p.join("out/edit.mp4"), stale: true, frames: 150 };
let lines = check::clips(&p, &notes, &run(Some(stale)), &mut s);
assert_eq!(lines, ["n1.1 notes/1/n1.ts: its clip waits for a render of edit.tsx#edit as it stands: it changed after its newest render"]);
assert!(s["n1.1"].clip.as_ref().unwrap().stale, "the clip kept from the render before is marked");
assert!(!p.join(".raea/notes-clips/n1.1.mp4").exists(), "nothing is cut from it");
let n = notes[0].note.as_ref().unwrap();
assert!(matches!(state::of_note(n, 1, &s).1[0].clone(), state::Standing::ToCheck(why) if why.contains("render it again")), "the agent's move");
// no render at all: said, and nothing is cut
assert_eq!(check::clips(&p, &notes, &run(None), &mut s), ["n1.1 notes/1/n1.ts: its clip waits for a render of edit.tsx#edit"]);
}
+22
View File
@@ -48,10 +48,32 @@ pub(crate) fn offscreen(mut run: Run, json: Option<String>, flat_out: bool, snap
// (bench/timelines/check.sh compares these with renders)
let seeks: Vec<(i64, String)> = std::env::args().collect::<Vec<_>>().windows(3).filter(|w| w[0] == "--seek").filter_map(|w| Some((w[1].parse().ok()?, w[2].clone()))).collect();
if !seeks.is_empty() {
// --view YAW,PITCH,DISTANCE[,X,Y,Z]: the 3D drawn from that orbit (radians, metres, about X,Y,Z) instead of
// the composition's camera; --pick X,Y (repeatable): what's under that point of each seeked frame (page px),
// the page and its 3D as one picture, a line of JSON each (docs/preview.feature PV1)
let args: Vec<String> = std::env::args().collect();
let nums = |flag: &str| -> Vec<Vec<f64>> { args.windows(2).filter(|w| w[0] == flag).map(|w| w[1].split(',').filter_map(|v| v.trim().parse().ok()).collect()).collect() };
let view = nums("--view").into_iter().find(|v| v.len() == 3 || v.len() == 6);
let picks: Vec<(f64, f64)> = nums("--pick").into_iter().filter(|p| p.len() == 2).map(|p| (p[0], p[1])).collect();
let mut said = Vec::new();
for (f, out) in &seeks {
live.step(*f, &[], None)?;
if let Some(v) = &view {
// the scene's engine opens at the first draw
live.snapshot()?;
let t = if v.len() == 6 { [v[3] as f32, v[4] as f32, v[5] as f32] } else { [0.0; 3] };
if !live.set_view(Some((v[0] as f32, v[1] as f32, v[2] as f32, t))) {
return Err("--view: this composition has no 3D to look around".into());
}
}
live.save_snapshot(std::path::Path::new(out))?;
eprintln!("seek to {f} -> {out}");
for (x, y) in &picks {
said.push(serde_json::json!({"frame": f, "x": x, "y": y, "pick": live.pick(*x, *y)}).to_string());
}
}
if !said.is_empty() {
return Ok(said.join("\n"));
}
return Ok(format!("SEEKED {} frames", seeks.len()));
}
+2
View File
@@ -8,6 +8,8 @@ description = "raea solid info and raea solid view: a solid file run, its parts
[dependencies]
raea-core-solidinfo = { path = "../../core/solidinfo" }
# what solid info finds, as raea's one Finding (docs/direction.feature DR3)
raea-core-facts = { path = "../../core/facts" }
serde_json = "1"
# --set's and the CLI's flags, read as the bundler reads them
raea-runtime-bundle = { path = "../../runtime/bundle" }
+16 -4
View File
@@ -11,6 +11,7 @@
use std::path::{Path, PathBuf};
use raea_core_facts::{Finding, Level, finding};
use raea_runtime_bundle::flag;
use serde_json::{Map, Value, json};
@@ -173,22 +174,33 @@ pub fn cli(args: &[String]) -> Result<String, String> {
}
out["walk"] = json!(walk);
}
let errors = out["errors"].as_u64().unwrap_or(0);
// what it found as raea's one Finding (docs/direction.feature DR3), about the part, or the solid's file
let name = file.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
let found = finding::ranked(out["found"].as_array().into_iter().flatten().filter_map(|v| Finding::of_value(v, "raea solid info")).map(|f| if f.about.is_empty() { f.about(&name, None) } else { f }).collect());
let errors = found.iter().any(|f| f.level == Level::Error);
if let Some(o) = out.as_object_mut() {
for k in ["found", "errors", "warnings"] {
o.remove(k);
}
}
out["count"] = json!(finding::count(&found));
out["findings"] = json!(found);
let text = if json_out {
serde_json::to_string_pretty(&out).unwrap_or_default()
} else {
let s = &out["solid"];
let mut t: Vec<String> = out["found"].as_array().into_iter().flatten().filter(|f| !matches!(f["level"].as_str(), Some("ok"))).map(|f| format!("{:<8} {}{}", f["level"].as_str().unwrap_or(""), f["part"].as_str().map(|p| format!("{p}: ")).unwrap_or_default(), f["says"].as_str().unwrap_or(""))).collect();
let mut t: Vec<String> = found.iter().map(Finding::line).collect();
for p in out["parts"].as_array().into_iter().flatten() {
t.push(format!("part {}: {} m³, size {}, {} pieces, genus {}", p["part"].as_str().unwrap_or(""), p["volume"], p["box"]["size"], p["pieces"], p["genus"]));
}
for w in out["walk"].as_array().into_iter().flatten() {
t.push(format!("walk {} = {}: {}{}", w["param"].as_str().unwrap_or(""), w["value"], w["verdict"].as_str().unwrap_or(""), w["says"].as_str().map(|s| format!(" ({s})")).unwrap_or_default()));
}
t.push(format!("solid: {} m³, size {} m, {} pieces, genus {}, {} triangles; {errors} errors, {} warnings", s["volume"], s["box"]["size"], s["pieces"], s["genus"], s["tris"], out["warnings"]));
t.push(format!("solid: {} m³, size {} m, {} pieces, genus {}, {} triangles", s["volume"], s["box"]["size"], s["pieces"], s["genus"], s["tris"]));
t.push(format!("raea solid info: {}", finding::count(&found)));
t.join("\n")
};
if errors > 0 {
if errors {
println!("{text}");
std::process::exit(1);
}
+2 -1
View File
@@ -87,7 +87,8 @@ pub(crate) fn view(file: &Path, set: &Map<String, Value>, info: &Value, out: &Pa
let tsx = file.with_file_name(format!(".{}.view.tsx", file.file_stem().and_then(|s| s.to_str()).unwrap_or("solid")));
std::fs::write(&tsx, scene(file, set, lo, hi)).map_err(|e| format!("{}: {e}", tsx.display()))?;
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let run = std::process::Command::new(exe).arg("render").arg(&tsx).arg("--review").arg(out).current_dir(tsx.parent().unwrap_or(Path::new("."))).output().map_err(|e| e.to_string())?;
// a scene made for this look and deleted after it: nothing for the project's record (DR3)
let run = std::process::Command::new(exe).arg("render").arg(&tsx).arg("--review").arg(out).current_dir(tsx.parent().unwrap_or(Path::new("."))).env("RAEA_RECORD", "off").output().map_err(|e| e.to_string())?;
let said = format!("{}{}", String::from_utf8_lossy(&run.stdout), String::from_utf8_lossy(&run.stderr));
if !run.status.success() || !out.join("colour.png").is_file() {
// the scene is left for a look: what failed is in it or in the file
+13
View File
@@ -0,0 +1,13 @@
[package]
name = "raea-app-sound"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "A render's sound alone (`raea render EDIT.tsx -o OUT.wav`, no frames drawn) and a video's sound written beside it from the same pass (`--audio OUT.wav`)"
[dependencies]
raea-runtime-export = { path = "../../runtime/export" }
raea-runtime-bundle = { path = "../../runtime/bundle" }
raea-sys-mix = { path = "../../systems/mix" }
raea-io-media = { path = "../../io/media", default-features = false }
+93
View File
@@ -0,0 +1,93 @@
//! A render's sound on its own (Shane 11-10: "we should add an audio-only render and also be able to render video and
//! audio at the same time"):
//! raea render EDIT.tsx -o OUT.wav the sound alone, mixed and mastered as the video's is, no frame drawn:
//! React stepped through every frame for its sounds (sound_only, which
//! live play also mixes from), so a 2-minute film's sound is minutes
//! sooner than its video
//! raea render EDIT.tsx -o OUT.mp4 --audio A.wav the video, and beside it the very bounce it carries (before AAC),
//! from the same pass: every render path writes RAEA_AUDIO_BOUNCE
use raea_runtime_bundle::{R, flag};
use std::path::{Path, PathBuf};
fn is_wav(p: &Path) -> bool {
p.extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("wav"))
}
/// Every render comes here first (raea render, and raea export capcut's parts). The folders its files go in are made
/// (out_folders); then Some(the answer) for a sound render (`-o OUT.wav`), None for every other render, which goes on
/// as before. A video render's `--audio A.wav` is set up here (the render writes it) and also answers None.
pub fn render(args: &[String]) -> Option<R<String>> {
if let Err(e) = out_folders(args) {
return Some(Err(e));
}
let out = PathBuf::from(flag(args, "-o")?);
if is_wav(&out) {
return Some(sound(args, &out));
}
let a = flag(args, "--audio")?;
if !is_wav(Path::new(&a)) {
return Some(Err(format!("--audio {a}: the sound is written as a .wav (OUT.wav)")));
}
let a = match std::path::absolute(&a) {
Ok(a) => a,
Err(e) => return Some(Err(format!("{a}: {e}"))),
};
// read where each render path bounces (raea-runtime-export sound.rs and fed.rs, raea-runtime-encode sound.rs); set
// before the render starts, as cli.rs sets RAEA_ROOT
unsafe { std::env::set_var("RAEA_AUDIO_BOUNCE", a) };
None
}
/// The composition's sound alone: bundled as a render bundles it (its --composition and flags), stepped for its sounds,
/// mastered by its <Mix>, written as 48 kHz WAV, with what it measures.
fn sound(args: &[String], out: &Path) -> R<String> {
let edit = args.get(1).filter(|a| !a.starts_with('-')).ok_or("raea render EDIT.tsx -o OUT.wav")?;
let tsx = PathBuf::from(edit).canonicalize().map_err(|e| format!("{edit}: {e}"))?;
let dir = tsx.parent().ok_or("the edit has no folder")?.to_path_buf();
let js = std::env::temp_dir().join(format!("raea-sound-{}.js", std::process::id()));
raea_runtime_bundle::bundle_composition(&tsx, &js, &raea_runtime_bundle::comp_opts(args)?, None)?;
let t = std::time::Instant::now();
let a = raea_runtime_export::sound_only(&js, &dir);
let _ = std::fs::remove_file(&js);
let a = a?.ok_or_else(|| format!("{edit} makes no sound: no <Audio>, no <Video> with sound and no Tone in any frame"))?;
raea_sys_mix::write_wav(&a, out)?;
Ok(format!(
"{}: {:.1} s of sound, {:.1} LUFS, true peak {:.1} dBTP, in {:.1} s (no frames drawn)",
out.display(),
a.duration(),
raea_io_media::audio::lufs(&a),
raea_io_media::audio::true_peak_db(&a),
t.elapsed().as_secs_f64()
))
}
/// The folders a render's files go in (`-o out/a.mp4`, `--audio out/a.wav`), made before it starts: a project made by
/// hand has no out/, and the render ran to the end and then failed writing with "No such file or directory". `-o DIR`
/// (frames) makes only what's above DIR; the render makes DIR.
pub fn out_folders(args: &[String]) -> R<()> {
for f in ["-o", "--audio"] {
let Some(file) = flag(args, f).map(PathBuf::from) else { continue };
if let Some(d) = file.parent().filter(|d| !d.as_os_str().is_empty()) {
std::fs::create_dir_all(d).map_err(|e| format!("{f} {}: couldn't make {}: {e}", file.display(), d.display()))?;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
#[test]
fn a_render_makes_the_folders_its_files_go_in() {
let root = std::env::temp_dir().join(format!("raea-out-folders-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
let (video, sound) = (root.join("out/shots/a.mp4"), root.join("bounces/a.wav"));
let args: Vec<String> = ["render", "EDIT.tsx", "-o", video.to_str().unwrap(), "--audio", sound.to_str().unwrap()].map(String::from).to_vec();
super::out_folders(&args).unwrap();
assert!(root.join("out/shots").is_dir() && root.join("bounces").is_dir());
assert!(!video.exists() && !sound.exists(), "the folders only, not the files");
// a bare name (the project's own folder) and no -o at all are left as they are
super::out_folders(&["render", "EDIT.tsx", "-o", "a.png"].map(String::from)).unwrap();
super::out_folders(&["render", "EDIT.tsx"].map(String::from)).unwrap();
std::fs::remove_dir_all(&root).unwrap();
}
}
+140
View File
@@ -0,0 +1,140 @@
//! The hooks `raea skills install` adds an agent (docs/agents.feature A5d, A5e; docs/skills.feature SK10), the same two
//! for every harness, each written where and how that harness reads hooks: before a shell command, `raea hook AGENT`
//! steers media opened in the Mac's viewer to `raea show`; after a file is saved, it runs the quick check on a
//! composition. An event that already has a `raea hook` entry is left as it is.
use crate::agent_mcp::user_home;
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
type R<T> = Result<T, String>;
/// One hook: the harness's event, the tools it matches, and the seconds it may take.
struct Hook {
event: &'static str,
matcher: &'static str,
secs: u64,
}
/// Each harness's two hooks, by its own event and tool names.
fn hooks(agent: &str) -> R<[Hook; 2]> {
let h = |event, matcher, secs| Hook { event, matcher, secs };
Ok(match agent {
"claude" => [h("PreToolUse", "Bash", 30), h("PostToolUse", "Write|Edit|MultiEdit", 60)],
"codex" => [h("PreToolUse", "^(Bash|shell|shell_command|exec_command)$", 30), h("PostToolUse", "^(apply_patch|Edit|Write)$", 60)],
"gemini" => [h("BeforeTool", "run_shell_command", 30), h("AfterTool", "write_file|replace", 60)],
"kimi" => [h("PreToolUse", "Bash|Shell", 30), h("PostToolUse", "Write|Edit|WriteFile|StrReplaceFile", 60)],
a => return Err(format!("no agent {a:?}: claude, codex, kimi or gemini")),
})
}
/// The folder an environment variable names, else the one given.
fn named_dir(var: &str, or: PathBuf) -> PathBuf {
std::env::var_os(var).filter(|v| !v.is_empty()).map_or(or, PathBuf::from)
}
/// Where the harness keeps its hooks.
fn file(agent: &str) -> R<PathBuf> {
let home = user_home()?;
Ok(match agent {
"claude" => home.join(".claude/settings.json"),
"codex" => named_dir("CODEX_HOME", home.join(".codex")).join("hooks.json"),
"gemini" => home.join(".gemini/settings.json"),
_ => named_dir("KIMI_CODE_HOME", home.join(".kimi-code")).join("config.toml"),
})
}
/// Adds a hook to a JSON file of `{"hooks": {EVENT: [{matcher, hooks: [...]}]}}` (Claude Code, Codex, Gemini CLI)
/// unless the event has a `raea hook` entry; true when it added.
fn add_json(path: &Path, agent: &str, h: &Hook) -> R<bool> {
let at = path.display();
let mut doc: Value = match std::fs::read_to_string(path) {
Ok(t) if !t.trim().is_empty() => serde_json::from_str(&t).map_err(|e| format!("{at}: {e}"))?,
_ => json!({}),
};
let hooks = doc.as_object_mut().ok_or(format!("{at} isn't a JSON object"))?.entry("hooks").or_insert_with(|| json!({}));
let list = hooks.as_object_mut().ok_or(format!("{at}: hooks isn't an object"))?.entry(h.event).or_insert_with(|| json!([]));
let list = list.as_array_mut().ok_or(format!("{at}: hooks.{} isn't a list", h.event))?;
if list.iter().any(|m| m["hooks"].as_array().into_iter().flatten().any(|x| x["command"].as_str().unwrap_or("").starts_with("raea hook"))) {
return Ok(false);
}
// Gemini CLI counts milliseconds and names each hook
let one = if agent == "gemini" { json!({"name": "raea", "type": "command", "command": "raea hook gemini", "timeout": h.secs * 1000}) } else { json!({"type": "command", "command": format!("raea hook {agent}"), "timeout": h.secs}) };
list.push(json!({"matcher": h.matcher, "hooks": [one]}));
write(path, &(serde_json::to_string_pretty(&doc).unwrap_or_default() + "\n"))?;
Ok(true)
}
/// Adds a `[[hooks]]` table to Kimi Code's config.toml (only event, matcher, command and timeout: it refuses other
/// keys) unless one runs `raea hook` on that event; true when it added.
fn add_toml(path: &Path, h: &Hook) -> R<bool> {
let text = std::fs::read_to_string(path).unwrap_or_default();
let ours = text.split("[[hooks]]").skip(1).any(|t| {
let t = t.split("\n[").next().unwrap_or(t);
t.contains("command = \"raea hook") && t.contains(&format!("event = \"{}\"", h.event))
});
if ours {
return Ok(false);
}
let sep = if text.is_empty() || text.ends_with("\n\n") { "" } else if text.ends_with('\n') { "\n" } else { "\n\n" };
write(path, &format!("{text}{sep}[[hooks]]\nevent = \"{}\"\nmatcher = \"{}\"\ncommand = \"raea hook kimi\"\ntimeout = {}\n", h.event, h.matcher, h.secs))?;
Ok(true)
}
/// Writes a config file whole, through a temporary file beside it.
fn write(path: &Path, text: &str) -> R<()> {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
}
let tmp = path.with_extension("raea-tmp");
std::fs::write(&tmp, text).map_err(|e| format!("{}: {e}", tmp.display()))?;
std::fs::rename(&tmp, path).map_err(|e| format!("{}: {e}", path.display()))
}
/// Adds raea's hooks for an agent; the line says what happened.
pub fn install(agent: &str) -> R<String> {
let (path, mut added) = (file(agent)?, Vec::new());
for h in hooks(agent)? {
if if agent == "kimi" { add_toml(&path, &h)? } else { add_json(&path, agent, &h)? } {
added.push(h.event);
}
}
let what = if added.is_empty() { "already there".to_string() } else { format!("added ({})", added.join(", ")) };
// Codex runs a new or changed hook only once the person trusts it
let trust = if agent == "codex" && !added.is_empty() { "; trust them in Codex's /hooks" } else { "" };
Ok(format!("{}: hooks `raea hook {agent}` {what}{trust}\n", path.display()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn each_harness_gets_both_hooks_once_and_keeps_its_own() {
let d = std::env::temp_dir().join(format!("raea-agent-hooks-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
let c = d.join("claude/settings.json");
std::fs::create_dir_all(c.parent().unwrap()).unwrap();
std::fs::write(&c, r#"{"model":"x","hooks":{"PostToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"other"}]},{"matcher":"Write","hooks":[{"type":"command","command":"raea hook claude"}]}]}}"#).unwrap();
let [pre, post] = hooks("claude").unwrap();
assert!(add_json(&c, "claude", &pre).unwrap() && !add_json(&c, "claude", &pre).unwrap());
assert!(!add_json(&c, "claude", &post).unwrap(), "an older raea's after-save hook stands");
let v: Value = serde_json::from_str(&std::fs::read_to_string(&c).unwrap()).unwrap();
assert_eq!((v["model"].as_str(), v["hooks"]["PostToolUse"].as_array().unwrap().len()), (Some("x"), 2));
assert_eq!(v["hooks"]["PreToolUse"][0]["hooks"][0]["command"], "raea hook claude");
let g = d.join("gemini/settings.json");
let [before, _] = hooks("gemini").unwrap();
assert!(add_json(&g, "gemini", &before).unwrap());
let v: Value = serde_json::from_str(&std::fs::read_to_string(&g).unwrap()).unwrap();
assert_eq!(v["hooks"]["BeforeTool"][0], json!({"matcher": "run_shell_command", "hooks": [{"name": "raea", "type": "command", "command": "raea hook gemini", "timeout": 30000}]}));
let k = d.join("kimi/config.toml");
std::fs::create_dir_all(k.parent().unwrap()).unwrap();
std::fs::write(&k, "default_model = \"k\"\n\n[[hooks]]\nevent = \"PreToolUse\"\nmatcher = \"Bash\"\ncommand = \"mine\"\n").unwrap();
let [pre, post] = hooks("kimi").unwrap();
assert!(add_toml(&k, &pre).unwrap() && !add_toml(&k, &pre).unwrap() && add_toml(&k, &post).unwrap() && !add_toml(&k, &post).unwrap());
let t = std::fs::read_to_string(&k).unwrap();
assert!(t.starts_with("default_model = \"k\"\n\n[[hooks]]\nevent = \"PreToolUse\"\nmatcher = \"Bash\"\ncommand = \"mine\"\n\n[[hooks]]\nevent = \"PreToolUse\"\nmatcher = \"Bash|Shell\"\ncommand = \"raea hook kimi\"\ntimeout = 30\n"), "{t}");
assert_eq!(t.matches("[[hooks]]").count(), 3);
assert!(hooks("cursor").is_err());
let _ = std::fs::remove_dir_all(&d);
}
}
Loaded 100 of 1940 files, more files were not shown because too many files have changed in this diff. Show more