mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-01 06:53:19 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b7b777fc8a | ||
|
|
b903c74e5c | ||
|
|
ab904156c6 | ||
|
|
1ac6f0b88f | ||
|
|
550b2b836d | ||
|
|
27e54e954f | ||
|
|
a3241af2b5 | ||
|
|
c9e5a20c6b | ||
|
|
8d111c6f5b | ||
|
|
f96fdda16a | ||
|
|
619816627e | ||
|
|
0295020a39 | ||
|
|
1e8b2e63dc | ||
|
|
67d2b3e3ea | ||
|
|
1be0cc4a5b | ||
|
|
b861af80be | ||
|
|
4855d4da0f | ||
|
|
eb56911dd6 | ||
|
|
ddf9a6adef | ||
|
|
4fe5eb115b | ||
|
|
d730ef1cdd | ||
|
|
52b9bb7f65 | ||
|
|
7116d23eeb | ||
|
|
c5269af648 | ||
|
|
a81a8a1e1e | ||
|
|
5aa10b955c | ||
|
|
cd6bb40834 | ||
|
|
a331bffd13 | ||
|
|
0eda5dc0f5 | ||
|
|
ad4fbf6b35 | ||
|
|
848ff9471d | ||
|
|
dfb13e6ec9 | ||
|
|
9ab4e05f86 | ||
|
|
d4e23b602a | ||
|
|
b85ce4f97d | ||
|
|
a4a213e05e | ||
|
|
fddaf29fb1 | ||
|
|
91157b6610 | ||
|
|
e9174676c7 | ||
|
|
87ccba76c1 | ||
|
|
45aa5ca212 | ||
|
|
7fd6282cb2 | ||
|
|
07cd85e663 | ||
|
|
ce920a5530 | ||
|
|
0ea4eabe4a | ||
|
|
0c72d3942a | ||
|
|
65074df06e | ||
|
|
3725537f35 | ||
|
|
98e215b4c9 | ||
|
|
beb69f40bc | ||
|
|
fe44ef6e42 | ||
|
|
33d5548254 | ||
|
|
8a9236fffa | ||
|
|
95cccb4af5 | ||
|
|
07b6e3c7ec | ||
|
|
87fa310c80 | ||
|
|
32fdfe0863 | ||
|
|
4dc3083c6e | ||
|
|
b2631ff5b6 | ||
|
|
3763a778de | ||
|
|
20391a0649 | ||
|
|
76f383300c | ||
|
|
c49cc6b267 | ||
|
|
b4aaa8204f | ||
|
|
85c13e6daa | ||
|
|
19102fac4c | ||
|
|
766eab881d | ||
|
|
6f7a3f4478 | ||
|
|
7f438bf130 | ||
|
|
2c2e3ad3b8 | ||
|
|
7099bb9226 | ||
|
|
9a2187a6b9 | ||
|
|
d7f2aaf076 | ||
|
|
8796ceb67c | ||
|
|
9ebedb3f6f | ||
|
|
75b1c69e71 | ||
|
|
f822be2c05 | ||
|
|
d0d71e67d5 | ||
|
|
c4f9a84988 | ||
|
|
7d66dfc59c | ||
|
|
5b2c7731e2 | ||
|
|
d412678357 | ||
|
|
96191842c4 | ||
|
|
4eb42e3476 | ||
|
|
db9973375f | ||
|
|
d407fde7ee | ||
|
|
ff3515eda4 | ||
|
|
38684c9246 | ||
|
|
71750e0542 | ||
|
|
0fbfcb1d48 | ||
|
|
4c773e5fcf | ||
|
|
b6675ced26 | ||
|
|
a4fd51bebe | ||
|
|
105d285691 | ||
|
|
2e5f9d7755 | ||
|
|
45d41783a2 | ||
|
|
afa0f61ece | ||
|
|
43e8892ce2 | ||
|
|
c6f4c9132d | ||
|
|
eb3c8ea6bf | ||
|
|
6668da3253 | ||
|
|
060380ead5 | ||
|
|
0198736cd4 | ||
|
|
0b96b5ebd8 | ||
|
|
22cac9cf13 | ||
|
|
089ff35577 | ||
|
|
973ee00acc | ||
|
|
5ba4688c74 | ||
|
|
9444f13df3 | ||
|
|
bb0a1768c5 | ||
|
|
43429e6f2a | ||
|
|
b5de0cbee4 | ||
|
|
1f4a825714 | ||
|
|
a3477d0721 | ||
|
|
8e15cfccd3 | ||
|
|
fc274e2870 | ||
|
|
f4c41e9996 | ||
|
|
bf7fed1817 | ||
|
|
eab9198a1e | ||
|
|
c98501a88f | ||
|
|
aebbdb2d4a | ||
|
|
8a67680058 | ||
|
|
44b446302d | ||
|
|
a0b770709f | ||
|
|
3a705253de | ||
|
|
1c49f37e06 | ||
|
|
4ca98b13a3 | ||
|
|
e98085bb45 | ||
|
|
9b9dd9e780 | ||
|
|
ebce4f28ab | ||
|
|
2c111623c7 | ||
|
|
0a895f8752 | ||
|
|
9f3ffa7b1c | ||
|
|
574a4d228f | ||
|
|
898a0068df | ||
|
|
05abcdfc82 | ||
|
|
b8e55e9d5f | ||
|
|
1b55218328 | ||
|
|
0207451f1b | ||
|
|
fcdcd8dbaa | ||
|
|
ca54307223 | ||
|
|
e0067e2f00 | ||
|
|
7222289a05 | ||
|
|
b46b6468f4 | ||
|
|
b30ef6adca | ||
|
|
086115c907 | ||
|
|
20a696e793 | ||
|
|
f25c925eec | ||
|
|
07e47b4ee1 | ||
|
|
05c9788672 | ||
|
|
bec8cddcf0 | ||
|
|
ee62b13253 | ||
|
|
281da9cc10 | ||
|
|
0614e4b950 | ||
|
|
a956d8f8ee | ||
|
|
b6aa8b1d1e | ||
|
|
85f20faaf0 | ||
|
|
f04b3ae1b4 | ||
|
|
fa78ed3bc4 | ||
|
|
dad6913856 | ||
|
|
aa0a416b73 | ||
|
|
85adac1697 | ||
|
|
4c990e1b75 | ||
|
|
794769e15b | ||
|
|
e1b7a97ebd | ||
|
|
29c7d81369 | ||
|
|
f0e01210c2 | ||
|
|
551b2102bb | ||
|
|
1bed45b774 | ||
|
|
e58ed228a4 | ||
|
|
7198060ab9 | ||
|
|
afb3eb6dc6 | ||
|
|
b529c4ea00 | ||
|
|
2293efc121 | ||
|
|
cf28bf1ca0 | ||
|
|
a7e5b6c1d1 | ||
|
|
eff11d8778 | ||
|
|
dfa94a073e | ||
|
|
94a1cc59f7 | ||
|
|
e9e0fba83e | ||
|
|
36c3fe1dd7 | ||
|
|
5512224403 | ||
|
|
397d502f67 | ||
|
|
28b1acb6d2 | ||
|
|
cbc763ef8d | ||
|
|
890e51afc5 | ||
|
|
c6bb61b248 | ||
|
|
bb1d2bd0d5 | ||
|
|
148379c6e4 | ||
|
|
3eccbe39e5 | ||
|
|
b85409d738 | ||
|
|
bf49796080 | ||
|
|
70946b84bf | ||
|
|
ed0ebd2c01 | ||
|
|
ea3d7f85ec | ||
|
|
d1edca2817 | ||
|
|
e029385319 | ||
|
|
7a3e87dddb | ||
|
|
c03edea294 | ||
|
|
09a935abd0 | ||
|
|
e1914cabca | ||
|
|
0adc2ed8f2 | ||
|
|
4ca212f207 | ||
|
|
ace0f1423f | ||
|
|
3240414eff | ||
|
|
311b7988ee | ||
|
|
ebd147a076 | ||
|
|
d3e2922058 | ||
|
|
ada5e5b5a3 | ||
|
|
f8844bb385 | ||
|
|
804f57664f | ||
|
|
151de4ba63 | ||
|
|
0f6c275bdb | ||
|
|
9aaf3f21e6 | ||
|
|
4b8157f98c | ||
|
|
d4a00c6044 | ||
|
|
97d93d244f | ||
|
|
b800a1c5e1 | ||
|
|
85f4f08e14 | ||
|
|
d854f1a7af | ||
|
|
19acea76e4 | ||
|
|
ca69ed1094 | ||
|
|
41d22acc0c | ||
|
|
8b94190778 | ||
|
|
4c9ddb3d42 | ||
|
|
494711189a | ||
|
|
b4b2f7f03c | ||
|
|
d6f41c605a | ||
|
|
65eb89e635 | ||
|
|
8b5f153ec5 | ||
|
|
39aade79f7 | ||
|
|
c5a6d4f846 | ||
|
|
9ce80fc134 | ||
|
|
b7fc9e964f | ||
|
|
1faf24f9ac | ||
|
|
bc052693ac | ||
|
|
b301c65570 | ||
|
|
19b72d3dee | ||
|
|
f63bbca23b | ||
|
|
668ae2eb08 | ||
|
|
2881f190bb | ||
|
|
e19e07b12f | ||
|
|
5a77c3c834 | ||
|
|
9f8a94cdfd | ||
|
|
2c5b71fef8 | ||
|
|
121cdc7a0a | ||
|
|
ce8f2d29d2 | ||
|
|
894f9821b4 | ||
|
|
4175c116fb | ||
|
|
426567fb63 | ||
|
|
0620a51e85 | ||
|
|
c240b8e99d | ||
|
|
9a6f3d7358 | ||
|
|
c5fec6aeb9 | ||
|
|
20ff5785b6 | ||
|
|
bcfdb9e2b0 | ||
|
|
eeea139ade | ||
|
|
ce63b7a280 | ||
|
|
d6c7bf8d36 | ||
|
|
be8bdd597e | ||
|
|
4217941ad5 | ||
|
|
be388ffe80 | ||
|
|
de1a6830c2 | ||
|
|
3f95080394 | ||
|
|
4103559dac | ||
|
|
4081e5ac17 | ||
|
|
087949140d | ||
|
|
e9b22879a0 | ||
|
|
6684ea7c77 | ||
|
|
c60db71abf | ||
|
|
ae61cbb3e6 | ||
|
|
1a516a8de1 | ||
|
|
eaf5406f39 | ||
|
|
c1acc96d8d | ||
|
|
94d62d7fd7 | ||
|
|
6f6daa1b3b | ||
|
|
ac39b671ee | ||
|
|
ffd2738dcc | ||
|
|
a3db7b6dba | ||
|
|
21f9dd6936 | ||
|
|
d356bf5819 | ||
|
|
c6157d0d81 | ||
|
|
8de480c11a | ||
|
|
498d7765cd | ||
|
|
4e83e0b4b2 | ||
|
|
47545d9212 | ||
|
|
011cd1bd6c | ||
|
|
f5cb4f3ae2 | ||
|
|
0dd03f7c24 | ||
|
|
2ff13ee50b | ||
|
|
fa6a5ed17f | ||
|
|
5acc123835 | ||
|
|
1b6fbfc390 | ||
|
|
21182ec6ba | ||
|
|
8ff3d0cf00 | ||
|
|
4f7944c463 | ||
|
|
fff38cbcd6 | ||
|
|
ffc9962cd0 | ||
|
|
66195f7472 | ||
|
|
a28118696e | ||
|
|
6aff2de92a | ||
|
|
d708518be1 | ||
|
|
ced8fe55a2 | ||
|
|
5f5e7190db | ||
|
|
e4a0704178 | ||
|
|
0105bb67c4 | ||
|
|
65a687182f | ||
|
|
01538b57e7 | ||
|
|
392e4c7f1b | ||
|
|
c94e26cc2a | ||
|
|
ec8669acba | ||
|
|
fb7a4e4aeb | ||
|
|
ac27341206 | ||
|
|
1db765c97d | ||
|
|
167f1b6e12 | ||
|
|
99003a573e | ||
|
|
f5596c75c6 | ||
|
|
8e0c2b8d3d | ||
|
|
4667346f40 | ||
|
|
53b0ce3fbb | ||
|
|
ffc337b68f | ||
|
|
3d170ce60d | ||
|
|
5c7540f91c | ||
|
|
450f8e4a97 | ||
|
|
3fcd4e56f3 | ||
|
|
0ef2239226 | ||
|
|
4219d620f6 | ||
|
|
85beee43c6 | ||
|
|
16b9726fdc | ||
|
|
d45b38ef60 | ||
|
|
ef05474017 | ||
|
|
695f54b966 | ||
|
|
b36c58f95d | ||
|
|
2a71a69d95 | ||
|
|
a800f3cfa5 | ||
|
|
d7982d95e5 | ||
|
|
bdf9e53397 | ||
|
|
485cb7b8aa | ||
|
|
a6d7ab2c6b | ||
|
|
ba97a973c0 | ||
|
|
c703bb308c | ||
|
|
c0fd55f43d | ||
|
|
900411c90e | ||
|
|
1af64f2a41 | ||
|
|
43eb20fbd7 | ||
|
|
0ee51a1c64 | ||
|
|
9fe4c0c307 | ||
|
|
601296ea0e | ||
|
|
b269cbc12e | ||
|
|
133e637b80 | ||
|
|
e31303c7fd | ||
|
|
c4e528f56a | ||
|
|
00327576cc | ||
|
|
ea501764b2 | ||
|
|
0d3d0401de | ||
|
|
90f65721d9 | ||
|
|
fb35f5d908 | ||
|
|
9f1152a6f9 | ||
|
|
0652b75313 | ||
|
|
a5663cb511 | ||
|
|
f546e1d8c5 | ||
|
|
1a23d1f9bb | ||
|
|
3892ac4367 | ||
|
|
b6053cf8a7 | ||
|
|
07908a430d | ||
|
|
2e6ff46aea | ||
|
|
fd4d06c4e4 | ||
|
|
a00a49319e | ||
|
|
c7918660d5 | ||
|
|
0c419d8164 | ||
|
|
67114ed2ca | ||
|
|
3e1efbab77 | ||
|
|
30960ed5fa | ||
|
|
e4bab2a77a | ||
|
|
22074b5ded | ||
|
|
342bcfc3c0 | ||
|
|
f0094cbc3b | ||
|
|
f84a89cd52 | ||
|
|
298d32431b | ||
|
|
ec33f6b871 | ||
|
|
1dca9ace77 | ||
|
|
6998f9e3e6 | ||
|
|
1eb646f7b9 | ||
|
|
ca41f80d16 | ||
|
|
36cbb99227 | ||
|
|
3675c7a9f9 | ||
|
|
9f91e35a8f | ||
|
|
abc859cf5d | ||
|
|
99428724de | ||
|
|
9027f9d1e5 | ||
|
|
6654b93639 | ||
|
|
7ca949df87 | ||
|
|
1acea1b83e | ||
|
|
9e3f99ff54 | ||
|
|
aef305429a | ||
|
|
c7530ccbdd | ||
|
|
089acda03a | ||
|
|
bea844ba6c | ||
|
|
8c96f67da8 | ||
|
|
1b023081a6 | ||
|
|
e94514d243 | ||
|
|
e63a155739 | ||
|
|
be661a5f0b | ||
|
|
c0d5f8306f | ||
|
|
5af23ab8d4 | ||
|
|
abd167408a | ||
|
|
5ada160314 | ||
|
|
03eaef2b66 | ||
|
|
b2d07d1165 | ||
|
|
934d9b0a72 | ||
|
|
08a4b7df02 | ||
|
|
ee771c453c | ||
|
|
461c7491ac | ||
|
|
b7c4052f30 | ||
|
|
4e570ce401 | ||
|
|
1fdc431b72 | ||
|
|
082aa7489f | ||
|
|
318b1939ab | ||
|
|
d03eb9d7c9 | ||
|
|
71a65438d8 | ||
|
|
0730b9cd73 | ||
|
|
e3df1da170 | ||
|
|
c33faa7e5e | ||
|
|
fa46f4ebb6 | ||
|
|
b4558ac472 | ||
|
|
c0aec0a804 | ||
|
|
b952bb580b | ||
|
|
3a2b027488 | ||
|
|
b78afb5676 | ||
|
|
86af87a90d | ||
|
|
8bd8e2c986 | ||
|
|
adb442d0f2 | ||
|
|
adedccddf0 |
No files matched your search
@@ -6,6 +6,6 @@
|
||||
"homepage": "https://raea.io",
|
||||
"repository": "https://github.com/shinyobjectz/raea",
|
||||
"license": "FSL-1.1-ALv2",
|
||||
"skills": ["./sdk/skills/"],
|
||||
"skills": ["./skills/skills/raea"],
|
||||
"keywords": ["video", "motion-graphics", "game-development", "rendering", "bevy", "react", "agent-skills"]
|
||||
}
|
||||
@@ -15,7 +15,8 @@ permissions:
|
||||
|
||||
concurrency:
|
||||
group: ci-${{ github.event.pull_request.number || github.ref }}
|
||||
cancel-in-progress: true
|
||||
# a pull request's newer push replaces its run; main's pushes each finish (on a busy main, cancelling meant none did)
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: never
|
||||
@@ -31,8 +32,13 @@ jobs:
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: gitleaks
|
||||
# GitHub's release host answered 504 for minutes at a time on 11-08, through every retry; the same version's
|
||||
# container image on ghcr.io is the fallback
|
||||
run: |
|
||||
curl -fsSL https://github.com/gitleaks/gitleaks/releases/download/v8.30.1/gitleaks_8.30.1_linux_x64.tar.gz | tar -xz -C /usr/local/bin gitleaks
|
||||
v=8.30.1
|
||||
curl -fsSL --retry 3 --retry-all-errors https://github.com/gitleaks/gitleaks/releases/download/v$v/gitleaks_${v}_linux_x64.tar.gz | tar -xz -C /usr/local/bin gitleaks \
|
||||
|| { c=$(docker create ghcr.io/gitleaks/gitleaks:v$v) && sudo docker cp "$c:/usr/bin/gitleaks" /usr/local/bin/gitleaks && docker rm "$c"; }
|
||||
gitleaks version
|
||||
- name: public-guard
|
||||
run: |
|
||||
base=${{ github.event.pull_request.base.sha || github.event.before }}
|
||||
@@ -54,6 +60,7 @@ jobs:
|
||||
- name: tools
|
||||
run: |
|
||||
rustup show active-toolchain
|
||||
sudo apt-get update && sudo apt-get install -y ripgrep
|
||||
cargo install --locked cargo-shear cargo-dupes
|
||||
- name: layers
|
||||
run: bash tools/layers.sh
|
||||
@@ -71,6 +78,9 @@ jobs:
|
||||
run: cargo shear --color never --deny-warnings
|
||||
- name: tasks
|
||||
run: bash tools/rask.sh check
|
||||
- name: sdk packages
|
||||
# sdk-coverage reads csstype and @types/react from them; node_modules aren't in git
|
||||
run: cd sdk/raea && bun install --frozen-lockfile
|
||||
- name: sdk coverage
|
||||
run: bash tools/sdk-coverage --check
|
||||
- name: sdk props
|
||||
@@ -92,10 +102,10 @@ jobs:
|
||||
lfs: false
|
||||
- name: Linux libraries
|
||||
if: runner.os == 'Linux'
|
||||
run: sudo apt-get update && sudo apt-get install -y cmake ninja-build libasound2-dev libfontconfig1-dev libvulkan-dev libudev-dev
|
||||
run: sudo apt-get update && sudo apt-get install -y cmake ninja-build libasound2-dev libfontconfig1-dev libvulkan-dev libudev-dev nasm
|
||||
- name: macOS tools
|
||||
if: runner.os == 'macOS'
|
||||
run: brew install cmake ninja
|
||||
run: brew install cmake ninja nasm
|
||||
- uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: 1.4.2
|
||||
|
||||
@@ -1,8 +1,18 @@
|
||||
# A release, built here where anyone can read how (public #6; docs/public-first.feature PF5): for a v* tag, macOS on
|
||||
# Apple Silicon and Linux on x86_64 are built from the tag on GitHub's runners, packed by tools/release.sh, checked by
|
||||
# tools/release-check.sh, attested (anyone can check a download with
|
||||
# Apple Silicon, Linux on x86_64 and Windows on x86_64 are built from the tag on GitHub's runners, packed by
|
||||
# tools/release.sh, checked by tools/release-check.sh, attested (anyone can check a download with
|
||||
# `gh attestation verify raea-VERSION-macos-arm64.tar.gz -R shinyobjectz/raea`) and attached to the tag's release.
|
||||
# Windows builds in windows.yml's release mode. The release's notes and whether it's a pre-release are set by hand.
|
||||
# The skills gate reads the feed app, which is private, so it runs in a maintainer's checkout first
|
||||
# (tools/skills.sh check), and the tag names the commit it passed on; tools/release.sh checks the gate's inputs haven't
|
||||
# changed since (tools/release/skills-passed.sh):
|
||||
# git tag -a v0.1.0 -m "raea 0.1.0" -m "skills-passed: <full sha>"
|
||||
# A tag with a suffix (v0.1.0-rc1, v0.1.0-canary.3) is made a pre-release; a plain version (v0.1.0) is a full release,
|
||||
# GitHub's latest. The release's notes are set by hand.
|
||||
# A release whose code is a candidate's is promoted, not compiled again (tools/release/promoted-from.sh: the tag's
|
||||
# "promoted-from: v0.1.0-rc5" line, which tools/agents/release-go.sh writes): each job takes the candidate's attested
|
||||
# binaries for its platform (tools/release/promoted-bins.sh) and packs, checks, attests and attaches them as the
|
||||
# release, in minutes instead of the three hours a cold build takes. Run by hand, dry_run packs and checks without
|
||||
# attesting or attaching (the archives are the run's artifacts), for trying a promote before the real one.
|
||||
name: release
|
||||
|
||||
on:
|
||||
@@ -11,9 +21,21 @@ on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: the tag to build (v0.1.0-canary.4)
|
||||
description: the tag to build (v0.1.0)
|
||||
required: true
|
||||
type: string
|
||||
skills_passed:
|
||||
description: the full SHA where tools/skills.sh check passed with the feed app (else the tag's skills-passed line)
|
||||
default: ""
|
||||
type: string
|
||||
promote_from:
|
||||
description: a candidate tag (v0.1.0-rc5) whose binaries this release is, else the tag's promoted-from line; none builds from source
|
||||
default: ""
|
||||
type: string
|
||||
dry_run:
|
||||
description: pack and check only; nothing attested or attached (the archives are this run's artifacts)
|
||||
default: false
|
||||
type: boolean
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
@@ -34,9 +56,10 @@ jobs:
|
||||
- os: macos-15
|
||||
lib: libraea_bundle.dylib
|
||||
extra: raea-perceive
|
||||
# raea-perceive (`raea song`'s map) builds off Apple since #43
|
||||
- os: ubuntu-24.04
|
||||
lib: libraea_bundle.so
|
||||
extra: ""
|
||||
extra: raea-perceive
|
||||
runs-on: ${{ matrix.os }}
|
||||
# a cold thin-LTO build of raea-cli with the plugin catalog is the long part; GitHub's own limit is 6 hours
|
||||
timeout-minutes: 340
|
||||
@@ -46,9 +69,13 @@ jobs:
|
||||
ref: ${{ env.TAG }}
|
||||
submodules: true
|
||||
lfs: false
|
||||
- name: Promoted from a candidate, or built (tools/release/promoted-from.sh)
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: bash tools/release/promoted-from.sh "$TAG" "${{ inputs.promote_from }}"
|
||||
- name: Linux libraries
|
||||
if: runner.os == 'Linux'
|
||||
run: sudo apt-get update && sudo apt-get install -y cmake ninja-build libasound2-dev libfontconfig1-dev libvulkan-dev libudev-dev mesa-vulkan-drivers xvfb
|
||||
run: sudo apt-get update && sudo apt-get install -y cmake ninja-build nasm libxkbcommon-dev libxkbcommon-x11-dev libasound2-dev libfontconfig1-dev libvulkan-dev libudev-dev mesa-vulkan-drivers xvfb
|
||||
- name: macOS tools
|
||||
if: runner.os == 'macOS'
|
||||
run: brew install cmake ninja
|
||||
@@ -65,7 +92,20 @@ jobs:
|
||||
curl -fsSL "$url" -o "$HOME/.local/share/raea-models/$path"
|
||||
echo "$sha $HOME/.local/share/raea-models/$path" | shasum -a 256 -c -
|
||||
done < tools/release/models.tsv
|
||||
# rc3's build left 576 MB of macos-15's 320 GB free, and rc4's dSYMs (#88) ran it out linking raea-page-host
|
||||
# (ld: write() failed, errno=28): the image's other Xcodes and the Android and .NET SDKs go first
|
||||
- name: Room for the build
|
||||
if: runner.os == 'macOS' && env.RAEA_PROMOTED_FROM == ''
|
||||
run: |
|
||||
df -h . | tail -1
|
||||
keep=$(cd "$(xcode-select -p)/../.." && pwd -P)
|
||||
for x in /Applications/Xcode*.app; do [ -L "$x" ] || [ "$(cd "$x" && pwd -P)" = "$keep" ] || sudo rm -rf "$x" & done
|
||||
sudo rm -rf "$HOME/Library/Android" "$HOME/.dotnet" /usr/local/share/dotnet &
|
||||
wait
|
||||
echo "kept $keep"
|
||||
df -h . | tail -1
|
||||
- name: Build
|
||||
if: env.RAEA_PROMOTED_FROM == ''
|
||||
run: |
|
||||
feat=$(bash tools/bevy-plugins.sh features sdk/raea/bench/bevy-plugins)
|
||||
cargo build --profile dist --locked -p raea-cli --bin raea --no-default-features --features "$feat"
|
||||
@@ -75,17 +115,249 @@ jobs:
|
||||
mkdir ship
|
||||
cp target/dist/raea target/dist/${{ matrix.lib }} target/dist/raea-rune-host target/dist/raea-page-host ship/
|
||||
if [ -n "${{ matrix.extra }}" ]; then cp target/dist/${{ matrix.extra }} ship/; fi
|
||||
# the Mac's dSYMs (tools/link-jit.sh made them as it stripped each binary, #88); release.sh keeps them
|
||||
if [ -d target/dist/symbols ]; then cp -R target/dist/symbols ship/; fi
|
||||
- name: The candidate's binaries (tools/release/promoted-bins.sh)
|
||||
if: env.RAEA_PROMOTED_FROM != ''
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: bash tools/release/promoted-bins.sh "$RAEA_PROMOTED_FROM" ship
|
||||
# the packing and its checks need only ship/, and macos-15's disk ran out packing rc1 with target/ kept
|
||||
- name: Free the build's disk
|
||||
run: |
|
||||
df -h . | tail -1
|
||||
rm -rf target
|
||||
df -h . | tail -1
|
||||
- name: Where the skills gate passed
|
||||
run: bash tools/release/skills-passed.sh "$TAG" "${{ inputs.skills_passed }}"
|
||||
- name: Pack and check (tools/release.sh)
|
||||
env:
|
||||
RAEA_CHECK_DIR: ${{ runner.temp }}/release-check
|
||||
run: |
|
||||
v=${TAG#v}
|
||||
if [ "$RUNNER_OS" = Linux ]; then xvfb-run -a -s "-screen 0 1280x1024x24" bash tools/release.sh "$v" ship HEAD
|
||||
else bash tools/release.sh "$v" ship HEAD; fi
|
||||
# a failed check's own files (the app check's frames, every step's log), not the unpacked release
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: failure()
|
||||
with:
|
||||
name: release-check-${{ runner.os }}
|
||||
path: |
|
||||
${{ runner.temp }}/release-check/app
|
||||
${{ runner.temp }}/release-check/**/*.log
|
||||
retention-days: 7
|
||||
if-no-files-found: ignore
|
||||
# the stripped binaries' symbols (#88), for symbolicating a crash report from this release; never published
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: symbols-${{ runner.os }}
|
||||
path: dist/raea-*-symbols
|
||||
retention-days: 90
|
||||
if-no-files-found: warn
|
||||
- uses: actions/attest-build-provenance@v2
|
||||
if: ${{ !inputs.dry_run }}
|
||||
with:
|
||||
subject-path: dist/raea-*.tar.gz
|
||||
- name: Attach to the release
|
||||
if: ${{ !inputs.dry_run }}
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
gh release view "$TAG" >/dev/null 2>&1 || gh release create "$TAG" --prerelease --title "raea ${TAG#v}" --notes "Built by .github/workflows/release.yml; notes follow."
|
||||
gh release view "$TAG" >/dev/null 2>&1 || gh release create "$TAG" ${{ contains(env.TAG, '-') && '--prerelease' || '' }} --title "raea ${TAG#v}" --notes "Built by .github/workflows/release.yml; notes follow."
|
||||
gh release upload "$TAG" dist/raea-*.tar.gz dist/raea-*.tar.gz.sha256 --clobber
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: ${{ inputs.dry_run }}
|
||||
with:
|
||||
name: dry-run-${{ runner.os }}
|
||||
path: dist/raea-*.tar.gz*
|
||||
retention-days: 3
|
||||
compression-level: 0
|
||||
|
||||
# Windows in Git's bash on GitHub's runner, with the Visual Studio Build Tools in its image (their image terms; we
|
||||
# accept no licence and download no Microsoft files). The C runtime is the DLL one (the VC++ redistributable): ort's
|
||||
# prebuilt ONNX Runtime is built against it, so crt-static doesn't link (LNK2019 on __imp_ symbols, 10-29).
|
||||
windows:
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 350
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ env.TAG }}
|
||||
submodules: true
|
||||
lfs: false
|
||||
- name: Promoted from a candidate, or built (tools/release/promoted-from.sh)
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: bash tools/release/promoted-from.sh "$TAG" "${{ inputs.promote_from }}"
|
||||
- name: Toolchain (rust-toolchain.toml's pin)
|
||||
if: env.RAEA_PROMOTED_FROM == ''
|
||||
run: rustup show active-toolchain || rustup toolchain install
|
||||
# jq for Windows ends -r lines with CRLF, so tools/bevy-plugins.sh read "ahoy\r" and lost its Bevy 0.20 block
|
||||
# (feature `ahoy` not found, 11-04); -b writes LF
|
||||
- name: jq that writes LF
|
||||
run: |
|
||||
mkdir -p "$RUNNER_TEMP/jq"
|
||||
printf '#!/bin/bash\nexec "%s" -b "$@"\n' "$(command -v jq)" > "$RUNNER_TEMP/jq/jq"
|
||||
chmod +x "$RUNNER_TEMP/jq/jq"
|
||||
echo "$RUNNER_TEMP/jq" >> "$GITHUB_PATH"
|
||||
- uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: 1.4.2
|
||||
- name: The runtime's packages
|
||||
run: for d in sdk/react/js sdk/react/tw; do (cd "$d" && bun install --frozen-lockfile); done
|
||||
# `raea song`'s beat model, which release.sh packs (into Git bash's ~/.local/share/raea-models, as on the others)
|
||||
- name: Models (pinned by URL and sha256 in tools/release/models.tsv)
|
||||
run: |
|
||||
while IFS=$'\t' read -r path url sha; do
|
||||
case $path in ''|'#'*) continue ;; esac
|
||||
mkdir -p "$HOME/.local/share/raea-models/$(dirname "$path")"
|
||||
curl -fsSL "$url" -o "$HOME/.local/share/raea-models/$path"
|
||||
echo "$sha $HOME/.local/share/raea-models/$path" | sha256sum -c -
|
||||
done < <(tr -d '\r' < tools/release/models.tsv)
|
||||
# the app targets' hosts a cargo call each: with raea-cli's crates in one call taffy's features unify and
|
||||
# rune-taffy doesn't build; raea-perceive (`raea song`'s map, #43) a call of its own too
|
||||
- name: Build
|
||||
if: env.RAEA_PROMOTED_FROM == ''
|
||||
run: |
|
||||
feat=$(bash tools/bevy-plugins.sh features sdk/raea/bench/bevy-plugins)
|
||||
cargo build --profile dist --locked -p raea-cli --bin raea --no-default-features --features "$feat"
|
||||
cargo build --profile dist --locked -p raea-rune-host
|
||||
cargo build --profile dist --locked -p raea-page-host --features window
|
||||
cargo build --profile dist --locked -p raea-perceive
|
||||
- name: The candidate's binaries (tools/release/promoted-bins.sh)
|
||||
if: env.RAEA_PROMOTED_FROM != ''
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: bash tools/release/promoted-bins.sh "$RAEA_PROMOTED_FROM" target/dist
|
||||
# which DLLs raea needs from the machine (the CRT's come from the VC++ redistributable)
|
||||
- name: What raea.exe imports
|
||||
run: |
|
||||
{ echo '### what raea.exe, raea_bundle.dll and raea-perceive.exe import'; echo '```'
|
||||
dumpbin=$(ls "/c/Program Files/Microsoft Visual Studio"/*/*/VC/Tools/MSVC/*/bin/HostX64/x64/dumpbin.exe | head -1)
|
||||
"$dumpbin" -nologo -dependents target/dist/raea.exe target/dist/raea_bundle.dll target/dist/raea-perceive.exe | grep -iE '\.dll$|Dump of' | sed 's/^ *//'
|
||||
echo '```'; } | tee -a "$GITHUB_STEP_SUMMARY" || true
|
||||
# release.sh's checks render on Mesa's lavapipe (software Vulkan, MIT; on the runner only, never in the zip): the
|
||||
# runner has no GPU, and WARP, Windows' own software DX12, crashes compiling one of Bevy's compute shaders there
|
||||
# (d3d10warp ComputeShaderTransformer::ConstructLoadStoreSets, an access violation; 11-04)
|
||||
- name: Software Vulkan
|
||||
run: bash tools/release/lavapipe.sh
|
||||
- name: Where the skills gate passed
|
||||
run: bash tools/release/skills-passed.sh "$TAG" "${{ inputs.skills_passed }}"
|
||||
- name: Pack and check (tools/release.sh)
|
||||
env:
|
||||
RAEA_CHECK_DIR: ${{ runner.temp }}/release-check
|
||||
run: bash tools/release.sh "${TAG#v}" target/dist HEAD
|
||||
# live play on Windows (PT20 left it unproven): bevy-ts's play cases, `play --offscreen` with an input script and
|
||||
# a snapshot's pixels probed, run by the raea just built; check.sh reads the pixels with ImageMagick, which the
|
||||
# image has only sometimes, and choco's PATH change doesn't reach the next step, so its folder goes on GITHUB_PATH
|
||||
- name: ImageMagick (check.sh reads a snapshot's pixels)
|
||||
shell: pwsh
|
||||
run: |
|
||||
if (-not (Get-Command magick -ErrorAction SilentlyContinue)) { choco install imagemagick -y --no-progress | Out-Null }
|
||||
$im = Get-ChildItem "C:\Program Files" -Directory -Filter "ImageMagick-*" | Select-Object -First 1
|
||||
if ($im) { Add-Content $env:GITHUB_PATH $im.FullName }
|
||||
# without the loader's debug lines (lavapipe.sh sets them for the driver's registration), and a failing case's
|
||||
# log tail in the job's log, since the runner and its logs go when the job ends
|
||||
# each case is bounded by check.sh (RAEA_CASE_SECONDS: a fresh runner's first play opens in about 100s, the next in
|
||||
# seconds); the step's own bound is for the rest
|
||||
- name: Live play (bevy-ts's play cases)
|
||||
timeout-minutes: 75
|
||||
env:
|
||||
VK_LOADER_DEBUG: ""
|
||||
RAEA_CASE_SECONDS: "300"
|
||||
# the zip's raea, unpacked, with RAEA_NO_TREE=1 and the cases copied out of the checkout, as a user's machine has
|
||||
# them: target/dist's raea has no share/raea beside it, so its home is this checkout, 2 h of build in target/
|
||||
# included, and there its 3D cases ran past 300 s each (rc1) where the unpacked zip's open in under 70 s
|
||||
run: |
|
||||
u="$RUNNER_TEMP/play-zip"; c="$RUNNER_TEMP/play-cases"
|
||||
mkdir -p "$u" && 7z x -y -o"$u" dist/raea-*.zip > /dev/null && cp -r sdk/raea/bench/bevy-ts/cases "$c"
|
||||
b="$u/raea/bin/raea.exe"
|
||||
out="${TMPDIR:-/tmp}/raea-bevy-ts"
|
||||
s=0; RAEA_NO_TREE=1 RAEA_BIN="$b" RAEA_PLUGIN_BIN="$b" bash sdk/raea/bench/bevy-ts/check.sh $(grep -l '^// play:' "$c"/*.tsx) 2>&1 | tee "$RUNNER_TEMP/play.txt" || s=$?
|
||||
cat "$RUNNER_TEMP/play.txt" >> "$GITHUB_STEP_SUMMARY"
|
||||
for n in $(sed -n 's/^\([^ ]*\) (.*): OPEN.*/\1/p' "$RUNNER_TEMP/play.txt"); do echo "--- $n"; { grep -v "known driver" "$out/$n.log" || echo "(its log is empty)"; } | tail -25; done
|
||||
exit $s
|
||||
- uses: actions/attest-build-provenance@v2
|
||||
if: ${{ !inputs.dry_run }}
|
||||
with:
|
||||
subject-path: dist/raea-*.zip
|
||||
# kept even when its check fails, with the check's own files, so a failure can be looked into on a fresh runner
|
||||
# without a rebuild; only windows-verify attaches it to the release
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: always()
|
||||
with:
|
||||
name: windows-zip
|
||||
path: dist/raea-*.zip*
|
||||
retention-days: 7
|
||||
compression-level: 0
|
||||
if-no-files-found: ignore
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: failure()
|
||||
with:
|
||||
name: release-check-Windows
|
||||
path: ${{ runner.temp }}/release-check/app
|
||||
retention-days: 7
|
||||
if-no-files-found: ignore
|
||||
|
||||
# the zip alone, on a runner that never had raea's sources, as a user's machine gets it; it also tests the
|
||||
# published installer (raea.io/install.ps1), pointed at the zip by RAEA_DOWNLOAD. Only a zip that passes is attached.
|
||||
windows-verify:
|
||||
needs: windows
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 20
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ env.TAG }}
|
||||
lfs: false
|
||||
sparse-checkout: |
|
||||
tools/release-check.sh
|
||||
tools/release/lavapipe.sh
|
||||
sparse-checkout-cone-mode: false
|
||||
path: check
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: windows-zip
|
||||
path: ${{ runner.temp }}/zip
|
||||
- name: Software Vulkan
|
||||
run: bash check/tools/release/lavapipe.sh
|
||||
- name: The zip, unpacked and checked
|
||||
run: |
|
||||
set -e
|
||||
v=${TAG#v}
|
||||
cp check/tools/release-check.sh "$RUNNER_TEMP/"
|
||||
rm -rf check
|
||||
cd "$RUNNER_TEMP/zip"
|
||||
sha256sum -c "raea-$v-windows-x86_64.zip.sha256"
|
||||
bash "$RUNNER_TEMP/release-check.sh" "$PWD/raea-$v-windows-x86_64.zip" | tee -a "$GITHUB_STEP_SUMMARY"
|
||||
- name: install.ps1, then a render from PATH
|
||||
shell: pwsh
|
||||
run: |
|
||||
$v = $env:TAG.Substring(1)
|
||||
$rel = Join-Path $env:RUNNER_TEMP "rel"
|
||||
New-Item -ItemType Directory -Force -Path (Join-Path $rel "v$v") | Out-Null
|
||||
Copy-Item (Join-Path $env:RUNNER_TEMP "zip/raea-$v-windows-x86_64.zip*") (Join-Path $rel "v$v")
|
||||
$env:RAEA_DOWNLOAD = $rel; $env:RAEA_VERSION = $v; $env:RAEA_NO_SKILLS = "1"
|
||||
& ([scriptblock]::Create((Invoke-RestMethod https://raea.io/install.ps1)))
|
||||
$p = Join-Path $env:RUNNER_TEMP "user"; New-Item -ItemType Directory -Force -Path $p | Out-Null; Set-Location $p
|
||||
$env:RAEA_NO_TREE = "1"; $env:RAEA_API = "http://127.0.0.1:9"
|
||||
raea init
|
||||
if ($LASTEXITCODE) { throw "raea init failed" }
|
||||
Set-Content hello.tsx 'import { AbsoluteFill, Composition, registerRoot } from "raea"; registerRoot(() => <Composition id="hello" component={() => <AbsoluteFill style={{ background: "#123", color: "#fff", fontSize: 90, justifyContent: "center", alignItems: "center" }}>raea on Windows</AbsoluteFill>} width={640} height={360} fps={30} durationInFrames={30} />);'
|
||||
$h = Join-Path $env:RUNNER_TEMP "hello"; New-Item -ItemType Directory -Force -Path $h | Out-Null; Move-Item hello.tsx $h; Set-Location $h
|
||||
raea render hello.tsx --frame 1 -o hello.png
|
||||
if ($LASTEXITCODE -or -not (Test-Path hello.png)) { throw "raea render failed" }
|
||||
Get-Item hello.png | Format-List Name, Length
|
||||
- name: Attach to the release
|
||||
if: ${{ !inputs.dry_run }}
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
gh release view "$TAG" -R "$GITHUB_REPOSITORY" >/dev/null 2>&1 || gh release create "$TAG" -R "$GITHUB_REPOSITORY" ${{ contains(env.TAG, '-') && '--prerelease' || '' }} --title "raea ${TAG#v}" --notes "Built by .github/workflows/release.yml; notes follow."
|
||||
gh release upload "$TAG" -R "$GITHUB_REPOSITORY" "$RUNNER_TEMP"/zip/raea-*.zip "$RUNNER_TEMP"/zip/raea-*.zip.sha256 --clobber
|
||||
@@ -1,3 +1,6 @@
|
||||
[submodule "tools/rask"]
|
||||
path = tools/rask
|
||||
url = https://github.com/shinyobjectz/rask.git
|
||||
[submodule "skills"]
|
||||
path = skills
|
||||
url = https://github.com/shinyobjectz/raea-skills.git
|
||||
Generated
+381
-11
@@ -2593,7 +2593,6 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "bevy_hanabi"
|
||||
version = "0.20.0-dev"
|
||||
source = "git+https://github.com/djeedai/bevy_hanabi?rev=77630ff1eed8b104f34e91d23e9440428dc5ab01#77630ff1eed8b104f34e91d23e9440428dc5ab01"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"bevy",
|
||||
@@ -3603,8 +3602,6 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "bevy_solari"
|
||||
version = "0.20.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6884816ec199c45499cc33bb5a992a89662b87dffb797e54e627dbd2d9bba618"
|
||||
dependencies = [
|
||||
"bevy_anti_alias",
|
||||
"bevy_app",
|
||||
@@ -3617,6 +3614,7 @@ dependencies = [
|
||||
"bevy_ecs",
|
||||
"bevy_image",
|
||||
"bevy_light",
|
||||
"bevy_material",
|
||||
"bevy_math",
|
||||
"bevy_mesh",
|
||||
"bevy_pbr",
|
||||
@@ -4280,7 +4278,7 @@ dependencies = [
|
||||
"arrayvec",
|
||||
"cc",
|
||||
"cfg-if",
|
||||
"constant_time_eq",
|
||||
"constant_time_eq 0.4.2",
|
||||
"cpufeatures 0.3.1",
|
||||
]
|
||||
|
||||
@@ -5076,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"
|
||||
@@ -13590,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",
|
||||
]
|
||||
|
||||
@@ -13607,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",
|
||||
@@ -13625,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",
|
||||
@@ -13641,6 +13710,7 @@ dependencies = [
|
||||
name = "raea-app-media"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"meshopt",
|
||||
"raea-io-home",
|
||||
"raea-io-media",
|
||||
"raea-page",
|
||||
@@ -13650,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"
|
||||
@@ -13667,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",
|
||||
@@ -13679,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"
|
||||
@@ -13706,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",
|
||||
]
|
||||
|
||||
@@ -13771,9 +13876,13 @@ dependencies = [
|
||||
name = "raea-bevy-parity"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"accesskit 0.24.1",
|
||||
"argh",
|
||||
"bevy",
|
||||
"bytemuck",
|
||||
"chacha20 0.10.2",
|
||||
"indexmap",
|
||||
"nonmax",
|
||||
"raea-sys-parity",
|
||||
"rand 0.10.3",
|
||||
]
|
||||
@@ -13916,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",
|
||||
@@ -13985,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"
|
||||
@@ -14088,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"
|
||||
@@ -14147,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"
|
||||
@@ -14173,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",
|
||||
@@ -14202,6 +14352,7 @@ name = "raea-io-home"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -14363,6 +14514,7 @@ dependencies = [
|
||||
"raea-runtime-plugins",
|
||||
"raea-runtime-twins",
|
||||
"raea-sys-fonts",
|
||||
"raea-sys-layers",
|
||||
"raea-sys-page",
|
||||
"serde_json",
|
||||
"stylo",
|
||||
@@ -14378,14 +14530,17 @@ 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",
|
||||
"raea-page",
|
||||
"raea-page-stage",
|
||||
"raea-page-window",
|
||||
"raea-rune-slots",
|
||||
"raea-runtime-dom",
|
||||
"raea-runtime-input",
|
||||
"raea-runtime-js",
|
||||
@@ -14430,6 +14585,7 @@ dependencies = [
|
||||
"raea-runtime-js",
|
||||
"raw-window-handle",
|
||||
"serde_json",
|
||||
"windows 0.62.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -14478,6 +14634,7 @@ dependencies = [
|
||||
"raea-sys-meshseq",
|
||||
"raea-sys-page",
|
||||
"raea-sys-parity",
|
||||
"raea-sys-phase",
|
||||
"raea-sys-post",
|
||||
"raea-sys-procmat",
|
||||
"raea-sys-rt",
|
||||
@@ -14505,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"
|
||||
@@ -14546,6 +14711,14 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-rune-layer"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"raea-core-wire",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-rune-look"
|
||||
version = "0.1.0"
|
||||
@@ -14579,6 +14752,24 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-rune-slots"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"blitz-dom",
|
||||
"raea-core-wire",
|
||||
"raea-rune-bevy",
|
||||
"raea-rune-layer",
|
||||
"raea-rune-media",
|
||||
"raea-rune-page",
|
||||
"raea-runtime-dom",
|
||||
"raea-runtime-twins",
|
||||
"raea-sys-page",
|
||||
"rune",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-rune-style"
|
||||
version = "0.1.0"
|
||||
@@ -14605,13 +14796,16 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"junction",
|
||||
"libc",
|
||||
"raea-core-scene",
|
||||
"raea-io-home",
|
||||
"raea-io-media",
|
||||
"raea-native",
|
||||
"raea-runtime-bundle-lib",
|
||||
"raea-sys-layers",
|
||||
"regex",
|
||||
"serde_json",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -14631,6 +14825,7 @@ dependencies = [
|
||||
"bevy",
|
||||
"image",
|
||||
"manifold-rust",
|
||||
"parley",
|
||||
"raea-core-place",
|
||||
"raea-core-scene",
|
||||
"raea-core-shape",
|
||||
@@ -14638,6 +14833,7 @@ dependencies = [
|
||||
"raea-io-net",
|
||||
"raea-native",
|
||||
"raea-runtime-plugins",
|
||||
"raea-sys-fonts",
|
||||
"raea-sys-mix",
|
||||
"raea-sys-ml",
|
||||
"raea-sys-speech",
|
||||
@@ -14654,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",
|
||||
]
|
||||
|
||||
@@ -14703,12 +14912,15 @@ 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",
|
||||
"raea-page",
|
||||
"raea-render",
|
||||
"raea-runtime-bake",
|
||||
@@ -14720,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",
|
||||
@@ -14765,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",
|
||||
@@ -14795,6 +15010,7 @@ dependencies = [
|
||||
"image",
|
||||
"raea-core-program",
|
||||
"raea-gpu-device",
|
||||
"raea-io-net",
|
||||
"raea-io-trace",
|
||||
"raea-render",
|
||||
"raea-runtime-bake",
|
||||
@@ -14802,6 +15018,7 @@ dependencies = [
|
||||
"raea-runtime-page",
|
||||
"raea-runtime-react",
|
||||
"raea-runtime-sound",
|
||||
"raea-sys-frame",
|
||||
"raea-sys-mix",
|
||||
"serde_json",
|
||||
"twox-hash",
|
||||
@@ -14826,10 +15043,12 @@ dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bevy",
|
||||
"image",
|
||||
"raea-core-scene",
|
||||
"raea-core-wire",
|
||||
"raea-io-assets",
|
||||
"raea-io-home",
|
||||
"raea-io-media",
|
||||
"raea-io-net",
|
||||
"raea-page",
|
||||
"raea-render",
|
||||
"raea-runtime-input",
|
||||
@@ -14841,6 +15060,7 @@ dependencies = [
|
||||
"raea-sys-image",
|
||||
"raea-sys-page",
|
||||
"raea-sys-screen",
|
||||
"raea-sys-shader",
|
||||
"serde_json",
|
||||
"wgpu",
|
||||
]
|
||||
@@ -14855,6 +15075,7 @@ dependencies = [
|
||||
"raea-core-shape",
|
||||
"raea-sys-frame",
|
||||
"raea-sys-material",
|
||||
"raea-sys-shader",
|
||||
"raea-sys-three-shader",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -14883,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",
|
||||
@@ -14902,11 +15124,23 @@ dependencies = [
|
||||
"raea-core-review",
|
||||
"raea-core-scene",
|
||||
"raea-runtime-look",
|
||||
"raea-runtime-scene2d",
|
||||
"raea-sys-frame",
|
||||
"raea-sys-procmat",
|
||||
"raea-sys-wear",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-scene2d"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"raea-core-program",
|
||||
"raea-core-scene",
|
||||
"raea-runtime-look",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-scene3d"
|
||||
version = "0.1.0"
|
||||
@@ -14914,7 +15148,6 @@ dependencies = [
|
||||
"bevy",
|
||||
"raea-core-program",
|
||||
"raea-runtime-plugins",
|
||||
"raea-sys-compose",
|
||||
"raea-sys-compute",
|
||||
"raea-sys-fog",
|
||||
"raea-sys-fog-half",
|
||||
@@ -14939,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"
|
||||
@@ -14992,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"
|
||||
@@ -15078,7 +15344,9 @@ name = "raea-sys-compute"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-sys-frame",
|
||||
"raea-sys-material",
|
||||
"raea-sys-sampler",
|
||||
"raea-sys-shader",
|
||||
"serde_json",
|
||||
]
|
||||
@@ -15088,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",
|
||||
@@ -15133,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",
|
||||
]
|
||||
@@ -15150,6 +15422,7 @@ dependencies = [
|
||||
"parley",
|
||||
"raea-io-net",
|
||||
"serde_json",
|
||||
"swash",
|
||||
"wuff",
|
||||
]
|
||||
|
||||
@@ -15173,8 +15446,11 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-core-program",
|
||||
"raea-core-scene",
|
||||
"raea-io-media",
|
||||
"raea-sys-layers",
|
||||
"serde_json",
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -15182,7 +15458,9 @@ name = "raea-sys-framepass"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-sys-frame",
|
||||
"raea-sys-material",
|
||||
"raea-sys-sampler",
|
||||
"raea-sys-shader",
|
||||
"serde_json",
|
||||
]
|
||||
@@ -15226,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"
|
||||
@@ -15240,6 +15531,7 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"image",
|
||||
"raea-core-facts",
|
||||
"raea-core-scene",
|
||||
"serde_json",
|
||||
]
|
||||
@@ -15277,11 +15569,25 @@ dependencies = [
|
||||
"raea-core-shape",
|
||||
"raea-io-net",
|
||||
"raea-sys-frame",
|
||||
"raea-sys-mesh",
|
||||
"raea-sys-sampler",
|
||||
"resvg 0.48.1",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-measure"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-mesh"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-core-shape",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-meshseq"
|
||||
version = "0.1.0"
|
||||
@@ -15330,13 +15636,12 @@ dependencies = [
|
||||
"parley",
|
||||
"raea-core-wire",
|
||||
"raea-gpu-device",
|
||||
"raea-sys-canvas",
|
||||
"raea-sys-filters",
|
||||
"raea-sys-fonts",
|
||||
"raea-sys-image",
|
||||
"raea-sys-page-net",
|
||||
"raea-sys-page-ops",
|
||||
"serde_json",
|
||||
"stylo",
|
||||
"vello",
|
||||
"wgpu",
|
||||
]
|
||||
@@ -15349,12 +15654,25 @@ dependencies = [
|
||||
"bevy",
|
||||
"blitz-dom",
|
||||
"blitz-traits",
|
||||
"percent-encoding",
|
||||
"raea-io-net",
|
||||
"raea-sys-image",
|
||||
"serde_json",
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-page-ops"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"blitz-dom",
|
||||
"raea-core-wire",
|
||||
"raea-sys-canvas",
|
||||
"serde_json",
|
||||
"stylo",
|
||||
"vello",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-parity"
|
||||
version = "0.1.0"
|
||||
@@ -15376,12 +15694,24 @@ dependencies = [
|
||||
"rten-tensor",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-phase"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"bytemuck",
|
||||
"indexmap",
|
||||
"nonmax",
|
||||
"raea-sys-shader",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-post"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-core-program",
|
||||
"raea-sys-compose",
|
||||
"raea-sys-frame",
|
||||
]
|
||||
|
||||
@@ -15420,6 +15750,7 @@ dependencies = [
|
||||
"image",
|
||||
"raea-core-program",
|
||||
"raea-sys-frame",
|
||||
"raea-sys-material",
|
||||
"serde_json",
|
||||
"wgpu",
|
||||
]
|
||||
@@ -15429,8 +15760,20 @@ name = "raea-sys-shader"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-gpu-device",
|
||||
"raea-sys-material",
|
||||
"raea-sys-sampler",
|
||||
"raea-sys-shader-wgsl",
|
||||
"serde_json",
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-shader-wgsl"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-sys-material",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
@@ -15441,6 +15784,7 @@ dependencies = [
|
||||
"deep_filter",
|
||||
"ndarray 0.15.6",
|
||||
"ort",
|
||||
"raea-io-home",
|
||||
"raea-io-media",
|
||||
"raea-sys-vision",
|
||||
"serde_json",
|
||||
@@ -15474,6 +15818,10 @@ dependencies = [
|
||||
"bevy",
|
||||
"raea-core-program",
|
||||
"raea-sys-frame",
|
||||
"raea-sys-mesh",
|
||||
"raea-sys-sampler",
|
||||
"raea-sys-shader",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -17057,7 +17405,6 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rune-taffy"
|
||||
version = "0.0.1"
|
||||
source = "git+https://github.com/anomalyco/rune?rev=7ead7d63fcf6f9dd9669385a8b90e2ae80015d7b#7ead7d63fcf6f9dd9669385a8b90e2ae80015d7b"
|
||||
dependencies = [
|
||||
"taffy",
|
||||
]
|
||||
@@ -20139,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"
|
||||
@@ -20568,8 +20921,6 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "vello_shaders"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2e653222cee49f2571729c3e4b0fa99bc4f826c6bb9487dbb88b825d552b3a27"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"log",
|
||||
@@ -22773,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"
|
||||
|
||||
+43
@@ -5,6 +5,7 @@ resolver = "2"
|
||||
members = [
|
||||
"core/animate",
|
||||
"core/brief",
|
||||
"core/facts",
|
||||
"core/ease",
|
||||
"core/fonts",
|
||||
"core/program",
|
||||
@@ -23,6 +24,8 @@ members = [
|
||||
"systems/animate",
|
||||
"systems/framepass",
|
||||
"systems/compute",
|
||||
"systems/phase",
|
||||
"systems/shader/wgsl",
|
||||
"systems/sampler",
|
||||
"systems/parity",
|
||||
"systems/shader",
|
||||
@@ -48,6 +51,8 @@ members = [
|
||||
"engine/rune/style",
|
||||
"engine/rune/bevy",
|
||||
"engine/rune/js",
|
||||
"engine/rune/layer",
|
||||
"engine/rune/slots",
|
||||
"engine/page/stage",
|
||||
"engine/page/window",
|
||||
"io/trace",
|
||||
@@ -63,6 +68,8 @@ members = [
|
||||
"io/ffmpeg",
|
||||
"io/apple",
|
||||
"io/apple-coding",
|
||||
"io/alpha",
|
||||
"io/capcut",
|
||||
"io/shell",
|
||||
"gpu/device",
|
||||
"core/k",
|
||||
@@ -81,6 +88,7 @@ members = [
|
||||
"systems/bake",
|
||||
"systems/contact",
|
||||
"systems/light-meter",
|
||||
"systems/measure",
|
||||
"systems/canvas",
|
||||
"systems/tweak",
|
||||
"systems/filters",
|
||||
@@ -88,7 +96,9 @@ members = [
|
||||
"systems/procmat",
|
||||
"systems/page",
|
||||
"systems/page-net",
|
||||
"systems/page-ops",
|
||||
"systems/frame",
|
||||
"systems/layers",
|
||||
"systems/splat",
|
||||
"systems/sprite",
|
||||
"systems/rt",
|
||||
@@ -103,6 +113,7 @@ members = [
|
||||
"systems/look",
|
||||
"systems/compose",
|
||||
"systems/material",
|
||||
"systems/mesh",
|
||||
"systems/post",
|
||||
"systems/fog",
|
||||
"systems/fog-half",
|
||||
@@ -112,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",
|
||||
@@ -126,28 +139,38 @@ 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",
|
||||
"runtime/sound",
|
||||
"runtime/look",
|
||||
"runtime/scene",
|
||||
"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",
|
||||
]
|
||||
@@ -262,6 +285,10 @@ bevy_seedling = { path = "vendor/bevy_seedling" }
|
||||
bevy_text = { path = "vendor/bevy_text" }
|
||||
# bevy_ui 0.20.0 on Taffy 0.15, Blitz's, so one Taffy builds (changes marked "raea:", docs/bevy-upgrade.md)
|
||||
bevy_ui = { path = "vendor/bevy_ui" }
|
||||
# bevy_solari 0.20.0 with alpha-tested and alpha-blended materials traced by their alpha, StandardMaterial's
|
||||
# uv_transform, and a panorama's sun sampled as a light rather than found by reflection rays alone (changes marked
|
||||
# "raea:", docs/raytracing.feature RT6). Back to upstream once Solari has these.
|
||||
bevy_solari = { path = "vendor/bevy_solari" }
|
||||
# bevy_ui_widgets 0.20.0 on parley 0.12, Blitz's (docs/blitz-bevy.feature B0a)
|
||||
bevy_ui_widgets = { path = "vendor/bevy_ui_widgets" }
|
||||
# blitz-paint 0.3.0-beta.4 with angled gradients in tiles laid out around the tile, many-tile gradient layers drawn
|
||||
@@ -298,9 +325,25 @@ anyrender_svg = { path = "vendor/anyrender_svg" }
|
||||
# BumpAllocationSizes; changes marked "raea:"): raea-page sizes them for its pages, not Vello's 165 MiB of defaults.
|
||||
# Back to upstream once #1861 lands.
|
||||
vello_encoding = { path = "vendor/vello_encoding" }
|
||||
# vello_shaders 0.11.0 with linear-light blending in the fine stage, switched by vello_encoding's set_blend_linear
|
||||
# (changes marked "raea:"): raea-page blends a bevy_ui page as Bevy does (bevy_ui on Blitz). No upstream
|
||||
# equivalent yet (linebender/vello blends the encoded values).
|
||||
vello_shaders = { path = "vendor/vello_shaders" }
|
||||
# Firewheel 0.12 on Bevy 0.20: bevy_reflect 0.20 and a glam-33 feature (BillyDM/Firewheel#144; changes marked "raea:")
|
||||
firewheel = { path = "vendor/firewheel" }
|
||||
firewheel-core = { path = "vendor/firewheel-core" }
|
||||
firewheel-graph = { path = "vendor/firewheel-graph" }
|
||||
firewheel-macros = { path = "vendor/firewheel-macros" }
|
||||
firewheel-nodes = { path = "vendor/firewheel-nodes" }
|
||||
|
||||
[patch."https://github.com/anomalyco/rune"]
|
||||
# rune-taffy at the rev above with encode_wrap covering taffy's flexbox_balance modes, which Blitz turns on: a crate
|
||||
# with Rune and Blitz in one build (raea-rune-slots) doesn't compile without it (changes marked "raea:"). Back to
|
||||
# upstream once Rune has it.
|
||||
rune-taffy = { path = "vendor/rune-taffy" }
|
||||
|
||||
[patch."https://github.com/djeedai/bevy_hanabi"]
|
||||
# bevy_hanabi at engine/bevy-plugins' rev with frame-pure particles: a new particle seeded by its spawn index, not the
|
||||
# slot it recycles, and blended effects drawn back to front (changes marked "raea:", raea #52). Only the plugin build
|
||||
# compiles it. Back to upstream once hanabi has a deterministic mode.
|
||||
bevy_hanabi = { path = "vendor/bevy_hanabi" }
|
||||
@@ -174,3 +174,28 @@ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2020 Andrew Straw
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
Copyright (c) 2018 Raph Levien
|
||||
Copyright (c) 2020 Andrew D. Straw
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2020 Andrew Straw
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
Copyright 2020 the Vello Authors
|
||||
Copyright (c) 2020 Andrew D. Straw
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
@@ -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.
|
||||
@@ -0,0 +1,12 @@
|
||||
Copyrights in the Rand project are retained by their contributors. No
|
||||
copyright assignment is required to contribute to the Rand project.
|
||||
|
||||
For full authorship information, see the version control history.
|
||||
|
||||
Except as otherwise noted (below and/or in individual files), Rand is
|
||||
licensed under the Apache License, Version 2.0 <LICENSE-APACHE> or
|
||||
<http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
<LICENSE-MIT> or <http://opensource.org/licenses/MIT>, at your option.
|
||||
|
||||
The Rand project includes code from the Rust project
|
||||
published under these same licenses.
|
||||
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
https://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
https://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -1,4 +1,5 @@
|
||||
Copyright 2025 the Vello Authors
|
||||
Copyright 2018 Developers of the Rand project
|
||||
Copyright (c) 2014 The Rust Project Developers
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
@@ -1,11 +1,13 @@
|
||||
Copyright (c) 2014-2020 Optimal Computing (NZ) Ltd
|
||||
The MIT License (MIT)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
this software and associated documentation files (the "Software"), to deal in
|
||||
the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do
|
||||
so, subject to the following conditions:
|
||||
Copyright (c) 2014 Mathijs van de Nes
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
@@ -14,6 +16,6 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
||||
IN THE SOFTWARE.
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -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
|
||||
@@ -92,7 +92,6 @@ LICENSES/<crate>-<version>/.
|
||||
bevy_flipbook 0.1.0: MIT
|
||||
bevy_ghx_grid 0.10.0: MIT OR Apache-2.0
|
||||
bevy_ghx_proc_gen 0.10.0: MIT OR Apache-2.0
|
||||
bevy_hanabi 0.20.0-dev: MIT OR Apache-2.0
|
||||
bevy_heavy 0.6.0: MIT OR Apache-2.0
|
||||
bevy_http_client 0.12.0: MIT OR Apache-2.0
|
||||
bevy_hui 0.8.0: MIT OR Apache-2.0
|
||||
@@ -193,13 +192,11 @@ LICENSES/<crate>-<version>/.
|
||||
fast_image_resize 6.1.0: MIT OR Apache-2.0
|
||||
fastbloom 0.17.0: MIT OR Apache-2.0
|
||||
fastnoise-lite 1.1.1: MIT
|
||||
fearless_simd 0.4.1: Apache-2.0 OR MIT
|
||||
fid-rs 0.2.0: MIT OR Apache-2.0
|
||||
file-id 0.2.3: MIT OR Apache-2.0
|
||||
fixed 1.31.0: MIT/Apache-2.0
|
||||
flagset 0.4.7: Apache-2.0
|
||||
float_next_after 2.0.0: MIT
|
||||
float-cmp 0.10.0: MIT
|
||||
float-ord 0.3.2: MIT / Apache-2.0
|
||||
fs_extra 1.3.0: MIT
|
||||
fsevent-sys 4.1.0: MIT
|
||||
@@ -212,7 +209,6 @@ LICENSES/<crate>-<version>/.
|
||||
ghx_proc_gen 0.10.0: MIT OR Apache-2.0
|
||||
glam_matrix_extras 0.4.0: MIT OR Apache-2.0
|
||||
glam 0.19.0: MIT OR Apache-2.0
|
||||
glifo 0.2.0: Apache-2.0 OR MIT
|
||||
gloo-timers 0.3.0: MIT OR Apache-2.0
|
||||
governor 0.10.4: MIT
|
||||
hash32 0.2.1: MIT OR Apache-2.0
|
||||
@@ -224,6 +220,8 @@ LICENSES/<crate>-<version>/.
|
||||
i_overlay 4.5.2: MIT OR Apache-2.0
|
||||
i_shape 1.18.0: MIT
|
||||
i_tree 0.18.0: MIT
|
||||
iana-time-zone-haiku 0.1.2: MIT OR Apache-2.0
|
||||
iana-time-zone 0.1.65: MIT OR Apache-2.0
|
||||
ilattice 0.1.0: MIT OR Apache-2.0
|
||||
imagesize 0.13.0: MIT
|
||||
inout 0.1.4: MIT OR Apache-2.0
|
||||
@@ -275,7 +273,6 @@ LICENSES/<crate>-<version>/.
|
||||
louds-rs 0.7.0: MIT OR Apache-2.0
|
||||
lz4_flex 0.13.1: MIT
|
||||
memoffset 0.9.1: MIT
|
||||
meshopt 0.6.2: MIT OR Apache-2.0
|
||||
metis-sys 0.3.2: MIT OR Apache-2.0
|
||||
metis 0.2.2: MIT OR Apache-2.0
|
||||
metrics-util 0.20.4: MIT
|
||||
@@ -332,6 +329,7 @@ LICENSES/<crate>-<version>/.
|
||||
quick-xml 0.31.0: MIT
|
||||
quick-xml 0.38.4: MIT
|
||||
radix_trie 0.2.1: MIT
|
||||
rand_chacha 0.3.1: MIT OR Apache-2.0
|
||||
rand_xorshift 0.3.0: MIT OR Apache-2.0
|
||||
rand_xoshiro 0.7.0: MIT OR Apache-2.0
|
||||
rapidhash 4.5.1: MIT OR Apache-2.0
|
||||
@@ -348,7 +346,6 @@ LICENSES/<crate>-<version>/.
|
||||
rune-kit 0.0.1: MIT
|
||||
rune-motion 0.1.0: MIT
|
||||
rune-staging 0.0.1: MIT
|
||||
rune-taffy 0.0.1: MIT
|
||||
rune 0.0.1: MIT
|
||||
rusticata-macros 4.1.0: MIT/Apache-2.0
|
||||
rustls-native-certs 0.8.5: Apache-2.0 OR ISC OR MIT
|
||||
@@ -367,6 +364,7 @@ LICENSES/<crate>-<version>/.
|
||||
sif-itree 0.4.1: MIT OR Apache-2.0
|
||||
sketches-ddsketch 0.3.1: Apache-2.0
|
||||
smart-default 0.7.1: MIT
|
||||
spin 0.9.9: MIT
|
||||
spinning_top 0.3.0: MIT/Apache-2.0
|
||||
spki 0.8.1: Apache-2.0 OR MIT
|
||||
steamworks-sys 0.13.0: MIT / Apache-2.0
|
||||
@@ -399,8 +397,6 @@ LICENSES/<crate>-<version>/.
|
||||
unsafe-libyaml 0.2.11: MIT
|
||||
urlencoding 2.1.3: MIT
|
||||
usvg 0.45.1: Apache-2.0 OR MIT
|
||||
vello_common 0.1.0: Apache-2.0 OR MIT
|
||||
vello_cpu 0.1.0: Apache-2.0 OR MIT
|
||||
vleue_navigator 0.17.0: MIT OR Apache-2.0
|
||||
voracious_radix_sort 1.2.0: MIT
|
||||
vox_bake 0.1.0: MIT
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
|
||||
<p align="center">
|
||||
<img alt="licence FSL-1.1-ALv2" src="https://img.shields.io/badge/licence-FSL--1.1--ALv2-black">
|
||||
<img alt="status canary" src="https://img.shields.io/badge/status-canary-black">
|
||||
<img alt="latest release" src="https://img.shields.io/github/v/release/shinyobjectz/raea?label=release&color=black">
|
||||
<img alt="macOS, Apple Silicon" src="https://img.shields.io/badge/macOS-Apple%20Silicon-black">
|
||||
<img alt="Linux x86_64" src="https://img.shields.io/badge/Linux-x86__64-black">
|
||||
<img alt="Windows x86_64" src="https://img.shields.io/badge/Windows-x86__64-black">
|
||||
@@ -32,8 +32,14 @@
|
||||
|
||||
---
|
||||
|
||||
> **Canary.** raea changes daily. Releases run on macOS (Apple Silicon), Linux (x86_64) and, new and least tested,
|
||||
> Windows (x86_64). Expect breaking changes, rough edges and gaps in the docs.
|
||||
> **v0.1.1** is raea's first full release: the engine and, for the first time, the desktop app, on macOS (Apple
|
||||
> Silicon), Linux (x86_64) and, newest and least tested, Windows (x86_64). raea is young: expect rough edges and gaps
|
||||
> in the docs.
|
||||
|
||||
## The app
|
||||
|
||||
The raea app is where you make video and games with your AI. Download it from [raea.io](https://raea.io) for the Mac,
|
||||
Windows or Linux. It tells you when a new version is out; on the Mac it updates itself.
|
||||
|
||||
## Install
|
||||
|
||||
@@ -94,16 +100,20 @@ floor (`raea check hello.mp4`). `raea init` starts a project, and `raea --help`
|
||||
|
||||
## Use it from your agent
|
||||
|
||||
- **Agent skills.** [`sdk/skills/raea`](sdk/skills/raea/SKILL.md) teaches an agent to write, render and check raea
|
||||
compositions; [`sdk/skills/raea-bevy`](sdk/skills/raea-bevy) covers 3D and games. The installer adds both to
|
||||
`~/.claude/skills`.
|
||||
- **Agent skills.** They live in [raea-skills](https://github.com/shinyobjectz/raea-skills), pinned here as
|
||||
[`skills/`](skills): `raea` teaches an agent to write, render and check raea compositions, 3D and games
|
||||
included. The installer adds it to `~/.claude/skills`, and `raea skills install --agent NAME` to other agents.
|
||||
- **Claude Code plugin.** `/plugin marketplace add shinyobjectz/raea`, then `/plugin install raea@raea`.
|
||||
- **Craft guides.** `raea guide` prints the floor every edit is held to and the guides for pitches, explainers, stories,
|
||||
games, motion, music and layout. `raea context PROJECT` says what to read before working on a project.
|
||||
|
||||
## Build from source
|
||||
|
||||
Requirements: [Rust](https://rustup.rs) (stable) and [bun](https://bun.sh). On macOS, Xcode's command-line tools; on Linux, the ALSA, fontconfig and Vulkan libraries.
|
||||
Requirements: [Rust](https://rustup.rs) (rustup reads the pinned version from rust-toolchain.toml), [bun](https://bun.sh)
|
||||
and CMake. On macOS, Xcode's command-line tools; on Linux, the ALSA, fontconfig, udev, xkbcommon (with its X11
|
||||
part, which the app targets' windows also load at run time) and Vulkan libraries and NASM (Ubuntu: `cmake ninja-build
|
||||
nasm libasound2-dev libfontconfig1-dev libudev-dev libvulkan-dev libxkbcommon-dev libxkbcommon-x11-dev`), as public CI
|
||||
installs them.
|
||||
|
||||
```sh
|
||||
git clone https://github.com/shinyobjectz/raea && cd raea
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
# Security
|
||||
|
||||
Report security problems privately through this repository's Security tab ("Report a vulnerability"), not in public
|
||||
issues. Fixes go into the latest release and main.
|
||||
@@ -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"] }
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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"
|
||||
@@ -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
@@ -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
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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 },
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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
@@ -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"];
|
||||
|
||||
|
||||
@@ -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 }
|
||||
@@ -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, ¬es);
|
||||
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 ®.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, ¬es, &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: ")
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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\""));
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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]);
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
@@ -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())
|
||||
}
|
||||
@@ -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, ¬))),
|
||||
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], ¬), "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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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"))
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
//! A shot's frames made by another engine, numbered from DIR/0000.png (docs/blender.feature BL36, docs/godot.feature
|
||||
//! GD11): what <BlenderShot> and <GodotShot> show, made through their native calls (runtime/react's scene/shots.rs).
|
||||
//! raea blender shot SCRIPT.ts|FILE.blend -o DIR --frames N [--fps F] [--size WxH] [--file FILE.blend]
|
||||
//! [--engine eevee|cycles|workbench] [--samples S] [--transparent] [--timeout S] [-- ARGS]
|
||||
//! raea godot shot SCRIPT.ts|res://SCENE.tscn [--project DIR] -o DIR --frames N [--fps F] [--size WxH] [--scene res://X]
|
||||
//! [--timeout S] [-- ARGS]
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
use crate::{R, blender_ts};
|
||||
|
||||
pub const BLENDER_USAGE: &str = "raea blender shot SCRIPT.ts|FILE.blend -o DIR --frames N [--fps F] [--size WxH] [--file FILE.blend] [--engine eevee|cycles|workbench] [--samples S] [--transparent] [--timeout S] [-- ARGS]";
|
||||
/// Both, as raea's help says them.
|
||||
pub const USAGE: &str = "raea blender shot SCRIPT.ts|FILE.blend -o DIR --frames N [--fps F] [--size WxH] [--engine eevee|cycles|workbench] [--samples S] [--transparent] (a shot's frames rendered by Blender, DIR/0000.png on: a raea/blender script's scene or a .blend's animation; what <BlenderShot> shows, from raea/blender/shot)\n raea godot shot SCRIPT.ts|res://SCENE.tscn [--project DIR] -o DIR --frames N [--fps F] [--size WxH] (a shot's frames recorded by Godot's Movie Maker, DIR/0000.png on, its sound as sound.wav; what <GodotShot> shows, from raea/godot/shot)";
|
||||
pub const GODOT_USAGE: &str = "raea godot shot SCRIPT.ts|res://SCENE.tscn [--project DIR] -o DIR --frames N [--fps F] [--size WxH] [--scene res://X.tscn] [--timeout S] [-- ARGS]";
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Shot {
|
||||
src: String,
|
||||
out: PathBuf,
|
||||
frames: u32,
|
||||
fps: f64,
|
||||
size: (u32, u32),
|
||||
transparent: bool,
|
||||
/// the flags that take a value, by name
|
||||
flags: BTreeMap<String, String>,
|
||||
rest: Vec<String>,
|
||||
}
|
||||
|
||||
/// args[2] the source, then the flags (each taking a value but --transparent), then -- and the script's own.
|
||||
fn parse(args: &[String], usage: &str) -> R<Shot> {
|
||||
let src = args.get(2).filter(|a| !a.starts_with('-')).ok_or(usage)?.clone();
|
||||
let (mut flags, mut rest, mut transparent) = (BTreeMap::new(), Vec::new(), false);
|
||||
let mut it = args[3..].iter();
|
||||
while let Some(a) = it.next() {
|
||||
match a.as_str() {
|
||||
"--" => rest.extend(it.by_ref().cloned()),
|
||||
"--transparent" => transparent = true,
|
||||
f if f.starts_with('-') => _ = flags.insert(a.clone(), it.next().ok_or_else(|| format!("{a} needs a value: {usage}"))?.clone()),
|
||||
_ => return Err(format!("{a}: not a flag of this verb: {usage}")),
|
||||
}
|
||||
}
|
||||
let out = std::path::absolute(flags.get("-o").ok_or(usage)?).map_err(|e| e.to_string())?;
|
||||
let frames = flags.get("--frames").and_then(|n| n.parse().ok()).filter(|n| *n > 0).ok_or("--frames needs a number of frames over 0")?;
|
||||
let fps: f64 = match flags.get("--fps") {
|
||||
Some(f) => f.parse().ok().filter(|f: &f64| *f > 0.0).ok_or("--fps needs frames a second")?,
|
||||
None => 30.0,
|
||||
};
|
||||
let size = match flags.get("--size") {
|
||||
Some(s) => s.split_once('x').and_then(|(w, h)| Some((w.parse().ok()?, h.parse().ok()?))).ok_or("--size needs WxH")?,
|
||||
None => (1920, 1080),
|
||||
};
|
||||
Ok(Shot { src, out, frames, fps, size, transparent, flags, rest })
|
||||
}
|
||||
|
||||
/// The frames a run wrote in `dir` (Blender's 0001.png on, Godot's f00000000.png on), by their number: the first
|
||||
/// `n` renamed 0000.png on, any past them removed. Too few is the run's failure.
|
||||
pub(crate) fn renumber(dir: &Path, n: u32) -> R<()> {
|
||||
let number = |p: &Path| p.file_stem()?.to_str()?.trim_start_matches(|c: char| !c.is_ascii_digit()).parse::<u64>().ok();
|
||||
let mut made: Vec<(u64, PathBuf)> = std::fs::read_dir(dir).map_err(|e| format!("{}: {e}", dir.display()))?
|
||||
.flatten()
|
||||
.map(|e| e.path())
|
||||
.filter(|p| p.extension().is_some_and(|e| e == "png"))
|
||||
.filter_map(|p| Some((number(&p)?, p)))
|
||||
.collect();
|
||||
made.sort();
|
||||
if made.len() < n as usize {
|
||||
return Err(format!("{} frames were made of the {n} asked for ({})", made.len(), dir.display()));
|
||||
}
|
||||
// through a name of their own first, so 0001.png -> 0000.png never meets a frame not yet moved
|
||||
let mut moved = Vec::new();
|
||||
for (i, (_, p)) in made.iter().enumerate() {
|
||||
if i < n as usize {
|
||||
let tmp = dir.join(format!("raea-{i:06}.tmp"));
|
||||
std::fs::rename(p, &tmp).map_err(|e| format!("{}: {e}", p.display()))?;
|
||||
moved.push((i, tmp));
|
||||
} else {
|
||||
let _ = std::fs::remove_file(p);
|
||||
}
|
||||
}
|
||||
for (i, tmp) in moved {
|
||||
std::fs::rename(&tmp, dir.join(format!("{i:04}.png"))).map_err(|e| e.to_string())?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn fresh(out: &Path) -> R<()> {
|
||||
let _ = std::fs::remove_dir_all(out);
|
||||
std::fs::create_dir_all(out).map_err(|e| format!("{}: {e}", out.display()))
|
||||
}
|
||||
|
||||
/// `raea blender shot ...`: the script's default export run (or the .blend opened), then sdk/blender's shoot().
|
||||
pub fn blender(args: &[String]) -> R<String> {
|
||||
let s = parse(args, BLENDER_USAGE)?;
|
||||
let src = std::path::absolute(&s.src).map_err(|e| e.to_string())?;
|
||||
let is_blend = s.src.ends_with(".blend");
|
||||
let file = if is_blend { Some(src.clone()) } else { s.flags.get("--file").map(PathBuf::from) };
|
||||
if let Some(f) = file.as_ref().filter(|f| !f.is_file()) {
|
||||
return Err(format!("{}: no such .blend", f.display()));
|
||||
}
|
||||
fresh(&s.out)?;
|
||||
let mut opts = json!({ "out": s.out.to_string_lossy(), "frames": s.frames, "fps": s.fps, "width": s.size.0, "height": s.size.1, "transparent": s.transparent });
|
||||
if let Some(e) = s.flags.get("--engine").map(String::as_str) {
|
||||
opts["engine"] = json!(e);
|
||||
}
|
||||
if let Some(n) = s.flags.get("--samples").map(String::as_str) {
|
||||
opts["samples"] = json!(n.parse::<u32>().map_err(|_| "--samples needs a whole number")?);
|
||||
}
|
||||
let shoot = "import { shoot } from \"@raea/blender/shoot\";\nconst call = (globalThis as any).__raea_call;\n";
|
||||
let entry = if is_blend {
|
||||
format!("{shoot}Promise.resolve().then(() => shoot({opts})){}\n", blender_ts::CLOSE)
|
||||
} else {
|
||||
let ts = src.canonicalize().map_err(|e| format!("{}: {e}", s.src))?;
|
||||
format!("import * as M from {};\n{shoot}{}.then(() => shoot({opts})){}\n", blender_ts::spec(&ts), blender_ts::DEFAULT, blender_ts::CLOSE)
|
||||
};
|
||||
let mut rest = s.rest.clone();
|
||||
let secs = s.flags.get("--timeout").map(String::as_str).and_then(|t| t.parse().ok()).unwrap_or_else(|| blender_ts::timeout(&mut rest));
|
||||
let code = blender_ts::session(&entry, file.as_deref(), &rest, secs)?;
|
||||
if code != 0 {
|
||||
return Err(format!("{} ended with exit {code}", s.src));
|
||||
}
|
||||
renumber(&s.out, s.frames)?;
|
||||
Ok(format!("{} frames by Blender in {}", s.frames, s.out.display()))
|
||||
}
|
||||
|
||||
/// Godot's window size for the shot: an override.cfg in the project (Godot reads it over project.godot) for the
|
||||
/// length of the run, since Movie Maker records the window the project opens; put back as it was after.
|
||||
struct Override {
|
||||
path: PathBuf,
|
||||
before: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl Override {
|
||||
fn set(project: &Path, (w, h): (u32, u32)) -> R<Override> {
|
||||
let path = project.join("override.cfg");
|
||||
let before = std::fs::read(&path).ok();
|
||||
let mut text = before.as_deref().map(String::from_utf8_lossy).unwrap_or_default().into_owned();
|
||||
text.push_str(&format!("\n[display]\nwindow/size/viewport_width={w}\nwindow/size/viewport_height={h}\n"));
|
||||
std::fs::write(&path, text).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
Ok(Override { path, before })
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Override {
|
||||
fn drop(&mut self) {
|
||||
let _ = match &self.before {
|
||||
Some(b) => std::fs::write(&self.path, b),
|
||||
None => std::fs::remove_file(&self.path),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// `raea godot shot ...`: `raea godot run` with --movie, --frames and --scene, its frames renumbered; the sound Movie
|
||||
/// Maker writes beside them kept as sound.wav.
|
||||
pub fn godot(args: &[String]) -> R<String> {
|
||||
let s = parse(args, GODOT_USAGE)?;
|
||||
let none = raea_io_home::home().join("sdk/godot/src/host/none.ts");
|
||||
let (script, scene) = match s.src.strip_prefix("res://") {
|
||||
Some(_) => (none.to_string_lossy().into_owned(), Some(s.src.clone())),
|
||||
None => (s.src.clone(), s.flags.get("--scene").cloned()),
|
||||
};
|
||||
fresh(&s.out)?;
|
||||
let mut run = vec!["godot".to_string(), "run".into(), script, "--movie".into(), s.out.join("f.png").to_string_lossy().into_owned()];
|
||||
run.extend(["--fps".into(), s.fps.round().to_string(), "--frames".into(), s.frames.to_string()]);
|
||||
let _over = match s.flags.get("--project").map(String::as_str) {
|
||||
Some(p) => {
|
||||
run.extend(["--project".into(), p.to_string()]);
|
||||
Some(Override::set(Path::new(p), s.size)?)
|
||||
}
|
||||
None => {
|
||||
run.extend(["--size".into(), format!("{}x{}", s.size.0, s.size.1)]);
|
||||
None
|
||||
}
|
||||
};
|
||||
if let Some(sc) = scene {
|
||||
run.extend(["--scene".into(), sc]);
|
||||
}
|
||||
if let Some(t) = s.flags.get("--timeout").map(String::as_str) {
|
||||
run.extend(["--timeout".into(), t.to_string()]);
|
||||
}
|
||||
if !s.rest.is_empty() {
|
||||
run.push("--".into());
|
||||
run.extend(s.rest.iter().cloned());
|
||||
}
|
||||
crate::godot_run::run(&run)?;
|
||||
let wav = s.out.join("f.wav");
|
||||
if wav.is_file() {
|
||||
let _ = std::fs::rename(&wav, s.out.join("sound.wav"));
|
||||
}
|
||||
renumber(&s.out, s.frames)?;
|
||||
Ok(format!("{} frames by Godot in {}", s.frames, s.out.display()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn frames_are_numbered_from_zero_by_their_own_numbers() {
|
||||
let d = std::env::temp_dir().join(format!("raea-shot-renumber-{}", std::process::id()));
|
||||
fresh(&d).unwrap();
|
||||
for f in ["0001.png", "0002.png", "0003.png", "10000.png", "notes.txt"] {
|
||||
std::fs::write(d.join(f), f).unwrap();
|
||||
}
|
||||
renumber(&d, 3).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(d.join("0000.png")).unwrap(), "0001.png");
|
||||
assert_eq!(std::fs::read_to_string(d.join("0002.png")).unwrap(), "0003.png");
|
||||
assert!(!d.join("10000.png").exists() && !d.join("0003.png").exists() && d.join("notes.txt").exists());
|
||||
// Godot's names, and too few
|
||||
fresh(&d).unwrap();
|
||||
for f in ["f00000000.png", "f00000001.png"] {
|
||||
std::fs::write(d.join(f), f).unwrap();
|
||||
}
|
||||
assert!(renumber(&d, 3).unwrap_err().contains("2 frames were made of the 3"));
|
||||
renumber(&d, 2).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(d.join("0001.png")).unwrap(), "f00000001.png");
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shot_needs_its_out_and_length() {
|
||||
let a = |s: &str| s.split_whitespace().map(String::from).collect::<Vec<_>>();
|
||||
assert!(parse(&a("blender shot x.ts --frames 3"), BLENDER_USAGE).is_err());
|
||||
assert!(parse(&a("blender shot x.ts -o d"), BLENDER_USAGE).unwrap_err().contains("--frames"));
|
||||
let s = parse(&a("godot shot res://m.tscn -o d --frames 4 --size 640x360 --project p -- go"), GODOT_USAGE).unwrap();
|
||||
assert_eq!((s.frames, s.size, s.flags.get("--project").map(String::as_str), s.rest.clone()), (4, (640, 360), Some("p"), vec!["go".to_string()]));
|
||||
}
|
||||
}
|
||||
@@ -23,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" }
|
||||
|
||||
@@ -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> {
|
||||
|
||||
@@ -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"
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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>;
|
||||
@@ -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
@@ -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"))
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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,9 +1,9 @@
|
||||
//! The media verbs' command line (`raea media|ffmpeg|ffprobe`, and raea's shell, in process): the agent's media
|
||||
//! work on raea-media (lib.rs and its files), and an HTML composition's render (html.rs).
|
||||
//!
|
||||
//! media probe|still|sheet|audio|loudness|motion|cuts|freezes|proxy|trim|concat FILE ... media work, native (media help)
|
||||
//! media probe|still|sheet|audio|loudness|motion|cuts|freezes|proxy|lod|trim|concat FILE ... media work, native (media help)
|
||||
//! ffmpeg ARGS | ffprobe ARGS ffmpeg and ffprobe command lines read as the media verbs (no ffmpeg involved)
|
||||
//! render PAGE.html -o OUT.mp4|DIR [--at F,F] [--codec apple|soft|av1|ffmpeg] [--kbps K | --quality Q]
|
||||
//! render PAGE.html -o OUT.mp4|OUT.png|DIR [--at F,F] [--alpha] [--codec apple|soft|av1|ffmpeg] [--kbps K | --quality Q]
|
||||
//! shots [--size WxH] [--root DIR] plain HTML pages' first frames as PNGs, over white: stdin lines `PAGE\tOUT.png`,
|
||||
//! one `ok OUT` or `err OUT: why` line each (bench/wpt's reftests)
|
||||
|
||||
@@ -53,8 +53,14 @@ fn run(args: Vec<String>) {
|
||||
"render" => {
|
||||
let out = PathBuf::from(flag("-o").unwrap_or_else(|| fail("render needs -o OUT.mp4|DIR")));
|
||||
let frames = flag("--at").map(|at| at.split(',').map(|f| f.trim().parse().unwrap_or_else(|_| fail(format!("bad frame {f}")))).collect());
|
||||
let opts = raea_runtime_encode::RenderOpts { frames, codec: flag("--codec"), kbps: flag("--kbps").and_then(|k| k.parse().ok()), quality: flag("--quality").map(|q| raea_io_media::parse_quality(&q).unwrap_or_else(|e| fail(e))), ssim: flag_on("--ssim"), sound: None, ten_bit: flag_on("--10bit") };
|
||||
let opts = raea_runtime_encode::RenderOpts { frames, codec: flag("--codec"), kbps: flag("--kbps").and_then(|k| k.parse().ok()), quality: flag("--quality").map(|q| raea_io_media::parse_quality(&q).unwrap_or_else(|e| fail(e))), ssim: flag_on("--ssim"), sound: None, ten_bit: flag_on("--10bit"), alpha: flag_on("--alpha") };
|
||||
if opts.alpha && out.extension().is_some_and(|x| x != "png") {
|
||||
fail("--alpha writes PNGs (OUT.png or a folder): video here is H.264 or HEVC, which hold no alpha");
|
||||
}
|
||||
raea_runtime_encode::render_file(&arg(1), &out, &opts).unwrap_or_else(|e| fail(e));
|
||||
if let Some(note) = raea_page::not_applied::said() {
|
||||
println!("{note}");
|
||||
}
|
||||
}
|
||||
"shots" => {
|
||||
let size = flag("--size").map(|s| s.split_once('x').and_then(|(w, h)| Some((w.parse().ok()?, h.parse().ok()?))).unwrap_or_else(|| fail(format!("bad --size {s} (WxH)"))));
|
||||
|
||||
@@ -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
@@ -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)
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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()}))
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
@@ -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, ¬es);
|
||||
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, ¬es, &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, ¬es, &ran, &mut s));
|
||||
state::write(project, &s)?;
|
||||
let tally = crate::tally(project, ¬es, &s);
|
||||
out.push(tally);
|
||||
Ok((out.join("\n"), i32::from(refused || !bad.is_empty())))
|
||||
}
|
||||
@@ -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 ¬es {
|
||||
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, ¬es, &s));
|
||||
if restate {
|
||||
out.push(take::RESTATE.into());
|
||||
}
|
||||
(out.join("\n"), code)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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"))
|
||||
}
|
||||
@@ -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, ¬es);
|
||||
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, ¬es, &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, ¬es, &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, ¬es, &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, ¬es, &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(¬e(), 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, ¬es, &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, ¬es, &run(None), &mut s), ["n1.1 notes/1/n1.ts: its clip waits for a render of edit.tsx#edit"]);
|
||||
}
|
||||
@@ -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()));
|
||||
}
|
||||
|
||||
@@ -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
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 }
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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-"));
|
||||
|
||||
@@ -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;
|
||||
@@ -59,8 +59,8 @@ pub fn song(args: &[String]) -> R<String> {
|
||||
return Err("song: the map is made by raea-perceive, which isn't installed beside raea. Update raea (`curl -fsSL https://raea.io/install | sh`: releases ship it in ~/.raea/bin), or from a checkout `cargo build --release -p raea-perceive`, or point RAEA_PERCEIVE at one".into());
|
||||
}
|
||||
// its beat model (Beat This!, MIT): an install keeps it in share/raea/models; raea-perceive reads it from
|
||||
// ~/.local/share/raea-models
|
||||
let model = PathBuf::from(std::env::var("HOME").unwrap_or_default()).join(".local/share/raea-models/beat-this/beat_this_small0.onnx");
|
||||
// raea_io_home::models() (~/.local/share/raea-models; %LOCALAPPDATA%\raea\models on Windows)
|
||||
let model = raea_io_home::models().join("beat-this/beat_this_small0.onnx");
|
||||
if !model.is_file() {
|
||||
let shipped = raea_io_home::home().join("models/beat-this/beat_this_small0.onnx");
|
||||
if !shipped.is_file() || std::fs::create_dir_all(model.parent().unwrap()).and_then(|_| std::fs::copy(&shipped, &model)).is_err() {
|
||||
|
||||
@@ -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" }
|
||||
@@ -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" }
|
||||
@@ -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(®, &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
|
||||
}
|
||||
}
|
||||
@@ -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(®.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 ®.compositions {
|
||||
by_id.entry(c.id.as_str()).or_default().insert(stem(&c.file));
|
||||
}
|
||||
for c in ®.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 ®.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(®.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 ®.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()))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
@@ -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()
|
||||
@@ -65,7 +64,7 @@ fn commit(ws: &Path, paths: &[&Path], what: &str, by: &str) -> R<()> {
|
||||
let mut add = Command::new("git");
|
||||
add.arg("-C").arg(ws).args(["add", "-A", "--"]).args(paths);
|
||||
add.status().map_err(|e| format!("git: {e}"))?;
|
||||
let ok = Command::new("git").arg("-C").arg(ws).args(["-c", &format!("user.name={by}"), "commit", "-q", "-m", &format!("{by}: {what}"), "--"]).args(paths).status().map_err(|e| format!("git: {e}"))?;
|
||||
let ok = workspace::git_cmd().arg("-C").arg(ws).args(["-c", &format!("user.name={by}"), "commit", "-q", "-m", &format!("{by}: {what}"), "--"]).args(paths).status().map_err(|e| format!("git: {e}"))?;
|
||||
if ok.success() { Ok(()) } else { Err(format!("couldn't commit {what}")) }
|
||||
}
|
||||
|
||||
|
||||
@@ -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()) };
|
||||
|
||||
@@ -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
@@ -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
|
||||
|
||||
@@ -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
@@ -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"));
|
||||
}
|
||||
@@ -5,10 +5,22 @@
|
||||
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
|
||||
/// user.email isn't set, so this gives a fresh Mac an address without overriding anyone's own.
|
||||
pub(crate) fn git_cmd() -> Command {
|
||||
let mut c = Command::new("git");
|
||||
if std::env::var_os("EMAIL").is_none() {
|
||||
let user = std::env::var("USER").unwrap_or_else(|_| "raea".into());
|
||||
c.env("EMAIL", format!("{user}@raea.local"));
|
||||
}
|
||||
c
|
||||
}
|
||||
|
||||
pub(crate) fn git(dir: &Path, args: &[&str]) -> R<String> {
|
||||
let out = Command::new("git").arg("-C").arg(dir).args(args).output().map_err(|e| format!("git: {e}"))?;
|
||||
let out = git_cmd().arg("-C").arg(dir).args(args).output().map_err(|e| format!("git: {e}"))?;
|
||||
if !out.status.success() {
|
||||
return Err(format!("git {}: {}", args.join(" "), String::from_utf8_lossy(&out.stderr).trim()));
|
||||
}
|
||||
@@ -53,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 {
|
||||
@@ -76,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
|
||||
@@ -215,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()))?;
|
||||
@@ -271,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 {
|
||||
@@ -293,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}")),
|
||||
}
|
||||
}
|
||||
|
||||
Executable
+17
@@ -0,0 +1,17 @@
|
||||
#!/bin/bash
|
||||
# A TSX composition drawn with --at 0 (the still a harness or a bench asks for): fill.tsx, one #246 fill, must write
|
||||
# frame-00000.png at 160 x 160 with every pixel #246, its last row too. The frame tag below the frame is drawn by its
|
||||
# own camera (raea-sys-frame spawn_tag): when the frame's camera drew it and that camera was given a w x h Viewport,
|
||||
# the tag was clipped and --at refused every frame ("no two readbacks with its tag agreed"). Exits 1 on a failure.
|
||||
# bench/at-0/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-0.XXXXXX")
|
||||
trap 'rm -rf "$OUT"' EXIT
|
||||
"$BIN" render bench/at-0/fill.tsx --at 0 -o "$OUT/at" > "$OUT/at.log" 2>&1 || { echo "FAIL: the --at 0 render failed"; grep -v WARN "$OUT/at.log" | tail -3; exit 1; }
|
||||
f="$OUT/at/frame-00000.png"
|
||||
[ -f "$f" ] || { echo "FAIL: no frame-00000.png"; exit 1; }
|
||||
got=$(magick "$f" -format "%wx%h %k %[pixel:p{0,159}]" info:)
|
||||
[ "$got" = "160x160 1 srgba(34,68,102,1)" ] || { echo "FAIL: frame 0 is '$got', not 160x160 1 srgba(34,68,102,1) (size, colours, last row)"; exit 1; }
|
||||
echo "PASS: --at 0 drew frame 0, every pixel #246"
|
||||
@@ -0,0 +1,6 @@
|
||||
// bench/at-0: a 160 x 160 composition of one #246 fill, drawn at frame 0 with --at (check.sh).
|
||||
import { AbsoluteFill, Composition, registerRoot } from "raea";
|
||||
|
||||
const Fill = () => <AbsoluteFill style={{ backgroundColor: "#246" }} />;
|
||||
|
||||
registerRoot(() => <Composition id="main" component={Fill} durationInFrames={10} fps={30} width={160} height={160} />);
|
||||
Executable
+28
@@ -0,0 +1,28 @@
|
||||
#!/bin/bash
|
||||
# #26: a 3D composition's --at frames step only themselves and their neighbours, and draw as the whole timeline stepped
|
||||
# draws them. scene.tsx (360 frames) is drawn at four frames with --at and must report the sparse stepping ("N of M
|
||||
# frames stepped"); frozen.tsx draws the same four frames as a 4-frame composition (each the scene under <Freeze>, so
|
||||
# its rows come from stepping every frame), and each pair must be pixel-identical; its --manifest must list the four
|
||||
# frames. Exits 1 on a failure.
|
||||
# bench/at-3d/check.sh (RAEA_BIN: the raea to run, default target/release/raea)
|
||||
cd "$(dirname "$0")/../.." || exit 2
|
||||
BIN=${RAEA_BIN:-$PWD/target/release/raea}
|
||||
# pixel checks: no Content Credentials or TrustMark id in the frames
|
||||
export RAEA_SIGN=0 RAEA_MARK=0 RAEA_EXPORT_CACHE=0
|
||||
OUT=$(mktemp -d "${TMPDIR:-/tmp}/raea-at-3d.XXXXXX")
|
||||
trap 'rm -rf "$OUT"' EXIT
|
||||
RAEA_STARTUP_TRACE=1 "$BIN" render bench/at-3d/scene.tsx --at 30,150,270,330 -o "$OUT/at" --manifest "$OUT/at.json" > "$OUT/at.log" 2>&1 || { echo "FAIL: the --at render failed"; tail -5 "$OUT/at.log"; exit 1; }
|
||||
"$BIN" render bench/at-3d/frozen.tsx -o "$OUT/frozen" > "$OUT/frozen.log" 2>&1 || { echo "FAIL: the frozen render failed"; tail -5 "$OUT/frozen.log"; exit 1; }
|
||||
status=0
|
||||
stepped=$(grep -o "[0-9]* of [0-9]* frames stepped" "$OUT/at.log")
|
||||
[ "$stepped" = "12 of 332 frames stepped" ] || { echo "FAIL: the --at render stepped '${stepped:-every frame}', not 12 of 332"; status=1; }
|
||||
# --manifest: written for 3D frames too, one entry a frame drawn (#28: a 3D still or --at wrote none)
|
||||
n=$(python3 -c 'import json,sys;print(len(json.load(open(sys.argv[1]))["frames"]))' "$OUT/at.json" 2>/dev/null)
|
||||
[ "$n" = 4 ] || { echo "FAIL: the --at render's manifest has ${n:-no} frames, not 4"; status=1; }
|
||||
for k in 0 1 2 3; do
|
||||
f=$(printf 'frame-%05d.png' $k)
|
||||
d=$(magick compare -metric AE "$OUT/at/$f" "$OUT/frozen/$f" null: 2>&1 | cut -d' ' -f1)
|
||||
[ "$d" = 0 ] || { echo "FAIL: $f differs from the frozen render's in ${d:-?} pixels"; status=1; }
|
||||
done
|
||||
[ $status = 0 ] && echo "PASS: $stepped, the four frames pixel-identical to the frozen render's"
|
||||
exit $status
|
||||
Loaded 100 of 1682 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user