Compare commits

...
227 Commits
Author SHA1 Message Date
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
880 changed files with 281841 additions and 3273 deletions

No files matched your search

+66
View File
@@ -8,6 +8,11 @@
# 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:
@@ -23,6 +28,14 @@ on:
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
@@ -56,6 +69,10 @@ 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 nasm libxkbcommon-dev libxkbcommon-x11-dev libasound2-dev libfontconfig1-dev libvulkan-dev libudev-dev mesa-vulkan-drivers xvfb
@@ -75,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"
@@ -85,6 +115,13 @@ 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: |
@@ -110,15 +147,31 @@ jobs:
${{ 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" ${{ 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
@@ -135,7 +188,12 @@ 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: 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
@@ -162,12 +220,18 @@ jobs:
# 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: |
@@ -217,6 +281,7 @@ jobs:
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
@@ -290,6 +355,7 @@ jobs:
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: |
Generated
+267 -3
View File
@@ -4278,7 +4278,7 @@ dependencies = [
"arrayvec",
"cc",
"cfg-if",
"constant_time_eq",
"constant_time_eq 0.4.2",
"cpufeatures 0.3.1",
]
@@ -5074,6 +5074,15 @@ version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b"
[[package]]
name = "constant_time_eq"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9eb6feb175df65d0a3ccd3e73484e940d0ac664e8034f0519fd49a93db3071d9"
dependencies = [
"rustversion",
]
[[package]]
name = "constgebra"
version = "0.1.4"
@@ -13588,11 +13597,28 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "019b4b213425016d7d84a153c4c73afb0946fbb4840e4eece7ba8848b9d6da22"
[[package]]
name = "raea-app-capcut"
version = "0.1.0"
dependencies = [
"image",
"raea-core-scene",
"raea-io-alpha",
"raea-io-capcut",
"raea-io-home",
"raea-io-media",
"raea-runtime-bundle",
"serde_json",
]
[[package]]
name = "raea-app-check"
version = "0.1.0"
dependencies = [
"raea-core-brief",
"raea-core-facts",
"raea-io-trace",
"raea-sys-measure",
"serde_json",
]
@@ -13605,12 +13631,44 @@ dependencies = [
"serde_json",
]
[[package]]
name = "raea-app-direction"
version = "0.1.0"
dependencies = [
"raea-app-check",
"raea-app-notes",
"raea-app-registry",
"raea-core-brief",
"raea-core-facts",
"raea-io-trace",
"raea-runtime-bundle",
"raea-runtime-react",
"raea-runtime-world",
"serde_json",
]
[[package]]
name = "raea-app-engines"
version = "0.1.0"
dependencies = [
"dunce",
"raea-app-interchange",
"raea-app-tools",
"raea-io-home",
"raea-runtime-bundle",
"raea-runtime-calls",
"raea-runtime-export",
"serde_json",
"zip",
]
[[package]]
name = "raea-app-game"
version = "0.1.0"
dependencies = [
"base64 0.22.1",
"raea-gpu-device",
"raea-io-home",
"raea-io-media",
"raea-io-net",
"raea-runtime-export",
@@ -13623,12 +13681,25 @@ dependencies = [
"winit",
]
[[package]]
name = "raea-app-interchange"
version = "0.1.0"
dependencies = [
"raea-core-scene",
"raea-core-shape",
"raea-runtime-bundle",
"raea-runtime-export",
"raea-runtime-scene",
"serde_json",
]
[[package]]
name = "raea-app-judge"
version = "0.1.0"
dependencies = [
"base64 0.22.1",
"image",
"raea-core-facts",
"raea-io-home",
"raea-runtime-bundle",
"serde_json",
@@ -13639,6 +13710,7 @@ dependencies = [
name = "raea-app-media"
version = "0.1.0"
dependencies = [
"meshopt",
"raea-io-home",
"raea-io-media",
"raea-page",
@@ -13648,6 +13720,18 @@ dependencies = [
"serde_json",
]
[[package]]
name = "raea-app-notes"
version = "0.1.0"
dependencies = [
"raea-core-facts",
"raea-io-trace",
"serde",
"serde_json",
"sha2 0.10.9",
"tempfile",
]
[[package]]
name = "raea-app-play"
version = "0.1.0"
@@ -13665,11 +13749,21 @@ dependencies = [
"winit",
]
[[package]]
name = "raea-app-registry"
version = "0.1.0"
dependencies = [
"oxc",
"raea-core-facts",
"serde_json",
]
[[package]]
name = "raea-app-solid"
version = "0.1.0"
dependencies = [
"raea-app-judge",
"raea-core-facts",
"raea-core-meshcheck",
"raea-core-shape",
"raea-core-solidinfo",
@@ -13677,6 +13771,16 @@ dependencies = [
"serde_json",
]
[[package]]
name = "raea-app-sound"
version = "0.1.0"
dependencies = [
"raea-io-media",
"raea-runtime-bundle",
"raea-runtime-export",
"raea-sys-mix",
]
[[package]]
name = "raea-app-targets"
version = "0.1.0"
@@ -13704,7 +13808,10 @@ dependencies = [
name = "raea-app-workspace"
version = "0.1.0"
dependencies = [
"raea-app-check",
"raea-app-registry",
"raea-core-brief",
"raea-core-facts",
"serde_json",
]
@@ -13918,13 +14025,18 @@ name = "raea-cli"
version = "0.1.0"
dependencies = [
"bevy",
"raea-app-capcut",
"raea-app-check",
"raea-app-ci",
"raea-app-direction",
"raea-app-engines",
"raea-app-game",
"raea-app-judge",
"raea-app-media",
"raea-app-notes",
"raea-app-play",
"raea-app-solid",
"raea-app-sound",
"raea-app-targets",
"raea-app-tools",
"raea-app-workspace",
@@ -13987,6 +14099,16 @@ dependencies = [
name = "raea-core-ease"
version = "0.1.0"
[[package]]
name = "raea-core-facts"
version = "0.1.0"
dependencies = [
"raea-core-brief",
"serde",
"serde_json",
"ts-rs",
]
[[package]]
name = "raea-core-fonts"
version = "0.1.0"
@@ -14090,6 +14212,24 @@ dependencies = [
"wgpu",
]
[[package]]
name = "raea-io-alpha"
version = "0.1.0"
dependencies = [
"block2 0.6.2",
"image",
"objc2 0.6.5",
"objc2-av-foundation",
"objc2-core-foundation",
"objc2-core-media",
"objc2-core-video",
"objc2-foundation 0.3.2",
"objc2-video-toolbox",
"png 0.17.16",
"raea-io-apple",
"serde_json",
]
[[package]]
name = "raea-io-apple"
version = "0.1.0"
@@ -14149,6 +14289,13 @@ dependencies = [
"rav1e",
]
[[package]]
name = "raea-io-capcut"
version = "0.1.0"
dependencies = [
"serde_json",
]
[[package]]
name = "raea-io-codec"
version = "0.1.0"
@@ -14175,6 +14322,7 @@ name = "raea-io-gen"
version = "0.1.0"
dependencies = [
"image",
"raea-core-facts",
"raea-core-meshcheck",
"raea-io-gen-comfy",
"raea-io-gen-core",
@@ -14366,6 +14514,7 @@ dependencies = [
"raea-runtime-plugins",
"raea-runtime-twins",
"raea-sys-fonts",
"raea-sys-layers",
"raea-sys-page",
"serde_json",
"stylo",
@@ -14381,8 +14530,10 @@ dependencies = [
"base64 0.22.1",
"bevy",
"blitz-dom",
"blitz-html",
"blitz-traits",
"image",
"keyboard-types",
"raea-io-media",
"raea-io-net-calls",
"raea-io-os",
@@ -14434,6 +14585,7 @@ dependencies = [
"raea-runtime-js",
"raw-window-handle",
"serde_json",
"windows 0.62.2",
]
[[package]]
@@ -14510,6 +14662,14 @@ dependencies = [
"wgpu",
]
[[package]]
name = "raea-rerender-ios"
version = "0.1.0"
dependencies = [
"raea-runtime-export",
"raea-runtime-react",
]
[[package]]
name = "raea-rune-bevy"
version = "0.1.0"
@@ -14642,6 +14802,7 @@ dependencies = [
"raea-io-media",
"raea-native",
"raea-runtime-bundle-lib",
"raea-sys-layers",
"regex",
"serde_json",
"windows-sys 0.61.2",
@@ -14689,14 +14850,27 @@ dependencies = [
"keyboard-types",
"raea-core-wire",
"raea-io-net",
"raea-runtime-dom-media",
"raea-runtime-js",
"raea-runtime-twins",
"raea-sys-canvas",
"raea-sys-image",
"raea-sys-page",
"serde_json",
"stylo",
"url",
]
[[package]]
name = "raea-runtime-dom-media"
version = "0.1.0"
dependencies = [
"bevy",
"blitz-dom",
"raea-io-net",
"raea-runtime-js",
"raea-sys-image",
"raea-sys-page",
"serde_json",
"vello",
]
@@ -14738,10 +14912,12 @@ version = "0.1.0"
dependencies = [
"bevy",
"image",
"raea-core-facts",
"raea-core-program",
"raea-core-review",
"raea-core-scene",
"raea-gpu-device",
"raea-io-alpha",
"raea-io-assets",
"raea-io-media",
"raea-io-net",
@@ -14756,6 +14932,8 @@ dependencies = [
"raea-runtime-sound",
"raea-runtime-view",
"raea-sys-contact",
"raea-sys-frame",
"raea-sys-layers",
"raea-sys-light-meter",
"raea-sys-mix",
"raea-sys-page",
@@ -14801,6 +14979,7 @@ version = "0.1.0"
dependencies = [
"base64 0.22.1",
"bevy",
"cpal 0.15.3",
"raea-bevy-world",
"raea-core-wire",
"raea-io-home",
@@ -14839,6 +15018,7 @@ dependencies = [
"raea-runtime-page",
"raea-runtime-react",
"raea-runtime-sound",
"raea-sys-frame",
"raea-sys-mix",
"serde_json",
"twox-hash",
@@ -14924,6 +15104,7 @@ dependencies = [
"raea-runtime-plugins",
"raea-runtime-scene",
"raea-runtime-shared",
"raea-runtime-shots",
"raea-runtime-twins",
"raea-runtime-view",
"raea-sys-animate",
@@ -14944,6 +15125,7 @@ dependencies = [
"raea-core-scene",
"raea-runtime-look",
"raea-runtime-scene2d",
"raea-sys-frame",
"raea-sys-procmat",
"raea-sys-wear",
"serde_json",
@@ -14966,7 +15148,6 @@ dependencies = [
"bevy",
"raea-core-program",
"raea-runtime-plugins",
"raea-sys-compose",
"raea-sys-compute",
"raea-sys-fog",
"raea-sys-fog-half",
@@ -14991,6 +15172,17 @@ dependencies = [
"serde_json",
]
[[package]]
name = "raea-runtime-shots"
version = "0.1.0"
dependencies = [
"raea-io-assets",
"raea-native",
"raea-runtime-calls",
"raea-sys-bake",
"serde_json",
]
[[package]]
name = "raea-runtime-sound"
version = "0.1.0"
@@ -15044,6 +15236,28 @@ dependencies = [
"wgpu",
]
[[package]]
name = "raea-runtime-world"
version = "0.1.0"
dependencies = [
"bevy",
"flate2",
"image",
"raea-core-facts",
"raea-core-scene",
"raea-io-media",
"raea-runtime-bake",
"raea-runtime-bundle",
"raea-runtime-page",
"raea-runtime-react",
"raea-runtime-scene",
"raea-sys-layers",
"raea-sys-measure",
"raea-sys-vision",
"serde_json",
"sha2 0.10.9",
]
[[package]]
name = "raea-sdk-props"
version = "0.1.0"
@@ -15142,6 +15356,7 @@ name = "raea-sys-contact"
version = "0.1.0"
dependencies = [
"bevy",
"raea-core-facts",
"raea-core-meshcheck",
"raea-core-scene",
"raea-core-shape",
@@ -15187,6 +15402,9 @@ name = "raea-sys-fog-half"
version = "0.1.0"
dependencies = [
"bevy",
"raea-core-program",
"raea-sys-compose",
"raea-sys-fog",
"raea-sys-frame",
"wgpu",
]
@@ -15230,7 +15448,9 @@ dependencies = [
"raea-core-program",
"raea-core-scene",
"raea-io-media",
"raea-sys-layers",
"serde_json",
"wgpu",
]
[[package]]
@@ -15284,6 +15504,19 @@ dependencies = [
"wgpu",
]
[[package]]
name = "raea-sys-layers"
version = "0.1.0"
dependencies = [
"anyrender",
"blitz-dom",
"blitz-paint",
"flate2",
"glifo",
"serde_json",
"vello_cpu",
]
[[package]]
name = "raea-sys-layout"
version = "0.1.0"
@@ -15298,6 +15531,7 @@ version = "0.1.0"
dependencies = [
"bevy",
"image",
"raea-core-facts",
"raea-core-scene",
"serde_json",
]
@@ -15341,6 +15575,10 @@ dependencies = [
"serde_json",
]
[[package]]
name = "raea-sys-measure"
version = "0.1.0"
[[package]]
name = "raea-sys-mesh"
version = "0.1.0"
@@ -15473,6 +15711,7 @@ version = "0.1.0"
dependencies = [
"bevy",
"raea-core-program",
"raea-sys-compose",
"raea-sys-frame",
]
@@ -20247,6 +20486,12 @@ version = "2.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2"
[[package]]
name = "typed-path"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e"
[[package]]
name = "typedmap"
version = "0.6.0"
@@ -22879,6 +23124,25 @@ dependencies = [
"syn 3.0.9",
]
[[package]]
name = "zip"
version = "9.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3476fd497ac8af5b1ec7b51acab7bef380f7e8dd8e0487595bafd839417a302"
dependencies = [
"constant_time_eq 0.6.1",
"crc32fast",
"flate2",
"getrandom 0.4.3",
"indexmap",
"libc",
"memchr",
"nix",
"typed-path",
"windows-sys 0.61.2",
"zeroize",
]
[[package]]
name = "zlib-rs"
version = "0.6.8"
+16
View File
@@ -5,6 +5,7 @@ resolver = "2"
members = [
"core/animate",
"core/brief",
"core/facts",
"core/ease",
"core/fonts",
"core/program",
@@ -67,6 +68,8 @@ members = [
"io/ffmpeg",
"io/apple",
"io/apple-coding",
"io/alpha",
"io/capcut",
"io/shell",
"gpu/device",
"core/k",
@@ -85,6 +88,7 @@ members = [
"systems/bake",
"systems/contact",
"systems/light-meter",
"systems/measure",
"systems/canvas",
"systems/tweak",
"systems/filters",
@@ -94,6 +98,7 @@ members = [
"systems/page-net",
"systems/page-ops",
"systems/frame",
"systems/layers",
"systems/splat",
"systems/sprite",
"systems/rt",
@@ -118,8 +123,10 @@ members = [
"systems/image",
"runtime/twins",
"runtime/dom",
"runtime/dom/media",
"runtime/edit",
"runtime/view",
"runtime/world",
"runtime/encode",
"runtime/plugins",
"runtime/input",
@@ -132,12 +139,14 @@ members = [
"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/export",
"runtime/live",
"runtime/page",
@@ -147,14 +156,21 @@ members = [
"runtime/scene2d",
"runtime/shared",
"apps/check",
"apps/direction",
"apps/notes",
"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",
]
-176
View File
@@ -1,176 +0,0 @@
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
-25
View File
@@ -1,25 +0,0 @@
Copyright (c) 2018 Raph Levien
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.
-19
View File
@@ -1,19 +0,0 @@
Copyright (c) 2014-2020 Optimal Computing (NZ) Ltd
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.
-176
View File
@@ -1,176 +0,0 @@
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
-25
View File
@@ -1,25 +0,0 @@
Copyright 2025 the Vello Authors
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.
-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.
-176
View File
@@ -1,176 +0,0 @@
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
-25
View File
@@ -1,25 +0,0 @@
Copyright 2020 the Vello Authors
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.
-176
View File
@@ -1,176 +0,0 @@
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
-25
View File
@@ -1,25 +0,0 @@
Copyright 2020 the Vello Authors
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,202 +0,0 @@
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 [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
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.
-25
View File
@@ -1,25 +0,0 @@
Copyright (c) 2019-2026 The RustCrypto 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.
-7
View File
@@ -192,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
@@ -211,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
@@ -276,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
@@ -401,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
@@ -434,7 +428,6 @@ LICENSES/<crate>-<version>/.
zbus 5.19.0: MIT
zbus 6.2.1: MIT
zcheapstr 1.1.0: MIT
zeroize_derive 1.5.0: Apache-2.0 OR MIT
zruntime 0.2.2: MIT
zstd-safe 7.4.0: BSD-3-Clause
zstd-sys 2.1.2+zstd.1.5.7: BSD-3-Clause
+9 -3
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
+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();
}
+6
View File
@@ -9,4 +9,10 @@ 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" }
# caption contrast and loudness, measured as `raea world` measures a render (DR2)
raea-sys-measure = { path = "../../systems/measure" }
serde_json = "1"
+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);
}
}
+77 -33
View File
@@ -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;
@@ -23,6 +23,7 @@ use flash::*;
mod text;
use text::*;
pub mod quick;
pub mod hook;
#[cfg(test)]
mod tests;
@@ -39,35 +40,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] [--shape 16:9|9:16|4:5|1:1] [--platform tiktok|reels|shorts] [--taste taste.ts|DIR] [-o check.json] (an export against the floor: clipped text, contrast, safe areas, freezes, flashing, cues, loudness, blotching, a placeholder brand kit; its findings errors, warns and notes)";
/// A rule from the person's taste: a form raea can measure, its value, and the taste line it stands for.
#[derive(Clone, Debug, PartialEq)]
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 +95,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 +107,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-") {
@@ -107,14 +120,31 @@ fn taste_text(rules: &[Taste], runs: &[Run], w: f64, h: f64, issues: &mut Vec<Is
const TAKES: [&str; 7] = ["--manifest", "--words", "--perception", "--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 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,
@@ -143,36 +173,50 @@ 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)> {
/// 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);
finding::ranked(
issues
.iter()
.map(|i| {
let f = Finding::new(i.rule, Level::of_rank(i.p), &i.says, "raea check");
// an issue at a second is about the frame it falls on
match i.at {
Some(t) => {
let fr = (t * fps).round() as i64;
f.frames(fr, fr + 1)
}
None => f,
}
})
.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 {
+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);
}
}
+4 -6
View File
@@ -206,17 +206,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 +256,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 },
});
}
+3 -3
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
+11 -58
View File
@@ -195,20 +195,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 +203,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 +221,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"];
+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 }
+371
View File
@@ -0,0 +1,371 @@
//! `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.
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") {
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| (w.join("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()]));
}
}
+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"
+1 -1
View File
@@ -1,7 +1,7 @@
//! 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|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`,
+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);
}
}
-32
View File
@@ -90,30 +90,6 @@ pub fn offer(agent: &str) -> R<String> {
Ok(line(add_json(&p)?, &p))
}
/// A hook entry raea added (its command is `raea hook ...`).
fn ours(hook: &Value) -> bool {
hook["command"].as_str().unwrap_or("").starts_with("raea hook")
}
/// Claude Code's PostToolUse hook running `raea hook claude` after a file is written, in its settings.json, unless one
/// is there; true when it added. Its findings reach the agent as the hook's additionalContext.
pub fn claude_hook(settings: &Path) -> R<bool> {
let mut doc: Value = match std::fs::read_to_string(settings) {
Ok(t) if !t.trim().is_empty() => serde_json::from_str(&t).map_err(|e| format!("{}: {e}", settings.display()))?,
_ => json!({}),
};
let post = doc.as_object_mut().ok_or("settings.json isn't an object")?.entry("hooks").or_insert_with(|| json!({})).as_object_mut().ok_or("settings.json: hooks isn't an object")?.entry("PostToolUse").or_insert_with(|| json!([]));
let list = post.as_array_mut().ok_or("settings.json: hooks.PostToolUse isn't a list")?;
if list.iter().any(|m| m["hooks"].as_array().into_iter().flatten().any(ours)) {
return Ok(false);
}
list.push(json!({"matcher": "Write|Edit|MultiEdit", "hooks": [{"type": "command", "command": "raea hook claude", "timeout": 60}]}));
let tmp = settings.with_extension("raea-tmp");
std::fs::write(&tmp, serde_json::to_string_pretty(&doc).unwrap_or_default() + "\n").map_err(|e| format!("{}: {e}", tmp.display()))?;
std::fs::rename(&tmp, settings).map_err(|e| format!("{}: {e}", settings.display()))?;
Ok(true)
}
/// A move's guide as a skill of its own, named for the move: its description from the guide's first paragraph.
pub fn pin(to: &Path, mv: &str, v: &str) -> R<String> {
let guide = raea_io_home::home().join("sdk/guides/craft/verbs").join(format!("{mv}.md"));
@@ -151,14 +127,6 @@ mod tests {
assert!(add_toml(&t).unwrap());
assert!(!add_toml(&t).unwrap());
assert_eq!(std::fs::read_to_string(&t).unwrap(), "model = \"x\"\n\n[mcp_servers.blender]\ncommand = \"uvx\"\nargs = [\"mcp-for-blender\"]\n");
let h = d.join("claude/settings.json");
std::fs::create_dir_all(h.parent().unwrap()).unwrap();
std::fs::write(&h, r#"{"model":"x","hooks":{"PostToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"other"}]}]}}"#).unwrap();
assert!(claude_hook(&h).unwrap());
assert!(!claude_hook(&h).unwrap());
let v: Value = serde_json::from_str(&std::fs::read_to_string(&h).unwrap()).unwrap();
assert_eq!(v["hooks"]["PostToolUse"].as_array().unwrap().len(), 2);
assert_eq!(v["model"], "x");
let _ = std::fs::remove_dir_all(&d);
}
+103 -28
View File
@@ -1,26 +1,28 @@
//! `raea setup blender` and `raea blender run` (docs/skills.feature SK11). Blender is GPL, so raea never bundles it: it
//! finds the person's Blender, or downloads the current LTS from blender.org into ~/.raea/tools/blender, and runs it as
//! its own program. The setup also installs the MCP for Blender add-on (github.com/ahujasid/mcp-for-blender, MIT) into
//! that Blender, so an agent's `blender` MCP server (raea skills install adds it) can drive a running Blender.
//! its own program. The setup also installs two add-ons into that Blender: raea's own (sdk/blender/python/raea_blender),
//! so a TypeScript script drives the Blender the person has open (RAEA_BLENDER=live; docs/blender.feature BL28), and
//! MCP for Blender (github.com/ahujasid/mcp-for-blender, MIT), so an agent's `blender` MCP server (raea skills install
//! adds it) can drive it too.
use std::path::{Path, PathBuf};
use std::process::Command;
type R<T> = Result<T, String>;
pub const USAGE: &str = "raea setup blender [--check] [--download] (find Blender or download the LTS into ~/.raea/tools/blender, and install its MCP add-on)\n raea blender run SCRIPT.py [ARGS...] (blender --background --python SCRIPT.py -- ARGS, headless; blender/X.py missing from the project is copied from the library: convert, decimate, repair, split, bake, rig, cloth)";
pub const USAGE: &str = "raea setup blender [--check] [--download] (find Blender or download the LTS into ~/.raea/tools/blender, and install raea's add-on and the MCP add-on)\n raea blender run SCRIPT.py [ARGS...] (blender --background --python SCRIPT.py -- ARGS, headless; blender/X.py missing from the project is copied from the library: convert, decimate, repair, split, bake, rig, cloth)\n raea blender run SCRIPT.ts [FILE.blend] [ARGS...] (a TypeScript script against Blender's whole Python API through raea/blender: bpy, bmesh, mathutils, typed; a headless Blender, FILE.blend opened, quit when the script ends)";
/// The LTS series raea downloads; the newest patch in blender.org/release/Blender<LTS>/ is taken. Moved when Blender
/// ships a new LTS (blender.org/download/lts).
const LTS: &str = "5.2";
/// Where raea keeps the Blender it downloads.
fn own_dir() -> R<PathBuf> {
Ok(crate::agent_mcp::user_home()?.join(".raea/tools/blender"))
/// Where raea keeps a tool it downloads, ~/.raea/tools/NAME: Blender here, Godot in apps/engines.
pub fn own_dir(name: &str) -> R<PathBuf> {
Ok(crate::agent_mcp::user_home()?.join(".raea/tools").join(name))
}
/// The Blender binary inside raea's own download, per platform.
fn own_binary() -> R<PathBuf> {
let d = own_dir()?;
let d = own_dir("blender")?;
Ok(if cfg!(target_os = "macos") { d.join("Blender.app/Contents/MacOS/Blender") } else if cfg!(windows) { d.join("blender.exe") } else { d.join("blender") })
}
@@ -51,10 +53,21 @@ pub fn find() -> Option<(PathBuf, &'static str)> {
/// `blender --version`'s first line ("Blender 5.2.1 LTS").
fn version(bin: &Path) -> R<String> {
let o = Command::new(bin).arg("--version").output().map_err(|e| format!("{}: {e}", bin.display()))?;
String::from_utf8_lossy(&o.stdout).lines().find(|l| l.starts_with("Blender ")).map(str::to_string).ok_or_else(|| format!("{} --version printed no version", bin.display()))
String::from_utf8_lossy(&o.stdout).lines().find(|l| l.starts_with("Blender ")).map(str::to_string).ok_or_else(|| {
let err = String::from_utf8_lossy(&o.stderr);
if err.contains("error while loading shared libraries") {
format!("{} can't start: {} (on Debian or Ubuntu: apt install {LINUX_LIBS})", bin.display(), err.trim())
} else {
format!("{} --version printed no version", bin.display())
}
})
}
fn run(cmd: &mut Command, what: &str) -> R<String> {
/// What Blender's Linux build needs that a slim Debian (trixie) lacks: found 11-11 by running it in debian:trixie-slim
/// (docs/blender.feature BL29); CUDA, HIP and oneAPI are loaded only when Cycles renders on those GPUs.
const LINUX_LIBS: &str = "libx11-6 libxi6 libxext6 libxfixes3 libxrender1 libxkbcommon0 libsm6 libice6 libgl1 libopengl0";
pub fn run(cmd: &mut Command, what: &str) -> R<String> {
let o = cmd.output().map_err(|e| format!("{what}: {e}"))?;
if !o.status.success() {
return Err(format!("{what} failed: {}{}", String::from_utf8_lossy(&o.stderr).trim(), String::from_utf8_lossy(&o.stdout).trim()));
@@ -89,11 +102,14 @@ fn newest(listing: &str) -> Option<String> {
best.map(|(_, v)| v)
}
fn sha256(file: &Path) -> R<String> {
pub fn sha256(file: &Path) -> R<String> {
let out = if cfg!(windows) {
run(Command::new("certutil").arg("-hashfile").arg(file).arg("SHA256"), "certutil")?.lines().nth(1).unwrap_or_default().replace(' ', "")
} else {
} else if on_path("shasum").is_some() {
run(Command::new("shasum").args(["-a", "256"]).arg(file), "shasum")?.split_whitespace().next().unwrap_or_default().to_string()
} else {
// a slim Linux (debian:trixie-slim) has coreutils' sha256sum, not perl's shasum
run(Command::new("sha256sum").arg(file), "sha256sum")?.split_whitespace().next().unwrap_or_default().to_string()
};
Ok(out.to_lowercase())
}
@@ -104,7 +120,7 @@ fn download() -> R<(PathBuf, String)> {
let listing = run(Command::new("curl").args(["-fsSL", &base]), "curl")?;
let v = newest(&listing).ok_or_else(|| format!("no Blender {LTS} release listed at {base}"))?;
let name = asset(&v)?;
let dir = own_dir()?;
let dir = own_dir("blender")?;
let tmp = dir.with_file_name("blender.download");
let _ = std::fs::remove_dir_all(&tmp);
std::fs::create_dir_all(&tmp).map_err(|e| format!("{}: {e}", tmp.display()))?;
@@ -140,53 +156,103 @@ fn download() -> R<(PathBuf, String)> {
Ok((own_binary()?, format!("downloaded Blender {v} LTS from blender.org")))
}
/// Python run inside Blender (background): prints the user add-ons folder, or whether the add-on is enabled.
/// Python run inside Blender (background): prints the user add-ons folder.
const ADDONS_DIR: &str = "import bpy; print('RAEA_ADDONS=' + bpy.utils.user_resource('SCRIPTS', path='addons', create=True))";
const ENABLE: &str = "import addon_utils, bpy; addon_utils.enable('blender_mcp', default_set=True, persistent=True); bpy.ops.wm.save_userpref(); print('RAEA_ENABLED=' + str(addon_utils.check('blender_mcp')[1]))";
const CHECK: &str = "import addon_utils; print('RAEA_ENABLED=' + str(addon_utils.check('blender_mcp')[1]))";
fn py(bin: &Path, code: &str, key: &str) -> R<String> {
let out = run(Command::new(bin).args(["--background", "--factory-startup", "--python-expr", code]), "blender")?;
out.lines().find_map(|l| l.strip_prefix(key)).map(str::to_string).ok_or_else(|| format!("blender printed no {key}"))
}
/// The add-on: uvx mcp-for-blender's own installer writes it into this Blender's add-ons folder, then Blender enables it.
/// Whether an add-on is enabled in this Blender's saved preferences (--factory-startup would skip them).
fn enabled(bin: &Path, module: &str) -> R<bool> {
let code = format!("import addon_utils; print('RAEA_ENABLED=' + str(addon_utils.check('{module}')[1]))");
run(Command::new(bin).args(["--background", "--python-expr", &code]), "blender").map(|o| o.contains("RAEA_ENABLED=True"))
}
/// Enables an add-on that is in the add-ons folder, and saves the preferences so it starts with Blender.
fn enable(bin: &Path, module: &str, dir: &str, name: &str) -> R<()> {
let code = format!("import addon_utils, bpy; addon_utils.enable('{module}', default_set=True, persistent=True); bpy.ops.wm.save_userpref(); print('RAEA_ENABLED=' + str(addon_utils.check('{module}')[1]))");
let on = run(Command::new(bin).args(["--background", "--python-expr", &code]), "blender")?;
if !on.contains("RAEA_ENABLED=True") {
return Err(format!("the add-on is in {dir} but Blender didn't enable it: enable \"{name}\" in Preferences > Add-ons"));
}
Ok(())
}
/// The MCP add-on: uvx mcp-for-blender's own installer writes it into this Blender's add-ons folder, then Blender enables it.
fn addon(bin: &Path, check: bool) -> R<String> {
// --factory-startup skips the person's add-ons for speed, so the check reads the saved preferences instead
let state = |b: &Path| run(Command::new(b).args(["--background", "--python-expr", CHECK]), "blender").map(|o| o.contains("RAEA_ENABLED=True"));
if state(bin)? {
if enabled(bin, "blender_mcp")? {
return Ok("MCP add-on enabled".into());
}
if check {
return Ok("MCP add-on not installed: raea setup blender installs it".into());
}
let uvx = on_path(if cfg!(windows) { "uvx.exe" } else { "uvx" }).ok_or("the MCP add-on comes from uv's uvx: install uv (https://docs.astral.sh/uv/getting-started/installation/), then run raea setup blender again")?;
// the MCP add-on is for agents; scripts don't need it, so a machine without uv still finishes its setup
let Some(uvx) = on_path(if cfg!(windows) { "uvx.exe" } else { "uvx" }) else {
return Ok("MCP add-on not installed: it comes from uv's uvx (install uv: https://docs.astral.sh/uv/getting-started/installation/, then raea setup blender again)".into());
};
let dir = py(bin, ADDONS_DIR, "RAEA_ADDONS=")?;
run(Command::new(&uvx).args(["mcp-for-blender", "install-addon", "--addons-dir", &dir]), "uvx mcp-for-blender install-addon")?;
let on = run(Command::new(bin).args(["--background", "--python-expr", ENABLE]), "blender")?;
if !on.contains("RAEA_ENABLED=True") {
return Err(format!("the add-on is in {dir} but Blender didn't enable it: enable \"MCP for Blender\" in Preferences > Add-ons"));
}
// its installer prints arrows, which Python can't encode for Windows' cp1252 console: it threw and setup failed
// (11-11), so it writes UTF-8
run(Command::new(&uvx).args(["mcp-for-blender", "install-addon", "--addons-dir", &dir]).env("PYTHONIOENCODING", "utf-8").env("PYTHONUTF8", "1"), "uvx mcp-for-blender install-addon")?;
enable(bin, "blender_mcp", &dir, "MCP for Blender")?;
Ok(format!("MCP add-on installed now ({dir})"))
}
/// raea's add-on as raea ships it (its home's sdk/, else this checkout's): the folder and its Python files.
fn bridge_files() -> R<(PathBuf, Vec<PathBuf>)> {
let shipped = raea_io_home::home().join("sdk/blender/python/raea_blender");
let here = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../sdk/blender/python/raea_blender");
let dir = [shipped.clone(), here].into_iter().find(|d| d.is_dir()).ok_or_else(|| format!("raea's Blender add-on isn't here ({}): reinstall raea", shipped.display()))?;
let mut files: Vec<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(|x| x == "py")).collect();
files.sort();
Ok((dir, files))
}
/// raea's add-on (BL28): copied into this Blender's add-ons folder, replacing an older copy, and enabled. Started with a
/// window, that Blender serves raea/blender on 127.0.0.1 behind a token and writes ~/.raea/blender/live.json.
fn bridge_addon(bin: &Path, check: bool) -> R<String> {
let (_, files) = bridge_files()?;
let dir = py(bin, ADDONS_DIR, "RAEA_ADDONS=")?;
let to = Path::new(&dir).join("raea_blender");
let current = files.iter().all(|f| f.file_name().is_some_and(|n| std::fs::read(to.join(n)).ok() == std::fs::read(f).ok()));
if current && enabled(bin, "raea_blender")? {
return Ok("raea's add-on enabled (live: start Blender, then RAEA_BLENDER=live or connect({ live: true }))".into());
}
if check {
return Ok(format!("raea's add-on {}: raea setup blender installs it", if to.is_dir() { "out of date or off" } else { "not installed" }));
}
let _ = std::fs::remove_dir_all(&to);
std::fs::create_dir_all(&to).map_err(|e| format!("{}: {e}", to.display()))?;
for f in &files {
let name = f.file_name().unwrap_or_default();
std::fs::copy(f, to.join(name)).map_err(|e| format!("{}: {e}", to.join(name).display()))?;
}
enable(bin, "raea_blender", &dir, "raea bridge")?;
Ok(format!("raea's add-on installed now ({}; live: start Blender, then RAEA_BLENDER=live or connect({{ live: true }}))", to.display()))
}
/// `raea setup blender [--check] [--download]`.
pub fn setup(args: &[String]) -> R<String> {
let check = args.iter().any(|a| a == "--check");
let fresh = args.iter().any(|a| a == "--download");
let (bin, from) = match find().filter(|_| !fresh) {
Some((b, f)) => (b, f.to_string()),
None if check => return Ok(format!("CHECKED no Blender found (raea.blender, {}, PATH): raea setup blender downloads Blender {LTS} LTS", own_dir()?.display())),
None if check => return Ok(format!("CHECKED no Blender found (raea.blender, {}, PATH): raea setup blender downloads Blender {LTS} LTS", own_dir("blender")?.display())),
None => {
let (b, f) = download()?;
run(Command::new("git").args(["config", "--global", "raea.blender"]).arg(&b), "git config")?;
// remembered for tools that read raea.blender; find() takes raea's download anyway, so a machine without
// git (a Mac before its command line tools, Windows) is set up all the same
let _ = run(Command::new("git").args(["config", "--global", "raea.blender"]).arg(&b), "git config");
(b, f)
}
};
let v = version(&bin)?;
let own = bridge_addon(&bin, check)?;
let add = addon(&bin, check)?;
let head = if check { "CHECKED " } else { "APPLIED " };
Ok(format!("{head} {v} ({from})\n {}\n {add}\n headless: raea blender run SCRIPT.py; live: start Blender and the agent's `blender` MCP server connects (raea skills install adds it)", bin.display()))
Ok(format!("{head} {v} ({from})\n {}\n {own}\n {add}\n headless: raea blender run SCRIPT.py|.ts; live: start Blender and the agent's `blender` MCP server connects (raea skills install adds it)", bin.display()))
}
/// The library's scripts (sdk/guides/craft/bevy/blender: convert, decimate, repair, split, bake, rig, cloth): a fix
@@ -238,6 +304,15 @@ mod tests {
assert_eq!(newest("nothing here"), None);
}
#[test]
fn sha256_of_a_known_file() {
let f = std::env::temp_dir().join(format!("raea-sha256-{}", std::process::id()));
std::fs::write(&f, b"abc").unwrap();
let got = sha256(&f);
let _ = std::fs::remove_file(&f);
assert_eq!(got.unwrap(), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
}
#[test]
fn every_supported_platform_names_one_file() {
assert!(asset("5.2.1").unwrap().starts_with("blender-5.2.1-"));
+1
View File
@@ -10,5 +10,6 @@ pub mod splat;
/// the MCP servers `raea skills install` offers an agent (blender, for a running Blender)
pub mod agent_mcp;
pub mod agent_hooks;
/// `raea setup blender` and `raea blender run`
pub mod blender;
+6
View File
@@ -10,3 +10,9 @@ description = "`raea workspace`, `raea project` and `raea controller`: a workspa
# the controller schema (core/brief controller.rs): a controller file is checked and normalized against it
raea-core-brief = { path = "../../core/brief" }
serde_json = "1"
# a project's compositions, components and controllers read from their source (docs/projects.feature PJ8)
raea-app-registry = { path = "registry" }
# the project's record of what renders and checks found, which raea next reads (docs/direction.feature DR3)
raea-core-facts = { path = "../../core/facts" }
# a command's words (its arguments that aren't flags or their values), read as raea check reads them
raea-app-check = { path = "../check" }
+14
View File
@@ -0,0 +1,14 @@
[package]
name = "raea-app-registry"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "A raea project's compositions, components and controllers, read from their source without running it, and lint for what isn't connected (docs/projects.feature PJ8)"
[dependencies]
# the version engine/bundle parses TSX with
oxc = { version = "=0.152.0", features = ["ast_visit"] }
serde_json = "1"
# what the scan finds, as raea's one Finding (docs/direction.feature DR3)
raea-core-facts = { path = "../../../core/facts" }
+320
View File
@@ -0,0 +1,320 @@
//! A project's compositions, components and controllers, registered by reading its files (docs/projects.feature PJ8),
//! so the raea app, `raea project scan`, `raea doctor` and `raea next` agree on what each file is:
//! - a composition is each <Composition> a registerRoot registers (its props read from the source, not rendered), or a
//! .tsx's default export with none that no other file imports, registered for it under its file's name (versions
//! NAME-vN.tsx are one composition), sized from its newest render's manifest when it has one;
//! - a component is a .tsx a composition imports, directly or through another;
//! - a controller is a module whose default export is `controller({...})` from "raea/brief".
//! What isn't connected is linted (lint.rs), each with its file and line and the fix. raea-app-workspace wraps `scan`
//! with the project's controller overrides (read from .raea/project's git config) and runs it for `raea project scan`,
//! `raea doctor`, `raea next` and `raea context`.
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use serde_json::{Value, json};
mod lint;
mod read;
pub use lint::{Fix, Level, Lint, apply};
pub use read::{Facts, Prop};
/// The nearest folder at or above a path that holds a marker (.raea/workspace, .raea/project), as the record finds it.
pub use raea_core_facts::record::up;
/// A name as a folder: lowercase, dashes. A controller's id from its title is this (core/brief fills it the same way).
pub fn slug(s: &str) -> String {
let mut out = String::new();
for c in s.trim().to_lowercase().chars() {
if c.is_ascii_alphanumeric() {
out.push(c);
} else if !out.is_empty() && !out.ends_with('-') {
out.push('-');
}
}
out.trim_end_matches('-').to_string()
}
#[cfg(test)]
mod tests;
/// Folders that hold no compositions: media, renders, packages, raea's own (host/compositions.ts skips the same).
const SKIP: &[&str] = &["node_modules", ".git", ".raea", "media", "out", "renders", "raw-audio", "stills", "dist", "build"];
const MAX_FILES: usize = 600;
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum How {
/// a <Composition> in a registerRoot
Registered,
/// a default export with no <Composition>, registered under its file's name
Default,
}
#[derive(Debug, Clone)]
pub struct Composition {
pub id: String,
/// relative to the scanned folder, with `/`
pub file: String,
pub line: usize,
pub how: How,
pub component: Option<String>,
pub width: Option<Prop>,
pub height: Option<Prop>,
pub fps: Option<Prop>,
pub frames: Option<Prop>,
}
#[derive(Debug, Clone)]
pub struct Component {
pub file: String,
/// the composition files that import it, directly or through another file
pub used_by: Vec<String>,
}
#[derive(Debug, Clone)]
pub struct Controller {
pub id: Option<String>,
pub file: String,
pub line: usize,
}
#[derive(Debug)]
pub struct Registry {
pub dir: PathBuf,
/// the folder is in a raea project (.raea/project at or above it)
pub project: bool,
pub compositions: Vec<Composition>,
pub components: Vec<Component>,
pub controllers: Vec<Controller>,
pub lint: Vec<Lint>,
}
/// One file read: its path and what it declares.
pub(crate) struct File {
pub path: PathBuf,
pub rel: String,
pub facts: Facts,
}
/// Every .tsx and .ts under the folder, a few levels down, skipping media, packages, raea's own folders and generated
/// files (NAME.gen.tsx: written by a tool, not a person).
fn sources(dir: &Path, rel: &str, depth: usize, out: &mut Vec<(PathBuf, String)>) {
if depth > 4 || out.len() >= MAX_FILES {
return;
}
let Ok(rd) = std::fs::read_dir(dir) else { return };
let mut entries: Vec<_> = rd.flatten().collect();
entries.sort_by_key(|e| e.file_name());
for e in entries {
let name = e.file_name().to_string_lossy().into_owned();
let p = e.path();
let r = if rel.is_empty() { name.clone() } else { format!("{rel}/{name}") };
if p.is_dir() {
if !name.starts_with('.') && !SKIP.contains(&name.as_str()) {
sources(&p, &r, depth + 1, out);
}
} else if (name.ends_with(".tsx") || name.ends_with(".ts")) && !name.ends_with(".d.ts") && !name.ends_with(".gen.tsx") && !name.ends_with(".gen.ts") {
out.push((p, r));
}
}
}
/// NAME for NAME.tsx and NAME-vN.tsx: one composition's versions share it.
pub fn stem(file: &str) -> String {
let base = file.rsplit('/').next().unwrap_or(file).trim_end_matches(".tsx").trim_end_matches(".ts");
match base.rsplit_once("-v") {
Some((name, n)) if !name.is_empty() && !n.is_empty() && n.chars().all(|c| c.is_ascii_digit()) => name.to_string(),
_ => base.to_string(),
}
}
/// The file a relative or absolute import names: as written, or with .tsx, .ts, .jsx or .js (in place of an extension
/// or after the name), or its folder's index.
pub(crate) fn resolve(from: &Path, spec: &str) -> Option<PathBuf> {
let base = if spec.starts_with('/') { PathBuf::from(spec) } else { from.parent()?.join(spec) };
let mut tries = vec![base.clone()];
for ext in ["tsx", "ts", "jsx", "js"] {
tries.push(base.with_extension(ext));
tries.push(PathBuf::from(format!("{}.{ext}", base.display())));
}
tries.extend([base.join("index.tsx"), base.join("index.ts")]);
let found = tries.into_iter().find(|p| p.is_file())?;
Some(std::fs::canonicalize(&found).unwrap_or(found))
}
/// An import of a file (not a package): relative or absolute.
pub(crate) fn is_path(spec: &str) -> bool {
spec.starts_with("./") || spec.starts_with("../") || spec.starts_with('/')
}
/// A version's newest render manifest: NAME[-vN][.play].render.json beside it, or the folder's render.json for edit.tsx.
fn manifest(path: &Path) -> Option<Value> {
let dir = path.parent()?;
let base = path.file_name()?.to_string_lossy().trim_end_matches(".tsx").to_string();
let mut tries = vec![dir.join(format!("{base}.render.json")), dir.join(format!("{base}.play.render.json"))];
if base == "edit" {
tries.push(dir.join("render.json"));
}
let f = tries.into_iter().find(|p| p.is_file())?;
serde_json::from_str(&std::fs::read_to_string(f).ok()?).ok()
}
/// The folder's registry. `overridden`: the controller ids the project's overrides name, each checked against the
/// controllers there (the folder's and its workspace's controllers/).
pub fn scan(dir: &Path, overridden: &[String]) -> Registry {
let dir = std::fs::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf());
let project = up(&dir, ".raea/project").is_some();
let mut found = Vec::new();
sources(&dir, "", 0, &mut found);
let files: Vec<File> = found
.into_iter()
.map(|(path, rel)| {
let src = std::fs::read_to_string(&path).unwrap_or_default();
let facts = read::read(&src, rel.ends_with(".tsx"));
File { path: std::fs::canonicalize(&path).unwrap_or(path), rel, facts }
})
.collect();
// a default-exported part another file imports (kit/statcard.tsx) is a component, not a piece of its own
let imported: BTreeSet<PathBuf> = files.iter().flat_map(|f| f.facts.imports.iter().filter(|(s, _)| is_path(s)).filter_map(|(s, _)| resolve(&f.path, s))).collect();
let mut compositions = Vec::new();
for f in &files {
if !f.facts.registered.is_empty() {
for r in &f.facts.registered {
let id = match &r.id {
Some(Prop::Text(t)) => t.clone(),
Some(Prop::Num(n)) => n.to_string(),
_ => stem(&f.rel),
};
compositions.push(Composition { id, file: f.rel.clone(), line: r.line, how: How::Registered, component: r.component.clone(), width: r.width.clone(), height: r.height.clone(), fps: r.fps.clone(), frames: r.frames.clone() });
}
} else if f.rel.ends_with(".tsx") && f.facts.default.is_some() && !imported.contains(&f.path) {
let m = manifest(&f.path);
let num = |k: &str| m.as_ref().and_then(|m| m[k].as_f64()).map(Prop::Num);
let frames = m.as_ref().and_then(|m| m["frames"].as_array()).map(|a| Prop::Num(a.len() as f64));
compositions.push(Composition { id: stem(&f.rel), file: f.rel.clone(), line: 1, how: How::Default, component: f.facts.default.clone().flatten(), width: num("width"), height: num("height"), fps: num("fps"), frames });
}
}
// the files each composition reaches through its imports, inside the scanned folder
let by_path: BTreeMap<&Path, &File> = files.iter().map(|f| (f.path.as_path(), f)).collect();
let comp_files: BTreeSet<&str> = compositions.iter().map(|c| c.file.as_str()).collect();
let mut used_by: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
for f in files.iter().filter(|f| comp_files.contains(f.rel.as_str())) {
let mut seen = BTreeSet::new();
let mut stack = vec![f];
while let Some(at) = stack.pop() {
for (spec, _) in at.facts.imports.iter().filter(|(s, _)| is_path(s)) {
let Some(to) = resolve(&at.path, spec) else { continue };
if let Some(g) = by_path.get(to.as_path())
&& seen.insert(g.rel.clone())
{
stack.push(g);
}
}
}
for r in seen {
used_by.entry(r).or_default().insert(f.rel.clone());
}
}
let components = files
.iter()
.filter(|f| f.rel.ends_with(".tsx") && !comp_files.contains(f.rel.as_str()) && used_by.contains_key(&f.rel))
.map(|f| Component { file: f.rel.clone(), used_by: used_by[&f.rel].iter().cloned().collect() })
.collect();
let controllers = files.iter().filter_map(|f| f.facts.controller.as_ref().map(|c| Controller { id: c.id.clone(), file: f.rel.clone(), line: c.line })).collect();
let mut reg = Registry { dir, project, compositions, components, controllers, lint: Vec::new() };
reg.lint = lint::lint(&reg, &files, &used_by, overridden);
reg
}
impl Registry {
/// What isn't connected: the warnings (the notes say what only the render knows).
pub fn warnings(&self) -> impl Iterator<Item = &Lint> {
self.lint.iter().filter(|l| l.level == Level::Warn)
}
/// The compositions' files, each once, the newest first.
pub fn composition_files(&self) -> Vec<PathBuf> {
let mut out: Vec<PathBuf> = Vec::new();
for c in &self.compositions {
let p = self.dir.join(&c.file);
if !out.contains(&p) {
out.push(p);
}
}
out.sort_by_cached_key(|p| std::cmp::Reverse(std::fs::metadata(p).and_then(|m| m.modified()).ok()));
out
}
pub fn json(&self) -> Value {
let p = |v: &Option<Prop>| v.as_ref().map_or(Value::Null, Prop::json);
json!({
"dir": self.dir,
"project": self.project,
"compositions": self.compositions.iter().map(|c| json!({
"id": c.id, "file": c.file, "line": c.line,
"how": if c.how == How::Registered { "registered" } else { "default" },
"component": c.component, "width": p(&c.width), "height": p(&c.height), "fps": p(&c.fps), "frames": p(&c.frames),
})).collect::<Vec<_>>(),
"components": self.components.iter().map(|c| json!({ "file": c.file, "usedBy": c.used_by })).collect::<Vec<_>>(),
"controllers": self.controllers.iter().map(|c| json!({ "id": c.id, "file": c.file, "line": c.line })).collect::<Vec<_>>(),
"findings": self.lint.iter().map(Lint::finding).collect::<Vec<_>>(),
})
}
/// For an agent (`raea context`): each composition with its id, file, size, fps and length, the components and
/// controllers, and what isn't connected (its warnings, at most ten; the notes are `raea project scan`'s).
pub fn summary(&self) -> String {
let p = |v: &Option<Prop>| match v {
Some(Prop::Num(n)) => format!("{n}"),
Some(Prop::Text(t)) => t.clone(),
Some(Prop::Computed(_)) => "(computed)".into(),
None => "?".into(),
};
let mut out = String::new();
for c in &self.compositions {
out.push_str(&format!("composition {}: {}:{}, {}x{}, {} fps, {} frames{}\n", c.id, c.file, c.line, p(&c.width), p(&c.height), p(&c.fps), p(&c.frames), if c.how == How::Default { " (its default export, not registered)" } else { "" }));
}
if self.compositions.is_empty() {
out.push_str("no compositions yet: a .tsx whose registerRoot registers a <Composition id width height fps durationInFrames />\n");
}
if !self.components.is_empty() {
out.push_str(&format!("components: {}\n", self.components.iter().map(|c| c.file.as_str()).collect::<Vec<_>>().join(", ")));
}
if !self.controllers.is_empty() {
out.push_str(&format!("controllers: {}\n", self.controllers.iter().map(|c| format!("{} ({})", c.id.as_deref().unwrap_or("?"), c.file)).collect::<Vec<_>>().join(", ")));
}
let warn: Vec<&Lint> = self.warnings().collect();
if !warn.is_empty() {
out.push_str(&format!("\nnot connected ({}; raea doctor --fix fixes what it can):\n", warn.len()));
for l in warn.iter().take(10) {
out.push_str(&format!("- {}\n", l.line()));
}
}
out.trim_end().to_string()
}
/// What it found, for a person: a line for the counts and one each composition, then its findings worst first,
/// each about its file:line with the fix, and their count last.
pub fn text(&self) -> String {
let mut out = format!(
"{}: {} compositions, {} components, {} controllers",
self.dir.display(),
self.compositions.len(),
self.components.len(),
self.controllers.len()
);
for c in &self.compositions {
out.push_str(&format!("\n composition {} ({}:{}{})", c.id, c.file, c.line, if c.how == How::Default { ", its default export" } else { "" }));
}
let found = raea_core_facts::finding::ranked(self.lint.iter().map(Lint::finding).collect());
for f in &found {
let at = f.about.first().map(|a| a.key.clone().unwrap_or_else(|| a.name.clone())).unwrap_or_default();
out.push_str(&format!("\n{at}: {}", f.line()));
}
out.push_str(&format!("\nraea project scan: {}", raea_core_facts::finding::count(&found)));
out
}
}
+229
View File
@@ -0,0 +1,229 @@
//! What in a project isn't connected to raea's project system (docs/projects.feature PJ8), each with its file and line,
//! what's wrong and the fix; `raea doctor --fix` applies the ones it can (`apply`).
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use raea_core_facts::{Finding, finding};
use super::{File, How, Prop, Registry, is_path, resolve, stem};
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Level {
/// not connected: something reads it wrong or not at all
Warn,
/// said so the person knows (a size only the render knows), not wrong
Info,
}
/// What `--fix` does.
#[derive(Debug, Clone)]
pub enum Fix {
/// registers a default export: an import line at the top (when one is missing) and a registerRoot at the end
Register { file: PathBuf, import: Option<String>, root: String },
/// a controller moved to the workspace's (or the project's) controllers/
Move { from: PathBuf, to: PathBuf },
}
#[derive(Debug, Clone)]
pub struct Lint {
/// relative to the scanned folder ("" for the folder itself)
pub file: String,
pub line: usize,
pub rule: &'static str,
pub level: Level,
pub says: String,
pub fix: String,
pub action: Option<Fix>,
}
impl Lint {
/// As raea's one Finding (docs/direction.feature DR3): about its file, keyed file:line; a warn, or a note for
/// what only the render knows. A fix `raea doctor --fix` applies starts by saying so.
pub fn finding(&self) -> Finding {
let level = if self.level == Level::Warn { finding::Level::Warn } else { finding::Level::Note };
let name = if self.file.is_empty() { "." } else { self.file.as_str() };
let key = (self.line > 0).then(|| format!("{name}:{}", self.line));
let fix = if self.action.is_some() && !self.fix.starts_with("raea doctor --fix") { format!("raea doctor --fix does it: {}", self.fix) } else { self.fix.clone() };
Finding::new(self.rule, level, &self.says, "raea project scan").about(name, key).fix(fix)
}
/// file:line: what (the fix)
pub fn line(&self) -> String {
let at = if self.file.is_empty() { ".".to_string() } else if self.line > 0 { format!("{}:{}", self.file, self.line) } else { self.file.clone() };
format!("{at}: {} ({})", self.says, self.fix)
}
}
/// A path with the home folder as ~, as a person reads it.
fn tilde(p: &Path) -> String {
match std::env::var_os("HOME").map(PathBuf::from) {
Some(h) if p.starts_with(&h) => format!("~/{}", p.strip_prefix(&h).unwrap_or(p).display()),
_ => p.display().to_string(),
}
}
fn warn(file: &str, line: usize, rule: &'static str, says: String, fix: impl Into<String>) -> Lint {
Lint { file: file.into(), line, rule, level: Level::Warn, says, fix: fix.into(), action: None }
}
pub(super) fn lint(reg: &Registry, files: &[File], used_by: &BTreeMap<String, BTreeSet<String>>, overridden: &[String]) -> Vec<Lint> {
let mut out = Vec::new();
if !reg.project && !(reg.compositions.is_empty() && reg.controllers.is_empty()) {
out.push(warn("", 0, "not-a-project", "this folder isn't in a raea project (no .raea/project at or above it)".into(), "raea project new NAME and move the files in, or raea workspace adopt the folder"));
}
let comp_files: BTreeSet<&str> = reg.compositions.iter().map(|c| c.file.as_str()).collect();
let controller_files: BTreeSet<&str> = reg.controllers.iter().map(|c| c.file.as_str()).collect();
for f in files {
if let Some(why) = &f.facts.broken {
out.push(warn(&f.rel, 1, "broken", format!("doesn't parse: {why}"), "fix the syntax: nothing reads a file that doesn't parse"));
continue;
}
// a registerRoot whose compositions a helper makes (`<>{shotComps(SHOTS)}</>`): registered, but not listed here
if f.facts.roots && f.facts.registered.is_empty() {
out.push(Lint { file: f.rel.clone(), line: 1, rule: "computed-root", level: Level::Info, says: "registers its root through code the scan doesn't follow (a helper that makes its <Composition>s), so its compositions aren't listed".into(), fix: "known when it renders; write each <Composition> inside registerRoot to have them listed before".into(), action: None });
}
// a .tsx that is neither a composition nor reached from one
if f.rel.ends_with(".tsx") && !f.facts.roots && !comp_files.contains(f.rel.as_str()) && !used_by.contains_key(&f.rel) && !controller_files.contains(f.rel.as_str()) {
out.push(warn(&f.rel, 1, "orphan", "isn't a composition, and no composition imports it".into(), "register it (a default export or a registerRoot <Composition>), import it from a composition, or delete it"));
}
for (spec, line) in f.facts.imports.iter().filter(|(s, _)| is_path(s)) {
match resolve(&f.path, spec) {
None => out.push(warn(&f.rel, *line, "unresolved", format!("imports {spec}, which isn't there"), "fix the path, or add the file")),
Some(to) if !to.starts_with(&reg.dir) => out.push(warn(
&f.rel,
*line,
"outside",
format!("imports {} from outside the project", tilde(&to)),
"copy it into the project (raea part add, for raea's parts), so the project renders on its own",
)),
_ => {}
}
}
}
// one id, two compositions (a composition's versions share theirs)
let mut by_id: BTreeMap<&str, BTreeSet<String>> = BTreeMap::new();
for c in &reg.compositions {
by_id.entry(c.id.as_str()).or_default().insert(stem(&c.file));
}
for c in &reg.compositions {
let names = &by_id[c.id.as_str()];
if names.len() > 1 {
let others: Vec<&str> = names.iter().map(String::as_str).filter(|n| *n != stem(&c.file)).collect();
let who = match others.as_slice() {
[one] => format!("{one} does"),
[rest @ .., last] => format!("{} and {last} do", rest.join(", ")),
[] => continue,
};
out.push(warn(&c.file, c.line, "duplicate-id", format!("registers \"{}\", as {who}", c.id), "give one of them its own id: `raea render --composition ID` picks by it"));
}
}
for c in &reg.compositions {
let f = files.iter().find(|f| f.rel == c.file).expect("a composition's file was read");
match c.how {
How::Registered => {
let computed: Vec<String> = [("width", &c.width), ("height", &c.height), ("fps", &c.fps), ("durationInFrames", &c.frames)]
.into_iter()
.filter_map(|(k, v)| match v {
Some(Prop::Computed(e)) => Some(format!("{k} = {e}")),
None => Some(format!("{k} missing")),
_ => None,
})
.collect();
if !computed.is_empty() {
out.push(Lint { file: c.file.clone(), line: c.line, rule: "computed", level: Level::Info, says: format!("<Composition id=\"{}\">: {}", c.id, computed.join(", ")), fix: "known when it renders; write them out to have them listed before".into(), action: None });
}
}
How::Default => {
let known = [&c.width, &c.height, &c.fps, &c.frames].iter().all(|v| matches!(v, Some(Prop::Num(_))));
let action = match (&c.component, known) {
(Some(name), true) => {
let n = |v: &Option<Prop>| match v {
Some(Prop::Num(n)) => *n,
_ => 0.0,
};
let missing: Vec<&str> = ["Composition", "registerRoot"].into_iter().filter(|x| !f.facts.raea_names.iter().any(|h| h == x)).collect();
Some(Fix::Register {
file: f.path.clone(),
import: (!missing.is_empty()).then(|| format!("import {{ {} }} from \"raea\";\n", missing.join(", "))),
root: format!("\nregisterRoot(() => <Composition id=\"{}\" component={{{name}}} width={{{}}} height={{{}}} fps={{{}}} durationInFrames={{{}}} />);\n", c.id, n(&c.width), n(&c.height), n(&c.fps), n(&c.frames)),
})
}
_ => None,
};
let fix = match (&c.component, known) {
(Some(_), true) => "raea doctor --fix registers it with its last render's size, fps and length".to_string(),
(None, _) => "name the default export (export default function Name) and register it: registerRoot(() => <Composition id component width height fps durationInFrames />)".to_string(),
(Some(_), false) => "render it once (raea render), then raea doctor --fix registers it with that size, fps and length; or write its registerRoot".to_string(),
};
out.push(Lint { file: c.file.clone(), line: 1, rule: "unregistered", level: Level::Info, says: format!("registered from its default export as \"{}\": raea renders it at 1080x1920, 30 fps unless told", c.id), fix, action });
}
}
}
// controllers: where they're kept, one id each, and every override naming one that's there
let ws = super::up(&reg.dir, ".raea/workspace");
let home = ws.clone().unwrap_or_else(|| reg.dir.clone()).join("controllers");
let mut ids: BTreeMap<String, Vec<&str>> = BTreeMap::new();
for c in &reg.controllers {
let f = files.iter().find(|f| f.rel == c.file).expect("a controller's file was read");
if let Some(id) = &c.id {
ids.entry(id.clone()).or_default().push(&c.file);
}
let in_home = f.path.parent().and_then(Path::file_name).is_some_and(|n| n == "controllers");
if !in_home {
let id = c.id.clone().unwrap_or_else(|| stem(&c.file));
let to = home.join(format!("{id}.ts"));
out.push(Lint {
file: c.file.clone(),
line: c.line,
rule: "controller-home",
level: Level::Warn,
says: "a controller outside controllers/: `raea controller` and the app don't read it".into(),
fix: format!("move it to {}", to.display()),
action: (!to.exists()).then(|| Fix::Move { from: f.path.clone(), to }),
});
}
}
for (id, at) in ids.iter().filter(|(_, at)| at.len() > 1) {
for f in at {
out.push(warn(f, 1, "controller-duplicate", format!("controller \"{id}\" is declared in {} files", at.len()), "keep one: the others' fields override nothing"));
}
}
// the workspace's controllers too, read the same way, for overrides naming them
let mut known: BTreeSet<String> = ids.keys().cloned().collect();
for e in std::fs::read_dir(&home).into_iter().flatten().flatten() {
let src = std::fs::read_to_string(e.path()).unwrap_or_default();
if let Some(id) = super::read::read(&src, false).controller.and_then(|c| c.id) {
known.insert(id);
}
}
let mut named = BTreeSet::new();
for id in overridden {
if !known.contains(id) && named.insert(id.clone()) {
out.push(warn(".raea/project", 0, "override-missing", format!("overrides controller \"{id}\", which isn't there"), format!("raea controller ls lists the ones there; remove the override with git config --file .raea/project --remove-section controller.{id}")));
}
}
out
}
/// Applies a fix; what it did, for doctor's output.
pub fn apply(fix: &Fix) -> Result<String, String> {
match fix {
Fix::Register { file, import, root } => {
let src = std::fs::read_to_string(file).map_err(|e| format!("{}: {e}", file.display()))?;
let text = format!("{}{}{root}", import.clone().unwrap_or_default(), src.trim_end_matches('\n'));
std::fs::write(file, text).map_err(|e| format!("{}: {e}", file.display()))?;
Ok(format!("registered {}", file.display()))
}
Fix::Move { from, to } => {
if let Some(d) = to.parent() {
std::fs::create_dir_all(d).map_err(|e| e.to_string())?;
}
std::fs::rename(from, to).map_err(|e| format!("{}: {e}", from.display()))?;
Ok(format!("moved {} to {}", from.display(), to.display()))
}
}
}
+296
View File
@@ -0,0 +1,296 @@
//! What one .tsx or .ts file declares, read from its source without running it (docs/projects.feature PJ8): the
//! compositions its registerRoot registers, each <Composition>'s id, component, size, fps and length (a value written
//! out, or the expression that computes it); its default export; what it imports; and whether its default export is a
//! controller (`export default controller({...})` from "raea/brief"). A prop written as a top-level constant, or simple
//! arithmetic on them (`const FPS = 30; … durationInFrames={15 * FPS}`), is read as its value.
use oxc::allocator::Allocator;
use oxc::ast::ast::*;
use oxc::ast_visit::{Visit, walk};
use oxc::parser::Parser;
use oxc::span::{GetSpan, SourceType};
use oxc::syntax::operator::{BinaryOperator, UnaryOperator};
use serde_json::{Value, json};
use std::collections::HashMap;
/// A <Composition> prop as written.
#[derive(Debug, Clone, PartialEq)]
pub enum Prop {
Num(f64),
Text(String),
/// an expression only the render knows the value of
Computed(String),
}
impl Prop {
pub fn json(&self) -> Value {
match self {
Prop::Num(n) => json!(n),
Prop::Text(t) => json!(t),
Prop::Computed(e) => json!({ "computed": e }),
}
}
}
/// One registered <Composition>.
#[derive(Debug, Clone, Default)]
pub struct Registered {
pub line: usize,
pub id: Option<Prop>,
pub component: Option<String>,
pub width: Option<Prop>,
pub height: Option<Prop>,
pub fps: Option<Prop>,
pub frames: Option<Prop>,
}
/// A controller the file's default export declares: its id (written, else from its title), at a line.
#[derive(Debug, Clone)]
pub struct Declared {
pub line: usize,
pub id: Option<String>,
}
#[derive(Debug, Default)]
pub struct Facts {
pub registered: Vec<Registered>,
/// the default export, with its name when it has one (`export default function Promo`)
pub default: Option<Option<String>>,
/// each import or re-export's module, at its line
pub imports: Vec<(String, usize)>,
pub controller: Option<Declared>,
/// the names it imports from "raea" (a fix that registers its default export adds only what's missing)
pub raea_names: Vec<String>,
/// why it didn't parse (the first diagnostic), when it didn't
pub broken: Option<String>,
/// it calls registerRoot (its compositions may come from a helper the scan doesn't follow)
pub roots: bool,
}
/// The file's facts; `tsx` for .tsx (JSX on), else plain TypeScript.
pub fn read(source: &str, tsx: bool) -> Facts {
let alloc = Allocator::default();
let st = if tsx { SourceType::tsx() } else { SourceType::ts() };
let parsed = Parser::new(&alloc, source, st).parse();
// 1-based: the newlines before it, plus one
let line = |at: u32| source.as_bytes()[..at as usize].iter().filter(|&&b| b == b'\n').count() + 1;
let mut f = Facts::default();
if let Some(d) = parsed.diagnostics.first() {
f.broken = Some(d.to_string());
return f;
}
let mut controller_fn = None;
for s in &parsed.program.body {
match s {
Statement::ImportDeclaration(d) => {
f.imports.push((d.source.value.to_string(), line(d.span.start)));
if d.source.value == "raea" {
f.raea_names.extend(d.specifiers.iter().flatten().map(|sp| sp.local().name.to_string()));
}
if d.source.value == "raea/brief" {
for sp in d.specifiers.iter().flatten() {
if let ImportDeclarationSpecifier::ImportSpecifier(x) = sp
&& x.imported.name() == "controller"
{
controller_fn = Some(sp.local().name.to_string());
}
}
}
}
Statement::ExportFromDeclaration(d) => f.imports.push((d.source.value.to_string(), line(d.span.start))),
Statement::ExportAllDeclaration(d) => f.imports.push((d.source.value.to_string(), line(d.span.start))),
Statement::ExportNamedDeclaration(d) => {
if let Some(sp) = d.specifiers.iter().find(|sp| sp.exported.name() == "default") {
f.default = Some(Some(sp.local.name().to_string()));
}
}
Statement::ExportDefaultDeclaration(d) => {
f.default = Some(match &d.declaration {
ExportDefaultDeclarationKind::FunctionDeclaration(x) => x.id.as_ref().map(|i| i.name.to_string()),
ExportDefaultDeclarationKind::ClassDeclaration(x) => x.id.as_ref().map(|i| i.name.to_string()),
ExportDefaultDeclarationKind::Identifier(x) => Some(x.name.to_string()),
_ => None,
});
if let ExportDefaultDeclarationKind::CallExpression(c) = &d.declaration
&& let Expression::Identifier(callee) = &c.callee
&& controller_fn.as_deref() == Some(callee.name.as_str())
{
f.controller = Some(Declared { line: line(d.span.start), id: controller_id(c) });
}
}
_ => {}
}
}
let mut v = Compositions { src: source, depth: 0, roots: false, found: Vec::new(), consts: consts(&parsed.program) };
v.visit_program(&parsed.program);
f.roots = v.roots;
f.registered = v.found.into_iter().map(|(at, mut r)| {
r.line = line(at);
r
}).collect();
f
}
/// A controller's id as written, else from its title (core/brief fills an id in from the title the same way).
fn controller_id(c: &CallExpression) -> Option<String> {
let Some(Argument::ObjectExpression(o)) = c.arguments.first() else { return None };
let text = |key: &str| {
o.properties.iter().find_map(|p| match p {
ObjectPropertyKind::ObjectProperty(p) if p.key.static_name().as_deref() == Some(key) => match &p.value {
Expression::StringLiteral(s) => Some(s.value.to_string()),
_ => None,
},
_ => None,
})
};
text("id").or_else(|| text("title").map(|t| super::slug(&t)))
}
/// The file's top-level numeric constants, in order: `const FPS = 30`, `const DUR = 15 * FPS`, and an object constant's
/// numeric properties as `NAME.prop` (`const edit = { fps: 30 }`).
fn consts(p: &Program) -> HashMap<String, f64> {
let mut k = HashMap::new();
for s in &p.body {
let v = match s {
Statement::VariableDeclaration(v) => v,
Statement::ExportDeclaration(d) => match &d.declaration {
Declaration::VariableDeclaration(v) => v,
_ => continue,
},
_ => continue,
};
if v.kind != VariableDeclarationKind::Const {
continue;
}
for d in &v.declarations {
let (BindingPattern::BindingIdentifier(id), Some(init)) = (&d.id, &d.init) else { continue };
match unwrap(init) {
Expression::ObjectExpression(o) => {
for p in &o.properties {
if let ObjectPropertyKind::ObjectProperty(p) = p
&& let (Some(key), Some(n)) = (p.key.static_name(), number(&p.value, &k))
{
k.insert(format!("{}.{key}", id.name), n);
}
}
}
e => {
if let Some(n) = number(e, &k) {
k.insert(id.name.to_string(), n);
}
}
}
}
}
k
}
/// Through `x as T`, `x satisfies T` and parentheses.
fn unwrap<'a, 'b>(e: &'b Expression<'a>) -> &'b Expression<'a> {
match e {
Expression::ParenthesizedExpression(p) => unwrap(&p.expression),
Expression::TSAsExpression(x) => unwrap(&x.expression),
Expression::TSSatisfiesExpression(x) => unwrap(&x.expression),
e => e,
}
}
/// An expression's value when it's numbers and known constants: + - * /, unary minus, Math.round, floor and ceil.
fn number(e: &Expression, k: &HashMap<String, f64>) -> Option<f64> {
match unwrap(e) {
Expression::NumericLiteral(n) => Some(n.value),
Expression::Identifier(id) => k.get(id.name.as_str()).copied(),
Expression::StaticMemberExpression(m) => match &m.object {
Expression::Identifier(o) => k.get(&format!("{}.{}", o.name, m.property.name)).copied(),
_ => None,
},
Expression::UnaryExpression(u) if u.operator == UnaryOperator::UnaryNegation => number(&u.argument, k).map(|n| -n),
Expression::BinaryExpression(b) => {
let (l, r) = (number(&b.left, k)?, number(&b.right, k)?);
match b.operator {
BinaryOperator::Addition => Some(l + r),
BinaryOperator::Subtraction => Some(l - r),
BinaryOperator::Multiplication => Some(l * r),
BinaryOperator::Division if r != 0.0 => Some(l / r),
_ => None,
}
}
Expression::CallExpression(c) => {
let Expression::StaticMemberExpression(m) = &c.callee else { return None };
let Expression::Identifier(o) = &m.object else { return None };
let x = number(c.arguments.first()?.as_expression()?, k)?;
match (o.name.as_str(), m.property.name.as_str()) {
("Math", "round") => Some(x.round()),
("Math", "floor") => Some(x.floor()),
("Math", "ceil") => Some(x.ceil()),
_ => None,
}
}
_ => None,
}
}
/// Every <Composition> inside a registerRoot(...) call's argument.
struct Compositions<'s> {
src: &'s str,
depth: usize,
/// it calls registerRoot, whether or not a <Composition> is written inside it
roots: bool,
found: Vec<(u32, Registered)>,
consts: HashMap<String, f64>,
}
impl<'a> Visit<'a> for Compositions<'_> {
fn visit_call_expression(&mut self, it: &CallExpression<'a>) {
let root = matches!(&it.callee, Expression::Identifier(id) if id.name == "registerRoot");
self.roots |= root;
self.depth += root as usize;
walk::walk_call_expression(self, it);
self.depth -= root as usize;
}
fn visit_jsx_element(&mut self, it: &JSXElement<'a>) {
let open = &it.opening_element;
if self.depth > 0 && matches!(&open.name, JSXElementName::IdentifierReference(r) if r.name == "Composition") {
let mut r = Registered::default();
for a in &open.attributes {
let JSXAttributeItem::Attribute(x) = a else { continue };
let JSXAttributeName::Identifier(n) = &x.name else { continue };
let value = x.value.as_ref().map(|v| self.prop(v));
match n.name.as_str() {
"id" => r.id = value,
"width" => r.width = value,
"height" => r.height = value,
"fps" => r.fps = value,
"durationInFrames" => r.frames = value,
"component" => {
r.component = match value {
Some(Prop::Computed(e)) => Some(e),
Some(Prop::Text(t)) => Some(t),
_ => None,
}
}
_ => {}
}
}
self.found.push((it.span.start, r));
}
walk::walk_jsx_element(self, it);
}
}
impl Compositions<'_> {
fn prop(&self, v: &JSXAttributeValue) -> Prop {
match v {
JSXAttributeValue::StringLiteral(l) => Prop::Text(l.value.to_string()),
JSXAttributeValue::ExpressionContainer(c) => match c.expression.as_expression() {
Some(Expression::NumericLiteral(n)) => Prop::Num(n.value),
Some(Expression::StringLiteral(s)) => Prop::Text(s.value.to_string()),
Some(Expression::TemplateLiteral(t)) if t.expressions.is_empty() && t.quasis.len() == 1 => Prop::Text(t.quasis[0].value.cooked.map(|c| c.to_string()).unwrap_or_default()),
Some(e) if number(e, &self.consts).is_some() => Prop::Num(number(e, &self.consts).unwrap_or_default()),
Some(e) => Prop::Computed(self.src[e.span().start as usize..e.span().end as usize].to_string()),
None => Prop::Computed(String::new()),
},
other => Prop::Computed(self.src[other.span().start as usize..other.span().end as usize].to_string()),
}
}
}
+150
View File
@@ -0,0 +1,150 @@
//! PJ8: a project's files read as compositions, components and controllers, and what isn't connected linted.
use super::*;
fn project() -> (tempdir::Dir, PathBuf) {
let t = tempdir::Dir::new();
let p = t.0.join("film");
let w = |rel: &str, text: &str| {
let f = p.join(rel);
std::fs::create_dir_all(f.parent().unwrap()).unwrap();
std::fs::write(f, text).unwrap();
};
w(".raea/project", "[project]\n\tid = pj-test\n");
w("promo.tsx", "import { Composition, registerRoot } from \"raea\";\nimport { Card } from \"./card\";\nconst FPS = 30, edit = { w: 1080 };\nfunction Promo() { return <Card />; }\nregisterRoot(() => <Composition id=\"promo\" component={Promo} width={edit.w} height={1920} fps={FPS} durationInFrames={Math.round(2.5 * FPS) + total()} />);\n");
w("promo-v2.tsx", "import { Composition, registerRoot } from \"raea\";\nfunction Promo() { return null; }\nregisterRoot(() => <Composition id=\"promo\" component={Promo} width={1080} height={1920} fps={30} durationInFrames={90} />);\n");
w("teaser.tsx", "import { Composition, registerRoot } from \"raea\";\nfunction T() { return null; }\nregisterRoot(() => (\n <Composition id=\"promo\" component={T} width={1080} height={1080} fps={30} durationInFrames={60} />\n));\n");
w("card.tsx", "import Glyph from \"./lib/glyph\";\nimport { gone } from \"./nope\";\nimport { far } from \"../outside\";\nexport function Card() { return <Glyph />; }\n");
w("lib/glyph.tsx", "export default function Glyph() { return <span />; }\n");
w("stray.tsx", "export function Stray() { return null; }\n");
w("shots.tsx", "import { registerRoot } from \"raea\";\nimport { shotComps, SHOTS } from \"./lib/glyph\";\nregisterRoot(() => <>{shotComps(SHOTS)}</>);\n");
w("bare.tsx", "import { AbsoluteFill } from \"raea\";\nexport default function Bare() { return <AbsoluteFill />; }\n");
w("bare.render.json", "{\"width\": 1080, \"height\": 1080, \"fps\": 30, \"frames\": [{}, {}, {}]}");
w("anon.tsx", "export default () => <div />;\n");
w("broken.tsx", "export default function (\n");
w("controllers/delivery.ts", "import { controller } from \"raea/brief\";\nexport default controller({ id: \"delivery\", title: \"Delivery\", groups: [] });\n");
w("settings/look.ts", "import { controller } from \"raea/brief\";\n\nexport default controller({ title: \"Look and feel\", groups: [] });\n");
std::fs::write(t.0.join("outside.tsx"), "export const far = 1;\n").unwrap();
(t, p)
}
/// A folder removed when the test ends.
mod tempdir {
pub struct Dir(pub std::path::PathBuf);
impl Dir {
pub fn new() -> Dir {
static N: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let d = std::env::temp_dir().join(format!("raea-registry-{}-{}", std::process::id(), N.fetch_add(1, std::sync::atomic::Ordering::Relaxed)));
std::fs::create_dir_all(&d).unwrap();
Dir(std::fs::canonicalize(&d).unwrap())
}
}
impl Drop for Dir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
}
#[test]
fn compositions_components_and_controllers_are_read_from_the_files() {
let (_t, p) = project();
let r = scan(&p, &[]);
assert!(r.project);
let comps: Vec<(&str, &str, How)> = r.compositions.iter().map(|c| (c.id.as_str(), c.file.as_str(), c.how)).collect();
assert!(comps.contains(&("promo", "promo.tsx", How::Registered)));
assert!(comps.contains(&("promo", "promo-v2.tsx", How::Registered)));
assert!(comps.contains(&("bare", "bare.tsx", How::Default)));
assert!(comps.contains(&("anon", "anon.tsx", How::Default)));
let promo = r.compositions.iter().find(|c| c.file == "promo.tsx").unwrap();
assert_eq!((promo.line, promo.component.as_deref(), promo.width.clone(), promo.fps.clone()), (5, Some("Promo"), Some(Prop::Num(1080.0)), Some(Prop::Num(30.0))), "constants read as their values");
assert_eq!(promo.frames, Some(Prop::Computed("Math.round(2.5 * FPS) + total()".into())), "a call only the render knows");
let teaser = r.compositions.iter().find(|c| c.file == "teaser.tsx").unwrap();
assert_eq!(teaser.line, 4, "the <Composition>'s own line, inside a multi-line registerRoot");
let bare = r.compositions.iter().find(|c| c.file == "bare.tsx").unwrap();
assert_eq!((bare.width.clone(), bare.frames.clone()), (Some(Prop::Num(1080.0)), Some(Prop::Num(3.0))), "sized from its render's manifest");
// card is imported by promo, glyph through card (a default export, but imported): both components, used by promo
let comps: Vec<(&str, Vec<&str>)> = r.components.iter().map(|c| (c.file.as_str(), c.used_by.iter().map(String::as_str).collect())).collect();
assert_eq!(comps, [("card.tsx", vec!["promo.tsx"]), ("lib/glyph.tsx", vec!["promo.tsx"])]);
let ctl: Vec<(Option<&str>, &str)> = r.controllers.iter().map(|c| (c.id.as_deref(), c.file.as_str())).collect();
assert_eq!(ctl, [(Some("delivery"), "controllers/delivery.ts"), (Some("look-and-feel"), "settings/look.ts")]);
}
#[test]
fn what_isnt_connected_is_linted_with_its_place_and_fix() {
let (_t, p) = project();
let r = scan(&p, &[]);
let has = |rule: &str, file: &str, line: usize| r.lint.iter().any(|l| l.rule == rule && l.file == file && l.line == line);
assert!(has("orphan", "stray.tsx", 1));
assert!(!r.lint.iter().any(|l| l.rule == "orphan" && ["card.tsx", "lib/glyph.tsx", "promo.tsx"].contains(&l.file.as_str())));
assert!(has("unresolved", "card.tsx", 2));
assert!(has("outside", "card.tsx", 3));
assert!(has("broken", "broken.tsx", 1));
// promo's versions share an id; teaser takes it too
assert!(has("duplicate-id", "teaser.tsx", 4));
assert!(r.lint.iter().filter(|l| l.rule == "duplicate-id").all(|l| l.says.contains("teaser") || l.file == "teaser.tsx"));
assert!(has("computed", "promo.tsx", 5));
assert!(has("controller-home", "settings/look.ts", 3));
assert!(!r.lint.iter().any(|l| l.file == "controllers/delivery.ts"));
// a default export with a render is registered by --fix; a nameless one says how
let bare = r.lint.iter().find(|l| l.rule == "unregistered" && l.file == "bare.tsx").unwrap();
assert!(bare.action.is_some());
let anon = r.lint.iter().find(|l| l.rule == "unregistered" && l.file == "anon.tsx").unwrap();
assert!(anon.action.is_none() && anon.fix.contains("name the default export"));
// a registerRoot whose compositions a helper makes is no orphan: it says the scan can't list them
assert!(!r.lint.iter().any(|l| l.rule == "orphan" && l.file == "shots.tsx"));
assert!(has("computed-root", "shots.tsx", 1));
// as Findings (DR3): about the file at its line, a fix --fix applies saying so, the count last
let home = r.lint.iter().find(|l| l.rule == "controller-home").unwrap().finding();
assert_eq!((home.about[0].key.as_deref(), home.fix.as_deref().map(|f| f.starts_with("raea doctor --fix does it: move it to"))), (Some("settings/look.ts:3"), Some(true)));
assert!(r.text().lines().last().unwrap().starts_with("raea project scan: 0 errors, "));
}
#[test]
fn fixes_register_a_default_export_and_move_a_controller_home() {
let (_t, p) = project();
let r = scan(&p, &[]);
for l in r.lint.iter().filter(|l| l.action.is_some()) {
lint::apply(l.action.as_ref().unwrap()).unwrap();
}
let bare = std::fs::read_to_string(p.join("bare.tsx")).unwrap();
assert!(bare.starts_with("import { Composition, registerRoot } from \"raea\";\nimport { AbsoluteFill }"), "{bare}");
assert!(bare.ends_with("registerRoot(() => <Composition id=\"bare\" component={Bare} width={1080} height={1080} fps={30} durationInFrames={3} />);\n"), "{bare}");
assert!(p.join("controllers/look-and-feel.ts").is_file() && !p.join("settings/look.ts").exists());
let again = scan(&p, &[]);
assert_eq!(again.compositions.iter().find(|c| c.file == "bare.tsx").unwrap().how, How::Registered);
assert!(!again.lint.iter().any(|l| l.rule == "controller-home" || (l.rule == "unregistered" && l.file == "bare.tsx")));
}
#[test]
fn a_folder_outside_any_project_says_so() {
let t = tempdir::Dir::new();
std::fs::write(t.0.join("a.tsx"), "export default function A() { return null; }\n").unwrap();
let r = scan(&t.0, &[]);
assert!(!r.project);
assert!(r.lint.iter().any(|l| l.rule == "not-a-project"));
}
#[test]
fn an_override_naming_a_controller_that_isnt_there_is_linted() {
let (_t, p) = project();
let r = scan(&p, &["delivery".into(), "gone".into(), "gone".into()]);
let named: Vec<&str> = r.lint.iter().filter(|l| l.rule == "override-missing").map(|l| l.says.as_str()).collect();
assert_eq!(named, ["overrides controller \"gone\", which isn't there"], "once, and not for one that's there");
}
#[test]
fn versions_share_a_stem() {
assert_eq!(stem("promo-v12.tsx"), "promo");
assert_eq!(stem("dir/my-video.tsx"), "my-video");
assert_eq!(stem("x-v.tsx"), "x-v");
}
/// A real folder's registry, printed: `RAEA_SCAN_DIR=~/Studio/x cargo test -p raea-app-registry real_folder -- --ignored --nocapture`.
#[test]
#[ignore]
fn real_folder() {
let Some(dir) = std::env::var_os("RAEA_SCAN_DIR") else { return };
let t = std::time::Instant::now();
let r = scan(Path::new(&dir), &[]);
println!("{}\n({} ms)", r.text(), t.elapsed().as_millis());
}
+2 -3
View File
@@ -22,8 +22,7 @@ pub fn load(ws: &Path, eval: Eval) -> R<Vec<(PathBuf, Controller)>> {
}
fn read(f: &Path, eval: Eval) -> R<Controller> {
let raw: serde_json::Value = serde_json::from_str(&eval(f)?).map_err(|e| format!("{}: {e}", f.display()))?;
ctl::normalize(&raw).map_err(|e| format!("{}: {e}", f.display()))
ctl::of_json(&eval(f)?).map_err(|e| format!("{}: {e}", f.display()))
}
/// The module a controller is kept as.
@@ -55,7 +54,7 @@ fn parse(f: &Field, s: &str) -> R<serde_json::Value> {
}
/// The overrides of the project `from` is in, by path.
fn overrides(from: &Path) -> Vec<(String, String)> {
pub(crate) fn overrides(from: &Path) -> Vec<(String, String)> {
let Some(p) = workspace::up(from, ".raea/project") else { return vec![] };
let text = workspace::config(Some(&p.join(".raea/project")), &["--get-regexp", "^controller\\."]).unwrap_or_default();
text.lines().filter_map(|l| l.split_once(' ')).map(|(k, v)| (k.trim_start_matches("controller.").to_string(), v.to_string())).collect()
+56 -2
View File
@@ -2,6 +2,8 @@
//! files raea no longer reads, a workspace or project file missing what this version writes (or not included from the
//! repo's git config), and an agent's copy of the raea skill from another version. `raea context` runs the same checks
//! and prints CONTEXT_STALE when any finds something, so they stay cheap: file reads and git config, no engine.
//! It also lists what in the project isn't connected to raea's project system (docs/projects.feature PJ8, registry.rs):
//! `--fix` registers a default export and moves a stray controller to controllers/, as a commit.
use super::*;
use crate::workspace::{get, git, include, new_id, set};
@@ -19,6 +21,8 @@ enum Fix {
Include(PathBuf, PathBuf),
/// an agent's skills reinstalled from this raea
Skills(String),
/// a project file connected to raea's project system (PJ8)
Registry(crate::registry::Fix),
}
impl Finding {
@@ -97,15 +101,57 @@ pub fn findings(from: &Path, skills: &[(&str, PathBuf)], version: &str) -> Vec<F
out
}
/// The folder a registry scan reads from here: the project, else the folder itself unless it's the workspace's root
/// (whose projects are each scanned in their own).
pub fn registry_dir(from: &Path) -> Option<PathBuf> {
if let Some(p) = up(from, ".raea/project") {
return Some(p);
}
let from = from.canonicalize().unwrap_or_else(|_| from.to_path_buf());
(up(&from, ".raea/workspace").as_deref() != Some(from.as_path())).then_some(from)
}
/// What isn't connected to raea's project system (PJ8's warnings; its notes are `raea project scan`'s), as findings.
pub fn registry_findings(from: &Path) -> Vec<Finding> {
let Some(dir) = registry_dir(from) else { return vec![] };
let reg = crate::registry::scan(&dir);
reg.warnings()
.map(|l| {
let at = if l.file.is_empty() { reg.dir.display().to_string() } else { reg.dir.join(&l.file).display().to_string() };
let at = if l.line > 0 { format!("{at}:{}", l.line) } else { at };
Finding { says: format!("{at}: {} ({})", l.says, l.fix), fix: l.action.clone().map_or(Fix::No, Fix::Registry) }
})
.collect()
}
/// A commit of the files a registry fix touched, in the repo that holds them, naming only them.
fn commit_touched(paths: &[PathBuf]) {
let Some(first) = paths.iter().find_map(|p| p.parent().filter(|d| d.is_dir())) else { return };
let Ok(top) = git(first, &["rev-parse", "--show-toplevel"]) else { return };
let top = PathBuf::from(top);
let rel: Vec<String> = paths.iter().map(|p| p.strip_prefix(&top).unwrap_or(p).display().to_string()).collect();
let mut add = vec!["add", "-A", "--"];
add.extend(rel.iter().map(String::as_str));
let mut changed = vec!["diff", "--cached", "--quiet", "--"];
changed.extend(rel.iter().map(String::as_str));
if git(&top, &add).is_ok() && git(&top, &changed).is_err() {
let mut c = vec!["commit", "-q", "-m", "raea: doctor --fix connected the project's files", "--"];
c.extend(rel.iter().map(String::as_str));
let _ = git(&top, &c);
}
}
/// `raea doctor [--fix] [DIR]`: what it found and, with --fix, what it fixed. `reinstall` puts an agent's skills back
/// (the raea CLI's `skills install`).
pub fn doctor(args: &[String], skills: &[(&str, PathBuf)], version: &str, reinstall: &dyn Fn(&str) -> R<String>) -> R<String> {
let fix = args.iter().any(|a| a == "--fix");
let from = PathBuf::from(args.iter().find(|a| !a.starts_with("--")).map(String::as_str).unwrap_or("."));
let found = findings(&from, skills, version);
let mut found = findings(&from, skills, version);
found.extend(registry_findings(&from));
if found.is_empty() {
return Ok("CHECKED nothing to fix: this folder's files and the agents' raea skill match this raea".into());
return Ok("CHECKED nothing to fix: this folder's files and the agents' raea skill match this raea, and its compositions, components and controllers are connected".into());
}
let mut touched = Vec::new();
let mut lines = Vec::new();
let mut fixed = 0;
for f in &found {
@@ -113,6 +159,13 @@ pub fn doctor(args: &[String], skills: &[(&str, PathBuf)], version: &str, reinst
(Fix::Set(file, k, v), true) => set(file, k, v).map(|_| true),
(Fix::Include(repo, file), true) => include(repo, file).map(|_| true),
(Fix::Skills(agent), true) => reinstall(agent).map(|_| true),
(Fix::Registry(r), true) => {
touched.extend(match r {
crate::registry::Fix::Register { file, .. } => vec![file.clone()],
crate::registry::Fix::Move { from, to } => vec![from.clone(), to.clone()],
});
crate::registry::apply(r).map(|_| true)
}
_ => Ok(false),
};
match done {
@@ -131,6 +184,7 @@ pub fn doctor(args: &[String], skills: &[(&str, PathBuf)], version: &str, reinst
let _ = crate::workspace::commit(&repo, &[marker], "doctor --fix");
}
}
commit_touched(&touched);
}
let can = found.iter().filter(|f| f.fixable()).count();
let head = if fix { format!("APPLIED {fixed} of {} fixed", found.len()) } else { format!("CHECKED {} to fix ({can} by raea doctor --fix)", found.len()) };
+3 -1
View File
@@ -9,12 +9,14 @@ mod controllers;
pub mod doctor;
mod literal;
pub mod next;
pub mod registry;
mod storage;
mod workspace;
pub use controllers::{controller, module, summary};
pub use registry::context;
pub use literal::{tidy, tidy_deep, ts_literal};
pub use workspace::{project, projects, root, slug, up, workspace};
pub use workspace::{default_root, project, projects, root, slug, up, workspace};
pub type R<T> = Result<T, String>;
+52 -30
View File
@@ -1,9 +1,11 @@
//! `raea next` (docs/skills.feature SK10): the two or three useful next steps for a project, read from its files: the
//! brief (what it still needs, from the raea CLI's brief doctor), the storyboard its modes want, its compositions, its
//! renders in out/ and their checks (`raea check ... -o out/NAME.check.json`). A menu for the agent or the person to
//! pick from; nothing runs.
//! brief (what it still needs, from the raea CLI's brief doctor), the storyboard its modes want, its compositions, and
//! from the project's record (docs/direction.feature DR3) its renders and their checks and what each found. A menu for
//! the agent or the person to pick from; nothing runs.
use super::*;
use std::time::SystemTime;
use raea_core_facts::Level;
use raea_core_facts::record::{self, Entry};
use std::time::{SystemTime, UNIX_EPOCH};
/// What the raea CLI read from the project's brief.
pub struct Brief {
@@ -27,16 +29,35 @@ fn name(p: &Path) -> String {
full.rsplit(['/', '\\']).next().unwrap_or_default().to_string()
}
/// The P0 and P1 issues a check file holds, as its lines.
fn blocking(check: &Path) -> Vec<String> {
let Ok(j) = std::fs::read_to_string(check).map_err(drop).and_then(|t| serde_json::from_str::<serde_json::Value>(&t).map_err(drop)) else { return vec![] };
let mut out = Vec::new();
for i in j["issues"].as_array().into_iter().flatten() {
if let (Some(p @ ("P0" | "P1")), Some(says)) = (i["p"].as_str(), i["says"].as_str()) {
out.push(format!("{p} {says}"));
}
/// An entry's first error, as `check: says`.
fn first_error(e: &Entry) -> Option<String> {
e.findings.iter().find(|f| f.level == Level::Error).map(|f| [f.check.as_str(), f.says.as_str()].join(": "))
}
/// The step after a composition's latest render in the project's record (docs/direction.feature DR3): its errors,
/// then its video (the newest render of it that wrote one: stills or a review since don't replace it, and one made
/// before the composition's last change, at `changed` seconds, is stale), then the video's check (a `raea check` of
/// it, kept after it) and what that found.
fn after_render(c: &Path, record: &[Entry], i: usize, changed: u64) -> String {
let e = &record[i];
if let Some(err) = first_error(e) {
return format!("fix {}: {err} (its render {} found it; `raea findings {}` lists them all)", name(c), e.id, name(c));
}
let video = record[..=i].iter().rposition(|k| k.by == "raea render" && k.of == e.of && k.out.as_deref().is_some_and(|o| o.ends_with(".mp4")));
let Some((v, out)) = video.and_then(|v| Some((v, record[v].out.as_deref()?))) else {
return format!("render the video: `raea render {} -o out/{}`", name(c), name(&c.with_extension("mp4")));
};
if record[v].at < changed {
return format!("render the video again: {} changed after {} made {out}", name(c), record[v].id);
}
let check = out.replace(".mp4", ".check.json");
match record[v + 1..].iter().rev().find(|k| (k.by.as_str(), k.of.as_str()) == ("raea check", out)) {
None => format!("check {out}: `raea check {out} -o {check}` (add --manifest when the render wrote one)"),
Some(k) => match first_error(k) {
Some(err) => format!("polish {out}: {err} (`raea guide polish`)"),
None => format!("show {out}: post it to the project's feed (feed_post), or give the person its path, and read their notes"),
},
}
out
}
/// The steps, most useful first, at most three. `stale` is what `raea doctor` found here.
@@ -53,23 +74,24 @@ pub fn steps(dir: &Path, brief: &Brief, stale: usize) -> Vec<String> {
if boarded && scripts.is_empty() {
out.push("plan it: write the storyboard as NAME.script.ts beside the brief (`raea spec NAME.script.ts` checks it) and wait for the person's approval".into());
}
let comps: Vec<PathBuf> = files(dir, ".tsx").into_iter().filter(|p| std::fs::read_to_string(p).map(|t| t.contains("registerRoot")).unwrap_or(false)).collect();
let renders = files(&dir.join("out"), ".mp4");
match (comps.first(), renders.first()) {
(None, _) => out.push("make the first item: one .tsx whose root registers a Composition (`raea guide craft` first)".into()),
(Some(c), None) => out.push(format!("render {}: stills to look at first (`raea render {} --at 0,45,89 -o frames/`), then the video into out/", name(c), name(c))),
(Some(c), Some(r)) if modified(c) > modified(r) => out.push(format!("render again: {} changed after {}", name(c), name(r))),
(_, Some(r)) => {
let check = r.with_extension("check.json");
if !check.is_file() || modified(&check) < modified(r) {
out.push(format!("check {}: `raea check out/{} -o out/{}` (add --manifest when the render wrote one)", name(r), name(r), name(&check)));
} else {
match blocking(&check).first() {
Some(issue) => out.push(format!("polish {}: {issue} (`raea guide polish`)", name(r))),
None => out.push(format!("show {}: post it to the project's feed (feed_post), or give the person its path, and read their notes", name(r))),
}
}
}
// the compositions as raea's project system reads them (PJ8), newest first; what isn't connected is a step before
let reg = crate::registry::scan(dir);
let loose: Vec<&crate::registry::Lint> = reg.warnings().collect();
if let Some(first) = loose.first() {
out.push(format!("connect the project's files: {} thing(s) aren't connected, first {} (`raea project scan` lists them, `raea doctor --fix` fixes what it can)", loose.len(), first.line()));
}
// the newest composition's renders and checks, from the project's record (DR3)
let comps = reg.composition_files();
let project = record::up(dir, ".raea/project").unwrap_or_else(|| dir.to_path_buf());
let kept = record::read(&project);
let secs = |p: &Path| modified(p).duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
match comps.first() {
None => out.push("make the first item: one .tsx whose root registers a Composition (`raea guide craft` first)".into()),
Some(c) => match kept.iter().rposition(|e| e.by == "raea render" && e.of == record::rel(&project, c)) {
None => out.push(format!("render {}: stills to look at first (`raea render {} --at 0,45,89 -o frames/`), then the video into out/", name(c), name(c))),
Some(i) if secs(c) > kept[i].at => out.push(format!("render again: {} changed after its render {}", name(c), kept[i].id)),
Some(i) => out.push(after_render(c, &kept, i, secs(c))),
},
}
out.truncate(3);
out
+25
View File
@@ -0,0 +1,25 @@
//! A project's compositions, components and controllers (docs/projects.feature PJ8): raea-app-registry's reading of
//! its files, with the project's controller overrides from .raea/project checked against the controllers there.
use std::path::Path;
use crate::Eval;
pub use raea_app_registry::{Component, Composition, Controller, Fix, How, Level, Lint, Prop, Registry, apply};
/// The folder's registry.
pub fn scan(dir: &Path) -> Registry {
let ids: Vec<String> = crate::controllers::overrides(dir).into_iter().filter_map(|(path, _)| path.split('.').next().map(str::to_string)).collect();
raea_app_registry::scan(dir, &ids)
}
/// What `raea context` reads of the workspace, as (section, text): its controllers with this project's overrides, and
/// the project's compositions, components and controllers as raea reads them.
pub fn context(from: &Path, eval: Eval) -> Vec<(String, String)> {
let mut out = Vec::new();
if let Some(text) = crate::summary(from, eval) {
out.push(("CONTROLLERS (raea controller ls; a project's own values marked)".to_string(), text));
}
if let Some(dir) = crate::doctor::registry_dir(from) {
out.push(("PROJECT FILES (raea project scan)".to_string(), scan(&dir).summary()));
}
out
}
+72 -10
View File
@@ -35,22 +35,68 @@ fn scratch(name: &str) -> PathBuf {
#[test]
fn next_walks_a_project_from_brief_to_show() {
let d = scratch("next");
std::fs::create_dir_all(d.join(".raea")).unwrap();
std::fs::write(d.join(".raea/project"), "").unwrap();
let shaped = next::Brief { needs: vec![], modes: vec!["tool".into()] };
let unshaped = next::Brief { needs: vec!["who it's for (audience)".into()], modes: vec!["pitch".into()] };
let s = next::steps(&d, &unshaped, 0);
assert!(s[0].starts_with("shape the brief: who it's for") && s[1].starts_with("plan it") && s[2].starts_with("make the first item"), "{s:?}");
assert!(next::steps(&d, &shaped, 2)[0].starts_with("raea doctor: 2"));
std::fs::write(d.join("piece.tsx"), "registerRoot(() => null)").unwrap();
assert!(next::steps(&d, &shaped, 0)[0].starts_with("render piece.tsx"));
std::fs::write(d.join("card.tsx"), "export const Card = () => null;\n").unwrap();
let s = next::steps(&d, &shaped, 0);
assert!(s[0].starts_with("connect the project's files: 1 thing(s) aren't connected, first card.tsx:1: isn't a composition"), "{s:?}");
std::fs::write(d.join("piece.tsx"), "import { Composition, registerRoot } from \"raea\";\nimport { Card } from \"./card\";\nregisterRoot(() => <Composition id=\"piece\" component={Card} width={1080} height={1920} fps={30} durationInFrames={90} />);\n").unwrap();
assert!(next::steps(&d, &shaped, 0)[0].starts_with("render piece.tsx"), "{:?}", next::steps(&d, &shaped, 0));
// the rest is read from the project's record (DR3): what each render and check found
use raea_core_facts::{Finding, Level, record::keep};
let (piece, video) = (d.join("piece.tsx"), d.join("out/piece.mp4"));
std::fs::create_dir_all(d.join("out")).unwrap();
std::thread::sleep(std::time::Duration::from_millis(20));
std::fs::write(d.join("out/piece.mp4"), "").unwrap();
assert!(next::steps(&d, &shaped, 0)[0].starts_with("check piece.mp4"));
std::thread::sleep(std::time::Duration::from_millis(20));
std::fs::write(d.join("out/piece.check.json"), r#"{"issues":[{"p":"P1","says":"text clipped at 2 s"}]}"#).unwrap();
assert_eq!(next::steps(&d, &shaped, 0)[0], "polish piece.mp4: P1 text clipped at 2 s (`raea guide polish`)");
std::fs::write(d.join("out/piece.check.json"), r#"{"issues":[{"p":"P3","says":"minor"}]}"#).unwrap();
assert!(next::steps(&d, &shaped, 0)[0].starts_with("show piece.mp4"));
std::fs::write(&video, "").unwrap();
let clips = Finding::new("clips", Level::Error, "the rider is in the seat", "raea render");
keep("raea render", &piece, Some(&video), &[clips], vec![], "20261110-160000").unwrap();
assert!(next::steps(&d, &shaped, 0)[0].starts_with("fix piece.tsx: clips: the rider is in the seat (its render 20261110-160000-piece found it"), "{:?}", next::steps(&d, &shaped, 0));
keep("raea render", &piece, Some(&video), &[], vec![], "20261110-160001").unwrap();
assert!(next::steps(&d, &shaped, 0)[0].starts_with("check out/piece.mp4: `raea check out/piece.mp4 -o out/piece.check.json`"));
keep("raea check", &video, None, &[Finding::new("clipped", Level::Error, "text clipped at 2 s", "raea check")], vec![], "20261110-160002").unwrap();
assert_eq!(next::steps(&d, &shaped, 0)[0], "polish out/piece.mp4: clipped: text clipped at 2 s (`raea guide polish`)");
keep("raea check", &video, None, &[Finding::new("reading", Level::Note, "minor", "raea check")], vec![], "20261110-160003").unwrap();
assert!(next::steps(&d, &shaped, 0)[0].starts_with("show out/piece.mp4"));
// stills (or a review) since the video don't replace it
keep("raea render", &piece, Some(&d.join("out")), &[], vec![], "20261110-160004").unwrap();
assert!(next::steps(&d, &shaped, 0)[0].starts_with("show out/piece.mp4"), "{:?}", next::steps(&d, &shaped, 0));
// the composition changed after the videos were made (their entries made old), before the stills: the video again
for id in ["20261110-160000-piece", "20261110-160001-piece"] {
let rec = d.join(format!(".raea/record/{id}.json"));
let mut v: serde_json::Value = serde_json::from_slice(&std::fs::read(&rec).unwrap()).unwrap();
v["at"] = 1.into();
std::fs::write(&rec, v.to_string()).unwrap();
}
let changed = std::time::UNIX_EPOCH + std::time::Duration::from_secs(100);
std::fs::File::options().write(true).open(&piece).unwrap().set_modified(changed).unwrap();
assert_eq!(next::steps(&d, &shaped, 0)[0], "render the video again: piece.tsx changed after 20261110-160001-piece made out/piece.mp4");
// no video at all: the video next
for id in ["20261110-160000-piece", "20261110-160001-piece"] {
std::fs::remove_file(d.join(format!(".raea/record/{id}.json"))).unwrap();
}
assert_eq!(next::steps(&d, &shaped, 0)[0], "render the video: `raea render piece.tsx -o out/piece.mp4`");
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn doctor_connects_a_projects_files() {
let d = scratch("doctor-pj8");
std::fs::create_dir_all(d.join(".raea")).unwrap();
std::fs::write(d.join(".raea/project"), "").unwrap();
std::fs::write(d.join("loose.tsx"), "export const Loose = () => null;\n").unwrap();
std::fs::write(d.join("pace.ts"), "import { controller } from \"raea/brief\";\nexport default controller({ title: \"Pace\", fields: {} });\n").unwrap();
let found = doctor::registry_findings(&d);
let says: Vec<&String> = found.iter().map(|f| &f.says).collect();
assert_eq!(found.len(), 2, "{says:?}");
assert!(says[0].contains("loose.tsx:1: isn't a composition") && !found[0].fixable(), "{says:?}");
assert!(says[1].contains("pace.ts:2: a controller outside controllers/") && found[1].fixable(), "{says:?}");
let out = doctor::doctor(&["--fix".into(), d.display().to_string()], &[], "0.0.1", &|_| Ok(String::new())).unwrap();
assert!(out.starts_with("APPLIED 3 of 4 fixed") && out.contains("fixed ") && d.join("controllers/pace.ts").is_file() && !d.join("pace.ts").exists(), "{out}");
assert_eq!(doctor::registry_findings(&d).len(), 1, "only the loose file is left");
let _ = std::fs::remove_dir_all(&d);
}
@@ -71,3 +117,19 @@ fn doctor_finds_old_briefs_and_old_skills() {
assert!(reinstalled.get() && out.starts_with("APPLIED 1 of 2 fixed"), "{out}");
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn the_root_with_none_set() {
let home = scratch("home-root");
assert_eq!(default_root(&home), home.join("Documents/raea"));
// an empty ~/Studio isn't one; one with a workspace stays the root
std::fs::create_dir_all(home.join("Studio/notes")).unwrap();
assert_eq!(default_root(&home), home.join("Documents/raea"));
std::fs::create_dir_all(home.join("Studio/acme/.raea")).unwrap();
std::fs::write(home.join("Studio/acme/.raea/workspace"), "").unwrap();
assert_eq!(default_root(&home), home.join("Studio"));
// iCloud keeping Documents: ~/raea
let synced = scratch("home-icloud");
std::fs::create_dir_all(synced.join("Library/Mobile Documents/com~apple~CloudDocs/Documents")).unwrap();
assert_eq!(default_root(&synced), synced.join("raea"));
}
+38 -23
View File
@@ -5,7 +5,7 @@
use super::*;
use std::process::Command;
const USAGE: &str = "usage: raea workspace [--json] | raea workspace init [NAME] [--layout monorepo|submodules] | raea workspace adopt DIR [--name NAME] [--layout monorepo|submodules]\n raea project [--json] | raea project new NAME [--storage inline|submodule] | raea project split NAME [--remote URL] | raea project join NAME";
const USAGE: &str = "usage: raea workspace [--json] | raea workspace init [NAME] [--layout monorepo|submodules] | raea workspace adopt DIR [--name NAME] [--layout monorepo|submodules]\n raea project [--json] | raea project new NAME [--storage inline|submodule] | raea project split NAME [--remote URL] | raea project join NAME | raea project scan [DIR] [--json]";
/// git for raea's own commits. A new Mac has no user.email and a hostname git can't make one from, so every commit
/// failed with "Author identity unknown" and the person's first project was never made. git reads $EMAIL only when
@@ -65,22 +65,12 @@ pub(crate) fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> {
/// The words of a command that aren't flags or a flag's value.
fn words(args: &[String]) -> Vec<&str> {
let takes = ["--layout", "--storage", "--name", "--remote"];
args.iter().enumerate().filter(|(i, a)| !a.starts_with("--") && !(*i > 0 && takes.contains(&args[i - 1].as_str()))).map(|(_, a)| a.as_str()).collect()
raea_app_check::words(args, &["--layout", "--storage", "--name", "--remote"])
}
/// A name as a folder: lowercase, dashes.
pub fn slug(s: &str) -> String {
let mut out = String::new();
for c in s.trim().to_lowercase().chars() {
if c.is_ascii_alphanumeric() {
out.push(c);
} else if !out.is_empty() && !out.ends_with('-') {
out.push('-');
}
}
out.trim_end_matches('-').to_string()
}
// a name as a folder (slug), and the nearest folder holding a marker (up): the registry's, which reads controller ids
// and projects with them
pub use raea_app_registry::{slug, up};
/// A new id: the prefix and eight hex digits from the clock and the process.
pub(crate) fn new_id(prefix: &str) -> String {
@@ -88,21 +78,40 @@ pub(crate) fn new_id(prefix: &str) -> String {
format!("{prefix}_{:08x}", (t as u64 ^ (std::process::id() as u64) << 20) as u32)
}
/// Where workspaces live on this machine: `git config --global raea.root`, else ~/Studio.
/// Where workspaces live on this machine: `git config --global raea.root`, else default_root.
pub fn root() -> PathBuf {
let set = config(None, &["--global", "raea.root"]).ok().filter(|s| !s.is_empty());
let home = std::env::var_os("HOME").map(PathBuf::from).unwrap_or_default();
match set {
Some(s) if s.starts_with("~/") => home.join(&s[2..]),
Some(s) => PathBuf::from(s),
None => home.join("Studio"),
None => default_root(&home),
}
}
/// The nearest folder at or above `from` that holds `marker` (.raea/workspace, .raea/project).
pub fn up(from: &Path, marker: &str) -> Option<PathBuf> {
let from = from.canonicalize().ok()?;
from.ancestors().find(|d| d.join(marker).is_file()).map(Path::to_path_buf)
/// Where workspaces go with no raea.root set: ~/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).
pub fn default_root(home: &Path) -> PathBuf {
let studio = home.join("Studio");
if holds_workspace(&studio) {
studio
} else if home.join("Library/Mobile Documents/com~apple~CloudDocs/Documents").is_dir() {
home.join("raea")
} else {
home.join("Documents/raea")
}
}
/// Whether a folder in `dir` is a workspace (it has .raea/workspace).
fn holds_workspace(dir: &Path) -> bool {
let Ok(entries) = std::fs::read_dir(dir) else { return false };
for e in entries.flatten() {
if e.path().join(".raea/workspace").exists() {
return true;
}
}
false
}
/// The include in a repo's own config that makes `git config` read a committed file. Idempotent; the path is relative
@@ -227,7 +236,7 @@ fn make_workspace(dir: &Path, name: &str, layout: &str) -> R<()> {
if !dir.join(".git").exists() && parent.exists() {
let top = git(parent, &["rev-parse", "--show-toplevel"]).ok().map(PathBuf::from);
if top.is_some_and(|t| t.canonicalize().ok() == parent.canonicalize().ok()) {
return Err(format!("{} would be a folder of the git repo {}: set where workspaces go, `git config --global raea.root ~/Studio`", dir.display(), parent.display()));
return Err(format!("{} would be a folder of the git repo {}: set where workspaces go, `git config --global raea.root ~/Documents/raea`", dir.display(), parent.display()));
}
}
std::fs::create_dir_all(dir.join("projects")).map_err(|e| format!("{}: {e}", dir.display()))?;
@@ -283,7 +292,7 @@ fn register(ws: &Path, dir: &Path, rel: &str, storage: &str) -> R<String> {
fn show_workspace(json_out: bool) -> R<String> {
let here = std::env::current_dir().map_err(|e| e.to_string())?;
let ws = up(&here, ".raea/workspace").ok_or("not in a workspace: raea workspace init NAME makes one (under `git config --global raea.root`, else ~/Studio)")?;
let ws = up(&here, ".raea/workspace").ok_or("not in a workspace: raea workspace init NAME makes one (under `git config --global raea.root`, else ~/Documents/raea)")?;
let file = ws.join(".raea/workspace");
let ps = projects(&ws);
if json_out {
@@ -305,6 +314,12 @@ pub fn project(args: &[String]) -> R<String> {
Some("new") => new_project(w.get(1).ok_or(USAGE)?, flag(args, "--storage")),
Some("split") => storage::split(w.get(1).ok_or(USAGE)?, flag(args, "--remote")),
Some("join") => storage::join(w.get(1).ok_or(USAGE)?),
// PJ8: the folder's compositions, components and controllers, and what isn't connected
Some("scan") => {
let dir = w.get(1).map(PathBuf::from).map_or_else(|| std::env::current_dir().map_err(|e| e.to_string()), Ok)?;
let r = crate::registry::scan(&dir);
Ok(if args.iter().any(|a| a == "--json") { r.json().to_string() } else { r.text() })
}
Some(v) => Err(format!("raea project has no {v:?}\n{USAGE}")),
}
}
+64
View File
@@ -0,0 +1,64 @@
#!/bin/bash
# A still late in a long 3D composition costs about what one early in it does (#77). A still at --at F stepped React
# only near F, but held every frame before it as copies, keyed each changing column on all of them and evaluated and
# kept every one in the timeline; and the engine drew every frame before F (catch_up: the plugin clock, installed in
# every build, though nothing in the scene was a plugin's): a film's --at 2448 took 234 s and 7.1 GB against 9 s and
# 3.1 GB at --at 30. 200 turning cubes over 3618 frames, with Bevy's own components on them, are drawn at --at 30 and
# --at 2448. The peak memory at 2448 must stay under 1.6x the one at 30 (the #60 build: 2.3x); the engine must step no
# frame to reach 2448 (RAEA_PLUGIN_TRACE; was 2447); and the 2448 still must match the same scene drawn at frame 30
# with its clock moved on 2418 frames (within 1 level, as frames are pure), so the shortcut changes no pixel. A scene
# a plugin steps is still stepped: runtime/plugins' only_rows_... test. Exits 1 on a failure.
# bench/at-cost/check.sh (RAEA_BIN: the raea to run, default target/release/raea)
cd "$(dirname "$0")/../.." || exit 2
BIN=${RAEA_BIN:-$PWD/target/release/raea}
export RAEA_SIGN=0 RAEA_MARK=0 RAEA_EXPORT_CACHE=0
OUT=$(mktemp -d "${TMPDIR:-/tmp}/raea-at-cost.XXXXXX")
trap 'rm -rf "$OUT"' EXIT
scene() { # FILE OFFSET
cat > "$1" <<TSX
import { AbsoluteFill, Composition, registerRoot, useCurrentFrame } from "raea";
import { StandardMaterial } from "raea/pbr";
import { Cuboid, Mesh3d } from "raea/mesh";
import { DirectionalLight } from "raea/light";
import { Transform, Quat } from "raea/transform";
import { Camera3d } from "raea/camera";
import { BevyComponent } from "raea/3d";
function Shot() {
const f = useCurrentFrame() + $2;
const parts = Array.from({ length: 200 }, (_, i) => (
<Mesh3d key={i} transform={Transform.fromXyz((i % 20) - 10, Math.floor(i / 20) - 5, -8).withRotation(Quat.fromEuler("XYZ", 0, f * 0.01 + i, 0))}>
<Cuboid half_size={[0.3, 0.3, 0.3]} />
<StandardMaterial base_color="#ff7a1a" />
{i === 0 ? <BevyComponent type="bevy_light::NotShadowCaster" value={{}} /> : null}
</Mesh3d>
));
return (
<AbsoluteFill style={{ backgroundColor: "#1b2230" }}>
<Camera3d transform={Transform.fromXyz(0, 0, 8).lookingAt([0, 0, 0])} />
<DirectionalLight illuminance={8000} transform={Transform.fromXyz(3, 5, 4).lookingAt([0, 0, 0])} />
{parts}
</AbsoluteFill>
);
}
registerRoot(() => <Composition id="c" component={Shot} width={640} height={360} fps={30} durationInFrames={3618} />);
TSX
}
scene "$OUT/late.tsx" 0
scene "$OUT/moved.tsx" 2418
status=0
peak() { # NAME TSX AT: the render's peak resident bytes on stdout
/usr/bin/time -l "$BIN" render "$2" --at "$3" -o "$OUT/$1" > "$OUT/$1.log" 2>&1 && [ -f "$OUT/$1/frame-00000.png" ] || { echo "FAIL $1: the render failed" >&2; tail -4 "$OUT/$1.log" | sed 's/^/ /' >&2; return 1; }
awk '/maximum resident set size/ { print $1 }' "$OUT/$1.log"
}
early=$(peak early "$OUT/late.tsx" 30) && late=$(peak late "$OUT/late.tsx" 2448) && moved=$(peak moved "$OUT/moved.tsx" 30) || exit 1
ratio=$(echo "scale=2; $late / $early" | bc)
if (( late * 10 < early * 16 )); then echo "ok --at 2448 peaks at ${ratio}x --at 30 ($((late >> 20)) MB, $((early >> 20)) MB)"
else echo "FAIL --at 2448 peaks at ${ratio}x --at 30 ($((late >> 20)) MB against $((early >> 20)) MB), wanted under 1.6x"; status=1; fi
steps=$(RAEA_PLUGIN_TRACE=1 "$BIN" render "$OUT/late.tsx" --at 2448 -o "$OUT/trace" 2>&1 | grep -c "^plugin clock: .* step$")
if (( steps == 0 )); then echo "ok --at 2448 draws no frame before it"
else echo "FAIL --at 2448 drew $steps frames before it, wanted none (the scene has nothing a plugin carries)"; status=1; fi
max=$(magick "$OUT/late/frame-00000.png" "$OUT/moved/frame-00000.png" -compose difference -composite -format "%[fx:int(maxima*255+0.5)]" info:)
if (( max <= 1 )); then echo "ok frame 2448 matches the scene moved on to it at frame 30 (largest difference $max)"
else echo "FAIL frame 2448 differs from the scene moved on to it at frame 30 by up to $max levels"; status=1; fi
[ $status = 0 ] && echo "PASS a late still costs about what an early one does, and draws the same frame"
exit $status
+162
View File
@@ -0,0 +1,162 @@
#!/usr/bin/env bash
# DR6's proof (docs/direction.feature): a note's asks held by checks.
# 1. The worked checks (sdk/guides/craft/checks, copied to checks/ as a project copies them), each named by an ask in
# notes/1, run by `raea check FILE --only nX.Y` on a piece that holds the ask and on each cheat that must fail it.
# 2. The notes' flow on a project of its own: a note said, restated as an ask about one composition, checked on the
# work as it stands (it must fail first), the work changed until it passes; an ask whose check passes on its first
# run is refused; an ask the person signs gets its clip cut from the newest render, and their sign from the app's
# inbox is kept, until the composition changes.
# Nothing is downloaded or generated; every case runs in a copy, so the bench folder stays clean.
#
# RAEA_BIN=path/to/raea bash bench/direction/asks/asks.sh
set -uo pipefail
here=$(cd "$(dirname "$0")" && pwd)
root=$(cd "$here/../../.." && pwd)
raea=${RAEA_BIN:-raea}
work=$(mktemp -d "${TMPDIR:-/tmp}/raea-dr6-asks.XXXXXX")
# KEEP=1 keeps the copy (its renders, logs, notes and state) and says where
if [ -n "${KEEP:-}" ]; then trap 'echo "asks: kept $work"' EXIT; else trap 'rm -rf "$work"' EXIT; fi
cp -R "$here/." "$work/"
rm -f "$work/asks.sh"
mkdir -p "$work/.raea" "$work/out" "$work/checks"
: >"$work/.raea/project"
cp "$root"/sdk/guides/craft/checks/*.ts "$work/checks/"
cd "$work" || exit 2
# the lyric's occlusion half reads who covers whom from a render's layers
for p in lyric lyric-deep lyric-bare lyric-words; do "$raea" render "$p.tsx" -o "out/$p.mp4" --layers >"out/$p.log" 2>&1 || { echo "asks: raea render $p.tsx failed:"; tail -5 "out/$p.log"; exit 2; }; done
bad=0
# FILE ID WANT: `raea check FILE --only ID` finds nothing (WANT none) or something (WANT some), waits for nothing,
# and every finding it prints is shown
case_() {
local file=$1 id=$2 want=$3
local out
out=$("$raea" check "$file" --only "$id" --json 2>"out/$file.$id.err")
local code=$?
if [ $code -eq 2 ] || ! jq -e .compositions >/dev/null 2>&1 <<<"$out"; then
echo "FAIL $file --only $id: raea check couldn't check it (exit $code): $(tail -3 "out/$file.$id.err") $(head -c 300 <<<"$out")"
bad=$((bad + 1))
return
fi
local n waits
n=$(jq '[.compositions[].findings[]] | length' <<<"$out")
waits=$(jq -r '[.compositions[].waits[] | "\(.rule) waits for \(.for)"] | join("; ")' <<<"$out")
local ok=1
{ [ "$want" = none ] && [ "$n" -ne 0 ]; } && ok=0
{ [ "$want" = some ] && [ "$n" -eq 0 ]; } && ok=0
[ -n "$waits" ] && ok=0
[ $ok -eq 1 ] || bad=$((bad + 1))
printf '%s %s --only %s: %s finding(s)%s\n' "$([ $ok -eq 1 ] && echo "ok " || echo FAIL)" "$file" "$id" "$n" "${waits:+, $waits}"
jq -r '.compositions[].findings[] | " \(.level) \(.check) \(.frames // "" | tostring): \(.says)"' <<<"$out"
}
echo "1. the worked checks, each on a piece that holds its ask and on its cheats"
case_ ride.tsx n1.1 none
for c in ride-left ride-into ride-gone; do case_ "$c.tsx" n1.1 some; done
case_ lyric.tsx n2.1 none
for c in lyric-deep lyric-bare lyric-words; do case_ "$c.tsx" n2.1 some; done
case_ office.tsx n3.1 none
case_ office.tsx n3.2 none
case_ office-turned.tsx n3.1 some
case_ office-kettle.tsx n3.2 some
case_ office-renamed.tsx n3.1 some
case_ office-renamed.tsx n3.2 some
case_ hold.tsx n4.1 none
for c in hold-short hold-renamed; do case_ "$c.tsx" n4.1 some; done
case_ office.tsx n5.1 none
for c in orb orb-renamed orb-tiny; do case_ "$c.tsx" n5.1 some; done
# 2. the flow, in a project of its own. The work as it stands: a desk turned from its chair with the kettle on it, and
# the reveal held two seconds
flow=$work/flow
mkdir -p "$flow/.raea" "$flow/checks" "$flow/inbox"
: >"$flow/.raea/project"
cp set.tsx "$flow/"
sed -e 's|<Office turned={3} />|<Office turned={3} kettle="desk" />|' -e 's|id="office-turned"|id="office"|' office-turned.tsx >"$flow/office.tsx"
sed 's|id="hold-short"|id="hold"|' hold-short.tsx >"$flow/hold.tsx"
cp checks/*.ts "$flow/checks/"
export RAEA_INBOX_DIR=$flow/inbox
cd "$flow" || exit 2
# NAME WANT-CODE LINE...: what `cmd` prints has each line (a fixed string), and it exits WANT-CODE
step() {
local name=$1 want=$2
shift 2
local out code
out=$("${cmd[@]}" 2>&1)
code=$?
local ok=1 l
[ "$code" -eq "$want" ] || ok=0
for l in "$@"; do grep -qF -- "$l" <<<"$out" || { ok=0; echo " missing: $l"; }; done
[ $ok -eq 1 ] || bad=$((bad + 1))
printf '%s %s (exit %s)\n' "$([ $ok -eq 1 ] && echo "ok " || echo FAIL)" "$name" "$code"
sed 's/^/ /' <<<"$out"
}
# FILE FROM TO: a note's file with FROM written as TO, as the agent edits it (FROM must be there)
edit() {
bun -e 'const [f, a, b] = process.argv.slice(1); const t = await Bun.file(f).text(); if (!t.includes(a)) { console.error(`${f}: no ${a}`); process.exit(1); } await Bun.write(f, t.replace(a, b));' "$@" || { echo "asks: couldn't edit $1"; exit 2; }
}
take=("$raea" notes take "$flow")
check=("$raea" notes check "$flow")
ls_=("$raea" notes ls "$flow")
echo "2. the notes' flow"
cmd=("${take[@]}" --said "The desks face the wrong way." --said "Hold the reveal longer, and let me see it." --said "And why is there a kettle on a desk?")
step "three notes said, taken to restate" 0 "notes/1/n1.ts: to restate" "notes/1/n3.ts: to restate" "round 1: 3 notes taken."
cmd=("${check[@]}")
step "nothing restated: nothing to check" 0 "no ask has a check or a clip to sign yet"
# restated as asks, each about one composition; the kettle's check names a part the scene doesn't have, so it can't fail
edit notes/1/n1.ts "asks: []," 'asks: [{ text: "every desk faces its chair", about: "desk", not: ["where the desks stand"], verb: "layout", of: "office.tsx", check: "../../checks/faces.ts", values: { what: "desk", toward: "chair" } }],'
edit notes/1/n2.ts "asks: []," 'asks: [{ text: "the reveal holds four seconds", about: "reveal", not: ["the lead-in"], verb: "retime", of: "hold.tsx", check: "../../checks/shot-length.ts", values: { shot: "reveal", seconds: 4 } }, { text: "the person sees the longer reveal and signs it", about: "reveal", not: ["the other shots"], verb: "retime", of: "hold.tsx", proof: { shot: "reveal", sign: true } }],'
edit notes/1/n3.ts "asks: []," 'asks: [{ text: "no kettle stands on a desk", about: "kettle, desk", not: ["the desks"], verb: "layout", of: "office.tsx", check: "../../checks/stands-on.ts", values: { what: "teapot", on: "desk" } }],'
cmd=("${ls_[@]}")
step "restated: where each ask stands" 0 " n1.1 every desk faces its chair; not: where the desks stand: to check: its check isn't shown failing on the work yet" " n2.2 the person sees the longer reveal and signs it; not: the other shots: to check: no clip yet"
cmd=("${check[@]}" --no-render)
step "checked on the work as it stands: two fail first; the kettle's passes, so it's refused" 1 \
"n1.1 notes/1/n1.ts: \"every desk faces its chair\": fails on the work as it stands (1 finding)" \
"n2.1 notes/1/n2.ts: \"the reveal holds four seconds\": fails on the work as it stands (1 finding)" \
"n3.1 notes/1/n3.ts: \"no kettle stands on a desk\": refused: its check passes on the work as it stands" \
"n2.2 notes/1/n2.ts: its clip waits for a render of hold.tsx"
cmd=("${ls_[@]}")
step "ls: failing, and the refused ask to check again" 0 " n1.1 every desk faces its chair; not: where the desks stand: failing (1 finding)" " n3.1 no kettle stands on a desk; not: the desks: to check: its check passed on its first run"
# the refused ask's check made to measure it: the kettle by its name
edit notes/1/n3.ts '"teapot"' '"kettle"'
cmd=("${check[@]}" --no-render)
step "the kettle's check, measuring it now, fails first" 0 "n3.1 notes/1/n3.ts: \"no kettle stands on a desk\": fails on the work as it stands (1 finding)" "n1.1 notes/1/n1.ts: \"every desk faces its chair\": failing (1 finding)"
# the work changes as the notes ask, and the hold is rendered for its clip
cp "$work/office.tsx" office.tsx
cp "$work/hold.tsx" hold.tsx
"$raea" render hold.tsx -o hold.mp4 >render.log 2>&1 || { echo "asks: raea render hold.tsx failed:"; tail -5 render.log; exit 2; }
cmd=("${check[@]}")
step "the work changed: every ask passes, and the reveal's clip is cut from the render" 0 \
"n1.1 notes/1/n1.ts: \"every desk faces its chair\": passing" \
"n2.1 notes/1/n2.ts: \"the reveal holds four seconds\": passing" \
"n3.1 notes/1/n3.ts: \"no kettle stands on a desk\": passing" \
"n2.2 notes/1/n2.ts: its clip, frames" "of hold.tsx#hold, cut from its newest render"
if [ -s .raea/notes-clips/n2.2.mp4 ]; then echo "ok the clip: .raea/notes-clips/n2.2.mp4, $(ffprobe -v error -show_entries format=duration -of csv=p=0 .raea/notes-clips/n2.2.mp4) s"; else echo "FAIL no clip at .raea/notes-clips/n2.2.mp4"; bad=$((bad + 1)); fi
cmd=("${ls_[@]}")
step "ls: the clip waits on the person" 0 " n2.2 the person sees the longer reveal and signs it; not: the other shots: to sign: its clip waits on the person"
# the person signs it in the app: the sign comes to the inbox, for the render the clip was cut from
render=$(jq -r '."n2.2".clip.render' .raea/notes-checks.json)
printf '{"kind":"sign","project":"flow","item":"i-show-1","comment":"cm-1","ask":2,"render":"%s","when":"2026-11-10T15:00:00Z"}\n' "$render" >inbox/a.jsonl
cmd=("${take[@]}")
step "a sign for a note that didn't come from that comment isn't kept" 0 "a sign for a note not in notes/ (app i-show-1 cm-1, ask 2)"
edit notes/1/n2.ts 'from: "session"' 'from: "app i-show-1 cm-1"'
cmd=("${take[@]}")
step "the person's sign is kept" 0 "notes/1/n2.ts: ask 2 signed by the person (unnamed: the app had no account), on the render ${render:0:12}…"
cmd=("${ls_[@]}")
step "ls: signed" 0 " n2.2 the person sees the longer reveal and signs it; not: the other shots: signed (unnamed: the app had no account)"
# the hold is shortened after its render: failing again, and the signed clip is no longer the work
sed 's|id="hold-short"|id="hold"|' "$work/hold-short.tsx" >hold.tsx
cmd=("${check[@]}")
step "the hold shortened again: failing, and its clip from a render that is no longer the work" 0 \
"n2.1 notes/1/n2.ts: \"the reveal holds four seconds\": failing (1 finding)" \
"n2.2 notes/1/n2.ts: its clip waits for a render of hold.tsx#hold as it stands: it changed after its newest render"
cmd=("${ls_[@]}")
step "ls: the sign doesn't hold, and rendering again is the agent's move" 0 " n2.2 the person sees the longer reveal and signs it; not: the other shots: to check: hold.tsx#hold changed after the render its clip is cut from: render it again"
if [ $bad -eq 0 ]; then echo "asks: every case as expected"; else echo "asks: $bad case(s) wrong"; fi
exit $((bad > 0))
+9
View File
@@ -0,0 +1,9 @@
// Cheat: the reveal renamed, so no shot is the one asked about. shot-length must fail it.
import { Composition, registerRoot } from "raea";
import { Hold } from "./set";
function Piece() {
return <Hold seconds={4} name="end" />;
}
registerRoot(() => <Composition id="hold-renamed" component={Piece} width={540} height={960} fps={30} durationInFrames={150} />);
+9
View File
@@ -0,0 +1,9 @@
// Cheat: the reveal left at two seconds. shot-length must fail it.
import { Composition, registerRoot } from "raea";
import { Hold } from "./set";
function Piece() {
return <Hold seconds={2} />;
}
registerRoot(() => <Composition id="hold-short" component={Piece} width={540} height={960} fps={30} durationInFrames={90} />);
+9
View File
@@ -0,0 +1,9 @@
// DR6's cut as asked: the reveal held four seconds.
import { Composition, registerRoot } from "raea";
import { Hold } from "./set";
function Piece() {
return <Hold seconds={4} />;
}
registerRoot(() => <Composition id="hold" component={Piece} width={540} height={960} fps={30} durationInFrames={150} />);
+9
View File
@@ -0,0 +1,9 @@
// Cheat: flat type with nothing in front of it. flat-type must fail it.
import { Composition, registerRoot } from "raea";
import { Lyric } from "./set";
function Piece() {
return <Lyric bare />;
}
registerRoot(() => <Composition id="lyric-bare" component={Piece} width={540} height={960} fps={30} durationInFrames={30} />);
Loaded 100 of 880 files, more files were not shown because too many files have changed in this diff. Show more