mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-01 06:53:19 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1be8199c85 | ||
|
|
3599e18b6f | ||
|
|
923163e7b9 | ||
|
|
691673f616 | ||
|
|
edd00ee9ca | ||
|
|
23f5a5ce53 | ||
|
|
a5a81f22b8 | ||
|
|
e05cee0c73 | ||
|
|
50a695f0fb | ||
|
|
c65baf2c81 | ||
|
|
d679fa1cc4 | ||
|
|
bf74492d50 | ||
|
|
43cfe87121 | ||
|
|
a2477cd71e | ||
|
|
33896c4518 | ||
|
|
c7d7b59dfb | ||
|
|
33380411d8 | ||
|
|
b537bcfffd | ||
|
|
af293fcc35 | ||
|
|
e81d06dd8b | ||
|
|
96d2820589 | ||
|
|
09eeb21fe9 | ||
|
|
ea5fc2e5ef | ||
|
|
d415e0c59d | ||
|
|
7452b0d90c | ||
|
|
d6d97c3b8d | ||
|
|
6c106fb8f4 | ||
|
|
869318073a | ||
|
|
cd268ef764 | ||
|
|
b8d21bf712 | ||
|
|
e652168202 | ||
|
|
6abeb6ed43 | ||
|
|
3dc3096963 | ||
|
|
55d9eeaa50 | ||
|
|
bf984d4656 | ||
|
|
0902d43201 | ||
|
|
5189132ef8 | ||
|
|
0f9da00368 | ||
|
|
9632d542cd | ||
|
|
d9a5296796 | ||
|
|
53d5f94888 | ||
|
|
a504787ad3 | ||
|
|
05fb89ab72 | ||
|
|
44ca3f16d6 | ||
|
|
8a51aa0433 | ||
|
|
677ca278ba | ||
|
|
9eb649bf98 | ||
|
|
1e8c404738 | ||
|
|
535acb5a4f | ||
|
|
8579b43228 | ||
|
|
e367fe8190 | ||
|
|
c6acc16633 | ||
|
|
6c7889dbf7 | ||
|
|
620ccb4093 | ||
|
|
aca025d343 | ||
|
|
e4b607e7f8 | ||
|
|
0226baca9a | ||
|
|
760fcc9ec8 | ||
|
|
4dcfa760b1 | ||
|
|
85b877f06b | ||
|
|
28fd448ea2 | ||
|
|
db58ead2c9 | ||
|
|
6f253b3fe5 | ||
|
|
64dfd63cd7 | ||
|
|
fb11b58f6f | ||
|
|
f89873c1df | ||
|
|
853b6ab3dc | ||
|
|
a983349265 | ||
|
|
ea741f6bef | ||
|
|
5d181dae28 | ||
|
|
bb7e6716b4 | ||
|
|
6cb250a531 | ||
|
|
99e3fe0751 | ||
|
|
ebff73dbc6 | ||
|
|
734b172d34 | ||
|
|
b30eb6aa88 | ||
|
|
fb4572f284 | ||
|
|
eb8d3ad795 | ||
|
|
203c26621c | ||
|
|
a5d89e95c1 | ||
|
|
37fc50782d | ||
|
|
34629d33b8 | ||
|
|
6da2995575 | ||
|
|
c7e857b243 | ||
|
|
657664d7d9 | ||
|
|
cb87e0cd59 | ||
|
|
b3fe2699d0 | ||
|
|
8a2f9c78ab | ||
|
|
2d869d719b | ||
|
|
272b94e765 | ||
|
|
ee171c4f85 | ||
|
|
7fb2194503 | ||
|
|
fc7bfa3a0c | ||
|
|
593ebb5226 | ||
|
|
97e03e7447 | ||
|
|
559d8274e0 | ||
|
|
645b0853cc | ||
|
|
e165d0c4a8 | ||
|
|
d1e61bee2b | ||
|
|
875006089f | ||
|
|
163f0b9e00 | ||
|
|
76a4ef7885 | ||
|
|
a185361869 | ||
|
|
e90d70f0dc | ||
|
|
6d8623ca9b | ||
|
|
2b8b43a420 | ||
|
|
ab0babcce7 | ||
|
|
09ee785138 | ||
|
|
6f88437dc1 | ||
|
|
6e79971b12 | ||
|
|
11dab02b51 | ||
|
|
6177e27d51 | ||
|
|
a78fb95e75 | ||
|
|
be220a6064 | ||
|
|
7fb6251bf9 | ||
|
|
5d320bc96e | ||
|
|
3de2c63bab | ||
|
|
c89de2a778 | ||
|
|
d70c8e6604 | ||
|
|
dfca0bcf12 | ||
|
|
14870df064 | ||
|
|
6ba881cf0f | ||
|
|
de994972cd | ||
|
|
13daeb9976 | ||
|
|
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 |
No files matched your search
@@ -3,6 +3,15 @@
|
||||
[target.aarch64-apple-darwin]
|
||||
linker = "tools/link-jit.sh"
|
||||
|
||||
# every Windows executable's main thread gets 8 MB of stack, as on macOS and Linux (Windows' default is 1 MB). The
|
||||
# desktop app's raea-page-host overflowed 1 MB inside a window callback (#112); engine/cli/build.rs did this for raea
|
||||
# alone. A DLL's link ignores /STACK.
|
||||
[target.x86_64-pc-windows-msvc]
|
||||
rustflags = ["-C", "link-arg=/STACK:8388608"]
|
||||
|
||||
[target.aarch64-pc-windows-msvc]
|
||||
rustflags = ["-C", "link-arg=/STACK:8388608"]
|
||||
|
||||
# no strip after linking: rustc's strip pass re-signs the binary and drops the entitlement (release has no debug info
|
||||
# of its own; std's stays)
|
||||
[profile.release]
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
{
|
||||
"name": "raea",
|
||||
"owner": { "name": "Shane Murphy", "url": "https://raea.io" },
|
||||
"owner": { "name": "raea", "url": "https://raea.io" },
|
||||
"metadata": {
|
||||
"description": "raea's plugin for Claude, from the skills/ folder of shinyobjectz/raea-skills: the raea skill and its hooks."
|
||||
},
|
||||
"plugins": [
|
||||
{
|
||||
"name": "raea",
|
||||
"source": "./",
|
||||
"description": "Make video, motion graphics, games and 3D with raea, the Render Anything Engine."
|
||||
"source": { "source": "git-subdir", "url": "https://github.com/shinyobjectz/raea-skills.git", "path": "skills" },
|
||||
"description": "Make video, motion graphics, games and 3D scenes with raea, the Render Anything Engine: the raea skill, and hooks that run raea's quick check on a composition after it's saved and show media in the raea app instead of the Mac's viewer."
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
{
|
||||
"name": "raea",
|
||||
"version": "0.1.0",
|
||||
"description": "Make video, motion graphics, games and 3D with raea, the Render Anything Engine: write raea compositions, render them on the GPU, check the frames.",
|
||||
"author": { "name": "Shane Murphy", "url": "https://raea.io" },
|
||||
"homepage": "https://raea.io",
|
||||
"repository": "https://github.com/shinyobjectz/raea",
|
||||
"license": "FSL-1.1-ALv2",
|
||||
"skills": ["./skills/skills/raea"],
|
||||
"keywords": ["video", "motion-graphics", "game-development", "rendering", "bevy", "react", "agent-skills"]
|
||||
}
|
||||
@@ -61,7 +61,9 @@ jobs:
|
||||
run: |
|
||||
rustup show active-toolchain
|
||||
sudo apt-get update && sudo apt-get install -y ripgrep
|
||||
cargo install --locked cargo-shear cargo-dupes
|
||||
# the versions L0 runs on the Mac, so a new release can't change the verdict (cargo-shear 1.14.1 calls
|
||||
# engine/cli's feature-only ignores redundant, which 1.14.0 needs; both ran red on main 11-13)
|
||||
cargo install --locked [email protected] [email protected]
|
||||
- name: layers
|
||||
run: bash tools/layers.sh
|
||||
- name: names
|
||||
@@ -113,4 +115,7 @@ jobs:
|
||||
- name: cargo check
|
||||
run: cargo check --locked -p raea-cli --tests
|
||||
- name: unit tests (the crates with no GPU or media device)
|
||||
run: cargo test --locked -p raea-io-media -p raea-core-fonts -p raea-native
|
||||
# debug info off: with it the test binaries of the app crates filled 27 GB of a runner's disk (#90)
|
||||
env:
|
||||
CARGO_PROFILE_TEST_DEBUG: "0"
|
||||
run: cargo test --locked -p raea-io-media -p raea-core-fonts -p raea-native -p raea-core-brief -p raea-core-k -p raea-bundle -p raea-app-check -p raea-app-check-flash -p raea-io-ffmpeg -p raea-app-workspace -p raea-app-tools -p raea-app-targets
|
||||
@@ -8,6 +8,11 @@
|
||||
# git tag -a v0.1.0 -m "raea 0.1.0" -m "skills-passed: <full sha>"
|
||||
# A tag with a suffix (v0.1.0-rc1, v0.1.0-canary.3) is made a pre-release; a plain version (v0.1.0) is a full release,
|
||||
# GitHub's latest. The release's notes are set by hand.
|
||||
# A release whose code is a candidate's is promoted, not compiled again (tools/release/promoted-from.sh: the tag's
|
||||
# "promoted-from: v0.1.0-rc5" line, which tools/agents/release-go.sh writes): each job takes the candidate's attested
|
||||
# binaries for its platform (tools/release/promoted-bins.sh) and packs, checks, attests and attaches them as the
|
||||
# release, in minutes instead of the three hours a cold build takes. Run by hand, dry_run packs and checks without
|
||||
# attesting or attaching (the archives are the run's artifacts), for trying a promote before the real one.
|
||||
name: release
|
||||
|
||||
on:
|
||||
@@ -23,6 +28,14 @@ on:
|
||||
description: the full SHA where tools/skills.sh check passed with the feed app (else the tag's skills-passed line)
|
||||
default: ""
|
||||
type: string
|
||||
promote_from:
|
||||
description: a candidate tag (v0.1.0-rc5) whose binaries this release is, else the tag's promoted-from line; none builds from source
|
||||
default: ""
|
||||
type: string
|
||||
dry_run:
|
||||
description: pack and check only; nothing attested or attached (the archives are this run's artifacts)
|
||||
default: false
|
||||
type: boolean
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
@@ -56,6 +69,10 @@ jobs:
|
||||
ref: ${{ env.TAG }}
|
||||
submodules: true
|
||||
lfs: false
|
||||
- name: Promoted from a candidate, or built (tools/release/promoted-from.sh)
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: bash tools/release/promoted-from.sh "$TAG" "${{ inputs.promote_from }}"
|
||||
- name: Linux libraries
|
||||
if: runner.os == 'Linux'
|
||||
run: sudo apt-get update && sudo apt-get install -y cmake ninja-build nasm libxkbcommon-dev libxkbcommon-x11-dev libasound2-dev libfontconfig1-dev libvulkan-dev libudev-dev mesa-vulkan-drivers xvfb
|
||||
@@ -75,7 +92,20 @@ jobs:
|
||||
curl -fsSL "$url" -o "$HOME/.local/share/raea-models/$path"
|
||||
echo "$sha $HOME/.local/share/raea-models/$path" | shasum -a 256 -c -
|
||||
done < tools/release/models.tsv
|
||||
# rc3's build left 576 MB of macos-15's 320 GB free, and rc4's dSYMs (#88) ran it out linking raea-page-host
|
||||
# (ld: write() failed, errno=28): the image's other Xcodes and the Android and .NET SDKs go first
|
||||
- name: Room for the build
|
||||
if: runner.os == 'macOS' && env.RAEA_PROMOTED_FROM == ''
|
||||
run: |
|
||||
df -h . | tail -1
|
||||
keep=$(cd "$(xcode-select -p)/../.." && pwd -P)
|
||||
for x in /Applications/Xcode*.app; do [ -L "$x" ] || [ "$(cd "$x" && pwd -P)" = "$keep" ] || sudo rm -rf "$x" & done
|
||||
sudo rm -rf "$HOME/Library/Android" "$HOME/.dotnet" /usr/local/share/dotnet &
|
||||
wait
|
||||
echo "kept $keep"
|
||||
df -h . | tail -1
|
||||
- name: Build
|
||||
if: env.RAEA_PROMOTED_FROM == ''
|
||||
run: |
|
||||
feat=$(bash tools/bevy-plugins.sh features sdk/raea/bench/bevy-plugins)
|
||||
cargo build --profile dist --locked -p raea-cli --bin raea --no-default-features --features "$feat"
|
||||
@@ -85,6 +115,13 @@ jobs:
|
||||
mkdir ship
|
||||
cp target/dist/raea target/dist/${{ matrix.lib }} target/dist/raea-rune-host target/dist/raea-page-host ship/
|
||||
if [ -n "${{ matrix.extra }}" ]; then cp target/dist/${{ matrix.extra }} ship/; fi
|
||||
# the Mac's dSYMs (tools/link-jit.sh made them as it stripped each binary, #88); release.sh keeps them
|
||||
if [ -d target/dist/symbols ]; then cp -R target/dist/symbols ship/; fi
|
||||
- name: The candidate's binaries (tools/release/promoted-bins.sh)
|
||||
if: env.RAEA_PROMOTED_FROM != ''
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: bash tools/release/promoted-bins.sh "$RAEA_PROMOTED_FROM" ship
|
||||
# the packing and its checks need only ship/, and macos-15's disk ran out packing rc1 with target/ kept
|
||||
- name: Free the build's disk
|
||||
run: |
|
||||
@@ -110,15 +147,31 @@ jobs:
|
||||
${{ runner.temp }}/release-check/**/*.log
|
||||
retention-days: 7
|
||||
if-no-files-found: ignore
|
||||
# the stripped binaries' symbols (#88), for symbolicating a crash report from this release; never published
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: symbols-${{ runner.os }}
|
||||
path: dist/raea-*-symbols
|
||||
retention-days: 90
|
||||
if-no-files-found: warn
|
||||
- uses: actions/attest-build-provenance@v2
|
||||
if: ${{ !inputs.dry_run }}
|
||||
with:
|
||||
subject-path: dist/raea-*.tar.gz
|
||||
- name: Attach to the release
|
||||
if: ${{ !inputs.dry_run }}
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
gh release view "$TAG" >/dev/null 2>&1 || gh release create "$TAG" ${{ contains(env.TAG, '-') && '--prerelease' || '' }} --title "raea ${TAG#v}" --notes "Built by .github/workflows/release.yml; notes follow."
|
||||
gh release upload "$TAG" dist/raea-*.tar.gz dist/raea-*.tar.gz.sha256 --clobber
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: ${{ inputs.dry_run }}
|
||||
with:
|
||||
name: dry-run-${{ runner.os }}
|
||||
path: dist/raea-*.tar.gz*
|
||||
retention-days: 3
|
||||
compression-level: 0
|
||||
|
||||
# Windows in Git's bash on GitHub's runner, with the Visual Studio Build Tools in its image (their image terms; we
|
||||
# accept no licence and download no Microsoft files). The C runtime is the DLL one (the VC++ redistributable): ort's
|
||||
@@ -135,7 +188,12 @@ jobs:
|
||||
ref: ${{ env.TAG }}
|
||||
submodules: true
|
||||
lfs: false
|
||||
- name: Promoted from a candidate, or built (tools/release/promoted-from.sh)
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: bash tools/release/promoted-from.sh "$TAG" "${{ inputs.promote_from }}"
|
||||
- name: Toolchain (rust-toolchain.toml's pin)
|
||||
if: env.RAEA_PROMOTED_FROM == ''
|
||||
run: rustup show active-toolchain || rustup toolchain install
|
||||
# jq for Windows ends -r lines with CRLF, so tools/bevy-plugins.sh read "ahoy\r" and lost its Bevy 0.20 block
|
||||
# (feature `ahoy` not found, 11-04); -b writes LF
|
||||
@@ -162,12 +220,18 @@ jobs:
|
||||
# the app targets' hosts a cargo call each: with raea-cli's crates in one call taffy's features unify and
|
||||
# rune-taffy doesn't build; raea-perceive (`raea song`'s map, #43) a call of its own too
|
||||
- name: Build
|
||||
if: env.RAEA_PROMOTED_FROM == ''
|
||||
run: |
|
||||
feat=$(bash tools/bevy-plugins.sh features sdk/raea/bench/bevy-plugins)
|
||||
cargo build --profile dist --locked -p raea-cli --bin raea --no-default-features --features "$feat"
|
||||
cargo build --profile dist --locked -p raea-rune-host
|
||||
cargo build --profile dist --locked -p raea-page-host --features window
|
||||
cargo build --profile dist --locked -p raea-perceive
|
||||
- name: The candidate's binaries (tools/release/promoted-bins.sh)
|
||||
if: env.RAEA_PROMOTED_FROM != ''
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: bash tools/release/promoted-bins.sh "$RAEA_PROMOTED_FROM" target/dist
|
||||
# which DLLs raea needs from the machine (the CRT's come from the VC++ redistributable)
|
||||
- name: What raea.exe imports
|
||||
run: |
|
||||
@@ -217,6 +281,7 @@ jobs:
|
||||
for n in $(sed -n 's/^\([^ ]*\) (.*): OPEN.*/\1/p' "$RUNNER_TEMP/play.txt"); do echo "--- $n"; { grep -v "known driver" "$out/$n.log" || echo "(its log is empty)"; } | tail -25; done
|
||||
exit $s
|
||||
- uses: actions/attest-build-provenance@v2
|
||||
if: ${{ !inputs.dry_run }}
|
||||
with:
|
||||
subject-path: dist/raea-*.zip
|
||||
# kept even when its check fails, with the check's own files, so a failure can be looked into on a fresh runner
|
||||
@@ -290,6 +355,7 @@ jobs:
|
||||
if ($LASTEXITCODE -or -not (Test-Path hello.png)) { throw "raea render failed" }
|
||||
Get-Item hello.png | Format-List Name, Length
|
||||
- name: Attach to the release
|
||||
if: ${{ !inputs.dry_run }}
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
|
||||
Generated
+520
-13
@@ -4165,6 +4165,8 @@ dependencies = [
|
||||
"cexpr",
|
||||
"clang-sys",
|
||||
"itertools 0.13.0",
|
||||
"log",
|
||||
"prettyplease",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"regex",
|
||||
@@ -4278,7 +4280,7 @@ dependencies = [
|
||||
"arrayvec",
|
||||
"cc",
|
||||
"cfg-if",
|
||||
"constant_time_eq",
|
||||
"constant_time_eq 0.4.2",
|
||||
"cpufeatures 0.3.1",
|
||||
]
|
||||
|
||||
@@ -5074,6 +5076,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"
|
||||
@@ -5668,8 +5679,18 @@ version = "0.20.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee"
|
||||
dependencies = [
|
||||
"darling_core",
|
||||
"darling_macro",
|
||||
"darling_core 0.20.11",
|
||||
"darling_macro 0.20.11",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling"
|
||||
version = "0.24.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec"
|
||||
dependencies = [
|
||||
"darling_core 0.24.1",
|
||||
"darling_macro 0.24.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5686,17 +5707,41 @@ dependencies = [
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling_core"
|
||||
version = "0.24.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff"
|
||||
dependencies = [
|
||||
"ident_case",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"strsim 0.11.1",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling_macro"
|
||||
version = "0.20.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead"
|
||||
dependencies = [
|
||||
"darling_core",
|
||||
"darling_core 0.20.11",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling_macro"
|
||||
version = "0.24.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785"
|
||||
dependencies = [
|
||||
"darling_core 0.24.1",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dary_heap"
|
||||
version = "0.3.9"
|
||||
@@ -5849,7 +5894,7 @@ version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e0df63c21a4383f94bd5388564829423f35c316aed85dc4f8427aded372c7c0d"
|
||||
dependencies = [
|
||||
"darling",
|
||||
"darling 0.20.11",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
@@ -6162,7 +6207,7 @@ version = "0.20.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8"
|
||||
dependencies = [
|
||||
"darling",
|
||||
"darling 0.20.11",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
@@ -10108,6 +10153,15 @@ version = "0.15.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e20f57f9918e5bd7bc58c22cdd70a6afc7375d4dd9683af5f2b34bd3d2bba619"
|
||||
|
||||
[[package]]
|
||||
name = "mach-sys"
|
||||
version = "0.5.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "48460c2e82a3a0de197152fdf8d2c2d5e43adc501501553e439bf2156e6f87c7"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mach2"
|
||||
version = "0.4.3"
|
||||
@@ -10406,6 +10460,66 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mlx-internal-macros"
|
||||
version = "0.34.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f11a82b6a4730c2c3778469d186cc3ee9585a5b27a8ffcdfd3c96179b76a895d"
|
||||
dependencies = [
|
||||
"darling 0.24.1",
|
||||
"itertools 0.15.0",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mlx-macros"
|
||||
version = "0.34.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32fc73395b87b961f5556e10104e7c08ed72c500765f44d38e320a6ac83977ed"
|
||||
dependencies = [
|
||||
"darling 0.24.1",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mlx-rs"
|
||||
version = "0.34.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2f0d7721525b23f77bc38d7757e6c17ea7c925cd2b2889ce86965a17b5e85e86"
|
||||
dependencies = [
|
||||
"dyn-clone",
|
||||
"half",
|
||||
"itertools 0.15.0",
|
||||
"libc",
|
||||
"mach-sys",
|
||||
"mlx-internal-macros",
|
||||
"mlx-macros",
|
||||
"mlx-sys",
|
||||
"num-complex",
|
||||
"num-traits",
|
||||
"num_enum",
|
||||
"parking_lot",
|
||||
"paste",
|
||||
"smallvec",
|
||||
"strum 0.28.0",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mlx-sys"
|
||||
version = "0.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "da965f83ce211b80f9b681d9bbd6fa625fe6bb2e659ba7bc55dd95eea8d3b028"
|
||||
dependencies = [
|
||||
"bindgen",
|
||||
"cc",
|
||||
"cmake",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mock_instant"
|
||||
version = "0.6.1"
|
||||
@@ -13205,6 +13319,16 @@ version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa"
|
||||
|
||||
[[package]]
|
||||
name = "prettyplease"
|
||||
version = "0.2.37"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "primal-check"
|
||||
version = "0.3.4"
|
||||
@@ -13588,14 +13712,37 @@ 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-app-check-flash",
|
||||
"raea-core-brief",
|
||||
"raea-core-facts",
|
||||
"raea-io-ffmpeg",
|
||||
"raea-io-trace",
|
||||
"raea-sys-measure",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-check-flash"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-ci"
|
||||
version = "0.1.0"
|
||||
@@ -13605,12 +13752,59 @@ 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-fingerprint"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"fastrand",
|
||||
"raea-app-check",
|
||||
"raea-sys-columns",
|
||||
"raea-sys-fingerprint",
|
||||
"raea-sys-fingerprint-things",
|
||||
"raea-sys-fingerprint-use",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-game"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"raea-gpu-device",
|
||||
"raea-io-home",
|
||||
"raea-io-media",
|
||||
"raea-io-net",
|
||||
"raea-runtime-export",
|
||||
@@ -13623,12 +13817,25 @@ dependencies = [
|
||||
"winit",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-interchange"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"raea-core-scene",
|
||||
"raea-core-shape",
|
||||
"raea-runtime-bundle",
|
||||
"raea-runtime-export",
|
||||
"raea-runtime-scene",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-judge"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"image",
|
||||
"raea-core-facts",
|
||||
"raea-io-home",
|
||||
"raea-runtime-bundle",
|
||||
"serde_json",
|
||||
@@ -13639,6 +13846,7 @@ dependencies = [
|
||||
name = "raea-app-media"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"meshopt",
|
||||
"raea-io-home",
|
||||
"raea-io-media",
|
||||
"raea-page",
|
||||
@@ -13648,6 +13856,18 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-notes"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"raea-core-facts",
|
||||
"raea-io-trace",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"tempfile",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-play"
|
||||
version = "0.1.0"
|
||||
@@ -13665,11 +13885,21 @@ dependencies = [
|
||||
"winit",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-registry"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"oxc",
|
||||
"raea-core-facts",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-solid"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"raea-app-judge",
|
||||
"raea-core-facts",
|
||||
"raea-core-meshcheck",
|
||||
"raea-core-shape",
|
||||
"raea-core-solidinfo",
|
||||
@@ -13677,6 +13907,16 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-sound"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"raea-io-media",
|
||||
"raea-runtime-bundle",
|
||||
"raea-runtime-export",
|
||||
"raea-sys-mix",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-targets"
|
||||
version = "0.1.0"
|
||||
@@ -13704,7 +13944,10 @@ dependencies = [
|
||||
name = "raea-app-workspace"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"raea-app-check",
|
||||
"raea-app-registry",
|
||||
"raea-core-brief",
|
||||
"raea-core-facts",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
@@ -13918,13 +14161,19 @@ 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-fingerprint",
|
||||
"raea-app-game",
|
||||
"raea-app-judge",
|
||||
"raea-app-media",
|
||||
"raea-app-notes",
|
||||
"raea-app-play",
|
||||
"raea-app-solid",
|
||||
"raea-app-sound",
|
||||
"raea-app-targets",
|
||||
"raea-app-tools",
|
||||
"raea-app-workspace",
|
||||
@@ -13987,6 +14236,16 @@ dependencies = [
|
||||
name = "raea-core-ease"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "raea-core-facts"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"raea-core-brief",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"ts-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-core-fonts"
|
||||
version = "0.1.0"
|
||||
@@ -14090,6 +14349,24 @@ dependencies = [
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-io-alpha"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"image",
|
||||
"objc2 0.6.5",
|
||||
"objc2-av-foundation",
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-media",
|
||||
"objc2-core-video",
|
||||
"objc2-foundation 0.3.2",
|
||||
"objc2-video-toolbox",
|
||||
"png 0.17.16",
|
||||
"raea-io-apple",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-io-apple"
|
||||
version = "0.1.0"
|
||||
@@ -14149,6 +14426,13 @@ dependencies = [
|
||||
"rav1e",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-io-capcut"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-io-codec"
|
||||
version = "0.1.0"
|
||||
@@ -14175,6 +14459,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",
|
||||
@@ -14356,6 +14641,7 @@ dependencies = [
|
||||
"blitz-dom",
|
||||
"blitz-html",
|
||||
"image",
|
||||
"parley",
|
||||
"raea-core-wire",
|
||||
"raea-gpu-device",
|
||||
"raea-io-media",
|
||||
@@ -14366,10 +14652,12 @@ dependencies = [
|
||||
"raea-runtime-plugins",
|
||||
"raea-runtime-twins",
|
||||
"raea-sys-fonts",
|
||||
"raea-sys-layers",
|
||||
"raea-sys-page",
|
||||
"serde_json",
|
||||
"stylo",
|
||||
"url",
|
||||
"usvg 0.48.1",
|
||||
"vello",
|
||||
"wgpu",
|
||||
]
|
||||
@@ -14381,8 +14669,10 @@ dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bevy",
|
||||
"blitz-dom",
|
||||
"blitz-html",
|
||||
"blitz-traits",
|
||||
"image",
|
||||
"keyboard-types",
|
||||
"raea-io-media",
|
||||
"raea-io-net-calls",
|
||||
"raea-io-os",
|
||||
@@ -14434,6 +14724,7 @@ dependencies = [
|
||||
"raea-runtime-js",
|
||||
"raw-window-handle",
|
||||
"serde_json",
|
||||
"windows 0.62.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -14510,6 +14801,14 @@ dependencies = [
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-rerender-ios"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"raea-runtime-export",
|
||||
"raea-runtime-react",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-rune-bevy"
|
||||
version = "0.1.0"
|
||||
@@ -14642,6 +14941,8 @@ dependencies = [
|
||||
"raea-io-media",
|
||||
"raea-native",
|
||||
"raea-runtime-bundle-lib",
|
||||
"raea-runtime-cssurls",
|
||||
"raea-sys-layers",
|
||||
"regex",
|
||||
"serde_json",
|
||||
"windows-sys 0.61.2",
|
||||
@@ -14679,6 +14980,25 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-canvas"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"blitz-dom",
|
||||
"raea-native",
|
||||
"raea-sys-canvas",
|
||||
"raea-sys-fonts",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-cssurls"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"raea-core-scene",
|
||||
"raea-io-home",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-dom"
|
||||
version = "0.1.0"
|
||||
@@ -14689,14 +15009,27 @@ dependencies = [
|
||||
"keyboard-types",
|
||||
"raea-core-wire",
|
||||
"raea-io-net",
|
||||
"raea-runtime-dom-media",
|
||||
"raea-runtime-js",
|
||||
"raea-runtime-twins",
|
||||
"raea-sys-canvas",
|
||||
"raea-sys-image",
|
||||
"raea-sys-page",
|
||||
"serde_json",
|
||||
"stylo",
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-dom-media"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"blitz-dom",
|
||||
"raea-io-net",
|
||||
"raea-runtime-js",
|
||||
"raea-sys-image",
|
||||
"raea-sys-page",
|
||||
"serde_json",
|
||||
"vello",
|
||||
]
|
||||
|
||||
@@ -14738,10 +15071,12 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"image",
|
||||
"raea-core-facts",
|
||||
"raea-core-program",
|
||||
"raea-core-review",
|
||||
"raea-core-scene",
|
||||
"raea-gpu-device",
|
||||
"raea-io-alpha",
|
||||
"raea-io-assets",
|
||||
"raea-io-media",
|
||||
"raea-io-net",
|
||||
@@ -14750,17 +15085,19 @@ dependencies = [
|
||||
"raea-runtime-bake",
|
||||
"raea-runtime-encode",
|
||||
"raea-runtime-page",
|
||||
"raea-runtime-pagestore",
|
||||
"raea-runtime-react",
|
||||
"raea-runtime-scene",
|
||||
"raea-runtime-scene3d",
|
||||
"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",
|
||||
"serde_json",
|
||||
"twox-hash",
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
@@ -14801,6 +15138,7 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bevy",
|
||||
"cpal 0.15.3",
|
||||
"raea-bevy-world",
|
||||
"raea-core-wire",
|
||||
"raea-io-home",
|
||||
@@ -14839,6 +15177,7 @@ dependencies = [
|
||||
"raea-runtime-page",
|
||||
"raea-runtime-react",
|
||||
"raea-runtime-sound",
|
||||
"raea-sys-frame",
|
||||
"raea-sys-mix",
|
||||
"serde_json",
|
||||
"twox-hash",
|
||||
@@ -14885,6 +15224,14 @@ dependencies = [
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-pagestore"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"twox-hash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-plugins"
|
||||
version = "0.1.0"
|
||||
@@ -14919,11 +15266,14 @@ dependencies = [
|
||||
"raea-render",
|
||||
"raea-runtime-bundle",
|
||||
"raea-runtime-calls",
|
||||
"raea-runtime-canvas",
|
||||
"raea-runtime-input",
|
||||
"raea-runtime-jsengine",
|
||||
"raea-runtime-plugins",
|
||||
"raea-runtime-scene",
|
||||
"raea-runtime-shared",
|
||||
"raea-runtime-shots",
|
||||
"raea-runtime-track",
|
||||
"raea-runtime-twins",
|
||||
"raea-runtime-view",
|
||||
"raea-sys-animate",
|
||||
@@ -14944,6 +15294,7 @@ dependencies = [
|
||||
"raea-core-scene",
|
||||
"raea-runtime-look",
|
||||
"raea-runtime-scene2d",
|
||||
"raea-sys-frame",
|
||||
"raea-sys-procmat",
|
||||
"raea-sys-wear",
|
||||
"serde_json",
|
||||
@@ -14966,7 +15317,6 @@ dependencies = [
|
||||
"bevy",
|
||||
"raea-core-program",
|
||||
"raea-runtime-plugins",
|
||||
"raea-sys-compose",
|
||||
"raea-sys-compute",
|
||||
"raea-sys-fog",
|
||||
"raea-sys-fog-half",
|
||||
@@ -14991,6 +15341,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"
|
||||
@@ -15004,6 +15365,18 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-track"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"raea-io-assets",
|
||||
"raea-native",
|
||||
"raea-runtime-bundle",
|
||||
"raea-runtime-calls",
|
||||
"raea-sys-bake",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-twins"
|
||||
version = "0.1.0"
|
||||
@@ -15044,6 +15417,27 @@ dependencies = [
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-world"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"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"
|
||||
@@ -15113,6 +15507,24 @@ dependencies = [
|
||||
"usvg 0.48.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-columns"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"fastrand",
|
||||
"half",
|
||||
"image",
|
||||
"ort",
|
||||
"raea-io-media",
|
||||
"raea-sys-ml",
|
||||
"rustfft",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"tokenizers",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-compose"
|
||||
version = "0.1.0"
|
||||
@@ -15142,6 +15554,7 @@ name = "raea-sys-contact"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-core-facts",
|
||||
"raea-core-meshcheck",
|
||||
"raea-core-scene",
|
||||
"raea-core-shape",
|
||||
@@ -15171,6 +15584,42 @@ dependencies = [
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-fingerprint"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"raea-sys-columns",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-fingerprint-things"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"fastrand",
|
||||
"raea-sys-columns",
|
||||
"raea-sys-fingerprint-use",
|
||||
"raea-sys-layers",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-fingerprint-use"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"fastrand",
|
||||
"image",
|
||||
"raea-sys-columns",
|
||||
"raea-sys-fingerprint",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-fog"
|
||||
version = "0.1.0"
|
||||
@@ -15187,6 +15636,9 @@ name = "raea-sys-fog-half"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-core-program",
|
||||
"raea-sys-compose",
|
||||
"raea-sys-fog",
|
||||
"raea-sys-frame",
|
||||
"wgpu",
|
||||
]
|
||||
@@ -15230,7 +15682,9 @@ dependencies = [
|
||||
"raea-core-program",
|
||||
"raea-core-scene",
|
||||
"raea-io-media",
|
||||
"raea-sys-layers",
|
||||
"serde_json",
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -15284,6 +15738,19 @@ dependencies = [
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-layers"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyrender",
|
||||
"blitz-dom",
|
||||
"blitz-paint",
|
||||
"flate2",
|
||||
"glifo",
|
||||
"serde_json",
|
||||
"vello_cpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-layout"
|
||||
version = "0.1.0"
|
||||
@@ -15298,6 +15765,7 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"image",
|
||||
"raea-core-facts",
|
||||
"raea-core-scene",
|
||||
"serde_json",
|
||||
]
|
||||
@@ -15341,6 +15809,10 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-measure"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-mesh"
|
||||
version = "0.1.0"
|
||||
@@ -15384,6 +15856,14 @@ dependencies = [
|
||||
"ureq 2.12.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-mlx"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"mlx-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-page"
|
||||
version = "0.1.0"
|
||||
@@ -15473,6 +15953,7 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-core-program",
|
||||
"raea-sys-compose",
|
||||
"raea-sys-frame",
|
||||
]
|
||||
|
||||
@@ -18326,6 +18807,9 @@ name = "strum"
|
||||
version = "0.28.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd"
|
||||
dependencies = [
|
||||
"strum_macros 0.28.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "strum_macros"
|
||||
@@ -18435,7 +18919,7 @@ version = "0.22.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4ee5c550c2e00a0b3c046bef84a9ee217e04e7c014142eeb96f9e48781c5cfd3"
|
||||
dependencies = [
|
||||
"darling",
|
||||
"darling 0.20.11",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
@@ -19622,7 +20106,7 @@ version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0f8e91a023810fd2019648410d00eea13a71f21d849e71d6d9ed936fb8061174"
|
||||
dependencies = [
|
||||
"darling",
|
||||
"darling 0.20.11",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
@@ -20247,6 +20731,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"
|
||||
@@ -20509,8 +20999,6 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "usvg"
|
||||
version = "0.48.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "977d0a4abdef933f424a99fe09f95576e089b90aebc6f016a3bc813762493e91"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"data-url 0.3.2",
|
||||
@@ -22879,6 +23367,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"
|
||||
|
||||
+29
@@ -5,6 +5,7 @@ resolver = "2"
|
||||
members = [
|
||||
"core/animate",
|
||||
"core/brief",
|
||||
"core/facts",
|
||||
"core/ease",
|
||||
"core/fonts",
|
||||
"core/program",
|
||||
@@ -67,6 +68,8 @@ members = [
|
||||
"io/ffmpeg",
|
||||
"io/apple",
|
||||
"io/apple-coding",
|
||||
"io/alpha",
|
||||
"io/capcut",
|
||||
"io/shell",
|
||||
"gpu/device",
|
||||
"core/k",
|
||||
@@ -75,9 +78,14 @@ members = [
|
||||
"systems/tone",
|
||||
"systems/mix",
|
||||
"systems/ml",
|
||||
"systems/mlx",
|
||||
"systems/speech",
|
||||
"systems/layout",
|
||||
"systems/vision",
|
||||
"systems/columns",
|
||||
"systems/fingerprint",
|
||||
"systems/fingerprint-use",
|
||||
"systems/fingerprint-things",
|
||||
"systems/song",
|
||||
"systems/perceive",
|
||||
"systems/footage",
|
||||
@@ -85,6 +93,7 @@ members = [
|
||||
"systems/bake",
|
||||
"systems/contact",
|
||||
"systems/light-meter",
|
||||
"systems/measure",
|
||||
"systems/canvas",
|
||||
"systems/tweak",
|
||||
"systems/filters",
|
||||
@@ -94,6 +103,7 @@ members = [
|
||||
"systems/page-net",
|
||||
"systems/page-ops",
|
||||
"systems/frame",
|
||||
"systems/layers",
|
||||
"systems/splat",
|
||||
"systems/sprite",
|
||||
"systems/rt",
|
||||
@@ -118,8 +128,10 @@ members = [
|
||||
"systems/image",
|
||||
"runtime/twins",
|
||||
"runtime/dom",
|
||||
"runtime/dom/media",
|
||||
"runtime/edit",
|
||||
"runtime/view",
|
||||
"runtime/world",
|
||||
"runtime/encode",
|
||||
"runtime/plugins",
|
||||
"runtime/input",
|
||||
@@ -129,15 +141,21 @@ members = [
|
||||
"engine/seedling",
|
||||
"engine/web",
|
||||
"runtime/react",
|
||||
"runtime/track",
|
||||
"runtime/pagestore",
|
||||
"runtime/cssurls",
|
||||
"bench/bridge",
|
||||
"bench/bevy-parity",
|
||||
"bench/bridge/swatch",
|
||||
"bench/rerender/ios",
|
||||
"core/alloc",
|
||||
"runtime/bake",
|
||||
"runtime/bundle",
|
||||
"runtime/bundle/lib",
|
||||
"engine/shape-web",
|
||||
"runtime/calls",
|
||||
"runtime/shots",
|
||||
"runtime/canvas",
|
||||
"runtime/export",
|
||||
"runtime/live",
|
||||
"runtime/page",
|
||||
@@ -147,14 +165,23 @@ members = [
|
||||
"runtime/scene2d",
|
||||
"runtime/shared",
|
||||
"apps/check",
|
||||
"apps/check/flash",
|
||||
"apps/direction",
|
||||
"apps/notes",
|
||||
"apps/fingerprint",
|
||||
"apps/sound",
|
||||
"apps/workspace",
|
||||
"apps/workspace/registry",
|
||||
"apps/ci",
|
||||
"apps/tools",
|
||||
"apps/engines",
|
||||
"apps/interchange",
|
||||
"apps/judge",
|
||||
"apps/solid",
|
||||
"apps/media",
|
||||
"apps/targets",
|
||||
"apps/game",
|
||||
"apps/capcut",
|
||||
"apps/play",
|
||||
"tools/sdk-props",
|
||||
]
|
||||
@@ -263,6 +290,8 @@ split-debuginfo = "packed"
|
||||
[patch.crates-io]
|
||||
# the MP4 muxer, vendored
|
||||
muxide = { path = "vendor/muxide" }
|
||||
# usvg 0.48.1 spacing a chunk's last letter as Chrome does (changes marked "raea:", docs/layout-reads.feature LR10)
|
||||
usvg = { path = "vendor/usvg" }
|
||||
# bevy_seedling 0.8.0 without its cpal 0.18 paths, ported to Bevy 0.20 (changes marked "raea:")
|
||||
bevy_seedling = { path = "vendor/bevy_seedling" }
|
||||
# bevy_text 0.20.0 on parley 0.12, so one parley builds (changes marked "raea:", docs/bevy-upgrade.md)
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
Copyright (c) 2018 Raph Levien
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
documentation files (the "Software"), to deal in the
|
||||
Software without restriction, including without
|
||||
limitation the rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software
|
||||
is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice
|
||||
shall be included in all copies or substantial portions
|
||||
of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
||||
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
||||
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
||||
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
||||
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
@@ -1,19 +0,0 @@
|
||||
Copyright (c) 2014-2020 Optimal Computing (NZ) Ltd
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
this software and associated documentation files (the "Software"), to deal in
|
||||
the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do
|
||||
so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
||||
IN THE SOFTWARE.
|
||||
@@ -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
|
||||
@@ -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.
|
||||
@@ -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
|
||||
@@ -1,25 +0,0 @@
|
||||
Copyright 2020 the Vello Authors
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
documentation files (the "Software"), to deal in the
|
||||
Software without restriction, including without
|
||||
limitation the rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software
|
||||
is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice
|
||||
shall be included in all copies or substantial portions
|
||||
of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
||||
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
||||
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
||||
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
||||
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
@@ -1,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
|
||||
@@ -1,25 +0,0 @@
|
||||
Copyright 2020 the Vello Authors
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
documentation files (the "Software"), to deal in the
|
||||
Software without restriction, including without
|
||||
limitation the rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software
|
||||
is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice
|
||||
shall be included in all copies or substantial portions
|
||||
of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
||||
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
||||
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
||||
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
||||
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
@@ -1,202 +0,0 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -1,25 +0,0 @@
|
||||
Copyright (c) 2019-2026 The RustCrypto Project Developers
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
documentation files (the "Software"), to deal in the
|
||||
Software without restriction, including without
|
||||
limitation the rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software
|
||||
is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice
|
||||
shall be included in all copies or substantial portions
|
||||
of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
||||
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
||||
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
||||
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
||||
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
@@ -192,13 +192,11 @@ LICENSES/<crate>-<version>/.
|
||||
fast_image_resize 6.1.0: MIT OR Apache-2.0
|
||||
fastbloom 0.17.0: MIT OR Apache-2.0
|
||||
fastnoise-lite 1.1.1: MIT
|
||||
fearless_simd 0.4.1: Apache-2.0 OR MIT
|
||||
fid-rs 0.2.0: MIT OR Apache-2.0
|
||||
file-id 0.2.3: MIT OR Apache-2.0
|
||||
fixed 1.31.0: MIT/Apache-2.0
|
||||
flagset 0.4.7: Apache-2.0
|
||||
float_next_after 2.0.0: MIT
|
||||
float-cmp 0.10.0: MIT
|
||||
float-ord 0.3.2: MIT / Apache-2.0
|
||||
fs_extra 1.3.0: MIT
|
||||
fsevent-sys 4.1.0: MIT
|
||||
@@ -211,7 +209,6 @@ LICENSES/<crate>-<version>/.
|
||||
ghx_proc_gen 0.10.0: MIT OR Apache-2.0
|
||||
glam_matrix_extras 0.4.0: MIT OR Apache-2.0
|
||||
glam 0.19.0: MIT OR Apache-2.0
|
||||
glifo 0.2.0: Apache-2.0 OR MIT
|
||||
gloo-timers 0.3.0: MIT OR Apache-2.0
|
||||
governor 0.10.4: MIT
|
||||
hash32 0.2.1: MIT OR Apache-2.0
|
||||
@@ -276,7 +273,6 @@ LICENSES/<crate>-<version>/.
|
||||
louds-rs 0.7.0: MIT OR Apache-2.0
|
||||
lz4_flex 0.13.1: MIT
|
||||
memoffset 0.9.1: MIT
|
||||
meshopt 0.6.2: MIT OR Apache-2.0
|
||||
metis-sys 0.3.2: MIT OR Apache-2.0
|
||||
metis 0.2.2: MIT OR Apache-2.0
|
||||
metrics-util 0.20.4: MIT
|
||||
@@ -401,8 +397,6 @@ LICENSES/<crate>-<version>/.
|
||||
unsafe-libyaml 0.2.11: MIT
|
||||
urlencoding 2.1.3: MIT
|
||||
usvg 0.45.1: Apache-2.0 OR MIT
|
||||
vello_common 0.1.0: Apache-2.0 OR MIT
|
||||
vello_cpu 0.1.0: Apache-2.0 OR MIT
|
||||
vleue_navigator 0.17.0: MIT OR Apache-2.0
|
||||
voracious_radix_sort 1.2.0: MIT
|
||||
vox_bake 0.1.0: MIT
|
||||
@@ -434,7 +428,6 @@ LICENSES/<crate>-<version>/.
|
||||
zbus 5.19.0: MIT
|
||||
zbus 6.2.1: MIT
|
||||
zcheapstr 1.1.0: MIT
|
||||
zeroize_derive 1.5.0: Apache-2.0 OR MIT
|
||||
zruntime 0.2.2: MIT
|
||||
zstd-safe 7.4.0: BSD-3-Clause
|
||||
zstd-sys 2.1.2+zstd.1.5.7: BSD-3-Clause
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -97,7 +103,9 @@ floor (`raea check hello.mp4`). `raea init` starts a project, and `raea --help`
|
||||
- **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`.
|
||||
- **Claude plugin.** The raea skill and two hooks (raea's quick check after a composition is saved, and media shown in
|
||||
the raea app). In Claude Code: `/plugin install raea --marketplace shinyobjectz/raea-skills`. It's the `skills/`
|
||||
folder of raea-skills, and `/plugin marketplace add shinyobjectz/raea` installs the same one.
|
||||
- **Craft guides.** `raea guide` prints the floor every edit is held to and the guides for pitches, explainers, stories,
|
||||
games, motion, music and layout. `raea context PROJECT` says what to read before working on a project.
|
||||
|
||||
|
||||
@@ -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,14 @@ description = "`raea check`: the floor's measurable lines on an export, ranked P
|
||||
[dependencies]
|
||||
# taste.ts rules, as the raea CLI evaluates them (docs/projects.feature PJ0)
|
||||
raea-core-brief = { path = "../../core/brief" }
|
||||
# a transcript's words, read as `raea world` reads them (docs/direction.feature DR1)
|
||||
raea-core-facts = { path = "../../core/facts" }
|
||||
# a check's record named by when it was (UTC, DR3)
|
||||
raea-io-trace = { path = "../../io/trace" }
|
||||
# ffmpeg's flag for every decoded frame, by its version
|
||||
raea-io-ffmpeg = { path = "../../io/ffmpeg" }
|
||||
# caption contrast and loudness, measured as `raea world` measures a render (DR2)
|
||||
raea-sys-measure = { path = "../../systems/measure" }
|
||||
# the flashing screen (WCAG 2.3.1), split out to keep this crate small
|
||||
raea-app-check-flash = { path = "flash" }
|
||||
serde_json = "1"
|
||||
@@ -0,0 +1,7 @@
|
||||
[package]
|
||||
name = "raea-app-check-flash"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "`raea check`'s flashing screen (WCAG 2.3.1): opposing swings in a frame's windows, from decoded RGB"
|
||||
@@ -0,0 +1,232 @@
|
||||
//! The flashing screen behind `raea check` (apps/check flash.rs feeds it the decoded frames): a pure measure of pixels,
|
||||
//! in a crate of its own so the check stays small (tools/size.sh).
|
||||
|
||||
/// Flashing past WCAG 2.3.1: more than three flashes in any one second, over enough of the frame to matter. A flash is a
|
||||
/// pair of opposing changes in the same pixels, so a shape sliding past isn't one. Each window, a third of the frame wide
|
||||
/// and high, stands in for WCAG's quarter of a 10-degree field (the real area depends on the screen and how far away it
|
||||
/// is, which a file doesn't say), and a quarter of its pixels must swing together: by 0.10 relative luminance with the
|
||||
/// darker end under 0.80, or by 20 of saturated red ((R-G-B)*320, where R/(R+G+B) is at least 0.8). Every decoded frame
|
||||
/// counts, on its own timestamp, and the picture is sampled twice, by area and by point, so fine patterns don't average
|
||||
/// away. A screen for review, not a Harding or PEAT certification; an interlaced picture isn't split into its fields.
|
||||
const FLASH_MOST: usize = 6;
|
||||
const FLASH_PAIR_S: f64 = 1.0 + 1e-9;
|
||||
|
||||
/// A pixel in one measure: its value, and whether it can count. Red's value runs on through the saturation line, and a change
|
||||
/// counts when either end of it is saturated; a one-level step across the line isn't a jump from zero.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Px {
|
||||
value: f32,
|
||||
counts: bool,
|
||||
}
|
||||
|
||||
struct Swing {
|
||||
at: f64,
|
||||
direction: f32,
|
||||
moved: Vec<bool>,
|
||||
plain: bool,
|
||||
kept: bool,
|
||||
}
|
||||
|
||||
/// One window's swings in one measure: the ones an opposite swing within a second moves back in the same pixels. The
|
||||
/// general measure leaves out swings where another quarter of the window moved the other way at once (a moving pattern).
|
||||
struct Swings {
|
||||
by: f32,
|
||||
under: f32,
|
||||
mixed_counts: bool,
|
||||
pivot: Vec<Px>,
|
||||
extreme: Vec<Px>,
|
||||
at: f64,
|
||||
direction: f32,
|
||||
recent: std::collections::VecDeque<Swing>,
|
||||
ends: Vec<f64>,
|
||||
}
|
||||
|
||||
impl Swings {
|
||||
fn new(by: f32, under: f32, mixed_counts: bool) -> Swings {
|
||||
Swings { by, under, mixed_counts, pivot: Vec::new(), extreme: Vec::new(), at: 0.0, direction: 0.0, recent: Default::default(), ends: Vec::new() }
|
||||
}
|
||||
|
||||
fn moves(&self, a: Px, b: Px, direction: f32) -> bool {
|
||||
(b.value - a.value) * direction >= self.by && a.value.min(b.value) < self.under && (a.counts || b.counts)
|
||||
}
|
||||
|
||||
fn changed(&self, earlier: &[Px], later: &[Px], direction: f32) -> bool {
|
||||
earlier.iter().zip(later).filter(|(a, b)| self.moves(**a, **b, direction)).count() * 4 >= earlier.len()
|
||||
}
|
||||
|
||||
fn push(&mut self, t: f64, px: &[Px]) {
|
||||
if self.pivot.is_empty() {
|
||||
self.pivot = px.to_vec();
|
||||
self.extreme = px.to_vec();
|
||||
self.at = t;
|
||||
return;
|
||||
}
|
||||
if self.direction == 0.0 {
|
||||
for direction in [1.0, -1.0] {
|
||||
if self.changed(&self.pivot, px, direction) {
|
||||
self.direction = direction;
|
||||
self.extreme = px.to_vec();
|
||||
self.at = t;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if self.changed(&self.extreme, px, -self.direction) {
|
||||
self.record();
|
||||
self.pivot = std::mem::replace(&mut self.extreme, px.to_vec());
|
||||
self.at = t;
|
||||
self.direction = -self.direction;
|
||||
} else if self.changed(&self.pivot, px, self.direction) && self.went_further(px) {
|
||||
self.extreme = px.to_vec();
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the pixels swinging from the pivot went further than the saved extreme, judged on those pixels alone: the
|
||||
/// rest of the window can dim by less than counts and still outweigh a patch that's flashing.
|
||||
fn went_further(&self, px: &[Px]) -> bool {
|
||||
let further: f32 = self.pivot.iter().zip(px).zip(&self.extreme).filter(|((p, n), _)| self.moves(**p, **n, self.direction)).map(|((_, n), e)| (n.value - e.value) * self.direction).sum();
|
||||
further > 0.0
|
||||
}
|
||||
|
||||
fn record(&mut self) {
|
||||
if !self.changed(&self.pivot, &self.extreme, self.direction) {
|
||||
return;
|
||||
}
|
||||
let moved: Vec<bool> = self.pivot.iter().zip(&self.extreme).map(|(a, b)| self.moves(*a, *b, self.direction)).collect();
|
||||
let plain = self.mixed_counts || !self.changed(&self.pivot, &self.extreme, -self.direction);
|
||||
let (at, direction) = (self.at, self.direction);
|
||||
let mut kept = false;
|
||||
for other in self.recent.iter_mut().rev() {
|
||||
if at - other.at > FLASH_PAIR_S {
|
||||
break;
|
||||
}
|
||||
let same = moved.iter().zip(&other.moved).filter(|(x, y)| **x && **y).count();
|
||||
if other.direction == -direction && same * 4 >= moved.len() {
|
||||
other.kept = true;
|
||||
kept = true;
|
||||
}
|
||||
}
|
||||
self.recent.push_back(Swing { at, direction, moved, plain, kept });
|
||||
while self.recent.front().is_some_and(|s| at - s.at > FLASH_PAIR_S) {
|
||||
self.retire();
|
||||
}
|
||||
}
|
||||
|
||||
/// The oldest swing leaves the second it could still pair within; only the seconds' ends are kept for good.
|
||||
fn retire(&mut self) {
|
||||
if let Some(s) = self.recent.pop_front()
|
||||
&& s.plain
|
||||
&& s.kept
|
||||
{
|
||||
self.ends.push(s.at);
|
||||
}
|
||||
}
|
||||
|
||||
/// The most swings in any one second, and when that second starts.
|
||||
fn busiest(&mut self) -> (usize, f64) {
|
||||
if self.direction != 0.0 {
|
||||
self.record();
|
||||
self.direction = 0.0;
|
||||
}
|
||||
while !self.recent.is_empty() {
|
||||
self.retire();
|
||||
}
|
||||
self.ends.sort_by(f64::total_cmp);
|
||||
let (mut best, mut from, mut j) = (0, 0.0, 0);
|
||||
for i in 0..self.ends.len() {
|
||||
while self.ends[i] - self.ends[j] >= 1.0 - 1e-9 {
|
||||
j += 1;
|
||||
}
|
||||
if i - j + 1 > best {
|
||||
(best, from) = (i - j + 1, self.ends[j]);
|
||||
}
|
||||
}
|
||||
(best, from)
|
||||
}
|
||||
}
|
||||
|
||||
/// Frames of two pictures side by side, each `w` by `h` RGB: the area sample and the point sample of one frame.
|
||||
pub struct FlashScreen {
|
||||
w: usize,
|
||||
h: usize,
|
||||
last: Vec<u8>,
|
||||
linear: Vec<f32>,
|
||||
luma: Vec<Px>,
|
||||
red: Vec<Px>,
|
||||
cut: Vec<Px>,
|
||||
windows: Vec<(usize, usize, Swings, Swings)>,
|
||||
}
|
||||
|
||||
impl FlashScreen {
|
||||
pub fn new(w: usize, h: usize) -> FlashScreen {
|
||||
let (ww, wh) = (w / 3, h / 3);
|
||||
let places = |size: usize, window: usize| {
|
||||
let mut at: Vec<usize> = (0..=size - window).step_by((size / 6).max(1)).collect();
|
||||
at.push(size - window);
|
||||
at.dedup();
|
||||
at
|
||||
};
|
||||
let mut windows = Vec::new();
|
||||
for sample in 0..2 {
|
||||
for &y in &places(h, wh) {
|
||||
for &x in &places(w, ww) {
|
||||
windows.push((x + sample * w, y, Swings::new(0.10, 0.80, false), Swings::new(20.0, f32::INFINITY, true)));
|
||||
}
|
||||
}
|
||||
}
|
||||
let linear = (0..=255u32)
|
||||
.map(|c| {
|
||||
let c = c as f32 / 255.0;
|
||||
if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) }
|
||||
})
|
||||
.collect();
|
||||
FlashScreen { w, h, last: Vec::new(), linear, luma: Vec::new(), red: Vec::new(), cut: Vec::new(), windows }
|
||||
}
|
||||
|
||||
pub fn push(&mut self, rgb: &[u8], t: f64) {
|
||||
if rgb == self.last {
|
||||
return;
|
||||
}
|
||||
self.luma.clear();
|
||||
self.red.clear();
|
||||
for px in rgb.chunks_exact(3) {
|
||||
let (r, g, b) = (self.linear[px[0] as usize], self.linear[px[1] as usize], self.linear[px[2] as usize]);
|
||||
self.luma.push(Px { value: 0.2126 * r + 0.7152 * g + 0.0722 * b, counts: true });
|
||||
let sum = r + g + b + 1e-9;
|
||||
self.red.push(Px { value: ((r - g - b) * 320.0).max(0.0), counts: r / sum >= 0.8 });
|
||||
}
|
||||
let (stride, ww, wh) = (self.w * 2, self.w / 3, self.h / 3);
|
||||
for (x, y, general, saturated) in &mut self.windows {
|
||||
self.cut.clear();
|
||||
for r in 0..wh {
|
||||
self.cut.extend_from_slice(&self.luma[(*y + r) * stride + *x..][..ww]);
|
||||
}
|
||||
general.push(t, &self.cut);
|
||||
self.cut.clear();
|
||||
for r in 0..wh {
|
||||
self.cut.extend_from_slice(&self.red[(*y + r) * stride + *x..][..ww]);
|
||||
}
|
||||
saturated.push(t, &self.cut);
|
||||
}
|
||||
self.last.clear();
|
||||
self.last.extend_from_slice(rgb);
|
||||
}
|
||||
|
||||
/// (swings in the worst second, when it starts, which measure) when past the limit
|
||||
pub fn finish(mut self) -> Option<(usize, f64, &'static str)> {
|
||||
let mut worst: Option<(usize, f64, &'static str)> = None;
|
||||
for (_, _, general, saturated) in &mut self.windows {
|
||||
for (swings, kind) in [(general, "general"), (saturated, "red")] {
|
||||
let (n, from) = swings.busiest();
|
||||
if n > FLASH_MOST && worst.is_none_or(|w| n > w.0) {
|
||||
worst = Some((n, from, kind));
|
||||
}
|
||||
}
|
||||
}
|
||||
worst
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,100 @@
|
||||
use super::*;
|
||||
|
||||
/// a 96x54 picture drawn by `paint(frame index, sample, x, y)`, sample 0 the area sample and 1 the point sample, for
|
||||
/// `frames` frames at `fps`
|
||||
fn flash_samples(frames: usize, fps: f64, paint: impl Fn(usize, usize, usize, usize) -> [u8; 3]) -> Option<(usize, f64, &'static str)> {
|
||||
let (w, h) = (96, 54);
|
||||
let mut screen = FlashScreen::new(w, h);
|
||||
for f in 0..frames {
|
||||
let mut rgb = Vec::with_capacity(w * 2 * h * 3);
|
||||
for y in 0..h {
|
||||
for sample in 0..2 {
|
||||
for x in 0..w {
|
||||
rgb.extend_from_slice(&paint(f, sample, x, y));
|
||||
}
|
||||
}
|
||||
}
|
||||
screen.push(&rgb, f as f64 / fps);
|
||||
}
|
||||
screen.finish()
|
||||
}
|
||||
|
||||
fn flash_of(seconds: usize, paint: impl Fn(usize, usize, usize) -> [u8; 3]) -> Option<(usize, f64, &'static str)> {
|
||||
flash_samples(seconds * 60, 60.0, move |f, _, x, y| paint(f, x, y))
|
||||
}
|
||||
|
||||
/// two colours taking turns `hz` times a second, over a box of the frame
|
||||
fn turns(hz: usize, on: [u8; 3], off: [u8; 3], bx: (usize, usize, usize, usize)) -> Option<(usize, f64, &'static str)> {
|
||||
flash_of(3, move |f, x, y| {
|
||||
let inside = x >= bx.0 && x < bx.0 + bx.2 && y >= bx.1 && y < bx.1 + bx.3;
|
||||
if inside && f * hz * 2 / 60 % 2 == 0 { on } else { off }
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flashing_is_found_past_three_a_second_and_not_at_it() {
|
||||
let (white, black) = ([255, 255, 255], [0, 0, 0]);
|
||||
let all = (0, 0, 96, 54);
|
||||
assert_eq!(turns(3, white, black, all), None, "three a second is the limit, not past it");
|
||||
let (swings, _, kind) = turns(4, white, black, all).expect("four a second");
|
||||
assert_eq!((swings / 2, kind), (4, "general"));
|
||||
// a small box: under a quarter of any window, and then over it
|
||||
assert_eq!(turns(5, white, black, (40, 20, 10, 10)), None);
|
||||
assert!(turns(5, white, black, (30, 18, 32, 18)).is_some());
|
||||
// too small a change, and both ends too bright for WCAG to count it
|
||||
assert_eq!(turns(5, [60, 60, 60], [30, 30, 30], all), None);
|
||||
assert_eq!(turns(5, [255, 255, 255], [235, 235, 235], all), None);
|
||||
// a dark saturated red: too dim to count as a general flash, past the limit as a red one
|
||||
assert_eq!(turns(5, [150, 0, 0], black, all).map(|t| t.2), Some("red"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flash_of_single_frames_counts_at_any_frame_rate() {
|
||||
// 120 fps with one white frame in every 30: four flashes a second, each gone within a sixtieth of a second
|
||||
let found = flash_samples(360, 120.0, |f, _, _, _| if f % 30 == 1 { [255, 255, 255] } else { [0, 0, 0] });
|
||||
assert_eq!(found.map(|(swings, _, kind)| (swings / 2, kind)), Some((4, "general")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flash_the_area_sample_averages_away_is_found_in_the_point_sample() {
|
||||
let found = flash_samples(180, 60.0, |f, sample, _, _| {
|
||||
if sample == 0 {
|
||||
return [128, 128, 128];
|
||||
}
|
||||
if f * 5 * 2 / 60 % 2 == 0 { [255, 255, 255] } else { [0, 0, 0] }
|
||||
});
|
||||
assert!(found.is_some(), "the same flash in the point sample alone");
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn a_shape_sliding_past_and_ordinary_cuts_are_not_flashing() {
|
||||
let (white, black) = ([255, 255, 255], [0, 0, 0]);
|
||||
assert_eq!(flash_of(3, move |f, x, _| if x < f { white } else { black }), None, "one wipe across the frame");
|
||||
assert_eq!(flash_of(4, move |f, _, _| if (f / 30) % 2 == 0 { white } else { black }), None, "a cut every half second");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_patch_strobing_while_its_background_dims_is_still_found() {
|
||||
// a third of a window: 0 then 124 on a 148 background, then the background settles at 124 and the patch cycles 124 and 160.
|
||||
// The background's drop is under the 0.10 that counts, but it outweighs the patch in the window's mean.
|
||||
let found = flash_samples(180, 60.0, |f, _, x, y| {
|
||||
let patch = x < 16 && y < 12;
|
||||
let level = match (patch, f) {
|
||||
(true, 0) => 0,
|
||||
(true, 1) => 124,
|
||||
(true, _) => if (f - 2) * 5 * 2 / 60 % 2 == 0 { 160 } else { 124 },
|
||||
(false, 0 | 1) => 148,
|
||||
(false, _) => 124,
|
||||
};
|
||||
[level, level, level]
|
||||
});
|
||||
assert!(found.is_some(), "the patch flashes five times a second");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_colour_crossing_the_saturation_line_is_not_a_red_flash() {
|
||||
// one level of green moves the pixel across R/(R+G+B) = 0.8 and hardly changes its red at all
|
||||
let found = flash_samples(180, 60.0, |f, _, _, _| if f * 5 * 2 / 60 % 2 == 0 { [100, 49, 0] } else { [100, 50, 0] });
|
||||
assert_eq!(found, None);
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
use super::*;
|
||||
|
||||
/// The defects Fingerprint's axes map to that a measure finds exactly (docs/fingerprint.feature FP4c), so the check
|
||||
/// wins over a head: clipping, a dropout, and a flash frame. Each on the same decoded sound or a small grey picture;
|
||||
/// each with red-team cases in tests.rs (a loud clean tone, a faded pause, a cut).
|
||||
///
|
||||
/// Clipping: a run of 3 samples or more at full scale (|x| 0.999 or more), or a flat top: 4 or more samples the same
|
||||
/// to the bit at a level a sound rarely holds still at (0.05 or more), as a hard limiter or a clamp leaves them.
|
||||
/// Counted per second; a second with CLIP_RUNS runs or more is a finding.
|
||||
pub(crate) const FULL: f32 = 0.999;
|
||||
pub(crate) const FLAT_LEVEL: f32 = 0.05;
|
||||
pub(crate) const CLIP_RUNS: usize = 3;
|
||||
|
||||
pub(crate) fn clipped(x: &[f32]) -> Vec<(f64, String)> {
|
||||
let mut per: Vec<usize> = vec![0; x.len() / SR + 1];
|
||||
let mut i = 0;
|
||||
while i < x.len() {
|
||||
let v = x[i];
|
||||
let mut j = i + 1;
|
||||
if v.abs() >= FULL {
|
||||
while j < x.len() && x[j].abs() >= FULL && x[j].signum() == v.signum() {
|
||||
j += 1;
|
||||
}
|
||||
if j - i >= 3 {
|
||||
per[i / SR] += 1;
|
||||
}
|
||||
} else if v.abs() >= FLAT_LEVEL {
|
||||
while j < x.len() && x[j].to_bits() == v.to_bits() {
|
||||
j += 1;
|
||||
}
|
||||
if j - i >= 4 {
|
||||
per[i / SR] += 1;
|
||||
}
|
||||
}
|
||||
i = j;
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let mut s = 0;
|
||||
while s < per.len() {
|
||||
if per[s] < CLIP_RUNS {
|
||||
s += 1;
|
||||
continue;
|
||||
}
|
||||
let mut e = s;
|
||||
while e + 1 < per.len() && per[e + 1] >= CLIP_RUNS {
|
||||
e += 1;
|
||||
}
|
||||
let runs: usize = per[s..=e].iter().sum();
|
||||
out.push((s as f64, format!("the sound clips: {runs} flat-topped runs over {} s; bring the level down before it hits the ceiling", e - s + 1)));
|
||||
s = e + 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A dropout: the sound falls from level (-45 dBFS or more) to digital silence (under -80 dBFS) in one 10 ms step and
|
||||
/// comes back within two, to within 10 dB of where it was, 50 ms to 3 s later. A pause that fades out or in isn't one.
|
||||
pub(crate) const SILENT: f64 = -80.0;
|
||||
pub(crate) const HAD_LEVEL: f64 = -45.0;
|
||||
|
||||
pub(crate) fn dropouts(x: &[f32]) -> Vec<(f64, String)> {
|
||||
let rms: Vec<f64> = x.as_chunks::<HOP>().0.iter().map(|f| crate::sound::db(f)).collect();
|
||||
let step = HOP as f64 / SR as f64;
|
||||
let mut out = Vec::new();
|
||||
let mut i = 1;
|
||||
while i < rms.len() {
|
||||
// a step that is silent, or nearly (the source cut partway through it), after one with level
|
||||
if !(rms[i] < HAD_LEVEL - 20.0 && rms[i - 1] >= HAD_LEVEL) {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let mut j = i + 1;
|
||||
while j < rms.len() && rms[j] < SILENT {
|
||||
j += 1;
|
||||
}
|
||||
let gap = (j - i) as f64 * step;
|
||||
let silent_inside = j > i + 1;
|
||||
// back at once: within two steps, to within 10 dB of the level before the gap (a fade in takes longer)
|
||||
let before = rms[i - 1];
|
||||
let back = rms[j.min(rms.len())..(j + 2).min(rms.len())].iter().any(|l| *l >= HAD_LEVEL.max(before - 10.0));
|
||||
if silent_inside && back && (0.05..=3.0).contains(&gap) {
|
||||
out.push((i as f64 * step, format!("the sound drops out for {:.2} s and comes back; a dropout, not a pause (no fade either side)", gap)));
|
||||
}
|
||||
i = j.max(i + 1);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A flash frame: one or two frames whose mean brightness differs from the frames either side by FLASH_STEP or more
|
||||
/// (0-1), while those two agree within FLASH_SAME: a black or white frame dropped into a shot. A cut (the brightness
|
||||
/// moves and stays) and a fade aren't flash frames.
|
||||
pub(crate) const FLASH_STEP: f32 = 0.25;
|
||||
pub(crate) const FLASH_SAME: f32 = 0.08;
|
||||
|
||||
pub(crate) fn flash_frames(luma: &[f32], fps: f64) -> Vec<(f64, String)> {
|
||||
let mut out = Vec::new();
|
||||
let mut i = 1;
|
||||
while i + 1 < luma.len() {
|
||||
let found = (1..=2).find(|&k| {
|
||||
let (before, after) = (luma[i - 1], luma.get(i + k - 1 + 1).copied());
|
||||
let Some(after) = after else { return false };
|
||||
(before - after).abs() <= FLASH_SAME && luma[i..i + k].iter().all(|&l| (l - before).abs() >= FLASH_STEP && (l - after).abs() >= FLASH_STEP)
|
||||
});
|
||||
match found {
|
||||
Some(k) => {
|
||||
out.push((i as f64 / fps, format!("{k} frame{} flash{} {} in the middle of a shot; a dropped or stray frame", if k == 1 { "" } else { "s" }, if k == 1 { "es" } else { "" }, if luma[i] < luma[i - 1] { "dark" } else { "bright" })));
|
||||
i += k + 1;
|
||||
}
|
||||
None => i += 1,
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Each frame's mean brightness (0-1), decoded small and grey
|
||||
fn lumas(video: &str) -> R<(Vec<f32>, f64)> {
|
||||
let out = Command::new("ffmpeg")
|
||||
.args(["-v", "error", "-nostdin", "-i", video, "-map", "0:v:0", "-vf", "scale=32:18:flags=area,format=gray", "-f", "rawvideo", "-"])
|
||||
.output()
|
||||
.map_err(|e| format!("ffmpeg: {e}"))?;
|
||||
if !out.status.success() {
|
||||
return Err(format!("ffmpeg couldn't read the picture of {video}: {}", String::from_utf8_lossy(&out.stderr).trim()));
|
||||
}
|
||||
let l = out.stdout.as_chunks::<{ 32 * 18 }>().0.iter().map(|f| f.iter().map(|&p| p as f32).sum::<f32>() / (32.0 * 18.0 * 255.0)).collect();
|
||||
let rate = ffmpeg_stderr(&["-hide_banner", "-i", video])?;
|
||||
let fps = rate.split(" fps").next().and_then(|s| s.rsplit(", ").next()).and_then(|s| s.trim().parse().ok()).unwrap_or(30.0);
|
||||
Ok((l, fps))
|
||||
}
|
||||
|
||||
pub(crate) fn flash_frame_rule(video: &str, issues: &mut Vec<Issue>, passed: &mut Vec<String>) -> R<()> {
|
||||
let (l, fps) = lumas(video)?;
|
||||
let found = flash_frames(&l, fps);
|
||||
if found.is_empty() {
|
||||
passed.push("flash-frame: no stray black or white frame".into());
|
||||
}
|
||||
issues.extend(moments("flash-frame", 1, found));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Each moment a rule found, as an issue of that priority
|
||||
pub(crate) fn moments(rule: &'static str, p: u8, found: Vec<(f64, String)>) -> impl Iterator<Item = Issue> {
|
||||
found.into_iter().map(move |(at, says)| Issue { rule, p, at: Some(at), says })
|
||||
}
|
||||
|
||||
/// The sound's defects on the decoded mix (sound.rs decodes it once)
|
||||
pub(crate) fn sound_defects(x: &[f32], issues: &mut Vec<Issue>, passed: &mut Vec<String>) {
|
||||
for (rule, found, ok) in [("clipping", clipped(x), "clipping: no flat-topped runs"), ("dropout", dropouts(x), "dropout: the sound never drops to silence and back")] {
|
||||
if found.is_empty() {
|
||||
passed.push(ok.into());
|
||||
}
|
||||
issues.extend(moments(rule, 1, found));
|
||||
}
|
||||
}
|
||||
+4
-238
@@ -1,243 +1,9 @@
|
||||
use super::*;
|
||||
use raea_app_check_flash::FlashScreen;
|
||||
|
||||
/// Flashing past WCAG 2.3.1: more than three flashes in any one second, over enough of the frame to matter. A flash is a
|
||||
/// pair of opposing changes in the same pixels, so a shape sliding past isn't one. Each window, a third of the frame wide
|
||||
/// and high, stands in for WCAG's quarter of a 10-degree field (the real area depends on the screen and how far away it
|
||||
/// is, which a file doesn't say), and a quarter of its pixels must swing together: by 0.10 relative luminance with the
|
||||
/// darker end under 0.80, or by 20 of saturated red ((R-G-B)*320, where R/(R+G+B) is at least 0.8). Every decoded frame
|
||||
/// counts, on its own timestamp, and the picture is sampled twice, by area and by point, so fine patterns don't average
|
||||
/// away. A screen for review, not a Harding or PEAT certification; an interlaced picture isn't split into its fields.
|
||||
/// The width each frame is decoded at for the flashing screen (raea-app-check-flash: its rule and its windows), twice over:
|
||||
/// the area sample and the point sample side by side
|
||||
const FLASH_W: usize = 192;
|
||||
const FLASH_MOST: usize = 6;
|
||||
const FLASH_PAIR_S: f64 = 1.0 + 1e-9;
|
||||
|
||||
/// A pixel in one measure: its value, and whether it can count. Red's value runs on through the saturation line, and a change
|
||||
/// counts when either end of it is saturated; a one-level step across the line isn't a jump from zero.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Px {
|
||||
value: f32,
|
||||
counts: bool,
|
||||
}
|
||||
|
||||
struct Swing {
|
||||
at: f64,
|
||||
direction: f32,
|
||||
moved: Vec<bool>,
|
||||
plain: bool,
|
||||
kept: bool,
|
||||
}
|
||||
|
||||
/// One window's swings in one measure: the ones an opposite swing within a second moves back in the same pixels. The
|
||||
/// general measure leaves out swings where another quarter of the window moved the other way at once (a moving pattern).
|
||||
struct Swings {
|
||||
by: f32,
|
||||
under: f32,
|
||||
mixed_counts: bool,
|
||||
pivot: Vec<Px>,
|
||||
extreme: Vec<Px>,
|
||||
at: f64,
|
||||
direction: f32,
|
||||
recent: std::collections::VecDeque<Swing>,
|
||||
ends: Vec<f64>,
|
||||
}
|
||||
|
||||
impl Swings {
|
||||
fn new(by: f32, under: f32, mixed_counts: bool) -> Swings {
|
||||
Swings { by, under, mixed_counts, pivot: Vec::new(), extreme: Vec::new(), at: 0.0, direction: 0.0, recent: Default::default(), ends: Vec::new() }
|
||||
}
|
||||
|
||||
fn moves(&self, a: Px, b: Px, direction: f32) -> bool {
|
||||
(b.value - a.value) * direction >= self.by && a.value.min(b.value) < self.under && (a.counts || b.counts)
|
||||
}
|
||||
|
||||
fn changed(&self, earlier: &[Px], later: &[Px], direction: f32) -> bool {
|
||||
earlier.iter().zip(later).filter(|(a, b)| self.moves(**a, **b, direction)).count() * 4 >= earlier.len()
|
||||
}
|
||||
|
||||
fn push(&mut self, t: f64, px: &[Px]) {
|
||||
if self.pivot.is_empty() {
|
||||
self.pivot = px.to_vec();
|
||||
self.extreme = px.to_vec();
|
||||
self.at = t;
|
||||
return;
|
||||
}
|
||||
if self.direction == 0.0 {
|
||||
for direction in [1.0, -1.0] {
|
||||
if self.changed(&self.pivot, px, direction) {
|
||||
self.direction = direction;
|
||||
self.extreme = px.to_vec();
|
||||
self.at = t;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if self.changed(&self.extreme, px, -self.direction) {
|
||||
self.record();
|
||||
self.pivot = std::mem::replace(&mut self.extreme, px.to_vec());
|
||||
self.at = t;
|
||||
self.direction = -self.direction;
|
||||
} else if self.changed(&self.pivot, px, self.direction) && self.went_further(px) {
|
||||
self.extreme = px.to_vec();
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the pixels swinging from the pivot went further than the saved extreme, judged on those pixels alone: the
|
||||
/// rest of the window can dim by less than counts and still outweigh a patch that's flashing.
|
||||
fn went_further(&self, px: &[Px]) -> bool {
|
||||
let further: f32 = self.pivot.iter().zip(px).zip(&self.extreme).filter(|((p, n), _)| self.moves(**p, **n, self.direction)).map(|((_, n), e)| (n.value - e.value) * self.direction).sum();
|
||||
further > 0.0
|
||||
}
|
||||
|
||||
fn record(&mut self) {
|
||||
if !self.changed(&self.pivot, &self.extreme, self.direction) {
|
||||
return;
|
||||
}
|
||||
let moved: Vec<bool> = self.pivot.iter().zip(&self.extreme).map(|(a, b)| self.moves(*a, *b, self.direction)).collect();
|
||||
let plain = self.mixed_counts || !self.changed(&self.pivot, &self.extreme, -self.direction);
|
||||
let (at, direction) = (self.at, self.direction);
|
||||
let mut kept = false;
|
||||
for other in self.recent.iter_mut().rev() {
|
||||
if at - other.at > FLASH_PAIR_S {
|
||||
break;
|
||||
}
|
||||
let same = moved.iter().zip(&other.moved).filter(|(x, y)| **x && **y).count();
|
||||
if other.direction == -direction && same * 4 >= moved.len() {
|
||||
other.kept = true;
|
||||
kept = true;
|
||||
}
|
||||
}
|
||||
self.recent.push_back(Swing { at, direction, moved, plain, kept });
|
||||
while self.recent.front().is_some_and(|s| at - s.at > FLASH_PAIR_S) {
|
||||
self.retire();
|
||||
}
|
||||
}
|
||||
|
||||
/// The oldest swing leaves the second it could still pair within; only the seconds' ends are kept for good.
|
||||
fn retire(&mut self) {
|
||||
if let Some(s) = self.recent.pop_front()
|
||||
&& s.plain
|
||||
&& s.kept
|
||||
{
|
||||
self.ends.push(s.at);
|
||||
}
|
||||
}
|
||||
|
||||
/// The most swings in any one second, and when that second starts.
|
||||
fn busiest(&mut self) -> (usize, f64) {
|
||||
if self.direction != 0.0 {
|
||||
self.record();
|
||||
self.direction = 0.0;
|
||||
}
|
||||
while !self.recent.is_empty() {
|
||||
self.retire();
|
||||
}
|
||||
self.ends.sort_by(f64::total_cmp);
|
||||
let (mut best, mut from, mut j) = (0, 0.0, 0);
|
||||
for i in 0..self.ends.len() {
|
||||
while self.ends[i] - self.ends[j] >= 1.0 - 1e-9 {
|
||||
j += 1;
|
||||
}
|
||||
if i - j + 1 > best {
|
||||
(best, from) = (i - j + 1, self.ends[j]);
|
||||
}
|
||||
}
|
||||
(best, from)
|
||||
}
|
||||
}
|
||||
|
||||
/// Frames of two pictures side by side, each `w` by `h` RGB: the area sample and the point sample of one frame.
|
||||
pub(crate) struct FlashScreen {
|
||||
w: usize,
|
||||
h: usize,
|
||||
last: Vec<u8>,
|
||||
linear: Vec<f32>,
|
||||
luma: Vec<Px>,
|
||||
red: Vec<Px>,
|
||||
cut: Vec<Px>,
|
||||
windows: Vec<(usize, usize, Swings, Swings)>,
|
||||
}
|
||||
|
||||
impl FlashScreen {
|
||||
pub(crate) fn new(w: usize, h: usize) -> FlashScreen {
|
||||
let (ww, wh) = (w / 3, h / 3);
|
||||
let places = |size: usize, window: usize| {
|
||||
let mut at: Vec<usize> = (0..=size - window).step_by((size / 6).max(1)).collect();
|
||||
at.push(size - window);
|
||||
at.dedup();
|
||||
at
|
||||
};
|
||||
let mut windows = Vec::new();
|
||||
for sample in 0..2 {
|
||||
for &y in &places(h, wh) {
|
||||
for &x in &places(w, ww) {
|
||||
windows.push((x + sample * w, y, Swings::new(0.10, 0.80, false), Swings::new(20.0, f32::INFINITY, true)));
|
||||
}
|
||||
}
|
||||
}
|
||||
let linear = (0..=255u32)
|
||||
.map(|c| {
|
||||
let c = c as f32 / 255.0;
|
||||
if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) }
|
||||
})
|
||||
.collect();
|
||||
FlashScreen { w, h, last: Vec::new(), linear, luma: Vec::new(), red: Vec::new(), cut: Vec::new(), windows }
|
||||
}
|
||||
|
||||
pub(crate) fn push(&mut self, rgb: &[u8], t: f64) {
|
||||
if rgb == self.last {
|
||||
return;
|
||||
}
|
||||
self.luma.clear();
|
||||
self.red.clear();
|
||||
for px in rgb.chunks_exact(3) {
|
||||
let (r, g, b) = (self.linear[px[0] as usize], self.linear[px[1] as usize], self.linear[px[2] as usize]);
|
||||
self.luma.push(Px { value: 0.2126 * r + 0.7152 * g + 0.0722 * b, counts: true });
|
||||
let sum = r + g + b + 1e-9;
|
||||
self.red.push(Px { value: ((r - g - b) * 320.0).max(0.0), counts: r / sum >= 0.8 });
|
||||
}
|
||||
let (stride, ww, wh) = (self.w * 2, self.w / 3, self.h / 3);
|
||||
for (x, y, general, saturated) in &mut self.windows {
|
||||
self.cut.clear();
|
||||
for r in 0..wh {
|
||||
self.cut.extend_from_slice(&self.luma[(*y + r) * stride + *x..][..ww]);
|
||||
}
|
||||
general.push(t, &self.cut);
|
||||
self.cut.clear();
|
||||
for r in 0..wh {
|
||||
self.cut.extend_from_slice(&self.red[(*y + r) * stride + *x..][..ww]);
|
||||
}
|
||||
saturated.push(t, &self.cut);
|
||||
}
|
||||
self.last.clear();
|
||||
self.last.extend_from_slice(rgb);
|
||||
}
|
||||
|
||||
/// (swings in the worst second, when it starts, which measure) when past the limit
|
||||
pub(crate) fn finish(mut self) -> Option<(usize, f64, &'static str)> {
|
||||
let mut worst: Option<(usize, f64, &'static str)> = None;
|
||||
for (_, _, general, saturated) in &mut self.windows {
|
||||
for (swings, kind) in [(general, "general"), (saturated, "red")] {
|
||||
let (n, from) = swings.busiest();
|
||||
if n > FLASH_MOST && worst.is_none_or(|w| n > w.0) {
|
||||
worst = Some((n, from, kind));
|
||||
}
|
||||
}
|
||||
}
|
||||
worst
|
||||
}
|
||||
}
|
||||
|
||||
/// Every decoded frame, once: -fps_mode from FFmpeg 5.1 on, -vsync before it.
|
||||
fn passthrough() -> [&'static str; 2] {
|
||||
let out = Command::new("ffmpeg").args(["-hide_banner", "-version"]).output().map(|o| o.stdout).unwrap_or_default();
|
||||
let head = String::from_utf8_lossy(&out);
|
||||
let version = head.split("version ").nth(1).and_then(|v| {
|
||||
let mut parts = v.trim_start_matches('n').split(|c: char| !c.is_ascii_digit());
|
||||
Some((parts.next()?.parse::<u32>().ok()?, parts.next()?.parse::<u32>().ok()?))
|
||||
});
|
||||
[if version.is_some_and(|v| v < (5, 1)) { "-vsync" } else { "-fps_mode" }, "passthrough"]
|
||||
}
|
||||
|
||||
/// A frame's number and time from showinfo's log, exact: its `pts` in ticks of the time base. `pts_time` is rounded to six
|
||||
/// significant digits, which is enough to push a legal third flash across the one-second line.
|
||||
@@ -269,7 +35,7 @@ pub(crate) fn flashing(video: &str, probe: &Probe, issues: &mut Vec<Issue>, pass
|
||||
let w = FLASH_W;
|
||||
let h = (((w as f64 * probe.h / probe.w.max(1.0)) / 2.0).round() as usize * 2).max(6);
|
||||
let graph = format!("showinfo,split=2[area][point];[area]scale={w}:{h}:flags=area[a];[point]scale={w}:{h}:flags=neighbor[b];[a][b]hstack=inputs=2,format=rgb24");
|
||||
let sync = passthrough();
|
||||
let sync = raea_io_ffmpeg::passthrough();
|
||||
let mut child = Command::new("ffmpeg")
|
||||
.args(["-hide_banner", "-nostats", "-nostdin", "-loglevel", "level+info", "-i", video, "-map", "0:v:0", "-vf", &graph, sync[0], sync[1], "-f", "rawvideo", "-"])
|
||||
.stdin(std::process::Stdio::null())
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
//! `raea hook [AGENT]` (docs/agents.feature A5d, A5e; docs/skills.feature SK10): one runner for every agent harness's
|
||||
//! tool hooks, whichever harness runs the agent (Claude Code, Codex, Gemini CLI, Kimi Code; `raea skills install
|
||||
//! --agent A` adds them, and they hold inside the raea app too, which leaves each agent its own shell). Before a shell
|
||||
//! command: media opened in the Mac's viewer or a browser is stopped once while the raea app is installed, the reason
|
||||
//! naming `raea show`; the same command tried again goes through, so an agent that means it says so twice. After a
|
||||
//! file is saved: the quick check on a composition. A stop is exit 2 with the reason on stderr, which every harness
|
||||
//! hands its agent; the quick check's findings go back in the shape each one reads.
|
||||
use serde_json::{Value, json};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
type R<T> = Result<T, String>;
|
||||
|
||||
/// What a still, a video or a sound ends with: what the raea app shows as an item.
|
||||
const MEDIA: [&str; 25] = ["png", "jpg", "jpeg", "gif", "webp", "heic", "heif", "tif", "tiff", "bmp", "avif", "exr", "mp4", "mov", "m4v", "webm", "mkv", "avi", "wav", "mp3", "m4a", "aac", "flac", "aif", "aiff"];
|
||||
/// A stopped command tried again within this many seconds goes through.
|
||||
const AGAIN: u64 = 600;
|
||||
|
||||
/// The harness that sent this input, when the hook's command doesn't name it: Gemini CLI names its events BeforeTool and
|
||||
/// AfterTool, Kimi Code says its client; Claude Code and Codex share one shape.
|
||||
fn agent_of(v: &Value) -> &'static str {
|
||||
match (v["hook_event_name"].as_str().unwrap_or(""), v["client_type"].as_str().unwrap_or("")) {
|
||||
("BeforeTool" | "AfterTool", _) => "gemini",
|
||||
(_, c) if c.contains("kimi") => "kimi",
|
||||
_ => "claude",
|
||||
}
|
||||
}
|
||||
|
||||
/// The shell command a tool call runs, if it's a shell tool's (Bash, shell, shell_command, exec_command,
|
||||
/// run_shell_command): Codex's apply_patch carries its patch in `command` too, and isn't one.
|
||||
fn shell_command(v: &Value) -> Option<&str> {
|
||||
let cmd = v["tool_input"]["command"].as_str()?;
|
||||
(v["tool_name"].as_str() != Some("apply_patch") && !cmd.trim_start().starts_with("*** Begin Patch")).then_some(cmd)
|
||||
}
|
||||
|
||||
/// A shell segment's words, quotes taken off (enough for `open "a b.png"`, not a shell).
|
||||
fn words(seg: &str) -> Vec<String> {
|
||||
let (mut out, mut cur, mut quote, mut any) = (Vec::new(), String::new(), None, false);
|
||||
for c in seg.chars() {
|
||||
match (quote, c) {
|
||||
(Some(q), c) if c == q => quote = None,
|
||||
(Some(_), c) => cur.push(c),
|
||||
(None, '\'' | '"') => (quote, any) = (Some(c), true),
|
||||
(None, c) if c.is_whitespace() => {
|
||||
if any || !cur.is_empty() {
|
||||
out.push(std::mem::take(&mut cur));
|
||||
}
|
||||
any = false;
|
||||
}
|
||||
(None, c) => cur.push(c),
|
||||
}
|
||||
}
|
||||
if any || !cur.is_empty() {
|
||||
out.push(cur);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The media files a command opens in the Mac's viewer or a browser (`open`, `open -a Preview`, `xdg-open`,
|
||||
/// `qlmanage -p`); `open -a raea`, `open -R` (Finder), links and other files aren't.
|
||||
pub fn opened_media(cmd: &str) -> Vec<String> {
|
||||
let mut found = Vec::new();
|
||||
for seg in cmd.split(['\n', ';', '|', '&']) {
|
||||
let w = words(seg);
|
||||
let mut it = w.iter().skip_while(|t| t.contains('=') && !t.starts_with('-') || ["command", "exec", "nohup", "env"].contains(&t.as_str()));
|
||||
let Some(tool) = it.next() else { continue };
|
||||
if !["open", "xdg-open", "qlmanage"].contains(&tool.rsplit_once('/').map_or(tool.as_str(), |(_, name)| name)) {
|
||||
continue;
|
||||
}
|
||||
// the files it names, apart from the app an -a or -b names; one naming raea, or Finder's -R, opens nothing here
|
||||
let (mut files, mut app, mut ours) = (Vec::new(), false, false);
|
||||
for t in it {
|
||||
if app {
|
||||
ours |= t.to_lowercase().contains("raea");
|
||||
app = false;
|
||||
} else if t == "-a" || t == "-b" {
|
||||
app = true;
|
||||
} else if t == "-R" {
|
||||
ours = true;
|
||||
} else if !t.starts_with('-') && !t.contains("://") && t.rsplit_once('.').is_some_and(|(_, e)| MEDIA.contains(&e.to_lowercase().as_str())) {
|
||||
files.push(t.clone());
|
||||
}
|
||||
}
|
||||
if !ours {
|
||||
found.extend(files);
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// The raea app on this Mac (RAEA_APP, /Applications or ~/Applications).
|
||||
fn app_installed(home: &str) -> bool {
|
||||
[std::env::var("RAEA_APP").unwrap_or_default(), "/Applications/raea.app".into(), format!("{home}/Applications/raea.app")].iter().any(|p| !p.is_empty() && std::path::Path::new(p).exists())
|
||||
}
|
||||
|
||||
/// True when this command was stopped for this session within AGAIN seconds (the agent's second yes, which clears it);
|
||||
/// else it's noted and false.
|
||||
fn tried_before(dir: &Path, key: &str) -> bool {
|
||||
let h = key.bytes().fold(0xcbf29ce484222325u64, |h, b| (h ^ u64::from(b)).wrapping_mul(0x100000001b3));
|
||||
let at = dir.join(format!("{h:016x}"));
|
||||
let fresh = std::fs::metadata(&at).and_then(|m| m.modified()).ok().and_then(|t| t.elapsed().ok()).is_some_and(|e| e.as_secs() < AGAIN);
|
||||
if fresh {
|
||||
let _ = std::fs::remove_file(&at);
|
||||
return true;
|
||||
}
|
||||
let _ = std::fs::create_dir_all(dir).and_then(|_| std::fs::write(&at, key));
|
||||
false
|
||||
}
|
||||
|
||||
/// Why the command stops, for the agent: what to run instead, and that the same command again goes through.
|
||||
pub fn steer(files: &[String]) -> String {
|
||||
let list = files.iter().map(|f| if f.contains(' ') { format!("{f:?}") } else { f.clone() }).collect::<Vec<_>>().join(" ");
|
||||
format!("raea: the raea app is installed here, so show this in it, not the Mac's viewer: `raea show {list}` (several stills make a storyboard; add --ask \"what you want from the person\"; inside the raea app, feed_post does the same). It brings the app's window up on it as an item the person can answer, and their answer comes to the inbox file it prints. If the Mac's viewer really is what's wanted (the person asked for it, or raea show can't), run the same command again and it goes through.")
|
||||
}
|
||||
|
||||
/// The files a tool call saved: `file_path` or `path` (Claude Code, Kimi Code, Gemini CLI), or the files an apply_patch
|
||||
/// adds or updates (Codex).
|
||||
fn saved(v: &Value) -> Vec<String> {
|
||||
let i = &v["tool_input"];
|
||||
if let Some(p) = i["file_path"].as_str().or(i["path"].as_str()).or(i["absolute_path"].as_str()) {
|
||||
return vec![p.to_string()];
|
||||
}
|
||||
let patch = i["command"].as_str().or(i["input"].as_str()).unwrap_or("");
|
||||
patch.lines().filter_map(|l| ["*** Add File: ", "*** Update File: "].iter().find_map(|head| l.strip_prefix(head))).map(str::trim).map(String::from).collect()
|
||||
}
|
||||
|
||||
/// Findings for the agent in the shape its harness reads after a tool: Gemini CLI's AfterTool context, Kimi Code's
|
||||
/// plain stdout, Claude Code's and Codex's PostToolUse context.
|
||||
fn after(agent: &str, text: &str) -> String {
|
||||
match agent {
|
||||
"kimi" => text.to_string(),
|
||||
"gemini" => json!({"hookSpecificOutput": {"hookEventName": "AfterTool", "additionalContext": text}}).to_string(),
|
||||
_ => json!({"hookSpecificOutput": {"hookEventName": "PostToolUse", "additionalContext": text}}).to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `raea hook [claude|codex|gemini|kimi]`: the harness's hook input on stdin. Prints what goes back to the agent, or
|
||||
/// stops the call (exit 2, the reason on stderr).
|
||||
pub fn hook(args: &[String]) -> R<String> {
|
||||
let named = args.first().map(String::as_str);
|
||||
if named.is_some_and(|a| !["claude", "codex", "gemini", "kimi"].contains(&a)) {
|
||||
return Err("usage: raea hook [claude|codex|gemini|kimi] (an agent's tool hooks; raea skills install --agent A adds them)".into());
|
||||
}
|
||||
let mut input = String::new();
|
||||
std::io::Read::read_to_string(&mut std::io::stdin(), &mut input).map_err(|e| e.to_string())?;
|
||||
let v: Value = serde_json::from_str(&input).unwrap_or_default();
|
||||
let agent = named.unwrap_or_else(|| agent_of(&v));
|
||||
if let Some(cmd) = shell_command(&v) {
|
||||
let home = std::env::var("HOME").unwrap_or_default();
|
||||
let files = opened_media(cmd);
|
||||
let key = format!("{}\n{}\n{cmd}", v["session_id"].as_str().unwrap_or(""), v["cwd"].as_str().unwrap_or(""));
|
||||
if !files.is_empty() && app_installed(&home) && !tried_before(&PathBuf::from(&home).join(".raea/hooks/again"), &key) {
|
||||
eprintln!("{}", steer(&files));
|
||||
std::process::exit(2);
|
||||
}
|
||||
return Ok(String::new());
|
||||
}
|
||||
let mut found = Vec::new();
|
||||
for path in saved(&v).iter().filter(|p| p.ends_with(".tsx") && std::fs::read_to_string(p).is_ok_and(|t| t.contains("registerRoot"))) {
|
||||
let (report, _) = crate::quick::quick(std::slice::from_ref(path), Vec::new())?;
|
||||
found.extend(report.lines().skip(1).filter(|l| !l.starts_with("ok ")).map(String::from));
|
||||
}
|
||||
Ok(if found.is_empty() { String::new() } else { after(agent, &format!("raea check --quick after this save:\n{}", found.join("\n"))) })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn media_opened_in_a_viewer_is_found_and_the_rest_isnt() {
|
||||
assert_eq!(opened_media("open out/a.png out/b.PNG"), ["out/a.png", "out/b.PNG"]);
|
||||
assert_eq!(opened_media("cd /tmp && open -a Preview \"sheet 1.jpg\""), ["sheet 1.jpg"]);
|
||||
assert_eq!(opened_media("FOO=1 /usr/bin/open cut.mp4; echo done"), ["cut.mp4"]);
|
||||
assert_eq!(opened_media("qlmanage -p still.webp >/dev/null 2>&1"), ["still.webp"]);
|
||||
assert_eq!(opened_media("xdg-open take.mov"), ["take.mov"]);
|
||||
for none in ["open -a raea", "open -a raea out/a.png", "open -R out/a.png", "open https://x.io/a.png", "open notes.pdf", "open .", "cat a.png", "git open a.png", "echo open a.png > x"] {
|
||||
assert!(opened_media(none).is_empty(), "{none}: {:?}", opened_media(none));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_harness_is_told_apart_and_answered_in_its_shape() {
|
||||
assert_eq!(agent_of(&json!({"hook_event_name": "BeforeTool", "tool_name": "run_shell_command"})), "gemini");
|
||||
assert_eq!(agent_of(&json!({"hook_event_name": "PreToolUse", "client_type": "kimi_code_cli"})), "kimi");
|
||||
assert_eq!(agent_of(&json!({"hook_event_name": "PreToolUse", "tool_name": "Bash"})), "claude");
|
||||
assert_eq!(shell_command(&json!({"tool_name": "shell_command", "tool_input": {"command": "open a.png"}})), Some("open a.png"));
|
||||
assert_eq!(shell_command(&json!({"tool_name": "apply_patch", "tool_input": {"command": "*** Begin Patch\n"}})), None);
|
||||
assert_eq!(saved(&json!({"tool_input": {"command": "*** Begin Patch\n*** Update File: a/E.tsx\n@@\n*** Add File: b.ts\n"}})), ["a/E.tsx", "b.ts"]);
|
||||
assert_eq!(saved(&json!({"tool_input": {"path": "E.tsx"}})), ["E.tsx"]);
|
||||
assert_eq!(after("kimi", "x"), "x");
|
||||
assert!(after("gemini", "x").contains("AfterTool") && after("codex", "x").contains("PostToolUse"));
|
||||
assert!(steer(&["a b.png".into()]).contains("`raea show \"a b.png\"`"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_command_again_goes_through_once() {
|
||||
let d = std::env::temp_dir().join(format!("raea-hook-again-{}", std::process::id()));
|
||||
assert!(!tried_before(&d, "s\n/x\nopen a.png"));
|
||||
assert!(tried_before(&d, "s\n/x\nopen a.png"));
|
||||
assert!(!tried_before(&d, "s\n/x\nopen a.png"), "a third try is a new first");
|
||||
assert!(!tried_before(&d, "other\n/x\nopen a.png"));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
}
|
||||
+96
-48
@@ -1,4 +1,4 @@
|
||||
//! `raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--shape 9:16]
|
||||
//! `raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--things T.json] [--shape 9:16]
|
||||
//! [--platform tiktok|reels|shorts] [-o check.json]`: the floor's measurable lines on an export (docs/craft-system.md, I; sdk/guides/craft/floor.md).
|
||||
//! Each issue is ranked P0 (breaks the piece) to P3 (polish), with where it is and what to do. Rules on the file alone:
|
||||
//! loudness and true peak, a steady sound that stops dead (a source run out, a cut with no fade), stretches where nothing
|
||||
@@ -11,7 +11,7 @@
|
||||
//! rules in their taste.ts files that carry a check (`{ text: "Captions sit clear of the bottom.", check: { form:
|
||||
//! "text-above", value: 62 } }`), each a P1 when broken, since the person's rule beats the floor's default (docs/craft-system.md, J). Exits 1 when a P0 or P1 is found.
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::BTreeMap;
|
||||
use raea_core_facts::{Finding, Level, finding};
|
||||
use std::process::Command;
|
||||
|
||||
mod sound;
|
||||
@@ -20,9 +20,12 @@ mod picture;
|
||||
use picture::*;
|
||||
mod flash;
|
||||
use flash::*;
|
||||
mod defects;
|
||||
use defects::*;
|
||||
mod text;
|
||||
use text::*;
|
||||
pub mod quick;
|
||||
pub mod hook;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -39,35 +42,47 @@ struct Issue {
|
||||
/// `raea check …` with the person's taste, none or more (taste.ts and the kinds beside it, which the raea CLI evaluates: it owns the engine):
|
||||
/// its rules' checks hold the export to the person's own lines.
|
||||
pub fn cli_with(args: &[String], tastes: Vec<raea_core_brief::Taste>) -> i32 {
|
||||
match run(args, tastes) {
|
||||
said(run(args, tastes), "REFUSED ")
|
||||
}
|
||||
|
||||
/// A check's report printed, and its exit code: 1 when it found an error, 2 when it couldn't check (said after
|
||||
/// `refused`). `raea check EDIT.tsx` (apps/direction) ends the same way.
|
||||
pub fn said(ran: R<(String, bool)>, refused: &str) -> i32 {
|
||||
match ran {
|
||||
Ok((report, bad)) => {
|
||||
println!("{report}");
|
||||
i32::from(bad)
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("REFUSED {e}");
|
||||
eprintln!("{refused}{e}");
|
||||
2
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A command's words: its arguments that are neither flags nor a flag's value (`takes`: the flags that take one).
|
||||
/// What `raea check` checks is its first; `raea workspace` and `raea project` read theirs the same way.
|
||||
pub fn words<'a>(args: &'a [String], takes: &[&str]) -> Vec<&'a str> {
|
||||
args.iter().enumerate().filter(|(i, a)| !a.starts_with('-') && !(*i > 0 && takes.contains(&args[i - 1].as_str()))).map(|(_, a)| a.as_str()).collect()
|
||||
}
|
||||
|
||||
fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> {
|
||||
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).map(String::as_str)
|
||||
}
|
||||
|
||||
pub const USAGE: &str = "raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--shape 16:9|9:16|4:5|1:1] [--platform tiktok|reels|shorts] [--taste taste.ts|DIR] [-o check.json] (an export against the floor: clipped text, contrast, safe areas, freezes, flashing, cues, loudness, blotching, a placeholder brand kit; P0-P3)";
|
||||
pub const USAGE: &str = "raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--things T.json] [--shape 16:9|9:16|4:5|1:1] [--platform tiktok|reels|shorts] [--taste taste.ts|DIR] [-o check.json] (an export against the floor: clipped text, contrast, safe areas, freezes, flashing, cues, loudness, blotching, a placeholder brand kit, and with --things what `raea fingerprint things --json` found: a thing floating or passing through another, the camera lurching mid-move, an empty frame; its findings errors, warns and notes)";
|
||||
|
||||
/// A rule from the person's taste: a form raea can measure, its value, and the taste line it stands for.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct Taste {
|
||||
form: String,
|
||||
form: &'static str,
|
||||
value: f64,
|
||||
line: String,
|
||||
}
|
||||
|
||||
/// The checks among a person's taste rules (taste.ts and its kinds), each with the line it stands for.
|
||||
fn taste_rules(tastes: &[raea_core_brief::Taste]) -> Vec<Taste> {
|
||||
tastes.iter().flat_map(|t| &t.sections).flat_map(|s| &s.rules).filter_map(|r| r.check.map(|c| Taste { form: c.form().to_string(), value: c.value(), line: r.text.clone() })).collect()
|
||||
tastes.iter().flat_map(|t| &t.sections).flat_map(|s| &s.rules).filter_map(|r| r.check.map(|c| Taste { form: c.form(), value: c.value(), line: r.text.clone() })).collect()
|
||||
}
|
||||
|
||||
fn taste_of<'a>(rules: &'a [Taste], form: &str) -> Option<&'a Taste> {
|
||||
@@ -82,7 +97,7 @@ fn taste_text(rules: &[Taste], runs: &[Run], w: f64, h: f64, issues: &mut Vec<Is
|
||||
for t in runs {
|
||||
let [x, y, bw, bh] = t.box_;
|
||||
let q = quote(&t.text);
|
||||
let why = match r.form.as_str() {
|
||||
let why = match r.form {
|
||||
"text-hold" if t.to - t.from + 0.05 < r.value => Some(format!("{q} is on for {:.1} s, under your {:.1} s", t.to - t.from, r.value)),
|
||||
"text-above" if y + bh > h * r.value / 100.0 + 1.0 => Some(format!("{q} reaches {:.0}% down the frame, below your {:.0}%", (y + bh) / h * 100.0, r.value)),
|
||||
"text-below" if y < h * r.value / 100.0 - 1.0 => Some(format!("{q} starts {:.0}% down the frame, above your {:.0}%", y / h * 100.0, r.value)),
|
||||
@@ -94,7 +109,7 @@ fn taste_text(rules: &[Taste], runs: &[Run], w: f64, h: f64, issues: &mut Vec<Is
|
||||
};
|
||||
if let Some(why) = why {
|
||||
broke += 1;
|
||||
issues.push(Issue { rule: "taste", p: 1, at: Some(t.from), says: format!("{why} (\"{}\")", r.line) });
|
||||
issues.push(Issue { rule: r.form, p: 1, at: Some(t.from), says: format!("{why} (\"{}\")", r.line) });
|
||||
}
|
||||
}
|
||||
if broke == 0 && r.form.starts_with("text-") {
|
||||
@@ -104,17 +119,33 @@ fn taste_text(rules: &[Taste], runs: &[Run], w: f64, h: f64, issues: &mut Vec<Is
|
||||
}
|
||||
|
||||
/// the flags `raea check` takes, each with a value
|
||||
const TAKES: [&str; 7] = ["--manifest", "--words", "--perception", "--shape", "--platform", "--taste", "-o"];
|
||||
const TAKES: [&str; 8] = ["--manifest", "--words", "--perception", "--things", "--shape", "--platform", "--taste", "-o"];
|
||||
|
||||
fn run(args: &[String], tastes: Vec<raea_core_brief::Taste>) -> R<(String, bool)> {
|
||||
let video = args.iter().enumerate().find(|(i, a)| !a.starts_with('-') && !(*i > 0 && TAKES.contains(&args[i - 1].as_str()))).map(|(_, a)| a.clone()).ok_or(USAGE)?;
|
||||
let (video, issues, passed, fps) = measured(args, taste_rules(&tastes))?;
|
||||
report(&video, issues, Vec::new(), passed, flag(args, "-o"), fps)
|
||||
}
|
||||
|
||||
/// raea's floor on a video (`args` as raea check takes them) as Findings, printed and kept nowhere: `raea check
|
||||
/// EDIT.tsx` runs it on the composition's newest render beside its other checks (apps/direction, DR4). `held`: the
|
||||
/// rules of the named checks it measures on the video itself (loudness, still-max), each its form, value and line.
|
||||
/// `without`: its own rules that a named check holds there instead (`reading`, which text-read holds against when
|
||||
/// a text can be read, not when it's on: DR28).
|
||||
pub fn floor(args: &[String], held: &[(&'static str, f64, String)], without: &[&str]) -> R<Vec<Finding>> {
|
||||
let held = held.iter().map(|(form, value, line)| Taste { form: *form, value: *value, line: line.clone() }).collect();
|
||||
let (_, mut issues, _, fps) = measured(args, held)?;
|
||||
issues.retain(|i| without.iter().all(|w| *w != i.rule));
|
||||
Ok(findings_of(issues, Vec::new(), fps))
|
||||
}
|
||||
|
||||
/// The video's issues and what passed, measured, and its frame rate.
|
||||
fn measured(args: &[String], taste: Vec<Taste>) -> R<(String, Vec<Issue>, Vec<String>, f64)> {
|
||||
let video = words(args, &TAKES).first().map(|v| v.to_string()).ok_or(USAGE)?;
|
||||
if !std::path::Path::new(&video).exists() {
|
||||
return Err(format!("no file at {video}\n{USAGE}"));
|
||||
}
|
||||
let probe = Probe::of(&video)?;
|
||||
let mut issues = Vec::new();
|
||||
let mut passed = Vec::new();
|
||||
let taste = taste_rules(&tastes);
|
||||
let (mut issues, mut passed) = (Vec::new(), Vec::new());
|
||||
let manifest: Option<Value> = match flag(args, "--manifest") {
|
||||
Some(m) => Some(serde_json::from_str(&std::fs::read_to_string(m).map_err(|e| format!("{m}: {e}"))?).map_err(|e| format!("{m}: {e}"))?),
|
||||
None => None,
|
||||
@@ -127,8 +158,12 @@ fn run(args: &[String], tastes: Vec<raea_core_brief::Taste>) -> R<(String, bool)
|
||||
}
|
||||
freezes(&video, &probe, taste_of(&taste, "still-max"), &mut issues, &mut passed)?;
|
||||
flashing(&video, &probe, &mut issues, &mut passed)?;
|
||||
flash_frame_rule(&video, &mut issues, &mut passed)?;
|
||||
blotching(&video, &probe, &mut issues, &mut passed)?;
|
||||
brand_kit(&[flag(args, "--manifest").unwrap_or(""), video.as_str()], &mut issues, &mut passed);
|
||||
if let Some(p) = flag(args, "--things") {
|
||||
things(p, &mut issues, &mut passed)?;
|
||||
}
|
||||
if let Some(manifest) = &manifest {
|
||||
let runs = text_runs(manifest);
|
||||
let (w, h) = (manifest["width"].as_f64().unwrap_or(probe.w), manifest["height"].as_f64().unwrap_or(probe.h));
|
||||
@@ -143,36 +178,56 @@ fn run(args: &[String], tastes: Vec<raea_core_brief::Taste>) -> R<(String, bool)
|
||||
face_cover(&runs, &faces, &mut issues, &mut passed);
|
||||
}
|
||||
}
|
||||
|
||||
report(&video, issues, passed, flag(args, "-o"))
|
||||
Ok((video, issues, passed, fps))
|
||||
}
|
||||
|
||||
/// The issues ranked, written to -o as JSON when asked, and the report's text; true when a P0 or P1 is among them.
|
||||
fn report(video: &str, mut issues: Vec<Issue>, passed: Vec<String>, out: Option<&str>) -> R<(String, bool)> {
|
||||
/// What `raea fingerprint things FILE --json` found (docs/fingerprint.feature FP13c): a thing floating, two passing
|
||||
/// through each other, the camera lurching mid-move, an empty frame; measured there, from depth, masks and the camera's
|
||||
/// path, never by a head
|
||||
fn things(p: &str, issues: &mut Vec<Issue>, passed: &mut Vec<String>) -> R<()> {
|
||||
let v: Value = serde_json::from_str(&std::fs::read_to_string(p).map_err(|e| format!("{p}: {e}"))?).map_err(|e| format!("{p}: {e}"))?;
|
||||
let before = issues.len();
|
||||
for i in v["issues"].as_array().into_iter().flatten() {
|
||||
let Some(rule) = ["floating", "passing-through", "camera-speed", "empty-frame"].into_iter().find(|r| i["rule"] == *r) else { continue };
|
||||
issues.push(Issue { rule, p: i["p"].as_u64().unwrap_or(2).min(3) as u8, at: i["at"].as_f64(), says: i["says"].as_str().unwrap_or_default().into() });
|
||||
}
|
||||
if issues.len() == before {
|
||||
passed.push("things: nothing floats, passes through, lurches or is empty".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The issues as Findings (docs/direction.feature DR3: P0 and P1 errors, P2 a warn, P3 a note; a time is its frame at
|
||||
/// `fps`), with `more` (a render's own), worst first then by time.
|
||||
fn findings_of(mut issues: Vec<Issue>, more: Vec<Finding>, fps: f64) -> Vec<Finding> {
|
||||
issues.sort_by(|a, b| a.p.cmp(&b.p).then(a.at.unwrap_or(0.0).total_cmp(&b.at.unwrap_or(0.0))));
|
||||
let bad = issues.iter().any(|i| i.p <= 1);
|
||||
let mut found = Vec::new();
|
||||
for i in &issues {
|
||||
// an issue at a second is about the frame it falls on
|
||||
let (f, fr) = (Finding::new(i.rule, Level::of_rank(i.p), &i.says, "raea check"), (i.at.unwrap_or(0.0) * fps).round() as i64);
|
||||
found.push(if i.at.is_some() { f.frames(fr, fr + 1) } else { f });
|
||||
}
|
||||
finding::ranked(found.into_iter().chain(more).collect())
|
||||
}
|
||||
|
||||
/// The findings (`findings_of`), written to -o as JSON when asked, and the report's text with the count last. True
|
||||
/// when an error is among them.
|
||||
fn report(video: &str, issues: Vec<Issue>, more: Vec<Finding>, passed: Vec<String>, out: Option<&str>, fps: f64) -> R<(String, bool)> {
|
||||
let found = findings_of(issues, more, fps);
|
||||
let bad = found.iter().any(|f| f.level == Level::Error);
|
||||
if let Some(out) = out {
|
||||
let j = json!({
|
||||
"file": video,
|
||||
"issues": issues.iter().map(|i| json!({"rule": i.rule, "p": format!("P{}", i.p), "at": i.at, "says": i.says})).collect::<Vec<_>>(),
|
||||
"passed": passed,
|
||||
});
|
||||
let j = json!({"file": video, "fps": fps, "findings": found, "passed": passed});
|
||||
std::fs::write(out, serde_json::to_string_pretty(&j).unwrap()).map_err(|e| format!("{out}: {e}"))?;
|
||||
}
|
||||
let mut by = BTreeMap::new();
|
||||
for i in &issues {
|
||||
*by.entry(i.p).or_insert(0) += 1;
|
||||
let mut s = format!("raea check {video}\n");
|
||||
// kept in its project's record beside its renders (DR3), what `raea findings` and `raea next` read
|
||||
let kept = raea_core_facts::record::keep("raea check", std::path::Path::new(video), out.map(std::path::Path::new), &found, vec![], &raea_io_trace::utc(std::time::SystemTime::now()).1);
|
||||
let kept = kept.map(|e| format!("raea check: kept in the project's record as {} (raea findings reads it)", e.id));
|
||||
for line in found.iter().map(Finding::line).chain(passed.iter().map(|p| format!("ok {p}"))).chain(kept) {
|
||||
s.push_str(&line);
|
||||
s.push('\n');
|
||||
}
|
||||
let counts = by.iter().map(|(p, n)| format!("P{p} {n}")).collect::<Vec<_>>().join(", ");
|
||||
let mut s = format!("raea check {}: {}\n", video, if issues.is_empty() { "nothing to fix".to_string() } else { format!("{} to fix ({counts})", issues.len()) });
|
||||
for i in &issues {
|
||||
let at = i.at.map(|t| format!("{t:6.2} s")).unwrap_or_else(|| " ".into());
|
||||
s.push_str(&format!("P{} {:<9} {at} {}\n", i.p, i.rule, i.says));
|
||||
}
|
||||
for p in &passed {
|
||||
s.push_str(&format!("ok {p}\n"));
|
||||
}
|
||||
Ok((s.trim_end().to_string(), bad))
|
||||
Ok((s + &format!("raea check: {}", finding::count(&found)), bad))
|
||||
}
|
||||
|
||||
struct Probe {
|
||||
@@ -200,10 +255,8 @@ fn last_packet_end(video: &str) -> Option<f64> {
|
||||
|
||||
impl Probe {
|
||||
fn of(video: &str) -> R<Probe> {
|
||||
let out = Command::new("ffprobe")
|
||||
.args(["-v", "error", "-show_entries", "stream=codec_type,width,height,r_frame_rate,duration,start_time:format=duration,start_time", "-of", "json", video])
|
||||
.output()
|
||||
.map_err(|e| format!("ffprobe: {e}"))?;
|
||||
let entries = "stream=codec_type,width,height,r_frame_rate,duration,start_time:format=duration,start_time";
|
||||
let out = Command::new("ffprobe").args(["-v", "error", "-show_entries", entries, "-of", "json", video]).output().map_err(|e| format!("ffprobe: {e}"))?;
|
||||
let v: Value = serde_json::from_slice(&out.stdout).map_err(|e| format!("ffprobe: {e}"))?;
|
||||
let streams = v["streams"].as_array().cloned().unwrap_or_default();
|
||||
let vid = streams.iter().find(|s| s["codec_type"] == "video").ok_or("no video stream")?;
|
||||
@@ -214,12 +267,7 @@ impl Probe {
|
||||
Some(length) => seconds(&vid["start_time"]).unwrap_or(origin) - origin + length,
|
||||
None => last_packet_end(video).map_or(duration, |end| end - origin),
|
||||
};
|
||||
Ok(Probe {
|
||||
w: vid["width"].as_f64().unwrap_or(1920.0),
|
||||
h: vid["height"].as_f64().unwrap_or(1080.0),
|
||||
duration,
|
||||
picture,
|
||||
audio: streams.iter().any(|s| s["codec_type"] == "audio"),
|
||||
})
|
||||
let audio = streams.iter().any(|s| s["codec_type"] == "audio");
|
||||
Ok(Probe { w: vid["width"].as_f64().unwrap_or(1920.0), h: vid["height"].as_f64().unwrap_or(1080.0), duration, picture, audio })
|
||||
}
|
||||
}
|
||||
+38
-50
@@ -1,87 +1,75 @@
|
||||
//! `raea check EDIT.tsx --quick` and `raea hook claude` (docs/skills.feature SK10). The quick check renders three stills
|
||||
//! of a composition (a quarter in, the middle, the last frame) with their manifest, about a second, and runs the full
|
||||
//! check's text rules and the person's text taste on it: clipped and cramped text, safe areas, sizes. The hook is
|
||||
//! Claude Code's PostToolUse command (`raea skills install --agent claude` adds it): after a .tsx that registers a root
|
||||
//! is written, the quick check's findings go back to the agent; a clean check says nothing.
|
||||
//! `raea check EDIT.tsx --quick` (docs/skills.feature SK10). The quick check renders three stills of a composition (a
|
||||
//! quarter in, the middle, the last frame, of the length frame 0's render reports) with their manifest, and runs the text rules
|
||||
//! and the person's text taste on it: clipped and cramped text, safe areas, sizes. Every agent's after-save hook runs
|
||||
//! it (hook.rs): after a .tsx that registers a root is saved, its findings go back to the agent; a clean check says
|
||||
//! nothing.
|
||||
use super::*;
|
||||
use std::path::Path;
|
||||
|
||||
/// The composition's length in frames, read from its source (the first `durationInFrames={N}`), 90 without one.
|
||||
fn frames(src: &str) -> u64 {
|
||||
src.split("durationInFrames={").nth(1).and_then(|r| r.split('}').next()).and_then(|n| n.trim().parse().ok()).unwrap_or(90)
|
||||
/// The stills' frames: a quarter in, the middle and the last of the length a render reports (render.json's `length`,
|
||||
/// the composition's own however it's written; #86 read its source's `durationInFrames={N}` and took 90 for a name).
|
||||
fn samples(m: &Value) -> Option<[u64; 3]> {
|
||||
let n = m["length"].as_u64()?.max(1);
|
||||
Some([n / 4, n / 2, n - 1])
|
||||
}
|
||||
|
||||
/// `raea check EDIT.tsx --quick [--shape S] [--platform P] [-o check.json]`: (report, P0 or P1 found). `tastes` are the
|
||||
/// person's, evaluated by the raea CLI when --taste names them.
|
||||
pub fn quick(args: &[String], tastes: Vec<raea_core_brief::Taste>) -> R<(String, bool)> {
|
||||
let file = args.iter().find(|a| a.ends_with(".tsx")).ok_or("raea check --quick takes a composition: EDIT.tsx")?;
|
||||
let src = std::fs::read_to_string(file).map_err(|e| format!("{file}: {e}"))?;
|
||||
let n = frames(&src).max(1);
|
||||
let at = format!("{},{},{}", n / 4, n / 2, n - 1);
|
||||
let tmp = std::env::temp_dir().join(format!("raea-quick-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&tmp).map_err(|e| format!("{}: {e}", tmp.display()))?;
|
||||
let manifest = tmp.join("render.json");
|
||||
let me = std::env::current_exe().map_err(|e| e.to_string())?;
|
||||
let out = std::process::Command::new(me).arg("render").arg(file).args(["--at", &at, "-o"]).arg(format!("{}/", tmp.display())).arg("--manifest").arg(&manifest).output().map_err(|e| e.to_string())?;
|
||||
let result = if out.status.success() {
|
||||
on_manifest(file, &manifest, args, tastes)
|
||||
// the stills are part of this check, which keeps the one entry in the project's record (DR3)
|
||||
let render = |at: &str| std::process::Command::new(&me).arg("render").arg(file).args(["--at", at, "-o"]).arg(format!("{}/", tmp.display())).arg("--manifest").arg(&manifest).env("RAEA_RECORD", "off").output().map_err(|e| e.to_string());
|
||||
// frame 0 first, for the length (its manifest's), then the three stills
|
||||
let mut out = render("0")?;
|
||||
let at = std::fs::read_to_string(&manifest).ok().and_then(|t| samples(&serde_json::from_str(&t).ok()?));
|
||||
if let Some(at) = at {
|
||||
let _ = std::fs::remove_file(&manifest);
|
||||
out = render(&at.map(|f| f.to_string()).join(","))?;
|
||||
}
|
||||
// rendered when its manifest was written: a render whose stills clip exits 1 (DR3), and those findings are read here
|
||||
let result = if let (Some(at), true) = (at, manifest.is_file()) {
|
||||
on_manifest(file, &manifest, args, tastes, at)
|
||||
} else {
|
||||
// a render that fails is the finding: the agent sees why
|
||||
let (err, out) = (String::from_utf8_lossy(&out.stderr), String::from_utf8_lossy(&out.stdout));
|
||||
let mut why = Vec::new();
|
||||
for line in err.lines().chain(out.lines()) {
|
||||
if line.contains("REFUSED") || line.contains("rror") {
|
||||
why.push(line);
|
||||
}
|
||||
}
|
||||
let why = why.join("\n");
|
||||
Ok((format!("raea check {file}: it doesn't render\nP0 render {why}"), true))
|
||||
let why: Vec<&str> = err.lines().chain(out.lines()).filter(|l| l.contains("REFUSED") || l.contains("rror")).collect();
|
||||
let f = raea_core_facts::Finding::new("render", raea_core_facts::Level::Error, why.join("\n"), "raea check --quick");
|
||||
Ok((format!("raea check {file}: it doesn't render\n{}\nraea check: {}", f.line(), raea_core_facts::finding::count(&[f])), true))
|
||||
};
|
||||
let _ = std::fs::remove_dir_all(&tmp);
|
||||
result
|
||||
}
|
||||
|
||||
/// `raea hook claude`: Claude Code's PostToolUse input on stdin; for a saved composition, the quick check's findings as
|
||||
/// the hook's additionalContext. Anything else, or a clean check, prints nothing.
|
||||
pub fn hook(args: &[String]) -> R<String> {
|
||||
if args.first().map(String::as_str) != Some("claude") {
|
||||
return Err("usage: raea hook claude (Claude Code's PostToolUse hook; raea skills install --agent claude adds it)".into());
|
||||
}
|
||||
let mut input = String::new();
|
||||
std::io::Read::read_to_string(&mut std::io::stdin(), &mut input).map_err(|e| e.to_string())?;
|
||||
let v: serde_json::Value = serde_json::from_str(&input).unwrap_or_default();
|
||||
let path = v["tool_input"]["file_path"].as_str().unwrap_or_default();
|
||||
let composition = path.ends_with(".tsx") && std::fs::read_to_string(path).map(|t| t.contains("registerRoot")).unwrap_or(false);
|
||||
if !composition {
|
||||
return Ok(String::new());
|
||||
}
|
||||
let (report, _) = quick(&[path.to_string()], Vec::new())?;
|
||||
if report.lines().nth(1).is_none_or(|l| l.starts_with("ok ")) {
|
||||
return Ok(String::new());
|
||||
}
|
||||
let found: Vec<&str> = report.lines().filter(|l| !l.starts_with("ok ")).collect();
|
||||
Ok(json!({"hookSpecificOutput": {"hookEventName": "PostToolUse", "additionalContext": format!("raea check --quick after this save:\n{}", found.join("\n"))}}).to_string())
|
||||
}
|
||||
|
||||
/// `raea check --quick`'s half (docs/skills.feature SK10): the text rules and the person's text taste on the manifest
|
||||
/// of a few stills (`raea render EDIT.tsx --at ... --manifest`), no video. What it can't see (contrast, freezes,
|
||||
/// sound, blotching) waits for the full check on the export.
|
||||
fn on_manifest(file: &str, manifest: &Path, args: &[String], tastes: Vec<raea_core_brief::Taste>) -> R<(String, bool)> {
|
||||
fn on_manifest(file: &str, manifest: &Path, args: &[String], tastes: Vec<raea_core_brief::Taste>, [a, b, c]: [u64; 3]) -> R<(String, bool)> {
|
||||
let at = manifest.display();
|
||||
let m: Value = serde_json::from_str(&std::fs::read_to_string(manifest).map_err(|e| format!("{at}: {e}"))?).map_err(|e| format!("{at}: {e}"))?;
|
||||
let (mut issues, mut passed) = (Vec::new(), Vec::new());
|
||||
let (mut issues, mut passed) = (Vec::new(), vec![format!("looked at frames {a}, {b} and {c} of {}", c + 1)]);
|
||||
let runs = text_runs(&m);
|
||||
let (w, h) = (m["width"].as_f64().unwrap_or(1080.0), m["height"].as_f64().unwrap_or(1920.0));
|
||||
text_rules(&runs, None, w, h, flag(args, "--shape"), flag(args, "--platform"), &mut issues, &mut passed);
|
||||
taste_text(&taste_rules(&tastes), &runs, w, h, &mut issues, &mut passed);
|
||||
report(file, issues, passed, flag(args, "-o"))
|
||||
// and what the render of the stills found (the 3D's clipping, DR3)
|
||||
let more = serde_json::from_value(m["findings"].clone()).unwrap_or_default();
|
||||
report(file, issues, more, passed, flag(args, "-o"), m["fps"].as_f64().unwrap_or(30.0))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
/// the length is the render's, so a `durationInFrames={DUR}` (#86: 300 frames, read as 90) is sampled to its end
|
||||
#[test]
|
||||
fn frames_come_from_the_source() {
|
||||
assert_eq!(super::frames("<Composition durationInFrames={240} fps={30} />"), 240);
|
||||
assert_eq!(super::frames("no composition"), 90);
|
||||
fn frames_come_from_the_render() {
|
||||
assert_eq!(super::samples(&json!({"length": 240})), Some([60, 120, 239]));
|
||||
assert_eq!(super::samples(&json!({"length": 300})), Some([75, 150, 299]));
|
||||
assert_eq!(super::samples(&json!({"length": 1})), Some([0, 0, 0]));
|
||||
// a render that reported no length: no stills to look at, so the frame-0 render's failure is the finding
|
||||
assert_eq!(super::samples(&json!({"width": 640})), None);
|
||||
}
|
||||
}
|
||||
+13
-9
@@ -27,6 +27,12 @@ pub(crate) fn pct(v: &[f64], q: f64) -> f64 {
|
||||
/// a bed that stops under a voice shows in the band the voice doesn't fill (a projector's clatter in the highs). A band's
|
||||
/// level is its share of the step's mean square (Parseval, undoing the Hann window's power), so a tone reads the same in
|
||||
/// its band as in the mix
|
||||
/// A stretch of sound's level in dB (its RMS)
|
||||
pub(crate) fn db(f: &[f32]) -> f64 {
|
||||
let ms = f.iter().map(|&v| (v as f64).powi(2)).sum::<f64>() / f.len().max(1) as f64;
|
||||
20.0 * (ms.sqrt() + 1e-9).log10()
|
||||
}
|
||||
|
||||
pub(crate) fn levels(x: &[f32]) -> (Vec<f64>, [Vec<f64>; 3]) {
|
||||
use std::f64::consts::PI;
|
||||
let n = x.len() / HOP;
|
||||
@@ -44,8 +50,7 @@ pub(crate) fn levels(x: &[f32]) -> (Vec<f64>, [Vec<f64>; 3]) {
|
||||
let scale = 2.0 / (HOP * HOP) as f64 / (hann.iter().map(|h| h * h).sum::<f64>() / HOP as f64);
|
||||
let (mut rms, mut bands) = (Vec::with_capacity(n), [Vec::with_capacity(n), Vec::with_capacity(n), Vec::with_capacity(n)]);
|
||||
for f in x.chunks_exact(HOP) {
|
||||
let ms = f.iter().map(|&v| (v as f64).powi(2)).sum::<f64>() / HOP as f64;
|
||||
rms.push(20.0 * (ms.sqrt() + 1e-9).log10());
|
||||
rms.push(db(f));
|
||||
let w: Vec<f64> = f.iter().zip(&hann).map(|(&v, h)| v as f64 * h).collect();
|
||||
let mut e = [0.0; 3];
|
||||
for (b, tw) in &bins {
|
||||
@@ -163,7 +168,8 @@ pub(crate) fn sound(video: &str, words: Option<&[Word]>, issues: &mut Vec<Issue>
|
||||
}
|
||||
let x: Vec<f32> = out.stdout.chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect();
|
||||
let (rms, bands) = levels(&x);
|
||||
let found = |list: Vec<(f64, String)>, p: u8| list.into_iter().map(move |(at, says)| Issue { rule: "sound", p, at: Some(at), says });
|
||||
sound_defects(&x, issues, passed);
|
||||
let found = |list: Vec<(f64, String)>, p: u8| crate::defects::moments("sound", p, list);
|
||||
let stops = dead_stops(&rms, &bands);
|
||||
if stops.is_empty() {
|
||||
passed.push("sound: no steady sound stops dead".into());
|
||||
@@ -206,17 +212,15 @@ pub(crate) fn ffmpeg_stderr(args: &[&str]) -> R<String> {
|
||||
|
||||
/// -14 LUFS integrated (±1) and a true peak at or below -1 dBTP (the floor's mix line)
|
||||
pub(crate) fn loudness(video: &str, taste: Option<&Taste>, issues: &mut Vec<Issue>, passed: &mut Vec<String>) -> R<()> {
|
||||
let err = ffmpeg_stderr(&["-hide_banner", "-nostats", "-i", video, "-vn", "-af", "ebur128=peak=true", "-f", "null", "-"])?;
|
||||
let summary = err.rsplit("Summary:").next().unwrap_or("");
|
||||
let num = |key: &str| summary.lines().find(|l| l.trim_start().starts_with(key)).and_then(|l| l.split_whitespace().nth(1)).and_then(|x| x.parse::<f64>().ok());
|
||||
let (Some(i), peak) = (num("I:"), num("Peak:")) else { return Ok(()) };
|
||||
// the same measure `raea world` joins to a render as its Mix (raea-sys-measure, DR2)
|
||||
let Some((i, peak)) = raea_sys_measure::loudness(std::path::Path::new(video)) else { return Ok(()) };
|
||||
let mut ok = true;
|
||||
let target = taste.map_or(-14.0, |t| t.value);
|
||||
if (i - target).abs() > 1.0 {
|
||||
ok = false;
|
||||
let says = format!("{i:.1} LUFS integrated; master at {target} (±1) with <Mix lufs={{{target}}} />");
|
||||
issues.push(match taste {
|
||||
Some(t) => Issue { rule: "taste", p: 1, at: None, says: format!("{says} (\"{}\")", t.line) },
|
||||
Some(t) => Issue { rule: t.form, p: 1, at: None, says: format!("{says} (\"{}\")", t.line) },
|
||||
None => Issue { rule: "loudness", p: 1, at: None, says },
|
||||
});
|
||||
}
|
||||
@@ -258,7 +262,7 @@ pub(crate) fn freezes(video: &str, probe: &Probe, taste: Option<&Taste>, issues:
|
||||
for &(s, d) in &stretches {
|
||||
let says = format!("nothing changes for {d:.1} s; give it a reason to hold, or cut it shorter");
|
||||
issues.push(match taste {
|
||||
Some(t) => Issue { rule: "taste", p: 1, at: Some(s), says: format!("{says} (\"{}\")", t.line) },
|
||||
Some(t) => Issue { rule: t.form, p: 1, at: Some(s), says: format!("{says} (\"{}\")", t.line) },
|
||||
None => Issue { rule: "frozen", p: if d >= 6.0 || d >= probe.duration * 0.5 { 1 } else { 2 }, at: Some(s), says },
|
||||
});
|
||||
}
|
||||
|
||||
+91
-92
@@ -64,8 +64,8 @@ fn taste_checks_hold_text_to_the_persons_line() {
|
||||
]}]})).unwrap();
|
||||
let rules = taste_rules(&[taste]);
|
||||
assert_eq!(rules, vec![
|
||||
Taste { form: "text-above".into(), value: 62.0, line: "Captions sit clear of the bottom.".into() },
|
||||
Taste { form: "text-hold".into(), value: 2.0, line: "Text holds two seconds".into() },
|
||||
Taste { form: "text-above", value: 62.0, line: "Captions sit clear of the bottom.".into() },
|
||||
Taste { form: "text-hold", value: 2.0, line: "Text holds two seconds".into() },
|
||||
]);
|
||||
let low = Run { text: "Render anything.".into(), from: 1.0, to: 4.0, box_: [800.0, 800.0, 300.0, 60.0], boxes: vec![[800.0, 800.0, 300.0, 60.0]], color: String::new(), size: 48.0 };
|
||||
let high = Run { text: "raea".into(), from: 5.0, to: 6.0, box_: [800.0, 300.0, 300.0, 60.0], boxes: vec![[800.0, 300.0, 300.0, 60.0]], color: String::new(), size: 48.0 };
|
||||
@@ -73,7 +73,7 @@ fn taste_checks_hold_text_to_the_persons_line() {
|
||||
taste_text(&rules, &[low, high], 1920.0, 1080.0, &mut issues, &mut passed);
|
||||
let says: Vec<_> = issues.iter().map(|i| (i.rule, i.p, i.at)).collect();
|
||||
// the low caption breaks the placement line (860 of 1080 is 80%); the short one breaks the hold
|
||||
assert_eq!(says, vec![("taste", 1, Some(1.0)), ("taste", 1, Some(5.0))]);
|
||||
assert_eq!(says, vec![("text-above", 1, Some(1.0)), ("text-hold", 1, Some(5.0))], "a taste line is the named check of its form (DR4)");
|
||||
}
|
||||
|
||||
/// `RAEA_CHECK_ARGS="film.mp4 --manifest film.render.json --taste DIR" cargo test -p raea-runtime-react --lib
|
||||
@@ -292,72 +292,6 @@ fn a_sign_the_camera_carries_off_isnt_clipped_but_a_title_held_off_is() {
|
||||
assert_eq!(rules, vec![("safe-area", "THE NIGHT MARKET".to_string()), ("clipped", "WIDE".to_string())]);
|
||||
}
|
||||
|
||||
/// a 96x54 picture drawn by `paint(frame index, sample, x, y)`, sample 0 the area sample and 1 the point sample, for
|
||||
/// `frames` frames at `fps`
|
||||
fn flash_samples(frames: usize, fps: f64, paint: impl Fn(usize, usize, usize, usize) -> [u8; 3]) -> Option<(usize, f64, &'static str)> {
|
||||
let (w, h) = (96, 54);
|
||||
let mut screen = FlashScreen::new(w, h);
|
||||
for f in 0..frames {
|
||||
let mut rgb = Vec::with_capacity(w * 2 * h * 3);
|
||||
for y in 0..h {
|
||||
for sample in 0..2 {
|
||||
for x in 0..w {
|
||||
rgb.extend_from_slice(&paint(f, sample, x, y));
|
||||
}
|
||||
}
|
||||
}
|
||||
screen.push(&rgb, f as f64 / fps);
|
||||
}
|
||||
screen.finish()
|
||||
}
|
||||
|
||||
fn flash_of(seconds: usize, paint: impl Fn(usize, usize, usize) -> [u8; 3]) -> Option<(usize, f64, &'static str)> {
|
||||
flash_samples(seconds * 60, 60.0, move |f, _, x, y| paint(f, x, y))
|
||||
}
|
||||
|
||||
/// two colours taking turns `hz` times a second, over a box of the frame
|
||||
fn turns(hz: usize, on: [u8; 3], off: [u8; 3], bx: (usize, usize, usize, usize)) -> Option<(usize, f64, &'static str)> {
|
||||
flash_of(3, move |f, x, y| {
|
||||
let inside = x >= bx.0 && x < bx.0 + bx.2 && y >= bx.1 && y < bx.1 + bx.3;
|
||||
if inside && f * hz * 2 / 60 % 2 == 0 { on } else { off }
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flashing_is_found_past_three_a_second_and_not_at_it() {
|
||||
let (white, black) = ([255, 255, 255], [0, 0, 0]);
|
||||
let all = (0, 0, 96, 54);
|
||||
assert_eq!(turns(3, white, black, all), None, "three a second is the limit, not past it");
|
||||
let (swings, _, kind) = turns(4, white, black, all).expect("four a second");
|
||||
assert_eq!((swings / 2, kind), (4, "general"));
|
||||
// a small box: under a quarter of any window, and then over it
|
||||
assert_eq!(turns(5, white, black, (40, 20, 10, 10)), None);
|
||||
assert!(turns(5, white, black, (30, 18, 32, 18)).is_some());
|
||||
// too small a change, and both ends too bright for WCAG to count it
|
||||
assert_eq!(turns(5, [60, 60, 60], [30, 30, 30], all), None);
|
||||
assert_eq!(turns(5, [255, 255, 255], [235, 235, 235], all), None);
|
||||
// a dark saturated red: too dim to count as a general flash, past the limit as a red one
|
||||
assert_eq!(turns(5, [150, 0, 0], black, all).map(|t| t.2), Some("red"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flash_of_single_frames_counts_at_any_frame_rate() {
|
||||
// 120 fps with one white frame in every 30: four flashes a second, each gone within a sixtieth of a second
|
||||
let found = flash_samples(360, 120.0, |f, _, _, _| if f % 30 == 1 { [255, 255, 255] } else { [0, 0, 0] });
|
||||
assert_eq!(found.map(|(swings, _, kind)| (swings / 2, kind)), Some((4, "general")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flash_the_area_sample_averages_away_is_found_in_the_point_sample() {
|
||||
let found = flash_samples(180, 60.0, |f, sample, _, _| {
|
||||
if sample == 0 {
|
||||
return [128, 128, 128];
|
||||
}
|
||||
if f * 5 * 2 / 60 % 2 == 0 { [255, 255, 255] } else { [0, 0, 0] }
|
||||
});
|
||||
assert!(found.is_some(), "the same flash in the point sample alone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_frame_gets_its_exact_time_from_the_log() {
|
||||
// lines FFmpeg 9.0.2 logged with -loglevel level+info
|
||||
@@ -382,34 +316,99 @@ fn only_a_lines_own_severity_counts_as_an_error() {
|
||||
assert_eq!(log_level("frame= 300 fps=0.0"), None);
|
||||
}
|
||||
|
||||
|
||||
/// A centred line in a left: 0; right: 0 box isn't in the left zone: its letters are tested where the render recorded
|
||||
/// them (#89); a left-aligned one is, the finding naming the edge, and a manifest without ink is tested by the box.
|
||||
#[test]
|
||||
fn a_shape_sliding_past_and_ordinary_cuts_are_not_flashing() {
|
||||
let (white, black) = ([255, 255, 255], [0, 0, 0]);
|
||||
assert_eq!(flash_of(3, move |f, x, _| if x < f { white } else { black }), None, "one wipe across the frame");
|
||||
assert_eq!(flash_of(4, move |f, _, _| if (f / 30) % 2 == 0 { white } else { black }), None, "a cut every half second");
|
||||
fn safe_area_tests_the_letters_not_the_box() {
|
||||
let safe_area = |ink: Value| {
|
||||
let m = json!({"fps": 1.0, "frames": [{"frame": 0, "text": [{"text": "centred", "box": [0, 160, 640, 40], "ink": ink}]}]});
|
||||
let (mut issues, mut passed) = (vec![], vec![]);
|
||||
text_rules(&text_runs(&m), None, 640.0, 360.0, None, None, &mut issues, &mut passed);
|
||||
issues.into_iter().filter(|i| i.rule == "safe-area").map(|i| i.says).collect::<String>()
|
||||
};
|
||||
assert_eq!(safe_area(json!([250, 160, 140, 40])), "");
|
||||
let left = safe_area(json!([0, 160, 140, 40]));
|
||||
assert!(left.contains("at the left") && left.contains("its letters 0,160 140x40"), "{left}");
|
||||
assert!(safe_area(Value::Null).contains("its box 0,160 640x40"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_patch_strobing_while_its_background_dims_is_still_found() {
|
||||
// a third of a window: 0 then 124 on a 148 background, then the background settles at 124 and the patch cycles 124 and 160.
|
||||
// The background's drop is under the 0.10 that counts, but it outweighs the patch in the window's mean.
|
||||
let found = flash_samples(180, 60.0, |f, _, x, y| {
|
||||
let patch = x < 16 && y < 12;
|
||||
let level = match (patch, f) {
|
||||
(true, 0) => 0,
|
||||
(true, 1) => 124,
|
||||
(true, _) => if (f - 2) * 5 * 2 / 60 % 2 == 0 { 160 } else { 124 },
|
||||
(false, 0 | 1) => 148,
|
||||
(false, _) => 124,
|
||||
};
|
||||
[level, level, level]
|
||||
});
|
||||
assert!(found.is_some(), "the patch flashes five times a second");
|
||||
fn a_card_sharing_one_word_with_another_line_isnt_held_to_it() {
|
||||
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 2.0, box_: [0.0; 4], boxes: vec![], color: String::new(), size: 48.0 };
|
||||
let said = |ws: &[(&str, f64)]| ws.iter().map(|(t, s)| Word { text: (*t).into(), start: *s, end: *s }).collect::<Vec<Word>>();
|
||||
let words = said(&[("at", 37.9), ("wirestock", 38.2), ("i", 38.9), ("worked", 39.0), ("on", 39.2), ("a", 39.3), ("sora", 39.5), ("campaign", 40.2)]);
|
||||
let (mut issues, mut passed) = (vec![], vec![]);
|
||||
// one word of three shared with the line, said 1.35 s before: not a caption of it (the film's false P1)
|
||||
cues(&[run("Wirestock × OpenAI Sora", 39.55)], &words, &mut issues, &mut passed);
|
||||
// one word of four, "campaign": the same
|
||||
cues(&[run("Classroom of Tomorrow campaign", 39.55)], &words, &mut issues, &mut passed);
|
||||
assert!(issues.is_empty(), "{:?}", issues.iter().map(|i| &i.says).collect::<Vec<_>>());
|
||||
// a one-word card is held only to the word said right by it: "wirestock" 1.35 s earlier is another moment
|
||||
cues(&[run("Wirestock", 39.55)], &words, &mut issues, &mut passed);
|
||||
assert!(issues.is_empty(), "{:?}", issues.iter().map(|i| &i.says).collect::<Vec<_>>());
|
||||
// a real caption late by 0.4 s is still found
|
||||
cues(&[run("a Sora campaign", 39.7)], &words, &mut issues, &mut passed);
|
||||
assert_eq!(issues.len(), 1, "{:?}", issues.iter().map(|i| &i.says).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_colour_crossing_the_saturation_line_is_not_a_red_flash() {
|
||||
// one level of green moves the pixel across R/(R+G+B) = 0.8 and hardly changes its red at all
|
||||
let found = flash_samples(180, 60.0, |f, _, _, _| if f * 5 * 2 / 60 % 2 == 0 { [100, 49, 0] } else { [100, 50, 0] });
|
||||
assert_eq!(found, None);
|
||||
fn clipping_is_found_and_a_loud_clean_tone_isnt() {
|
||||
// a clean tone near full scale, then the same tone clamped (a limiter's flat tops), then pushed past full scale
|
||||
let loud = tone(3.0, &[(0.0, 3.0, -1.0)]);
|
||||
assert!(clipped(&loud).is_empty(), "{:?}", clipped(&loud));
|
||||
let clamped: Vec<f32> = loud.iter().map(|v| (v * 10.0).clamp(-0.3, 0.3)).collect();
|
||||
assert_eq!(clipped(&clamped).len(), 1);
|
||||
let over: Vec<f32> = loud.iter().map(|v| (v * 2.0).clamp(-1.0, 1.0)).collect();
|
||||
assert_eq!(clipped(&over).len(), 1);
|
||||
// one transient hitting full scale once isn't clipping
|
||||
let mut once = tone(3.0, &[(0.0, 3.0, -20.0)]);
|
||||
once[SR] = 1.0;
|
||||
assert!(clipped(&once).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropout_is_found_and_a_faded_pause_isnt() {
|
||||
// a bed at -20 dBFS with 0.6 s cut out of it, as the bootstrap's dropout does
|
||||
let mut cut = tone(4.0, &[(0.0, 4.0, -20.0)]);
|
||||
cut[(1.7 * SR as f64) as usize..(2.3 * SR as f64) as usize].iter_mut().for_each(|v| *v = 0.0);
|
||||
let found = dropouts(&cut);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert!((found[0].0 - 1.7).abs() < 0.02, "{found:?}");
|
||||
// a pause that fades out over 300 ms and back in isn't one, nor a sound that stops and stays stopped
|
||||
let gain = |t: f32| ((1.7 - t) / 0.3).max((t - 2.3) / 0.3).clamp(0.0, 1.0);
|
||||
let paused: Vec<f32> = tone(4.0, &[(0.0, 4.0, -20.0)]).into_iter().enumerate().map(|(i, v)| v * gain(i as f32 / SR as f32)).collect();
|
||||
assert!(dropouts(&paused).is_empty(), "{:?}", dropouts(&paused));
|
||||
assert!(dropouts(&tone(4.0, &[(0.0, 2.0, -20.0)])).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flash_frame_is_found_and_a_cut_or_a_fade_isnt() {
|
||||
let mut shot = vec![0.5f32; 60];
|
||||
shot[30] = 0.0;
|
||||
assert_eq!(flash_frames(&shot, 30.0).len(), 1);
|
||||
shot[31] = 0.0;
|
||||
assert_eq!(flash_frames(&shot, 30.0).len(), 1, "two frames are one flash");
|
||||
let cut: Vec<f32> = (0..60).map(|i| if i < 30 { 0.6 } else { 0.1 }).collect();
|
||||
assert!(flash_frames(&cut, 30.0).is_empty());
|
||||
let fade: Vec<f32> = (0..60).map(|i| 0.6 * (1.0 - i as f32 / 59.0)).collect();
|
||||
assert!(flash_frames(&fade, 30.0).is_empty());
|
||||
// a white frame, too
|
||||
let mut white = vec![0.3f32; 20];
|
||||
white[10] = 1.0;
|
||||
assert_eq!(flash_frames(&white, 30.0)[0].0, 10.0 / 30.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn things_found_are_findings_and_an_unknown_rule_is_not() {
|
||||
let p = std::env::temp_dir().join(format!("raea-check-things-{}.json", std::process::id()));
|
||||
let found = r#"{"issues": [{"rule": "floating", "p": 2, "at": 1.5, "to": 3.0, "says": "cup floats"}, {"rule": "made-up", "p": 0, "at": 0.0, "says": "x"}]}"#;
|
||||
std::fs::write(&p, found).unwrap();
|
||||
let (mut issues, mut passed) = (Vec::new(), Vec::new());
|
||||
things(p.to_str().unwrap(), &mut issues, &mut passed).unwrap();
|
||||
assert_eq!(issues.iter().map(|i| (i.rule, i.p, i.at)).collect::<Vec<_>>(), [("floating", 2, Some(1.5))]);
|
||||
std::fs::write(&p, r#"{"issues": []}"#).unwrap();
|
||||
things(p.to_str().unwrap(), &mut Vec::new(), &mut passed).unwrap();
|
||||
let _ = std::fs::remove_file(&p);
|
||||
assert_eq!(passed.len(), 1, "nothing found is a pass");
|
||||
}
|
||||
+29
-63
@@ -8,7 +8,8 @@ pub(crate) struct Run {
|
||||
pub(crate) from: f64,
|
||||
pub(crate) to: f64,
|
||||
pub(crate) box_: [f64; 4],
|
||||
/// its box on every frame it shows its whole text: a text the camera carries (a sign on a panning street) moves
|
||||
/// where its letters are on every frame it shows its whole text (the manifest's `ink`, else its box: a centred line in
|
||||
/// a full-width box is nowhere near x = 0, #89): a text the camera carries (a sign on a panning street) moves
|
||||
/// through the frame's edges and zones, which only counts against it when no frame shows it clear
|
||||
pub(crate) boxes: Vec<[f64; 4]>,
|
||||
pub(crate) color: String,
|
||||
@@ -61,7 +62,8 @@ pub(crate) fn text_runs(manifest: &Value) -> Vec<Run> {
|
||||
let mut next = Vec::new();
|
||||
for x in shown {
|
||||
let text = x["text"].as_str().unwrap_or("").trim().to_string();
|
||||
let b = x["box"].as_array().map(|b| [0, 1, 2, 3].map(|i| b.get(i).and_then(Value::as_f64).unwrap_or(0.0))).unwrap_or([0.0; 4]);
|
||||
let quad = |k: &str| x[k].as_array().map(|b| [0, 1, 2, 3].map(|i| b.get(i).and_then(Value::as_f64).unwrap_or(0.0)));
|
||||
let (b, ink) = (quad("box").unwrap_or([0.0; 4]), quad("ink"));
|
||||
let k = key(&text);
|
||||
let found = open.iter().position(|r| {
|
||||
let rk = key(&r.text);
|
||||
@@ -77,7 +79,7 @@ pub(crate) fn text_runs(manifest: &Value) -> Vec<Run> {
|
||||
if text.len() >= r.text.len() {
|
||||
r.text = text;
|
||||
r.box_ = b;
|
||||
r.boxes.push(b);
|
||||
r.boxes.push(ink.unwrap_or(b));
|
||||
}
|
||||
r.to = t + 1.0 / fps;
|
||||
r.color = x["color"].as_str().unwrap_or("rgb(255, 255, 255)").to_string();
|
||||
@@ -169,7 +171,9 @@ pub(crate) fn text_rules(runs: &[Run], heard: Option<&[Word]>, w: f64, h: f64, s
|
||||
issues.push(Issue { rule: "clipped", p: 0, at: Some(r.from), says: format!("{q} runs off the frame (box {x:.0},{y:.0} {bw:.0}x{bh:.0} in {w:.0}x{h:.0}); fit it or break the line") });
|
||||
} else if r.boxes.iter().all(zoned) {
|
||||
unsafe_ += 1;
|
||||
issues.push(Issue { rule: "safe-area", p: 1, at: Some(r.from), says: format!("{q} sits in the app's UI zone (keep {zt:.0} px top, {zb:.0} bottom, {zl:.0} left, {zr:.0} right clear)") });
|
||||
let [ix, iy, iw, ih] = *r.boxes.last().unwrap_or(&r.box_);
|
||||
let edge = if iy < zt { format!("the top (keep {zt:.0} px clear)") } else if iy + ih > h - zb { format!("the bottom (keep {zb:.0} px clear)") } else if ix < zl { format!("the left (keep {zl:.0} px clear)") } else { format!("the right (keep {zr:.0} px clear)") };
|
||||
issues.push(Issue { rule: "safe-area", p: 1, at: Some(r.from), says: format!("{q} sits in the app's UI zone at {edge}: its {} {ix:.0},{iy:.0} {iw:.0}x{ih:.0} in {w:.0}x{h:.0}", if r.boxes.last() == Some(&r.box_) { "box" } else { "letters" }) });
|
||||
}
|
||||
let words = r.text.split_whitespace().count() as f64;
|
||||
let need = (0.3 * words).max(1.0);
|
||||
@@ -195,20 +199,6 @@ pub(crate) fn quote(s: &str) -> String {
|
||||
format!("\u{201c}{s}\u{201d}")
|
||||
}
|
||||
|
||||
pub(crate) fn rgb_of(css: &str) -> [f64; 3] {
|
||||
let n: Vec<f64> = css.split(|c: char| !(c.is_ascii_digit() || c == '.')).filter(|s| !s.is_empty()).filter_map(|s| s.parse().ok()).collect();
|
||||
[n.first().copied().unwrap_or(255.0), n.get(1).copied().unwrap_or(255.0), n.get(2).copied().unwrap_or(255.0)]
|
||||
}
|
||||
|
||||
/// relative luminance (WCAG) of an sRGB colour 0-255
|
||||
pub(crate) fn lum([r, g, b]: [f64; 3]) -> f64 {
|
||||
let c = |v: f64| {
|
||||
let v = v / 255.0;
|
||||
if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
|
||||
};
|
||||
0.2126 * c(r) + 0.7152 * c(g) + 0.0722 * c(b)
|
||||
}
|
||||
|
||||
/// Caption contrast: at each text's middle frame, the pixels behind it against its colour, at least 3:1. The pixels
|
||||
/// behind are the half of the box least like the text.
|
||||
pub(crate) fn contrast(video: &str, runs: &[Run], w: f64, h: f64, probe: &Probe, issues: &mut Vec<Issue>, passed: &mut Vec<String>) {
|
||||
@@ -217,29 +207,13 @@ pub(crate) fn contrast(video: &str, runs: &[Run], w: f64, h: f64, probe: &Probe,
|
||||
let mut measured = 0;
|
||||
for r in runs.iter().filter(|r| r.size >= 20.0).take(80) {
|
||||
let [x, y, bw, bh] = r.box_;
|
||||
// even sizes and offsets: the decoder's 4:2:0 frame crops to them
|
||||
let (cx, cy, cw, ch) = ((x * sx).max(0.0) as u32 & !1, (y * sy).max(0.0) as u32 & !1, ((bw * sx) as u32).max(2) & !1, ((bh * sy) as u32).max(2) & !1);
|
||||
if cx + cw > probe.w as u32 || cy + ch > probe.h as u32 {
|
||||
let crop = [(x * sx).max(0.0) as u32, (y * sy).max(0.0) as u32, (bw * sx) as u32, (bh * sy) as u32];
|
||||
if crop[0] + crop[2] > probe.w as u32 || crop[1] + crop[3] > probe.h as u32 {
|
||||
continue;
|
||||
}
|
||||
let t = (r.from + r.to) / 2.0;
|
||||
let Ok(out) = Command::new("ffmpeg")
|
||||
.args(["-v", "error", "-ss", &format!("{t:.3}"), "-i", video, "-frames:v", "1", "-vf", &format!("crop={cw}:{ch}:{cx}:{cy}"), "-f", "rawvideo", "-pix_fmt", "rgb24", "-"])
|
||||
.output()
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if out.stdout.len() < (cw * ch * 3) as usize {
|
||||
continue;
|
||||
}
|
||||
let text = lum(rgb_of(&r.color));
|
||||
let mut ls: Vec<f64> = out.stdout.chunks_exact(3).map(|p| lum([p[0] as f64, p[1] as f64, p[2] as f64])).collect();
|
||||
ls.sort_by(|a, b| (b - text).abs().total_cmp(&(a - text).abs()));
|
||||
let behind = &ls[..ls.len() / 2];
|
||||
let mut sorted = behind.to_vec();
|
||||
sorted.sort_by(f64::total_cmp);
|
||||
let bg = sorted[sorted.len() / 2];
|
||||
let ratio = (text.max(bg) + 0.05) / (text.min(bg) + 0.05);
|
||||
// the same measure `raea world` joins to a text from its render (raea-sys-measure, DR2)
|
||||
let Some(ratio) = raea_sys_measure::contrast(std::path::Path::new(video), t, crop, &r.color) else { continue };
|
||||
measured += 1;
|
||||
if ratio < 3.0 {
|
||||
low += 1;
|
||||
@@ -251,35 +225,18 @@ pub(crate) fn contrast(video: &str, runs: &[Run], w: f64, h: f64, probe: &Probe,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Word {
|
||||
pub(crate) text: String,
|
||||
pub(crate) start: f64,
|
||||
/// when the word ends, in seconds (its start when the transcript doesn't say)
|
||||
pub(crate) end: f64,
|
||||
}
|
||||
/// A transcript's word: its text, start and end in seconds (its end is its start when the transcript doesn't say).
|
||||
pub(crate) use raea_core_facts::Word;
|
||||
|
||||
/// raea's transcript shape (an array of {text|word, start|from|start_ms, …}), or a flat array of {w, t}
|
||||
/// A transcript's words: {text, start} in seconds (or t, or start_ms), or {text, from} in frames at `fps`, as the app's
|
||||
/// words.json and `raea render --words` have them.
|
||||
/// A transcript's words (raea_core_facts::transcript_words: {text, start} in seconds, or t, start_ms, or {text, from}
|
||||
/// in frames at `fps`), as the app's words.json and `raea render --words` have them.
|
||||
pub(crate) fn transcript(path: &str, fps: f64) -> R<Vec<Word>> {
|
||||
let v: Value = serde_json::from_str(&std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"))?).map_err(|e| format!("{path}: {e}"))?;
|
||||
let list = v.as_array().ok_or_else(|| format!("{path}: expected an array of words ({{text, start}} in seconds or {{text, from}} in frames)"))?;
|
||||
Ok(list
|
||||
.iter()
|
||||
.filter_map(|w| {
|
||||
let text = w.get("text").or_else(|| w.get("word")).or_else(|| w.get("w"))?.as_str()?.to_string();
|
||||
// the time keys a transcript may use, each with what turns it into seconds
|
||||
let secs = |keys: &[(&str, f64)]| keys.iter().find_map(|(k, to_s)| Some(w.get(*k)?.as_f64()? * to_s));
|
||||
let start = secs(&[("start", 1.0), ("t", 1.0), ("a", 1.0), ("start_ms", 0.001), ("from", 1.0 / fps)])?;
|
||||
let end = secs(&[("end", 1.0), ("b", 1.0), ("end_ms", 0.001), ("to", 1.0 / fps)]).unwrap_or(start);
|
||||
Some(Word { text, start, end })
|
||||
})
|
||||
.collect())
|
||||
v.as_array().ok_or_else(|| format!("{path}: expected an array of words ({{text, start}} in seconds or {{text, from}} in frames)"))?;
|
||||
Ok(raea_core_facts::transcript_words(&v, fps))
|
||||
}
|
||||
|
||||
pub(crate) fn norm(s: &str) -> String {
|
||||
s.chars().filter(|c| c.is_alphanumeric()).collect::<String>().to_lowercase()
|
||||
}
|
||||
pub(crate) use raea_core_facts::word_key as norm;
|
||||
|
||||
pub(crate) const SMALL: [&str; 24] = ["the", "and", "you", "your", "for", "with", "that", "this", "its", "it's", "are", "was", "our", "out", "from", "into", "then", "than", "but", "not", "all", "can", "has", "have"];
|
||||
|
||||
@@ -291,12 +248,21 @@ pub(crate) fn cues(runs: &[Run], words: &[Word], issues: &mut Vec<Issue>, passed
|
||||
for r in runs {
|
||||
let shown: Vec<String> = r.text.split_whitespace().map(norm).filter(|t| !t.is_empty()).collect();
|
||||
let Some((k, i)) = shown.iter().enumerate().filter(|(_, t)| t.len() >= 3 && !SMALL.contains(&t.as_str())).find_map(|(k, t)| {
|
||||
words.iter().enumerate().filter(|(_, w)| norm(&w.text) == *t && (w.start - r.from).abs() <= 2.0).min_by(|(_, a), (_, b)| (a.start - r.from).abs().total_cmp(&(b.start - r.from).abs())).map(|(i, _)| (k, i))
|
||||
// a one-word card matches only a word said right by it: the same word said 2 s earlier is another moment
|
||||
let near = if shown.len() == 1 { 0.75 } else { 2.0 };
|
||||
words.iter().enumerate().filter(|(_, w)| norm(&w.text) == *t && (w.start - r.from).abs() <= near).min_by(|(_, a), (_, b)| (a.start - r.from).abs().total_cmp(&(b.start - r.from).abs())).map(|(i, _)| (k, i))
|
||||
}) else {
|
||||
continue;
|
||||
};
|
||||
// back over the words the text shows before it, while the voice says them in the same order just before
|
||||
let back = (1..=k.min(i)).take_while(|&n| norm(&words[i - n].text) == shown[k - n]).last().unwrap_or(0);
|
||||
// a caption says what the voice says: at least half its words, in order, around the anchor. A card that only
|
||||
// shares one word with another line ("Wirestock x OpenAI Sora" against "At Wirestock, I worked on...") isn't
|
||||
// a caption of it, and holding it to that word's time was a false P1
|
||||
let fwd = (1..).take_while(|&n| k + n < shown.len() && i + n < words.len() && norm(&words[i + n].text) == shown[k + n]).last().unwrap_or(0);
|
||||
if (back + 1 + fwd) * 2 < shown.len() {
|
||||
continue;
|
||||
}
|
||||
let w = &words[i - back];
|
||||
let tok = norm(&w.text);
|
||||
checked += 1;
|
||||
|
||||
@@ -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,378 @@
|
||||
//! `raea check PROJECT|EDIT.tsx` (docs/direction.feature DR4): every check that applies, run over each
|
||||
//! composition's worlds. The rules come from raea's floor, the person's taste (and the workspace's), and the
|
||||
//! workspace's and the project's controllers; each is one of raea's named checks (systems.rs) or a project's TS check
|
||||
//! (ts.rs), and where it was written changes nothing about how it runs. A check that needs a render runs on the
|
||||
//! composition's newest render; with none, it waits, and the command says what for. `raea check VIDEO.mp4` is the
|
||||
//! floor alone (apps/check).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use raea_core_brief::{controller, taste};
|
||||
use raea_core_facts::{finding, record, Facts, Finding, Level, Rule, Shot};
|
||||
use raea_runtime_bundle::flag;
|
||||
use raea_runtime_world::{Ask, Render};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use crate::systems::{self, Frames};
|
||||
use crate::ts;
|
||||
|
||||
type R<T> = Result<T, String>;
|
||||
|
||||
pub const USAGE: &str = "raea check [PROJECT|EDIT.tsx] [--composition ID] [--only ID] [--taste T] [--render OUT | --no-render] [--json] (every check that applies to each composition, over its frames: raea's floor on its newest render, the person's taste, the workspace's and the project's rules (a controller's rule fields: one of raea's checks by name, or a project's .ts check); what needs a render and has none waits, and says so)";
|
||||
|
||||
/// The flags raea check takes with a value (its own, and the floor's on a video).
|
||||
const TAKES: [&str; 10] = ["--composition", "--only", "--taste", "--render", "--manifest", "--words", "--perception", "--shape", "--platform", "-o"];
|
||||
|
||||
/// What the CLI lends `raea check`: its TS evaluator and headless run, and the taste kinds a mode needs (as `raea
|
||||
/// context` reads the person's taste).
|
||||
pub struct Host {
|
||||
pub ts: ts::Host,
|
||||
pub kinds: fn(&str) -> &'static [&'static str],
|
||||
}
|
||||
|
||||
/// The person's taste folder: RAEA_TASTE, else ~/.raea/taste.
|
||||
pub fn taste_dir() -> Option<PathBuf> {
|
||||
std::env::var_os("RAEA_TASTE").map(PathBuf::from).or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".raea/taste")))
|
||||
}
|
||||
|
||||
/// The .ts files `--taste` names: the file, or every .ts in the folder. A file named under the person's taste folder
|
||||
/// that isn't there yet is a note, not a refusal: the skill prescribes --taste on that folder's own taste file, and a
|
||||
/// machine with none yet should still check (#89); any other missing path is left to the reader to refuse.
|
||||
pub fn taste_files(args: &[String]) -> Vec<PathBuf> {
|
||||
let Some(t) = flag(args, "--taste").map(PathBuf::from) else { return vec![] };
|
||||
if t.extension().is_some_and(|x| x == "ts") {
|
||||
let home = taste_dir().map(std::path::absolute).and_then(Result::ok);
|
||||
if !t.is_file() && t.parent().map(std::path::absolute).and_then(Result::ok) == home {
|
||||
eprintln!("note: no taste yet ({} isn't there); checking without it", t.display());
|
||||
return vec![];
|
||||
}
|
||||
return vec![t];
|
||||
}
|
||||
let mut v: Vec<PathBuf> = std::fs::read_dir(&t).into_iter().flatten().filter_map(|e| e.ok().map(|e| e.path())).filter(|f| f.extension().is_some_and(|x| x == "ts")).collect();
|
||||
v.sort();
|
||||
v
|
||||
}
|
||||
|
||||
/// The taste files a project is held to: `--taste`'s when given, else the person's taste.ts (RAEA_TASTE, or
|
||||
/// ~/.raea/taste) and the kinds its brief's modes need, then the workspace's house rules.
|
||||
fn tastes(project: &Path, given: Vec<PathBuf>, host: &Host) -> Vec<PathBuf> {
|
||||
if !given.is_empty() {
|
||||
return given;
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
if let Some(dir) = taste_dir().filter(|d| d.join("taste.ts").is_file()) {
|
||||
out.push(dir.join("taste.ts"));
|
||||
let brief: Value = (host.ts.eval)(&project.join("brief.ts")).ok().and_then(|j| serde_json::from_str(&j).ok()).unwrap_or_default();
|
||||
for m in brief["mode"].as_array().into_iter().flatten().filter_map(Value::as_str) {
|
||||
for f in (host.kinds)(&m.trim().to_ascii_lowercase()).iter().map(|k| dir.join(format!("{k}.ts"))) {
|
||||
if f.is_file() && !out.contains(&f) {
|
||||
out.push(f);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out.extend(record::up(project, ".raea/workspace").map(|ws| ws.join("taste.ts")).filter(|f| f.is_file()));
|
||||
out
|
||||
}
|
||||
|
||||
/// One rule as it runs: a named check, or a project's check file's declaration.
|
||||
enum How {
|
||||
Named(systems::Named),
|
||||
File(ts::Meta),
|
||||
}
|
||||
|
||||
/// Every rule `project` is held to (`given`: `--taste`'s files) with its notes' asks (DR6), the notes, and a finding
|
||||
/// for each file of rules or note raea couldn't read.
|
||||
fn rules(project: &Path, given: Vec<PathBuf>, host: &Host) -> (Vec<Rule>, Vec<Finding>, Vec<raea_app_notes::Kept>) {
|
||||
let (mut out, mut bad) = held(project, given, host);
|
||||
let notes = raea_app_notes::read(project, host.ts.eval);
|
||||
let (asks, unread) = raea_app_notes::check::rules(project, ¬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| (raea_app_registry::shared_dir(w, "controllers"), "workspace")).chain([(project.join("controllers"), "project")]) {
|
||||
// a workspace's own folder is its project's too: read once
|
||||
if scope == "project" && ws.as_deref() == Some(project) {
|
||||
continue;
|
||||
}
|
||||
let mut files: Vec<PathBuf> = std::fs::read_dir(&dir).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "ts")).collect();
|
||||
files.sort();
|
||||
for f in files {
|
||||
match (host.ts.eval)(&f).and_then(|j| controller::of_json(&j)) {
|
||||
Ok(c) => out.extend(Rule::of_controller(&c, &dir, &format!("{scope} {}", name(&f)))),
|
||||
Err(e) => bad.push(Finding::new("controller", Level::Error, format!("raea can't read it: {e}"), "raea check").about(name(&f), None)),
|
||||
}
|
||||
}
|
||||
}
|
||||
(out, bad)
|
||||
}
|
||||
|
||||
/// The compositions `target` names: each (its file, its id when the file registers several).
|
||||
fn compositions(target: &Path, args: &[String]) -> R<Vec<(PathBuf, Option<String>)>> {
|
||||
let one = flag(args, "--composition");
|
||||
let (dir, file) = if target.is_dir() { (target.to_path_buf(), None) } else { (target.parent().unwrap_or(Path::new(".")).to_path_buf(), Some(target.canonicalize().map_err(|e| format!("{}: {e}", target.display()))?)) };
|
||||
let reg = raea_app_registry::scan(&dir, &[]);
|
||||
let mut out: Vec<(PathBuf, Option<String>)> = Vec::new();
|
||||
for c in ®.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()]));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
[package]
|
||||
name = "raea-app-fingerprint"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "`raea fingerprint` (docs/fingerprint.feature FP3a): new, bootstrap, teach, score and report, run by a resident service on localhost that keeps the encoders loaded"
|
||||
|
||||
[dependencies]
|
||||
# the taxonomy, evidence and heads
|
||||
raea-sys-fingerprint = { path = "../../systems/fingerprint" }
|
||||
# scoring and the sheet, which one judges a piece, diff and profiles
|
||||
raea-sys-fingerprint-use = { path = "../../systems/fingerprint-use" }
|
||||
raea-sys-fingerprint-things = { path = "../../systems/fingerprint-things" }
|
||||
# the encoders and the columns they make
|
||||
raea-sys-columns = { path = "../../systems/columns" }
|
||||
# raea check's floor on the file: its findings go in the summary, and a check wins over a head (FP4c)
|
||||
raea-app-check = { path = "../check" }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
anyhow = "1"
|
||||
# the draws of FP0b's few-shot curves, seeded (bootstrap.rs)
|
||||
fastrand = "2"
|
||||
@@ -0,0 +1,86 @@
|
||||
//! Approvals are positives (docs/fingerprint.feature FP6a): an approved cut, a picture lock, a publish or a golden
|
||||
//! reference says every moment of it is clean on every axis, except where the person left a note. `raea fingerprint
|
||||
//! approve FILE... [--project P]` adds a clean row on every axis ("*") for each 2 s window of each file, skipping the
|
||||
//! windows within 2 s of a pinned note on that file in its project's feed (.raea/feed/*.json), since a note there may
|
||||
//! name a defect. Notes aren't read into labels here; that is FP5a.
|
||||
|
||||
use crate::bootstrap::WIN;
|
||||
use crate::flag;
|
||||
use anyhow::{Result, anyhow};
|
||||
use raea_sys_columns::Encoders;
|
||||
use raea_sys_fingerprint::evidence::{Row, features};
|
||||
use raea_sys_fingerprint::folder::Folder;
|
||||
use raea_sys_fingerprint::taxonomy::Fingerprint;
|
||||
use std::path::Path;
|
||||
|
||||
/// The seconds a note was pinned at on `file`, from every post in its project's feed that shows a file of that name
|
||||
pub(crate) fn noted(file: &Path) -> Vec<f64> {
|
||||
let Some(name) = file.file_name().and_then(|n| n.to_str()) else { return Vec::new() };
|
||||
let Some(feed) = file.ancestors().map(|d| d.join(".raea/feed")).find(|d| d.is_dir()) else { return Vec::new() };
|
||||
let mut at = Vec::new();
|
||||
for e in std::fs::read_dir(feed).into_iter().flatten().flatten() {
|
||||
let Ok(text) = std::fs::read_to_string(e.path()) else { continue };
|
||||
let Ok(post) = serde_json::from_str::<serde_json::Value>(&text) else { continue };
|
||||
let shows = post["media"].as_array().into_iter().flatten().any(|m| m["path"].as_str().is_some_and(|p| p.ends_with(name)));
|
||||
if shows {
|
||||
at.extend(post["notes"].as_array().into_iter().flatten().filter_map(|n| n["pin"]["t"].as_f64()));
|
||||
}
|
||||
}
|
||||
at
|
||||
}
|
||||
|
||||
/// The windows an approval labels clean: every WIN seconds of the piece, away from its notes
|
||||
pub(crate) fn windows(dur: f64, notes: &[f64]) -> Vec<(f64, f64)> {
|
||||
let n = (dur / WIN).floor() as usize;
|
||||
(0..n).map(|i| (i as f64 * WIN, (i + 1) as f64 * WIN)).filter(|(a, b)| !notes.iter().any(|t| *t > a - WIN && *t < b + WIN)).collect()
|
||||
}
|
||||
|
||||
pub(crate) fn approve(enc: &mut Encoders, dir: &Folder, fp: &Fingerprint, args: &[String], cwd: &Path, project: impl Fn(&Path) -> String) -> Result<(String, usize)> {
|
||||
let files = crate::named(args, cwd)?;
|
||||
if files.is_empty() {
|
||||
return Err(anyhow!("which approved work? raea fingerprint approve FILE..."));
|
||||
}
|
||||
let mut l = dir.ledger()?;
|
||||
let mut out = String::new();
|
||||
let mut added = 0;
|
||||
for file in &files {
|
||||
let c = enc.columns(file)?;
|
||||
// an approval given again replaces the last one for that media
|
||||
l.retain(|r| !(r.source == "approval" && r.media == c.media));
|
||||
let notes = noted(file);
|
||||
let w = windows(c.dur, ¬es);
|
||||
for (a, b) in &w {
|
||||
let row = Row {
|
||||
media: c.media.clone(),
|
||||
a: *a,
|
||||
b: *b,
|
||||
axis: "*".into(),
|
||||
bad: false,
|
||||
weight: 1.0,
|
||||
who: fp.who.clone().unwrap_or_else(|| "me".into()),
|
||||
source: "approval".into(),
|
||||
project: flag(args, "--project").map_or_else(|| project(file), str::to_string),
|
||||
kind: None,
|
||||
region: None,
|
||||
words: None,
|
||||
at: 0,
|
||||
pin: None,
|
||||
};
|
||||
l.push(row, &features(&c, *a, *b));
|
||||
}
|
||||
added += w.len();
|
||||
out += &format!("approved {}: {} clean windows on every axis{}\n", file.display(), w.len(), if notes.is_empty() { String::new() } else { format!(", {} noted moments left out", notes.len()) });
|
||||
}
|
||||
dir.write_ledger(&l)?;
|
||||
Ok((out, added))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn an_approval_leaves_out_the_windows_near_a_note() {
|
||||
assert_eq!(super::windows(9.0, &[]), vec![(0.0, 2.0), (2.0, 4.0), (4.0, 6.0), (6.0, 8.0)]);
|
||||
// a note at 5 s: the windows within 2 s of it go
|
||||
assert_eq!(super::windows(12.0, &[5.0]), vec![(0.0, 2.0), (8.0, 10.0), (10.0, 12.0)]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
//! The bootstrap (FP4a, FP4b): known defects put into windows of the person's own real work, so the mechanical axes
|
||||
//! learn from labels by construction, and the cheats each must still catch. Each source gives `per` 2 s windows
|
||||
//! from 0.5 s to its end less 2.5 s (FP0b's protocol); each window gives a clean row ("*"), a row per picture and
|
||||
//! sound defect, and a row per cheat. Only what the damage changed is embedded again: a freeze reuses the first
|
||||
//! frame's vector, a flash re-embeds one frame, a sound defect leaves the picture alone.
|
||||
//!
|
||||
//! Then it measures what FP0b measured, in Rust: each axis's AUC from k = 4, 16 and 32 labelled windows a class, held
|
||||
//! out by source (5 folds x 5 draws, the scaler fit on every plain row of the training sources), on its own
|
||||
//! modality and on the one FP0b used; and each word head's AUC and catch rate with no labels (FP0g).
|
||||
|
||||
use raea_sys_fingerprint::evidence::{Ledger, Row, features, slice};
|
||||
use raea_sys_fingerprint::head::{Logistic, Scaler, auc, quantile, share_over};
|
||||
use raea_sys_fingerprint::taxonomy::Fingerprint;
|
||||
use raea_sys_fingerprint::train::{C, folds};
|
||||
use raea_sys_fingerprint::words::Words;
|
||||
use anyhow::Result;
|
||||
use raea_sys_columns::damage::{self, CHEATS, Noise, PICTURE, SOUND};
|
||||
use raea_sys_columns::media::{self, Rgb};
|
||||
use raea_sys_columns::window::Modality;
|
||||
use raea_sys_columns::{Columns, Encoders, FPS};
|
||||
use serde::Serialize;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// The window, seconds
|
||||
pub const WIN: f64 = 2.0;
|
||||
/// Sources shorter than this are skipped (FP0b's)
|
||||
pub const SHORTEST: f64 = 6.0;
|
||||
pub const KS: [usize; 3] = [4, 16, 32];
|
||||
|
||||
/// FP0b's AUC at k = 32 for each axis, on the modality it was measured on (docs/fingerprint.md FP0b, FP0g)
|
||||
pub const FP0B: [(&str, Modality, f64); 11] = [
|
||||
("blur", Modality::Picture, 1.00),
|
||||
("dark", Modality::Picture, 0.95),
|
||||
("glow", Modality::Picture, 0.80),
|
||||
("flash", Modality::Change, 0.97),
|
||||
("freeze", Modality::Change, 1.00),
|
||||
("noise", Modality::Events, 1.00),
|
||||
("dropout", Modality::Events, 0.97),
|
||||
("clip", Modality::Events, 0.98),
|
||||
("noise", Modality::Sound, 1.00),
|
||||
("dropout", Modality::Sound, 0.99),
|
||||
("clip", Modality::Sound, 1.00),
|
||||
];
|
||||
|
||||
#[derive(Debug, Default, Serialize)]
|
||||
pub struct Made {
|
||||
pub sources: usize,
|
||||
pub windows: usize,
|
||||
pub rows: usize,
|
||||
/// windows too quiet for a gap or clipping to change them, which get only the noise damage
|
||||
pub quiet: usize,
|
||||
pub skipped: Vec<String>,
|
||||
}
|
||||
|
||||
/// The rows a bootstrap makes, which the next bootstrap replaces
|
||||
fn made_here(r: &Row) -> bool {
|
||||
matches!(r.source.as_str(), "damage" | "cheat")
|
||||
}
|
||||
|
||||
/// A plain damage row on `axis` ("*" for the clean windows)
|
||||
fn damage_on(r: &Row, axis: &str) -> bool {
|
||||
r.source == "damage" && r.axis == axis
|
||||
}
|
||||
|
||||
/// The plain damage rows on `axis`
|
||||
fn damage_rows(l: &Ledger, axis: &str) -> Vec<usize> {
|
||||
(0..l.rows.len()).filter(|&i| damage_on(&l.rows[i], axis)).collect()
|
||||
}
|
||||
|
||||
/// Each defect of a sense as (kind, axis, source): the plain ones, then their disguises
|
||||
fn damages(sense: &[&'static str]) -> Vec<(&'static str, &'static str, &'static str)> {
|
||||
sense.iter().map(|k| (*k, *k, "damage")).chain(CHEATS.iter().filter(|c| sense.contains(&c.1)).map(|c| (c.0, c.1, "cheat"))).collect()
|
||||
}
|
||||
|
||||
/// Below this a window is near silence: a gap or clipping changes nothing, and a row saying it does teaches noise
|
||||
const QUIET_DB: f32 = -45.0;
|
||||
|
||||
/// The window's loudness in dB over all of it
|
||||
fn loudness(pcm: &[f32]) -> f32 {
|
||||
if pcm.is_empty() {
|
||||
return -100.0;
|
||||
}
|
||||
(10.0 * (pcm.iter().map(|x| x * x).sum::<f32>() / pcm.len() as f32).max(1e-10).log10()).max(-100.0)
|
||||
}
|
||||
|
||||
fn zeros_to(mut v: Vec<f32>, n: usize) -> Vec<f32> {
|
||||
v.resize(n, 0.0);
|
||||
v
|
||||
}
|
||||
|
||||
/// The picture columns of damaged frames, embedding only frames the damage changed
|
||||
fn picture_of(enc: &mut Encoders, clean: &[Rgb], sig: &[f32], look: &[f32], d: &[Rgb]) -> Result<(Vec<f32>, Vec<f32>)> {
|
||||
let (sd, ld) = (sig.len() / clean.len().max(1), look.len() / clean.len().max(1));
|
||||
let mut fresh: Vec<Rgb> = Vec::new();
|
||||
let mut from: Vec<Result<usize, usize>> = Vec::new();
|
||||
for f in d {
|
||||
match clean.iter().position(|c| c == f) {
|
||||
Some(j) => from.push(Ok(j)),
|
||||
None => {
|
||||
fresh.push(f.clone());
|
||||
from.push(Err(fresh.len() - 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
let (fs, fl) = if fresh.is_empty() { (Vec::new(), Vec::new()) } else { enc.picture(&fresh)? };
|
||||
let (mut s, mut l) = (Vec::with_capacity(sig.len()), Vec::with_capacity(look.len()));
|
||||
for f in from {
|
||||
let (ss, ll, j) = match f {
|
||||
Ok(j) => (sig, look, j),
|
||||
Err(k) => (&fs[..], &fl[..], k),
|
||||
};
|
||||
s.extend_from_slice(&ss[j * sd..(j + 1) * sd]);
|
||||
l.extend_from_slice(&ll[j * ld..(j + 1) * ld]);
|
||||
}
|
||||
Ok((s, l))
|
||||
}
|
||||
|
||||
/// The bootstrap's rows for `files` into the ledger, replacing any it made before. `say` hears each source's progress.
|
||||
pub fn rows(enc: &mut Encoders, who: &str, files: &[PathBuf], per: usize, l: &mut Ledger, say: &mut dyn FnMut(String)) -> Result<Made> {
|
||||
l.retain(|r| !made_here(r));
|
||||
let mut made = Made::default();
|
||||
let mut noise = Noise::new(0);
|
||||
for (n, file) in files.iter().enumerate() {
|
||||
let dur = media::duration(file).unwrap_or(0.0);
|
||||
if dur < SHORTEST {
|
||||
made.skipped.push(format!("{} ({dur:.1} s, under {SHORTEST} s)", file.display()));
|
||||
continue;
|
||||
}
|
||||
let sha = media::sha256(file)?;
|
||||
let frames = media::frames(file, FPS, 0.0, dur)?;
|
||||
let (p16, p48) = (media::sound(file, 16_000)?, media::sound(file, 48_000)?);
|
||||
made.sources += 1;
|
||||
for w in 0..per {
|
||||
let t = 0.5 + (dur - 3.0) * w as f64 / (per - 1).max(1) as f64;
|
||||
let i0 = (t * FPS).round() as usize;
|
||||
let Some(fr) = frames.get(i0..i0 + (WIN * FPS) as usize) else { continue };
|
||||
let cut = |p: &[f32], rate: f64| zeros_to(p.get((t * rate) as usize..).unwrap_or(&[]).iter().take((WIN * rate) as usize).copied().collect(), (WIN * rate) as usize);
|
||||
let (w16, w48) = (cut(&p16, 16_000.0), cut(&p48, 48_000.0));
|
||||
let (sig, look) = enc.picture(fr)?;
|
||||
let (clap, yam) = enc.sound(&w16, &w48)?;
|
||||
let clean = Columns { media: sha.clone(), dur: WIN, sig, look, clap, yam, level: media::levels(&w16, 16_000), text: Vec::new() };
|
||||
let push = |l: &mut Ledger, c: &Columns, axis: &str, kind: &str, source: &str| {
|
||||
let r = Row {
|
||||
media: sha.clone(),
|
||||
a: t,
|
||||
b: t + WIN,
|
||||
axis: axis.into(),
|
||||
bad: axis != "*",
|
||||
weight: 1.0,
|
||||
who: who.into(),
|
||||
source: source.into(),
|
||||
project: sha[..12].to_string(),
|
||||
kind: Some(kind.into()),
|
||||
region: None,
|
||||
words: None,
|
||||
at: 0,
|
||||
pin: None,
|
||||
};
|
||||
l.push(r, &features(c, 0.0, WIN));
|
||||
};
|
||||
push(l, &clean, "*", "clean", "damage");
|
||||
for (kind, axis, source) in damages(&PICTURE) {
|
||||
let (sig, look) = picture_of(enc, fr, &clean.sig, &clean.look, &damage::picture(fr, kind))?;
|
||||
push(l, &Columns { sig, look, ..clean.clone() }, axis, kind, source);
|
||||
}
|
||||
let quiet = loudness(&w16) < QUIET_DB;
|
||||
made.quiet += quiet as usize;
|
||||
for (kind, axis, source) in damages(&SOUND).into_iter().filter(|s| !quiet || s.1 == "noise") {
|
||||
let (d16, d48) = (damage::sound(&w16, kind, 16_000, &mut noise), damage::sound(&w48, kind, 48_000, &mut noise));
|
||||
let (clap, yam) = enc.sound(&d16, &d48)?;
|
||||
push(l, &Columns { clap, yam, level: media::levels(&d16, 16_000), ..clean.clone() }, axis, kind, source);
|
||||
}
|
||||
made.windows += 1;
|
||||
}
|
||||
say(format!("source {}/{} {}: {} windows so far", n + 1, files.len(), file.display(), made.windows));
|
||||
}
|
||||
made.rows = l.rows.iter().filter(|r| made_here(r)).count();
|
||||
Ok(made)
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct Curve {
|
||||
pub axis: String,
|
||||
pub modality: Modality,
|
||||
/// AUC at each k
|
||||
pub k: BTreeMap<usize, f64>,
|
||||
/// FP0b's at k = 32 on this modality, and whether this run came within 0.03 of it or beat it
|
||||
pub fp0b: Option<f64>,
|
||||
pub holds: Option<bool>,
|
||||
}
|
||||
|
||||
fn sample(rng: &mut fastrand::Rng, from: &[usize], k: usize) -> Vec<usize> {
|
||||
let mut v = from.to_vec();
|
||||
rng.shuffle(&mut v);
|
||||
v.truncate(k);
|
||||
v
|
||||
}
|
||||
|
||||
/// FP0b's few-shot curve for one axis on one modality, from the bootstrap's rows
|
||||
pub fn curve(l: &Ledger, axis: &str, m: Modality, rng: &mut fastrand::Rng) -> Curve {
|
||||
let s = slice(m);
|
||||
let row = |i: usize| &l.features(i)[s.clone()];
|
||||
let plain = |i: &usize| l.rows[*i].source == "damage";
|
||||
let (clean, bad) = (damage_rows(l, "*"), damage_rows(l, axis));
|
||||
let projects = l.projects(&clean);
|
||||
let mut k_auc = BTreeMap::new();
|
||||
for k in KS {
|
||||
let mut aucs = Vec::new();
|
||||
for fold in folds(&projects) {
|
||||
let held = |i: &usize| fold.contains(&l.rows[*i].project);
|
||||
let base: Vec<&[f32]> = (0..l.rows.len()).filter(|i| plain(i) && !held(i)).map(row).collect();
|
||||
let sc = Scaler::fit(&base);
|
||||
let (tc, tb): (Vec<usize>, Vec<usize>) = (clean.iter().copied().filter(|i| !held(i)).collect(), bad.iter().copied().filter(|i| !held(i)).collect());
|
||||
if tc.len() < k || tb.len() < k {
|
||||
continue;
|
||||
}
|
||||
for _ in 0..5 {
|
||||
let (a, b) = (sample(rng, &tc, k), sample(rng, &tb, k));
|
||||
let x: Vec<&[f32]> = a.iter().chain(&b).map(|&i| row(i)).collect();
|
||||
let y: Vec<bool> = (0..2 * k).map(|i| i >= k).collect();
|
||||
let f = Logistic::fit(sc.clone(), &x, &y, None, C, true);
|
||||
let score = |v: &Vec<usize>| -> Vec<f32> { v.iter().filter(|i| held(i)).map(|&i| f.score(row(i))).collect() };
|
||||
aucs.push(auc(&score(&bad), &score(&clean)));
|
||||
}
|
||||
}
|
||||
let ok: Vec<f64> = aucs.into_iter().filter(|a| a.is_finite()).collect();
|
||||
if !ok.is_empty() {
|
||||
k_auc.insert(k, ok.iter().sum::<f64>() / ok.len() as f64);
|
||||
}
|
||||
}
|
||||
let fp0b = FP0B.iter().find(|(a, mm, _)| *a == axis && *mm == m).map(|x| x.2);
|
||||
let holds = fp0b.zip(k_auc.get(&32)).map(|(want, got)| *got >= want - 0.03);
|
||||
Curve { axis: axis.into(), modality: m, k: k_auc, fp0b, holds }
|
||||
}
|
||||
|
||||
/// Every mechanical axis's curve on its own modality and on FP0b's
|
||||
pub fn curves(fp: &Fingerprint, l: &Ledger) -> Vec<Curve> {
|
||||
let mut rng = fastrand::Rng::with_seed(1);
|
||||
let mut out = Vec::new();
|
||||
for axis in PICTURE.iter().chain(&SOUND) {
|
||||
let own = fp.axis(axis).map(|a| a.modality);
|
||||
let mut ms: Vec<Modality> = own.into_iter().chain(FP0B.iter().filter(|x| x.0 == *axis).map(|x| x.1)).collect();
|
||||
ms.dedup();
|
||||
for m in ms.into_iter().collect::<BTreeSet<_>>() {
|
||||
out.push(curve(l, axis, m, &mut rng));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct WordScore {
|
||||
pub axis: String,
|
||||
/// AUC, damaged against clean windows, with no labels
|
||||
pub auc: f64,
|
||||
/// the share of damaged windows over the score that flags 10% of clean ones
|
||||
pub caught: f64,
|
||||
/// each cheat's share over that same score
|
||||
pub cheats: BTreeMap<String, f64>,
|
||||
}
|
||||
|
||||
/// Each word head on the bootstrap's windows (FP0g)
|
||||
pub fn word_scores(l: &Ledger, words: &Words) -> Vec<WordScore> {
|
||||
let z = |i: usize, axis: &str| words.z(axis, l.features(i));
|
||||
let of = |axis: &str, pick: &dyn Fn(&Row) -> bool| -> Vec<f32> { l.rows.iter().enumerate().filter(|(_, r)| pick(r)).filter_map(|(i, _)| z(i, axis)).collect() };
|
||||
let mut out = Vec::new();
|
||||
for axis in PICTURE.iter().chain(&SOUND) {
|
||||
if !words.axes.iter().any(|w| w.0 == *axis) {
|
||||
continue;
|
||||
}
|
||||
let clean = of(axis, &|r| damage_on(r, "*"));
|
||||
let bad = of(axis, &|r| damage_on(r, axis));
|
||||
let thr = quantile(&clean, 0.9);
|
||||
let share = |v: &[f32]| share_over(v, thr);
|
||||
let cheats = CHEATS.iter().filter(|c| c.1 == *axis).map(|c| (c.0.to_string(), share(&of(axis, &|r| r.source == "cheat" && r.kind.as_deref() == Some(c.0))))).collect();
|
||||
out.push(WordScore { axis: axis.to_string(), auc: auc(&bad, &clean), caught: share(&bad), cheats });
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
//! `raea fingerprint` (docs/fingerprint.feature FP3a): a person's fingerprint made, bootstrapped, taught and used to
|
||||
//! score a piece. The encoders take seconds to load, so the verbs run in a resident service (`raea fingerprint
|
||||
//! serve`, serve.rs) that keeps them loaded: the first verb starts it, on localhost, and later verbs reach it in
|
||||
//! milliseconds (earshot's CLI reloads its models on every call, 20-40 s). It leaves after 30 idle minutes, or on
|
||||
//! `raea fingerprint stop`. RAEA_FINGERPRINT_HERE=1 runs a verb in this process instead.
|
||||
|
||||
mod approve;
|
||||
mod bootstrap;
|
||||
mod moving;
|
||||
mod notes;
|
||||
mod pairing;
|
||||
mod pick;
|
||||
mod postmortem;
|
||||
mod profiles;
|
||||
mod reembed;
|
||||
mod serve;
|
||||
mod things;
|
||||
mod verbs;
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
pub use serve::serve;
|
||||
|
||||
pub const USAGE: &str = "raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] [--kinds K,K] [--tags T,T] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint approve FILE... [--project P] | raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2] | raea fingerprint versions V1 V2... | raea fingerprint profile REFS... --as NAME [--against LIST] | raea fingerprint score FILE [--was OLD] [--json] [--sheet out.png] [--timeline] [--profile NAME] | raea fingerprint report [--json] | raea fingerprint which [PATH] [--json] | raea fingerprint use NAME [--in project|workspace] [PATH] | raea fingerprint diff A B [--json] | raea fingerprint share NAME [--in project|workspace] [PATH] | raea fingerprint reembed PLACE... | raea fingerprint read PROJECT [--by kimi|claude] | raea fingerprint readings [PROJECT] [--ask N] [--tally] | raea fingerprint learn-notes [PROJECT] | raea fingerprint move [--fp CHILD] [--to PARENT] [--axis A] [--source S] [--project P] | raea fingerprint postmortem [PROJECT] [--ask N] [--tally] | raea fingerprint things FILE [--project P] [--json] | raea fingerprint stop [--fp NAME] (a person's sense of good work as axes with small heads over on-device encoders, docs/fingerprint.md: new makes ~/.raea/fingerprints/NAME with raea's base taxonomy in fingerprint.ts (or FP's axes with --extends), what it's for, the kinds of piece and project tags it judges, and every axis scoring from its words; bootstrap puts known defects into windows of real work and trains the mechanical axes, held out by source, and patch heads that say where in the frame a picture defect is; teach adds a label at a moment; approve makes approved work clean on every axis, away from its notes; pair says one moment is better than another on an axis (a pick, a hand edit); versions makes weak pairs of noted moments the next version changed; score prints the moments it expects a note on first (where in the frame, and the layers there, when its patch head points held out), then every axis per window with --json, a sheet PNG with --sheet, or the piece second by second in words with --timeline, and with --was OLD whether each of OLD's gating flags is fixed, still there, or looks disguised (nearer the axis's disguised defects than clean work); profile takes the ranges of work you admire (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside them, where and which way; report says each head's held-out score, labels, cheats, gate and what it can't judge; which says the one that judges a piece (its project's, its workspace's, then yours) and why, use pins one there, diff lists the axes two fingerprints rank the same evidence most differently on, and share copies one's taxonomy and evidence (no heads, no media) into a project or workspace for its team; reembed moves a fingerprint's evidence to this machine's encoders, re-embedding the rows whose media it finds; read has a fresh kimi or claude session read a project's pinned notes into kinds and axes, readings puts them to you to check and tallies your answers, and learn-notes makes the defects and praise evidence once you've agreed with 45 kinds and 40 axes in 50, each project's in the fingerprint that judges it; move takes a child's own labels (by axis, source or project) up into a fingerprint it extends, which never reads them otherwise; postmortem scores every version in a project's feed and asks you at most ten yes/no questions in the app, each with its moment playing, where the fingerprint disagrees with your labels or is least sure, and --tally makes your answers evidence and says how each head's held-out score moved; things finds a piece's shots, its things (a render's layers, and the marks drawn on its notes) with their depth, and the camera's path, and says where a thing floats, two pass through each other, the camera lurches mid-move or nothing is on screen, as JSON for `raea check --things` with --json)";
|
||||
|
||||
/// Evaluates a .ts file's default export to its JSON (the CLI's spec host)
|
||||
pub type Eval = fn(&Path) -> Result<String, String>;
|
||||
|
||||
/// The flags each verb takes, and whether each takes a value
|
||||
pub(crate) const FLAGS: [(&str, bool); 31] = [
|
||||
("--fp", true),
|
||||
("--was", true),
|
||||
("--to", true),
|
||||
("--source", true),
|
||||
("--kinds", true),
|
||||
("--tags", true),
|
||||
("--who", true),
|
||||
("--about", true),
|
||||
("--extends", true),
|
||||
("--from", true),
|
||||
("--per", true),
|
||||
("--axis", true),
|
||||
("--at", true),
|
||||
("--then", true),
|
||||
("--span", true),
|
||||
("--box", true),
|
||||
("--words", true),
|
||||
("--project", true),
|
||||
("--sheet", true),
|
||||
("--in", true),
|
||||
("--as", true),
|
||||
("--against", true),
|
||||
("--profile", true),
|
||||
("--by", true),
|
||||
("--ask", true),
|
||||
("--tally", false),
|
||||
("--bad", false),
|
||||
("--good", false),
|
||||
("--json", false),
|
||||
("--timeline", false),
|
||||
("--here", false),
|
||||
];
|
||||
|
||||
/// A flag's value
|
||||
pub(crate) fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> {
|
||||
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).map(String::as_str)
|
||||
}
|
||||
|
||||
pub(crate) fn has(args: &[String], name: &str) -> bool {
|
||||
args.iter().any(|a| a == name)
|
||||
}
|
||||
|
||||
/// A path as given, against the folder the verb ran in (an absolute one stays itself)
|
||||
pub(crate) fn at(cwd: &Path, p: &str) -> std::path::PathBuf {
|
||||
cwd.join(p)
|
||||
}
|
||||
|
||||
/// The files a verb names, against the folder it ran in
|
||||
pub(crate) fn named(args: &[String], cwd: &Path) -> anyhow::Result<Vec<std::path::PathBuf>> {
|
||||
Ok(words(args).map_err(anyhow::Error::msg)?.iter().map(|f| at(cwd, f)).collect())
|
||||
}
|
||||
|
||||
/// The files a list names, one a line against the list's own folder; blank lines and # lines are skipped
|
||||
pub(crate) fn listed(cwd: &Path, list: &str) -> anyhow::Result<Vec<std::path::PathBuf>> {
|
||||
use anyhow::Context;
|
||||
let list = at(cwd, list);
|
||||
let text = std::fs::read_to_string(&list).with_context(|| list.display().to_string())?;
|
||||
let base = list.parent().unwrap_or(cwd);
|
||||
Ok(text.lines().map(str::trim).filter(|l| !(l.is_empty() || l.starts_with('#'))).map(|l| at(base, l)).collect())
|
||||
}
|
||||
|
||||
/// The words that aren't flags or their values; an unknown flag is an error
|
||||
pub(crate) fn words(args: &[String]) -> Result<Vec<&str>, String> {
|
||||
let mut out = Vec::new();
|
||||
let mut it = args.iter();
|
||||
while let Some(a) = it.next() {
|
||||
match FLAGS.iter().find(|(f, _)| f == a) {
|
||||
Some((_, true)) => {
|
||||
it.next().ok_or_else(|| format!("{a} takes a value"))?;
|
||||
}
|
||||
Some(_) => {}
|
||||
None if a.starts_with("--") => return Err(format!("no flag {a}")),
|
||||
None => out.push(a.as_str()),
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// `raea fingerprint VERB ...`, printed; its exit code (1: the verb failed, 2: the command was wrong)
|
||||
pub fn cli(args: &[String], eval: Eval) -> i32 {
|
||||
let verb = match args.first().map(String::as_str) {
|
||||
None | Some("--help" | "-h" | "help") => {
|
||||
println!("{USAGE}");
|
||||
return 0;
|
||||
}
|
||||
Some(v) => v,
|
||||
};
|
||||
if let Err(e) = words(&args[1..]) {
|
||||
eprintln!("raea fingerprint: {e}\n{USAGE}");
|
||||
return 2;
|
||||
}
|
||||
match verb {
|
||||
"serve" => match serve(eval) {
|
||||
Ok(()) => 0,
|
||||
Err(e) => {
|
||||
eprintln!("raea fingerprint serve: {e:#}");
|
||||
1
|
||||
}
|
||||
},
|
||||
"report" => verbs::report_here(args),
|
||||
"which" => pick::which_here(&args[1..], &std::env::current_dir().unwrap_or_default()),
|
||||
"diff" => pick::diff_here(&args[1..]),
|
||||
"read" => notes::read_here(&args[1..], &std::env::current_dir().unwrap_or_default()),
|
||||
"readings" => notes::readings_here(&args[1..], &std::env::current_dir().unwrap_or_default()),
|
||||
"share" => pick::share_here(&args[1..], &std::env::current_dir().unwrap_or_default()),
|
||||
"use" => pick::use_here(&args[1..], &std::env::current_dir().unwrap_or_default()),
|
||||
"new" | "bootstrap" | "teach" | "approve" | "pair" | "versions" | "learn-notes" | "move" | "postmortem" | "things" | "reembed" | "profile" | "score" | "stop" => {
|
||||
let cwd = std::env::current_dir().unwrap_or_default();
|
||||
let here = has(args, "--here") || std::env::var_os("RAEA_FINGERPRINT_HERE").is_some();
|
||||
let (out, code) = if here { serve::here(args, &cwd, eval) } else { serve::call(args, &cwd) };
|
||||
if !out.is_empty() {
|
||||
println!("{}", out.trim_end());
|
||||
}
|
||||
code
|
||||
}
|
||||
v => {
|
||||
eprintln!("raea fingerprint: no verb {v}\n{USAGE}");
|
||||
2
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn the_usage_names_every_flag() {
|
||||
let missing: Vec<_> = super::FLAGS.iter().filter(|(f, _)| *f != "--here" && !super::USAGE.contains(f)).collect();
|
||||
assert!(missing.is_empty(), "raea fingerprint takes flags its usage doesn't name: {missing:?}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
//! `raea fingerprint move [--fp CHILD] [--to PARENT] [--axis A] [--source S] [--project P]` (docs/fingerprint.feature
|
||||
//! FP14d). A note or mark teaches the fingerprint that judged the piece, and a parent never reads a child's evidence
|
||||
//! (inherit.rs), so one client's taste doesn't move the person's own. Moving labels up is the person's call: the
|
||||
//! child's own rows that match leave its ledger for a fingerprint it extends (its nearest unless --to names one). A
|
||||
//! row on an axis the parent hasn't, or on one the child says otherwise, stays: in the parent it would mean something
|
||||
//! else.
|
||||
|
||||
use crate::{Eval, flag};
|
||||
use anyhow::{Result, anyhow, bail};
|
||||
use raea_sys_fingerprint::evidence::{Ledger, Row};
|
||||
use raea_sys_fingerprint::folder::Folder;
|
||||
use raea_sys_fingerprint::inherit;
|
||||
use raea_sys_fingerprint::taxonomy::Fingerprint;
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
/// The rows `pick` takes from `child` into `parent`; returns how many moved
|
||||
pub fn rows(child: &mut Ledger, parent: &mut Ledger, pick: &dyn Fn(&Row) -> bool) -> usize {
|
||||
let mut n = 0;
|
||||
for i in 0..child.rows.len() {
|
||||
if pick(&child.rows[i]) {
|
||||
parent.push(child.rows[i].clone(), child.features(i));
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
child.retain(|r| !pick(r));
|
||||
n
|
||||
}
|
||||
|
||||
/// The axes a row may carry into `parent`: the parent's own and inherited ones, less those the child overrides
|
||||
pub fn carried(parent: &Fingerprint, eval: Eval, over: &BTreeSet<String>) -> BTreeSet<String> {
|
||||
let full = inherit::axes(parent, &inherit::parents(parent, Some(eval)));
|
||||
full.axes.iter().map(|a| a.name.clone()).filter(|a| !over.contains(a)).chain(["*".to_string()]).collect()
|
||||
}
|
||||
|
||||
/// Moves the child's matching rows up and writes both ledgers; returns the parent's name and what it did
|
||||
pub(crate) fn up(dir: &Folder, child: &Fingerprint, args: &[String], eval: Eval) -> Result<(String, String)> {
|
||||
let (axis, source, project) = (flag(args, "--axis"), flag(args, "--source"), flag(args, "--project"));
|
||||
if axis.is_none() && source.is_none() && project.is_none() {
|
||||
bail!("say which labels: --axis A, --source S (note, teach, approval, pair, damage) or --project P");
|
||||
}
|
||||
let parents = inherit::parents(child, Some(eval));
|
||||
let (pdir, parent) = match flag(args, "--to") {
|
||||
Some(n) => parents.iter().find(|(_, p)| p.name == n).ok_or_else(|| anyhow!("{} doesn't extend {n}: labels only move up", child.name))?,
|
||||
None => parents.first().ok_or_else(|| anyhow!("{} extends nothing, so its labels have nowhere to move up to", child.name))?,
|
||||
};
|
||||
let keep = carried(parent, eval, &inherit::overrides(child, &parents));
|
||||
let wanted = |r: &Row| axis.is_none_or(|a| r.axis == a) && source.is_none_or(|s| r.source == s) && project.is_none_or(|p| r.project == p);
|
||||
let (mut lc, mut lp) = (dir.ledger()?, pdir.ledger()?);
|
||||
let stay = lc.rows.iter().filter(|r| wanted(r) && !keep.contains(&r.axis)).count();
|
||||
let n = rows(&mut lc, &mut lp, &|r| wanted(r) && keep.contains(&r.axis));
|
||||
if n == 0 && stay == 0 {
|
||||
bail!("none of {}'s own labels match", child.name);
|
||||
}
|
||||
pdir.write_ledger(&lp)?;
|
||||
dir.write_ledger(&lc)?;
|
||||
let mut out = format!("{n} labels moved from {} up to {}\n", child.name, parent.name);
|
||||
if stay > 0 {
|
||||
out += &format!("{stay} stay: their axes are {}'s own, and would mean something else in {}\n", child.name, parent.name);
|
||||
}
|
||||
Ok((parent.name.clone(), out))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn row(axis: &str, source: &str) -> Row {
|
||||
Row { media: "m".into(), a: 0.0, b: 2.0, axis: axis.into(), bad: true, weight: 1.0, who: "me".into(), source: source.into(), project: "p".into(), kind: None, region: None, words: None, at: 0, pin: None }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_picked_rows_move_and_keep_their_features() {
|
||||
let w = raea_sys_fingerprint::evidence::width();
|
||||
let (mut c, mut p) = (Ledger::default(), Ledger::default());
|
||||
c.push(row("blur", "note"), &vec![1.0; w]);
|
||||
c.push(row("glow", "note"), &vec![2.0; w]);
|
||||
c.push(row("blur", "damage"), &vec![3.0; w]);
|
||||
p.push(row("hiss", "teach"), &vec![4.0; w]);
|
||||
let n = rows(&mut c, &mut p, &|r| r.source == "note" && r.axis == "blur");
|
||||
assert_eq!(n, 1);
|
||||
assert_eq!(c.rows.iter().map(|r| r.axis.as_str()).collect::<Vec<_>>(), ["glow", "blur"]);
|
||||
assert_eq!((c.features(0)[0], c.features(1)[0]), (2.0, 3.0), "the child's rows keep their own features");
|
||||
assert_eq!(p.rows.len(), 2);
|
||||
assert_eq!(p.features(1)[0], 1.0, "a moved row carries its features");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
//! Notes become evidence (docs/fingerprint.feature FP5a, FP5b). `raea fingerprint read PROJECT [--by kimi|claude]`
|
||||
//! has a fresh agent session read each pinned note on the project's videos into a kind (defect, direction, praise or
|
||||
//! both) and an axis from the fingerprint's own axes, kept in the fingerprint's readings.jsonl. Nothing trains on them
|
||||
//! yet: `raea fingerprint readings --ask N` puts N readings to the person as questions in the app (`raea show
|
||||
//! --question`, answers to the "fingerprint" inbox), `readings --tally` counts how often the person agreed, and only
|
||||
//! once the kind is right 45 times in 50 and the axis 40 (FP5b) does `raea fingerprint learn-notes` make each defect
|
||||
//! or praise an evidence row over its span (1.5 s before the pin to 0.5 s after). A direction goes to the brief and the
|
||||
//! agent, never into a head. A note's marks (FP11b) make its row a region label: the box around its marks, boxes and
|
||||
//! lassos; a span pin sets the row's time. On a render with a layer pass, a reading keeps the layers under its pin,
|
||||
//! and the reader is told them.
|
||||
|
||||
use crate::{flag, has, words};
|
||||
use raea_sys_fingerprint::folder::Folder;
|
||||
use raea_sys_fingerprint::taxonomy::Fingerprint;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// FP5b's bar, out of every 50 checked
|
||||
pub const KIND_BAR: f64 = 45.0 / 50.0;
|
||||
pub const AXIS_BAR: f64 = 40.0 / 50.0;
|
||||
pub const INBOX: &str = "fingerprint";
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
pub struct Reading {
|
||||
pub note: String,
|
||||
pub text: String,
|
||||
pub who: String,
|
||||
pub media: PathBuf,
|
||||
pub t: f64,
|
||||
pub project: String,
|
||||
/// defect, direction, praise or both
|
||||
pub kind: String,
|
||||
pub axis: Option<String>,
|
||||
/// how it was read: kimi or claude
|
||||
pub by: String,
|
||||
/// the person's check: Some(true) agreed, Some(false) not; None until asked
|
||||
#[serde(default)]
|
||||
pub kind_ok: Option<bool>,
|
||||
#[serde(default)]
|
||||
pub axis_ok: Option<bool>,
|
||||
/// a span pin's end: the label covers t..to (FP11b)
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub to: Option<f64>,
|
||||
/// where in the frame the note's marks say the thing is, x0,y0,x1,y1 in 0-1 (FP11b)
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub region: Option<[f32; 4]>,
|
||||
/// the layers under the pin's x,y in the layer pass, on a render with one (FP5a)
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub layers: Vec<String>,
|
||||
}
|
||||
|
||||
|
||||
/// A post's video on this machine: the renders library, else the project's own folder
|
||||
fn media(project: &Path, m: &Value) -> Option<PathBuf> {
|
||||
let p = m["path"].as_str()?;
|
||||
let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());
|
||||
[home.join(".raea/feed/media").join(p), project.join(p)].into_iter().find(|f| f.is_file())
|
||||
}
|
||||
|
||||
/// Every video in the project's feed, each version's, found on this machine (FP7a's postmortem looks back on them)
|
||||
pub fn videos(project: &Path) -> Vec<PathBuf> {
|
||||
let mut out: Vec<PathBuf> = Vec::new();
|
||||
for e in std::fs::read_dir(project.join(".raea/feed")).into_iter().flatten().flatten() {
|
||||
let Some(post) = std::fs::read_to_string(e.path()).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok()) else { continue };
|
||||
for m in post["media"].as_array().into_iter().flatten().filter(|m| m["kind"] == "video") {
|
||||
if let Some(v) = media(project, m).filter(|v| !out.contains(v)) {
|
||||
out.push(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
/// Every person's pinned note on a video in the project's feed
|
||||
pub fn pinned(project: &Path) -> Vec<Reading> {
|
||||
let name = project.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let mut out = Vec::new();
|
||||
for e in std::fs::read_dir(project.join(".raea/feed")).into_iter().flatten().flatten() {
|
||||
let Ok(post) = std::fs::read_to_string(e.path()).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok()).ok_or(()) else { continue };
|
||||
let Some(video) = post["media"].as_array().into_iter().flatten().find(|m| m["kind"] == "video").and_then(|m| media(project, m)) else { continue };
|
||||
for n in post["notes"].as_array().into_iter().flatten() {
|
||||
let (Some(t), Some(text)) = (n["pin"]["t"].as_f64(), n["text"].as_str()) else { continue };
|
||||
if n["author"]["kind"] != "person" {
|
||||
continue;
|
||||
}
|
||||
let to = n["pin"]["to"].as_f64().filter(|&to| to > t);
|
||||
let at = n["pin"]["x"].as_f64().zip(n["pin"]["y"].as_f64()).map(|(x, y)| [x - 0.01, y - 0.01, x + 0.01, y + 0.01].map(|v| v.clamp(0.0, 1.0)));
|
||||
let layers = at.map(|b| raea_sys_fingerprint_things::located::layers(&video, t, b)).unwrap_or_default();
|
||||
out.push(Reading { note: n["id"].as_str().unwrap_or("").into(), text: text.into(), who: n["author"]["name"].as_str().unwrap_or("me").into(), media: video.clone(), t, project: name.clone(), to, region: raea_sys_fingerprint_use::grow::marked(&n["pin"]), layers, ..Default::default() });
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The reading prompt: the axes with their words, then the notes, and the JSON to answer
|
||||
pub fn prompt(fp: &Fingerprint, notes: &[Reading]) -> String {
|
||||
let axes = fp.axes.iter().map(|a| format!("- {}: {}", a.name, a.words.join("; "))).collect::<Vec<_>>().join("\n");
|
||||
let on = |n: &Reading| if n.layers.is_empty() { String::new() } else { format!(" (pinned on {})", n.layers.join(", ")) };
|
||||
let list = notes.iter().map(|n| format!("{}: {}{}", n.note, n.text.replace('\n', " "), on(n))).collect::<Vec<_>>().join("\n");
|
||||
format!(
|
||||
"You read a person's review notes on their videos. Read each note only; open no file and change nothing.\n\
|
||||
For each note say its kind: \"defect\" (it names something wrong at that moment), \"direction\" (it asks for a creative change, \
|
||||
not a fault), \"praise\" (it says something is good) or \"both\" (a defect and a direction). Then the axis it is about, from \
|
||||
these and only these, or null when none fits:\n{axes}\n\nThe notes, one a line, id first:\n{list}\n\n\
|
||||
End with only this JSON, nothing after it: [{{\"id\": \"\", \"kind\": \"defect|direction|praise|both\", \"axis\": \"name or null\"}}]"
|
||||
)
|
||||
}
|
||||
|
||||
/// The JSON array an answer ends with
|
||||
pub fn answer(text: &str) -> Option<Vec<Value>> {
|
||||
let end = text.rfind(']')?;
|
||||
let start = text[..end].rfind("[{").or_else(|| text[..end].rfind('['))?;
|
||||
serde_json::from_str(&text[start..=end]).ok()
|
||||
}
|
||||
|
||||
/// Fold an answer into the notes: a kind it doesn't know or an axis not in the fingerprint is dropped
|
||||
pub fn fold(notes: &mut [Reading], fp: &Fingerprint, ans: &[Value], by: &str) {
|
||||
for a in ans {
|
||||
let Some(id) = a["id"].as_str() else { continue };
|
||||
let Some(n) = notes.iter_mut().find(|n| n.note == id) else { continue };
|
||||
let kind = a["kind"].as_str().unwrap_or("");
|
||||
if !matches!(kind, "defect" | "direction" | "praise" | "both") {
|
||||
continue;
|
||||
}
|
||||
n.kind = kind.into();
|
||||
n.axis = a["axis"].as_str().filter(|x| fp.axis(x).is_some()).map(str::to_string);
|
||||
n.by = by.into();
|
||||
}
|
||||
}
|
||||
|
||||
/// One fresh session's words: kimi's or claude's stream, the assistant's text joined
|
||||
fn ask(by: &str, p: &str) -> Result<String, String> {
|
||||
let mut c = std::process::Command::new(by);
|
||||
match by {
|
||||
"kimi" => c.args(["-p", p, "--output-format", "stream-json"]),
|
||||
"claude" => c.args(["-p", p, "--output-format", "stream-json", "--verbose", "--allowedTools", ""]),
|
||||
o => return Err(format!("--by {o}: kimi or claude")),
|
||||
};
|
||||
let out = c.output().map_err(|e| format!("couldn't run {by}: {e}"))?;
|
||||
let mut text = String::new();
|
||||
for line in String::from_utf8_lossy(&out.stdout).lines() {
|
||||
let Ok(v) = serde_json::from_str::<Value>(line) else { continue };
|
||||
let content = if v["role"] == "assistant" { &v["content"] } else if v["type"] == "assistant" { &v["message"]["content"] } else if v["type"] == "result" { &v["result"] } else { continue };
|
||||
match content {
|
||||
Value::String(s) => text += s,
|
||||
Value::Array(a) => a.iter().filter_map(|p| p["text"].as_str()).for_each(|s| text += s),
|
||||
_ => {}
|
||||
}
|
||||
text.push('\n');
|
||||
}
|
||||
if text.trim().is_empty() {
|
||||
return Err(format!("{by} said nothing: {}", String::from_utf8_lossy(&out.stderr).lines().last().unwrap_or("")));
|
||||
}
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
pub fn readings_of(dir: &Folder) -> Vec<Reading> {
|
||||
std::fs::read_to_string(dir.dir.join("readings.jsonl")).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).collect()
|
||||
}
|
||||
|
||||
pub fn write_readings(dir: &Folder, r: &[Reading]) -> std::io::Result<()> {
|
||||
std::fs::write(dir.dir.join("readings.jsonl"), r.iter().filter_map(|x| serde_json::to_string(x).ok()).map(|l| l + "\n").collect::<String>())
|
||||
}
|
||||
|
||||
/// `raea fingerprint read PROJECT [--by kimi|claude]`
|
||||
pub(crate) fn read_here(args: &[String], cwd: &Path) -> i32 {
|
||||
let run = || -> Result<String, String> {
|
||||
let w = words(args)?;
|
||||
let project = w.first().map_or(cwd.to_path_buf(), |p| cwd.join(p));
|
||||
let by = flag(args, "--by").unwrap_or("kimi");
|
||||
let dir = crate::pick::chosen(args, Some(&crate::pick::piece_in(args, cwd))).0;
|
||||
let fp = dir.read(None).map_err(|e| e.to_string())?;
|
||||
let mut notes = pinned(&project);
|
||||
let mut kept = readings_of(&dir);
|
||||
notes.retain(|n| !kept.iter().any(|k| k.note == n.note && k.media == n.media));
|
||||
if notes.is_empty() {
|
||||
return Ok(format!("no new pinned notes in {}", project.display()));
|
||||
}
|
||||
for chunk in notes.chunks_mut(40) {
|
||||
let text = ask(by, &prompt(&fp, chunk))?;
|
||||
let ans = answer(&text).ok_or_else(|| format!("{by} answered no readings JSON"))?;
|
||||
fold(chunk, &fp, &ans, by);
|
||||
eprintln!("read {} notes", chunk.len());
|
||||
}
|
||||
let read = notes.iter().filter(|n| !n.kind.is_empty()).count();
|
||||
kept.extend(notes.into_iter().filter(|n| !n.kind.is_empty()));
|
||||
write_readings(&dir, &kept).map_err(|e| e.to_string())?;
|
||||
Ok(format!("{read} notes read into labels by {by}, kept in {}; none trains a head until you've checked them: raea fingerprint readings --ask 50", dir.dir.join("readings.jsonl").display()))
|
||||
};
|
||||
match run() {
|
||||
Ok(o) => {
|
||||
println!("{o}");
|
||||
0
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("raea fingerprint read: {e}");
|
||||
1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The share of checked readings the person agreed with, for kind and for axis, and how many were checked
|
||||
pub fn agreement(r: &[Reading]) -> (Option<f64>, Option<f64>, usize) {
|
||||
let share = |v: Vec<bool>| (!v.is_empty()).then(|| v.iter().filter(|x| **x).count() as f64 / v.len() as f64);
|
||||
let checked = r.iter().filter(|x| x.kind_ok.is_some()).count();
|
||||
(share(r.iter().filter_map(|x| x.kind_ok).collect()), share(r.iter().filter_map(|x| x.axis_ok).collect()), checked)
|
||||
}
|
||||
|
||||
/// Whether the readings have earned training (FP5b): 50 checked, the kind right 45 times and the axis 40
|
||||
pub fn earned(r: &[Reading]) -> bool {
|
||||
matches!(agreement(r), (Some(k), Some(a), n) if n >= 50 && k >= KIND_BAR && a >= AXIS_BAR)
|
||||
}
|
||||
|
||||
/// The choices a reading is checked with, and what each says about kind and axis
|
||||
pub const CHOICES: [(&str, bool, bool); 4] = [("Right", true, true), ("Right kind, wrong axis", true, false), ("Wrong kind", false, false), ("Right axis, wrong kind", false, true)];
|
||||
|
||||
/// `raea fingerprint readings [PROJECT] [--ask N] [--tally]`: the readings kept in the fingerprint that judges PROJECT
|
||||
pub(crate) fn readings_here(args: &[String], cwd: &Path) -> i32 {
|
||||
let dir = crate::pick::chosen(args, Some(&crate::pick::piece_in(args, cwd))).0;
|
||||
let mut r = readings_of(&dir);
|
||||
if let Some(n) = flag(args, "--ask").and_then(|n| n.parse::<usize>().ok()) {
|
||||
let todo: Vec<usize> = r.iter().enumerate().filter(|(_, x)| x.kind_ok.is_none()).map(|(i, _)| i).take(n).collect();
|
||||
let mut cmd = std::process::Command::new(std::env::current_exe().unwrap_or_else(|_| "raea".into()));
|
||||
cmd.args(["show", "--title", "Check how raea read your notes", "--inbox", INBOX]);
|
||||
for &i in &todo {
|
||||
let x = &r[i];
|
||||
let q = format!("[{}] \"{}\" read as {} on {}", x.note, x.text.replace('\n', " "), x.kind, x.axis.as_deref().unwrap_or("no axis"));
|
||||
cmd.args(["--question", &q, "--preview", &x.media.display().to_string()]);
|
||||
for (c, _, _) in CHOICES {
|
||||
cmd.args(["--choice", c]);
|
||||
}
|
||||
}
|
||||
if todo.is_empty() {
|
||||
println!("every reading is checked");
|
||||
return 0;
|
||||
}
|
||||
let Ok(out) = cmd.output() else { return 1 };
|
||||
let said = String::from_utf8_lossy(&out.stdout).into_owned();
|
||||
// the item raea show made, so the answers can be matched to the notes asked, in order
|
||||
let Some(item) = said.split(|c: char| c.is_whitespace() || c == '(' || c == ')' || c == ',').find(|w| w.starts_with("i-show-")) else {
|
||||
eprintln!("raea fingerprint readings: raea show didn't say its item: {said}{}", String::from_utf8_lossy(&out.stderr));
|
||||
return 1;
|
||||
};
|
||||
let mut asked: serde_json::Map<String, Value> = std::fs::read(dir.dir.join("asked.json")).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default();
|
||||
asked.insert(item.to_string(), json!(todo.iter().map(|&i| [r[i].note.clone(), r[i].media.display().to_string()]).collect::<Vec<_>>()));
|
||||
let _ = std::fs::write(dir.dir.join("asked.json"), serde_json::to_vec_pretty(&asked).unwrap_or_default());
|
||||
println!("{} readings put to you in the app ({item}); `raea fingerprint readings --tally` counts your answers", todo.len());
|
||||
return 0;
|
||||
}
|
||||
if has(args, "--tally") {
|
||||
let asked: serde_json::Map<String, Value> = std::fs::read(dir.dir.join("asked.json")).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default();
|
||||
let inbox = PathBuf::from(std::env::var("HOME").unwrap_or_default()).join(format!(".raea/inbox/{INBOX}.jsonl"));
|
||||
for line in std::fs::read_to_string(inbox).unwrap_or_default().lines() {
|
||||
let Ok(v) = serde_json::from_str::<Value>(line) else { continue };
|
||||
let Some(batch) = v["item"].as_str().and_then(|i| asked.get(i)).and_then(Value::as_array) else { continue };
|
||||
for (k, who) in batch.iter().enumerate() {
|
||||
let Some(a) = v["answers"][format!("q{}", k + 1)].as_str() else { continue };
|
||||
let Some((_, ok_kind, ok_axis)) = CHOICES.iter().find(|c| c.0 == a) else { continue };
|
||||
if let Some(x) = r.iter_mut().find(|x| who[0].as_str() == Some(x.note.as_str()) && who[1].as_str() == Some(&x.media.display().to_string())) {
|
||||
(x.kind_ok, x.axis_ok) = (Some(*ok_kind), Some(*ok_axis));
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = write_readings(&dir, &r);
|
||||
}
|
||||
let (k, a, n) = agreement(&r);
|
||||
let f = |x: Option<f64>| x.map_or("-".into(), |v| format!("{:.0}%", v * 100.0));
|
||||
println!("{} readings, {n} checked: kind right {}, axis right {} (FP5b needs 50 checked, 90% and 80%): {}", r.len(), f(k), f(a), if earned(&r) { "notes may train" } else { "notes don't train yet" });
|
||||
println!("{}", json!({"readings": r.len(), "checked": n, "kind": k, "axis": a, "earned": earned(&r)}));
|
||||
0
|
||||
}
|
||||
|
||||
/// `learn-notes`: each checked-off reading's defect or praise as an evidence row over its span, once the readings
|
||||
/// have earned it; a reading already learned is replaced, so learning again is safe
|
||||
pub(crate) fn learn(enc: &mut raea_sys_columns::Encoders, dir: &Folder, l: &mut raea_sys_fingerprint::evidence::Ledger) -> anyhow::Result<String> {
|
||||
let r = readings_of(dir);
|
||||
if !earned(&r) {
|
||||
let (k, a, n) = agreement(&r);
|
||||
anyhow::bail!("notes don't train yet: {n} readings checked, kind right {:?}, axis right {:?} (FP5b needs 50 checked, 90% and 80%: raea fingerprint readings --ask 50)", k, a);
|
||||
}
|
||||
// only these readings' rows are remade: notes another fingerprint's person moved up here (FP14d) stay
|
||||
let ids: std::collections::BTreeSet<&str> = r.iter().map(|x| x.note.as_str()).collect();
|
||||
l.retain(|x| x.source != "note" || !x.kind.as_deref().is_some_and(|k| ids.contains(k)));
|
||||
let mut made = 0;
|
||||
for x in r.iter().filter(|x| x.kind_ok != Some(false) && x.axis_ok != Some(false)) {
|
||||
let bad = match x.kind.as_str() {
|
||||
"defect" | "both" => true,
|
||||
"praise" => false,
|
||||
_ => continue,
|
||||
};
|
||||
let axis = match (&x.axis, bad) {
|
||||
(Some(a), _) => a.clone(),
|
||||
(None, false) => "*".into(),
|
||||
(None, true) => continue,
|
||||
};
|
||||
let c = enc.columns(&x.media)?;
|
||||
// a span is the label's time; a moment, 1.5 s before the pin to 0.5 s after (FP11b)
|
||||
let (a, b) = x.to.map_or(((x.t - 1.5).max(0.0), (x.t + 0.5).min(c.dur)), |to| (x.t.max(0.0), to.min(c.dur)));
|
||||
if b - a < 0.5 {
|
||||
continue;
|
||||
}
|
||||
// a defect's marks, grown into the thing by EdgeTAM and followed through its shot: a row for each 2 s it stays
|
||||
// in, with its box there (grow.rs through); else the mark's own box over the label
|
||||
let seed = x.region.filter(|_| bad);
|
||||
let shot = seed.and_then(|s| raea_sys_fingerprint_use::grow::through(&x.media, x.t, c.dur, s, 2.0).ok().flatten()).filter(|w| !w.is_empty());
|
||||
for (a, b, region) in shot.map_or_else(|| vec![(a, b, seed)], |w| w.into_iter().map(|(a, b, r)| (a, b, Some(r))).collect()) {
|
||||
let (media, axis, who, project, kind, words) = (c.media.clone(), axis.clone(), x.who.clone(), x.project.clone(), Some(x.note.clone()), Some(x.text.clone()));
|
||||
let row = raea_sys_fingerprint::evidence::Row { media, a, b, axis, bad, weight: 1.0, who, source: "note".into(), project, kind, region, words, at: 0, pin: None };
|
||||
l.push(row, &raea_sys_fingerprint::evidence::features(&c, a, b));
|
||||
}
|
||||
made += 1;
|
||||
}
|
||||
Ok(format!("{made} notes are evidence now (defects and praise; directions stay with the brief)\n"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
|
||||
#[test]
|
||||
fn a_reading_keeps_only_kinds_and_axes_it_knows() {
|
||||
let fp = raea_sys_fingerprint::taxonomy::base("me");
|
||||
let mut n = vec![Reading { note: "n1".into(), ..Default::default() }, Reading { note: "n2".into(), ..Default::default() }, Reading { note: "n3".into(), ..Default::default() }];
|
||||
let ans = answer("I read them.\n[{\"id\": \"n1\", \"kind\": \"defect\", \"axis\": \"glitch\"}, {\"id\": \"n2\", \"kind\": \"direction\", \"axis\": \"made up\"}, {\"id\": \"n3\", \"kind\": \"rant\", \"axis\": null}]").unwrap();
|
||||
fold(&mut n, &fp, &ans, "kimi");
|
||||
assert_eq!((n[0].kind.as_str(), n[0].axis.as_deref()), ("defect", Some("glitch")));
|
||||
assert_eq!((n[1].kind.as_str(), n[1].axis.as_deref()), ("direction", None), "an axis the fingerprint hasn't is dropped");
|
||||
assert_eq!(n[2].kind, "", "a kind it doesn't know is no reading");
|
||||
n[0].layers = vec!["Floor".into()];
|
||||
assert!(prompt(&fp, &n).contains("n1: ") && prompt(&fp, &n).contains("(pinned on Floor)"), "the reader is told the layer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn notes_train_only_once_the_person_agrees_enough() {
|
||||
let r = |k: bool, a: bool| Reading { kind_ok: Some(k), axis_ok: Some(a), ..Default::default() };
|
||||
let mut v: Vec<Reading> = (0..45).map(|_| r(true, true)).collect();
|
||||
v.extend((0..5).map(|_| r(false, false)));
|
||||
assert!(earned(&v), "45 and 45 of 50");
|
||||
v[0] = r(false, true);
|
||||
assert!(!earned(&v), "44 kinds of 50 is under the bar");
|
||||
assert!(!earned(&v[..40]), "fewer than 50 checked");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
//! Pairs from what the person already does (docs/fingerprint.feature FP6b, FP6c). `raea fingerprint pair WORSE BETTER
|
||||
//! --axis A [--at T] [--then T2]` records a pick between real options or a hand edit's before and after: the better
|
||||
//! window against the worse on that axis. `raea fingerprint versions V1 V2...` (the files in version order) makes a
|
||||
//! weak pair (weight 0.5, every axis) of each noted moment whose picture or sound changed in the next version (cosine
|
||||
//! distance 0.01 or more) and wasn't noted again within 1 s there.
|
||||
|
||||
use crate::approve::noted;
|
||||
use crate::flag;
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use raea_sys_columns::Encoders;
|
||||
use raea_sys_columns::window::Modality;
|
||||
use raea_sys_fingerprint::evidence::{Ledger, Row, features, slice};
|
||||
use raea_sys_fingerprint::pairs::difference;
|
||||
use std::path::Path;
|
||||
|
||||
fn row(media: &str, a: f64, b: f64, axis: &str, weight: f32, who: &str, project: String, words: Option<String>) -> Row {
|
||||
Row { media: media.into(), a, b, axis: axis.into(), bad: true, weight, who: who.into(), source: "pair".into(), project, kind: None, region: None, words, at: 0, pin: None }
|
||||
}
|
||||
|
||||
|
||||
/// `pair`: one row, the worse window's features minus the better one's
|
||||
pub(crate) fn pair(enc: &mut Encoders, l: &mut Ledger, who: &str, args: &[String], cwd: &Path, project: impl Fn(&Path) -> String) -> Result<String> {
|
||||
let f = crate::named(args, cwd)?;
|
||||
let [worse, better] = f.as_slice() else { bail!("raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2]") };
|
||||
let axis = flag(args, "--axis").ok_or_else(|| anyhow!("--axis A: the axis the better one is better on"))?;
|
||||
let span: f64 = flag(args, "--span").map_or(Ok(2.0), str::parse).context("--span takes seconds")?;
|
||||
let t: f64 = flag(args, "--at").map_or(Ok(span / 2.0), str::parse).context("--at takes seconds")?;
|
||||
let t2: f64 = flag(args, "--then").map_or(Ok(t), str::parse).context("--then takes seconds")?;
|
||||
let (cw, cb) = (enc.columns(worse)?, enc.columns(better)?);
|
||||
let win = |dur: f64, t: f64| {
|
||||
let a = (t - span / 2.0).clamp(0.0, (dur - span).max(0.0));
|
||||
(a, (a + span).min(dur))
|
||||
};
|
||||
let ((a, b), (a2, b2)) = (win(cw.dur, t), win(cb.dur, t2));
|
||||
let d = difference(&features(&cw, a, b), &features(&cb, a2, b2));
|
||||
l.push(row(&cw.media, a, b, axis, 1.0, who, flag(args, "--project").map_or_else(|| project(worse), str::to_string), flag(args, "--words").map(str::to_string)), &d);
|
||||
Ok(format!("paired on {axis}: {} at {a:.1} s is worse than {} at {a2:.1} s\n", worse.display(), better.display()))
|
||||
}
|
||||
|
||||
fn distance(x: &[f32], y: &[f32]) -> f32 {
|
||||
let d: f32 = x.iter().zip(y).map(|(a, b)| a * b).sum();
|
||||
1.0 - d / (x.iter().map(|a| a * a).sum::<f32>().sqrt() * y.iter().map(|b| b * b).sum::<f32>().sqrt()).max(1e-9)
|
||||
}
|
||||
|
||||
/// Whether a noted moment changed in the next version and wasn't noted there again
|
||||
pub(crate) fn weak(before: &[f32], after: &[f32], t: f64, next_notes: &[f64]) -> bool {
|
||||
let changed = [Modality::Picture, Modality::Sound].iter().any(|&m| distance(&before[slice(m)], &after[slice(m)]) >= 0.01);
|
||||
changed && !next_notes.iter().any(|n| (n - t).abs() <= 1.0)
|
||||
}
|
||||
|
||||
/// `versions`: weak pairs along a chain of versions
|
||||
pub(crate) fn versions(enc: &mut Encoders, l: &mut Ledger, who: &str, args: &[String], cwd: &Path, project: impl Fn(&Path) -> String) -> Result<String> {
|
||||
let f = crate::named(args, cwd)?;
|
||||
if f.len() < 2 {
|
||||
bail!("raea fingerprint versions V1 V2... takes the versions in order");
|
||||
}
|
||||
let mut made = 0;
|
||||
for w in f.windows(2) {
|
||||
let (now, next) = (&w[0], &w[1]);
|
||||
let (cn, cx) = (enc.columns(now)?, enc.columns(next)?);
|
||||
let next_notes = noted(next);
|
||||
for t in noted(now) {
|
||||
let (a, b) = ((t - 1.5).max(0.0), (t + 0.5).min(cn.dur.min(cx.dur)));
|
||||
if b - a < 1.0 {
|
||||
continue;
|
||||
}
|
||||
let (fb, fa) = (features(&cn, a, b), features(&cx, a, b));
|
||||
if weak(&fb, &fa, t, &next_notes) {
|
||||
l.push(row(&cn.media, a, b, "*", 0.5, who, flag(args, "--project").map_or_else(|| project(now), str::to_string), None), &difference(&fb, &fa));
|
||||
made += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(format!("{made} weak pairs from {} versions: noted moments the next version changed and nobody noted again\n", f.len()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use raea_sys_fingerprint::evidence::width;
|
||||
|
||||
#[test]
|
||||
fn a_changed_moment_not_noted_again_is_a_weak_pair() {
|
||||
let a = vec![1.0; width()];
|
||||
let mut b = a.clone();
|
||||
assert!(!super::weak(&a, &b, 5.0, &[]), "unchanged: no pair");
|
||||
b.iter_mut().enumerate().for_each(|(i, x)| *x = if i % 2 == 0 { 1.0 } else { -1.0 });
|
||||
assert!(super::weak(&a, &b, 5.0, &[]));
|
||||
assert!(!super::weak(&a, &b, 5.0, &[5.6]), "noted again within 1 s: no pair");
|
||||
assert!(super::weak(&a, &b, 5.0, &[7.0]));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
//! Which fingerprint judges a piece (docs/fingerprint.feature FP14c): `raea fingerprint which PATH` says the one
|
||||
//! chosen, what it's for and why; `raea fingerprint use NAME [--in project|workspace] [PATH]` pins one by writing that
|
||||
//! level's `default`. score and teach use the chosen one unless --fp names another. No encoders are needed.
|
||||
|
||||
use crate::{flag, has, words};
|
||||
use raea_sys_fingerprint::folder::{Folder, root};
|
||||
use raea_sys_fingerprint_use::which::{Choice, default_file, levels, piece, which};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// The fingerprint a verb uses: --fp, else the one that judges `file`, else the account's default, else "me"
|
||||
pub(crate) fn chosen(args: &[String], file: Option<&Path>) -> (Folder, Option<Choice>) {
|
||||
if let Some(n) = flag(args, "--fp") {
|
||||
return (Folder::named(n), None);
|
||||
}
|
||||
if let Some(c) = file.and_then(which) {
|
||||
return (Folder { dir: c.dir.clone() }, Some(c));
|
||||
}
|
||||
let n = std::fs::read_to_string(root().join("default")).ok().map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).unwrap_or_else(|| "me".into());
|
||||
(Folder::named(&n), None)
|
||||
}
|
||||
|
||||
/// A piece in the project a verb names (its first word, else the current folder), so `read`, `readings` and
|
||||
/// `learn-notes` keep a project's notes in the fingerprint that judges it (FP14d)
|
||||
pub(crate) fn piece_in(args: &[String], cwd: &Path) -> PathBuf {
|
||||
here(cwd, args, 0).join("piece.mp4")
|
||||
}
|
||||
|
||||
fn here(cwd: &Path, args: &[String], at: usize) -> PathBuf {
|
||||
let w = words(args).unwrap_or_default();
|
||||
w.get(at).map_or_else(|| cwd.to_path_buf(), |p| cwd.join(p))
|
||||
}
|
||||
|
||||
pub(crate) fn which_here(args: &[String], cwd: &Path) -> i32 {
|
||||
let path = here(cwd, args, 0);
|
||||
let Some(c) = which(&path) else {
|
||||
eprintln!("raea fingerprint which: you have no fingerprint yet (`raea fingerprint new me` makes one)");
|
||||
return 1;
|
||||
};
|
||||
if has(args, "--json") {
|
||||
let p = piece(&path);
|
||||
println!("{}", serde_json::json!({"chosen": c, "piece": p, "looked_in": levels(&p).iter().map(|(l, d)| serde_json::json!({"level": l, "dir": d})).collect::<Vec<_>>()}));
|
||||
} else {
|
||||
println!("{} {}", c.name, c.about.as_deref().unwrap_or(""));
|
||||
println!(" why: {}", c.why);
|
||||
println!(" at: {}", c.dir.display());
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
pub(crate) fn use_here(args: &[String], cwd: &Path) -> i32 {
|
||||
let Some(name) = words(args).ok().and_then(|w| w.first().map(|s| s.to_string())) else {
|
||||
eprintln!("raea fingerprint use: which one? raea fingerprint use NAME [--in project|workspace] [PATH]");
|
||||
return 2;
|
||||
};
|
||||
let level = flag(args, "--in").unwrap_or("account");
|
||||
if !matches!(level, "project" | "workspace" | "account") {
|
||||
eprintln!("raea fingerprint use: --in takes project or workspace, not {level}");
|
||||
return 2;
|
||||
}
|
||||
let path = here(cwd, args, 1);
|
||||
let Some(file) = default_file(&path, level) else {
|
||||
eprintln!("raea fingerprint use: {} isn't in a {level} (no .raea/{level} above it)", path.display());
|
||||
return 1;
|
||||
};
|
||||
let p = piece(&path);
|
||||
let all = levels(&p);
|
||||
let from = all.iter().position(|(l, _)| *l == level).unwrap_or(0);
|
||||
if !all[from..].iter().any(|(_, d)| Folder { dir: d.join(&name) }.exists()) {
|
||||
eprintln!("raea fingerprint use: no fingerprint {name} at the {level} or above it");
|
||||
return 1;
|
||||
}
|
||||
let wrote = std::fs::create_dir_all(file.parent().unwrap_or(cwd)).and(std::fs::write(&file, &name));
|
||||
if let Err(e) = wrote {
|
||||
eprintln!("raea fingerprint use: {}: {e}", file.display());
|
||||
return 1;
|
||||
}
|
||||
println!("{name} judges this {level}'s pieces now ({})", file.display());
|
||||
0
|
||||
}
|
||||
|
||||
/// `raea fingerprint diff A B [--json]` (FP8b): the axes two fingerprints rank the same evidence most differently on
|
||||
pub(crate) fn diff_here(args: &[String]) -> i32 {
|
||||
let w = words(args).unwrap_or_default();
|
||||
let [a, b] = w.as_slice() else {
|
||||
eprintln!("raea fingerprint diff: which two? raea fingerprint diff A B");
|
||||
return 2;
|
||||
};
|
||||
match raea_sys_fingerprint_use::diff::diff(&Folder::named(a), &Folder::named(b), 3) {
|
||||
Ok(d) if has(args, "--json") => {
|
||||
println!("{}", serde_json::to_string_pretty(&d).unwrap_or_default());
|
||||
0
|
||||
}
|
||||
Ok(d) => {
|
||||
println!("where {a} and {b} differ, most apart first (0 agree, 1 unrelated, 2 opposed):");
|
||||
for x in &d {
|
||||
println!(" {:16} {:.2} over {} windows", x.axis, x.apart, x.windows);
|
||||
for m in &x.moments {
|
||||
println!(" {} {:.1}-{:.1}s: {a} ranks it {:.0}%, {b} {:.0}%", &m.media[..m.media.len().min(12)], m.a, m.b, m.rank_a * 100.0, m.rank_b * 100.0);
|
||||
}
|
||||
}
|
||||
0
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("raea fingerprint diff: {e:#}");
|
||||
1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `raea fingerprint share NAME --in project|workspace [PATH]` (FP8a): the fingerprint's taxonomy, words and evidence
|
||||
/// copied into that level's .raea/fingerprints, to travel with its repo; never its heads (each machine retrains them)
|
||||
/// and never media (the rows hold embeddings, spans and labels)
|
||||
pub(crate) fn share_here(args: &[String], cwd: &Path) -> i32 {
|
||||
let Some(name) = words(args).ok().and_then(|w| w.first().map(|s| s.to_string())) else {
|
||||
eprintln!("raea fingerprint share: which one? raea fingerprint share NAME --in project|workspace [PATH]");
|
||||
return 2;
|
||||
};
|
||||
let level = flag(args, "--in").unwrap_or("project");
|
||||
let path = here(cwd, args, 1);
|
||||
let Some(to) = default_file(&path, level).and_then(|f| f.parent().map(|d| d.join(&name))) else {
|
||||
eprintln!("raea fingerprint share: {} isn't in a {level} (no .raea/{level} above it)", path.display());
|
||||
return 1;
|
||||
};
|
||||
let from = Folder::named(&name);
|
||||
let run = || -> anyhow::Result<usize> {
|
||||
from.read(None)?;
|
||||
let dest = Folder { dir: to.clone() };
|
||||
if dest.exists() {
|
||||
anyhow::bail!("{} has a fingerprint {name} already", to.display());
|
||||
}
|
||||
std::fs::create_dir_all(&to)?;
|
||||
for f in ["fingerprint.ts", "fingerprint.json", "words.json", "words.f16"] {
|
||||
if from.dir.join(f).is_file() {
|
||||
std::fs::copy(from.dir.join(f), to.join(f))?;
|
||||
}
|
||||
}
|
||||
let l = from.ledger()?;
|
||||
dest.write_ledger(&l)?;
|
||||
Ok(l.rows.len())
|
||||
};
|
||||
match run() {
|
||||
Ok(n) => {
|
||||
println!("shared {name} into {} with {n} evidence rows, no heads and no media; commit it with the {level}", to.display());
|
||||
0
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("raea fingerprint share: {e:#}");
|
||||
1
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
//! `raea fingerprint postmortem [PROJECT] [--ask N] [--tally]` (docs/fingerprint.feature FP7a; the picking, the clips
|
||||
//! and the questions are raea-sys-fingerprint-use's postmortem.rs). It scores every version of the project's pieces with
|
||||
//! the fingerprint that judges the project and asks at most ten yes/no questions in the app; `--tally` makes each answer
|
||||
//! an evidence row, retrains, and says how each head's held-out score moved.
|
||||
|
||||
use crate::{Eval, flag, has};
|
||||
use anyhow::{Result, anyhow, bail};
|
||||
use raea_sys_columns::Encoders;
|
||||
use raea_sys_fingerprint::evidence::{Row, features};
|
||||
use raea_sys_fingerprint::retrain;
|
||||
use raea_sys_fingerprint_use::postmortem::{self as pm, MOST};
|
||||
use raea_sys_fingerprint_use::score::{Scored, score};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub(crate) fn run(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result<(String, i32)> {
|
||||
let project = crate::pick::piece_in(args, cwd).parent().map(Path::to_path_buf).unwrap_or_else(|| cwd.to_path_buf());
|
||||
let name = project.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let (dir, fp, w) = crate::verbs::open(enc, args, eval, Some(&crate::pick::piece_in(args, cwd)))?;
|
||||
let before = dir.trained()?.map(|t| t.0).ok_or_else(|| anyhow!("{} has no trained heads yet: `raea fingerprint bootstrap` or teach it first", fp.name))?;
|
||||
if has(args, "--tally") {
|
||||
let inbox = std::fs::read_to_string(PathBuf::from(std::env::var("HOME").unwrap_or_default()).join(format!(".raea/inbox/{}.jsonl", pm::INBOX))).unwrap_or_default();
|
||||
let answers = pm::answered(&dir.dir, &inbox);
|
||||
let mut l = dir.ledger()?;
|
||||
// every tally adds every answer again, so tallying twice is safe
|
||||
l.retain(|r| r.source != "postmortem");
|
||||
for (x, yes) in &answers {
|
||||
let c = enc.columns(&x.file)?;
|
||||
let (a, b) = (x.a.min(c.dur), x.b.min(c.dur));
|
||||
if b - a < 0.5 {
|
||||
continue;
|
||||
}
|
||||
let who = fp.who.clone().unwrap_or_else(|| "me".into());
|
||||
let row = Row { media: c.media.clone(), a, b, axis: x.axis.clone(), bad: *yes, weight: 1.0, who, source: "postmortem".into(), project: name.clone(), kind: None, region: None, words: Some(x.words.clone()), at: 0, pin: None };
|
||||
l.push(row, &features(&c, a, b));
|
||||
}
|
||||
dir.write_ledger(&l)?;
|
||||
let after = retrain(&dir, &fp, &w, &l, None)?;
|
||||
let f = |v: Option<f64>| v.map_or("-".into(), |v| format!("{v:.2}"));
|
||||
let mut out = format!("{} answers are evidence now\n", answers.len());
|
||||
for (axis, was, now) in pm::moved(&before, &after) {
|
||||
out += &format!(" {axis}: held out {} -> {}\n", f(was), f(now));
|
||||
}
|
||||
return Ok((out, 0));
|
||||
}
|
||||
let n = flag(args, "--ask").map_or(Ok(MOST), str::parse).map_err(|_| anyhow!("--ask takes a count"))?.min(MOST);
|
||||
let files = crate::notes::videos(&project);
|
||||
if files.is_empty() {
|
||||
bail!("{} has no videos in its feed to look back on", project.display());
|
||||
}
|
||||
let scored = files.iter().map(|f| -> Result<Scored> { Ok(score(&fp, Some(&w), Some(&before), &enc.columns(f)?, &f.display().to_string())) }).collect::<Result<Vec<_>>>()?;
|
||||
let asks = pm::picks(&scored, &before, &fp, &dir.ledger()?, n);
|
||||
if asks.is_empty() {
|
||||
return Ok((format!("nothing to ask: on {} versions, no head disagrees with you or sits near its flag\n", files.len()), 0));
|
||||
}
|
||||
let item = pm::ask(&std::env::current_exe()?, &dir.dir, &name, &asks)?;
|
||||
let against = asks.iter().filter(|x| x.why == "disagrees with you").count();
|
||||
Ok((format!("{} questions on {} versions put to you in the app ({item}): {against} where it disagrees with you, the rest where it's least sure; `raea fingerprint postmortem --tally` adds your answers\n", asks.len(), files.len()), 0))
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
//! `raea fingerprint profile REFS... --as NAME [--against LIST]` and `score FILE --profile NAME` (docs/fingerprint.feature
|
||||
//! FP6e): a profile's measures taken from work the person admires, kept in the fingerprint's profiles/NAME.json, and a
|
||||
//! piece critiqued against it, measure by measure, with where and which way to move.
|
||||
|
||||
use crate::{flag, listed, named};
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use raea_sys_columns::{Encoders, media};
|
||||
use raea_sys_fingerprint::folder::Folder;
|
||||
use raea_sys_fingerprint_use::profile::{Measures, NAMES, Out, Profile, critique, measures, profile};
|
||||
use raea_sys_fingerprint_use::score::clock;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
const BINS: usize = 12;
|
||||
/// The windows the critique says "where" with, seconds
|
||||
const WIN: f64 = 4.0;
|
||||
|
||||
/// A piece's measures, whole and in windows
|
||||
pub(crate) fn measured(enc: &mut Encoders, file: &Path) -> Result<(Measures, Vec<((f64, f64), Measures)>)> {
|
||||
let c = enc.columns(file)?;
|
||||
let pcm = media::sound(file, 16_000).unwrap_or_default();
|
||||
let cols = ((c.dur * 10.0) as usize).max(1);
|
||||
let spec = media::spectrogram(&pcm, 16_000, cols, BINS);
|
||||
let whole = measures(&c, &spec, BINS, 0.0, c.dur);
|
||||
let n = (c.dur / WIN).ceil() as usize;
|
||||
let windows = (0..n).map(|i| {
|
||||
let (a, b) = (i as f64 * WIN, ((i + 1) as f64 * WIN).min(c.dur));
|
||||
((a, b), measures(&c, &spec, BINS, a, b))
|
||||
}).collect();
|
||||
Ok((whole, windows))
|
||||
}
|
||||
|
||||
fn path(dir: &Folder, name: &str) -> PathBuf {
|
||||
dir.dir.join("profiles").join(format!("{name}.json"))
|
||||
}
|
||||
|
||||
pub(crate) fn make(enc: &mut Encoders, dir: &Folder, args: &[String], cwd: &Path) -> Result<String> {
|
||||
let name = flag(args, "--as").ok_or_else(|| anyhow!("name it: raea fingerprint profile REFS... --as NAME"))?;
|
||||
let refs = named(args, cwd)?;
|
||||
if refs.len() < 2 {
|
||||
bail!("a profile needs two references or more (three for its leave-one-out check)");
|
||||
}
|
||||
let mut r = Vec::new();
|
||||
for f in &refs {
|
||||
r.push((f.display().to_string(), measured(enc, f)?.0));
|
||||
}
|
||||
let mut other = Vec::new();
|
||||
if let Some(list) = flag(args, "--against") {
|
||||
for f in listed(cwd, list)? {
|
||||
other.push(measured(enc, &f)?.0);
|
||||
}
|
||||
}
|
||||
let p = profile(name, r, &other);
|
||||
std::fs::create_dir_all(dir.dir.join("profiles"))?;
|
||||
std::fs::write(path(dir, name), serde_json::to_vec_pretty(&p)?)?;
|
||||
let mut out = format!("profile {name} from {} references:\n", p.refs.len());
|
||||
for (k, words) in NAMES {
|
||||
if let Some((lo, hi)) = p.ranges.get(k) {
|
||||
out += &format!(" {words:40} {lo:.2} to {hi:.2}\n");
|
||||
}
|
||||
}
|
||||
out += &match (p.inside_own, p.inside_other) {
|
||||
(Some(o), Some(x)) => format!("leave-one-out: a reference falls in the others' ranges {:.0}% of the time, unrelated work {:.0}%: {}\n", o * 100.0, x * 100.0, if p.tells == Some(true) { "it tells this taste apart" } else { "it does NOT tell this taste apart" }),
|
||||
(Some(o), None) => format!("leave-one-out: a reference falls in the others' ranges {:.0}% of the time (give --against LIST to compare with unrelated work)\n", o * 100.0),
|
||||
_ => "leave-one-out needs three references\n".into(),
|
||||
};
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The critique of a piece against a saved profile, as lines
|
||||
pub(crate) fn against(enc: &mut Encoders, dir: &Folder, name: &str, file: &Path) -> Result<(String, Vec<Out>)> {
|
||||
let p: Profile = serde_json::from_slice(&std::fs::read(path(dir, name)).with_context(|| format!("no profile {name} (raea fingerprint profile REFS... --as {name})"))?)?;
|
||||
let (whole, windows) = measured(enc, file)?;
|
||||
let out = critique(&p, &whole, &windows);
|
||||
let words = |k: &str| NAMES.iter().find(|n| n.0 == k).map_or(k.to_string(), |n| n.1.to_string());
|
||||
let mut t = format!("against the {name} profile: {}\n", if out.is_empty() { "every measure in range".to_string() } else { format!("{} out of range", out.len()) });
|
||||
for o in &out {
|
||||
t += &format!(" {} {:.2} is outside {:.2} to {:.2}: {} it{}\n", words(&o.measure), o.value, o.range.0, o.range.1, o.move_, o.at.map_or(String::new(), |(a, _)| format!(", most at {}", clock(a))));
|
||||
}
|
||||
Ok((t, out))
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
//! Encoder upgrades keep the evidence (docs/fingerprint.feature FP8c). When this machine's encoders aren't the ones a
|
||||
//! fingerprint was trained on, `raea fingerprint reembed PLACE...` re-embeds every row whose media it finds under
|
||||
//! those files and folders (matched by content hash), moves the fingerprint to the new encoders and retrains. A row
|
||||
//! whose media isn't found keeps its old pin and trains no head until it's re-embedded or labelled again; a bootstrap's
|
||||
//! damaged rows are remade by running the bootstrap again.
|
||||
|
||||
use crate::words;
|
||||
use anyhow::{Result, anyhow};
|
||||
use raea_sys_columns::{Encoders, media};
|
||||
use raea_sys_fingerprint::evidence::features;
|
||||
use raea_sys_fingerprint::folder::Folder;
|
||||
use raea_sys_fingerprint::taxonomy::Fingerprint;
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
const MEDIA: [&str; 9] = ["mp4", "mov", "m4v", "webm", "mkv", "wav", "mp3", "m4a", "flac"];
|
||||
|
||||
/// An encoder set's short name, as a row's pin
|
||||
pub(crate) fn pin_of(p: &BTreeMap<String, String>) -> String {
|
||||
p.iter().map(|(k, v)| format!("{k}:{}", &v[..v.len().min(8)])).collect::<Vec<_>>().join(",")
|
||||
}
|
||||
|
||||
/// The media files under each place, two folders deep
|
||||
fn files(places: &[PathBuf]) -> Vec<PathBuf> {
|
||||
fn walk(d: &Path, depth: usize, out: &mut Vec<PathBuf>) {
|
||||
for e in std::fs::read_dir(d).into_iter().flatten().flatten() {
|
||||
let p = e.path();
|
||||
if p.is_dir() && depth > 0 {
|
||||
walk(&p, depth - 1, out);
|
||||
} else if MEDIA.iter().any(|m| p.extension().is_some_and(|x| x.eq_ignore_ascii_case(m))) {
|
||||
out.push(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for p in places {
|
||||
if p.is_dir() { walk(p, 2, &mut out) } else { out.push(p.clone()) }
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Rows moved to `here`'s encoders where their media is found; returns the fingerprint as it is now and what happened
|
||||
pub(crate) fn reembed(enc: &mut Encoders, dir: &Folder, mut fp: Fingerprint, here: BTreeMap<String, String>, args: &[String], cwd: &Path) -> Result<(Fingerprint, String)> {
|
||||
let places: Vec<PathBuf> = words(args).map_err(|e| anyhow!(e))?.iter().map(|f| cwd.join(f)).collect();
|
||||
let mut l = dir.ledger()?;
|
||||
if fp.encoders != here {
|
||||
let old = pin_of(&fp.encoders);
|
||||
l.rows.iter_mut().filter(|r| r.pin.is_none()).for_each(|r| r.pin = Some(old.clone()));
|
||||
fp.encoders = here;
|
||||
dir.rewrite(&fp)?;
|
||||
}
|
||||
let waiting: std::collections::BTreeSet<String> = l.rows.iter().filter(|r| r.pin.is_some() && !matches!(r.source.as_str(), "damage" | "cheat")).map(|r| r.media.clone()).collect();
|
||||
let mut done = 0;
|
||||
for f in files(&places) {
|
||||
if waiting.is_empty() {
|
||||
break;
|
||||
}
|
||||
let Ok(sha) = media::sha256(&f) else { continue };
|
||||
if !waiting.contains(&sha) {
|
||||
continue;
|
||||
}
|
||||
let c = enc.columns(&f)?;
|
||||
for i in 0..l.rows.len() {
|
||||
let r = &l.rows[i];
|
||||
if r.media == sha && r.pin.is_some() && !matches!(r.source.as_str(), "damage" | "cheat") {
|
||||
let x = features(&c, r.a, r.b);
|
||||
l.set_features(i, &x);
|
||||
l.rows[i].pin = None;
|
||||
done += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
dir.write_ledger(&l)?;
|
||||
let left = l.rows.iter().filter(|r| r.pin.is_some()).count();
|
||||
let damage = l.rows.iter().filter(|r| r.pin.is_some() && matches!(r.source.as_str(), "damage" | "cheat")).count();
|
||||
let mut out = format!("re-embedded {done} rows on this machine's encoders; {left} wait on their old ones");
|
||||
if damage > 0 {
|
||||
out += &format!(" ({damage} from a bootstrap: run raea fingerprint bootstrap again to remake them)");
|
||||
}
|
||||
Ok((fp, out + "\n"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn a_pin_names_each_encoder_and_its_hash() {
|
||||
let p = std::collections::BTreeMap::from([("clap".to_string(), "0123456789abcdef".to_string()), ("siglip".to_string(), "fedcba".to_string())]);
|
||||
assert_eq!(super::pin_of(&p), "clap:01234567,siglip:fedcba");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
//! The resident service: the encoders loaded once, on 127.0.0.1 at a port the host file names
|
||||
//! (~/.raea/fingerprints/.serve.json). A request is one JSON line, {"args": [...], "cwd": "..."}; the answer is
|
||||
//! progress lines, {"say": "..."}, then {"out": "...", "code": N}. One request at a time, in order.
|
||||
|
||||
use crate::{Eval, verbs};
|
||||
use anyhow::{Context, Result};
|
||||
use raea_sys_columns::Encoders;
|
||||
use raea_sys_fingerprint::folder::root;
|
||||
use serde_json::{Value, json};
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
/// The service leaves after this long with no request
|
||||
const IDLE: Duration = Duration::from_secs(30 * 60);
|
||||
/// How long a verb waits for a service it started to come up (the first run fetches the models)
|
||||
const UP: Duration = Duration::from_secs(900);
|
||||
|
||||
fn host() -> PathBuf {
|
||||
root().join(".serve.json")
|
||||
}
|
||||
|
||||
fn now() -> u64 {
|
||||
SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// `raea fingerprint serve`: load the encoders, listen, answer until idle or stopped
|
||||
pub fn serve(eval: Eval) -> Result<()> {
|
||||
let started = Instant::now();
|
||||
let mut enc = Encoders::load().context("loading the encoders")?;
|
||||
let listener = TcpListener::bind("127.0.0.1:0")?;
|
||||
let port = listener.local_addr()?.port();
|
||||
std::fs::create_dir_all(root())?;
|
||||
std::fs::write(host(), json!({"port": port, "pid": std::process::id()}).to_string())?;
|
||||
eprintln!("raea fingerprint serve: encoders loaded in {:.1} s, on 127.0.0.1:{port}", started.elapsed().as_secs_f64());
|
||||
let last = Arc::new(AtomicU64::new(now()));
|
||||
let seen = last.clone();
|
||||
std::thread::spawn(move || {
|
||||
loop {
|
||||
std::thread::sleep(Duration::from_secs(60));
|
||||
if now().saturating_sub(seen.load(Ordering::Relaxed)) > IDLE.as_secs() {
|
||||
let _ = std::fs::remove_file(host());
|
||||
eprintln!("raea fingerprint serve: idle for {} min, leaving", IDLE.as_secs() / 60);
|
||||
std::process::exit(0);
|
||||
}
|
||||
}
|
||||
});
|
||||
for stream in listener.incoming() {
|
||||
let Ok(mut s) = stream else { continue };
|
||||
last.store(now(), Ordering::Relaxed);
|
||||
let mut line = String::new();
|
||||
if BufReader::new(&s).read_line(&mut line).is_err() {
|
||||
continue;
|
||||
}
|
||||
let req: Value = serde_json::from_str(&line).unwrap_or_default();
|
||||
let args: Vec<String> = serde_json::from_value(req["args"].clone()).unwrap_or_default();
|
||||
let cwd = PathBuf::from(req["cwd"].as_str().unwrap_or("."));
|
||||
if args.first().is_some_and(|v| v == "stop") {
|
||||
let _ = writeln!(s, "{}", json!({"out": "raea fingerprint serve: stopped", "code": 0}));
|
||||
let _ = std::fs::remove_file(host());
|
||||
return Ok(());
|
||||
}
|
||||
let mut say = |m: String| {
|
||||
let _ = writeln!(s, "{}", json!({ "say": m }));
|
||||
};
|
||||
let (out, code) = verbs::run(&mut enc, &args, &cwd, eval, &mut say);
|
||||
let _ = writeln!(s, "{}", json!({"out": out, "code": code}));
|
||||
last.store(now(), Ordering::Relaxed);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A verb run in this process, with the encoders loaded for it
|
||||
pub(crate) fn here(args: &[String], cwd: &Path, eval: Eval) -> (String, i32) {
|
||||
match Encoders::load() {
|
||||
Ok(mut enc) => verbs::run(&mut enc, args, cwd, eval, &mut |m| eprintln!("{m}")),
|
||||
Err(e) => (format!("raea fingerprint: loading the encoders: {e:#}"), 1),
|
||||
}
|
||||
}
|
||||
|
||||
fn reach() -> Option<TcpStream> {
|
||||
let h: Value = serde_json::from_slice(&std::fs::read(host()).ok()?).ok()?;
|
||||
TcpStream::connect(("127.0.0.1", h["port"].as_u64()? as u16)).ok()
|
||||
}
|
||||
|
||||
/// The service started in the background, its output in ~/.raea/fingerprints/.serve.log; its stream once it's up
|
||||
fn start() -> Result<TcpStream, String> {
|
||||
let _ = std::fs::remove_file(host());
|
||||
std::fs::create_dir_all(root()).map_err(|e| e.to_string())?;
|
||||
let log = root().join(".serve.log");
|
||||
let file = std::fs::File::create(&log).map_err(|e| e.to_string())?;
|
||||
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
|
||||
let mut cmd = std::process::Command::new(exe);
|
||||
cmd.args(["fingerprint", "serve"]).stdin(std::process::Stdio::null()).stdout(file.try_clone().map_err(|e| e.to_string())?).stderr(file);
|
||||
#[cfg(unix)]
|
||||
std::os::unix::process::CommandExt::process_group(&mut cmd, 0);
|
||||
let mut child = cmd.spawn().map_err(|e| format!("starting the service: {e}"))?;
|
||||
eprintln!("raea fingerprint: starting the service (loading the encoders once; its log is {})", log.display());
|
||||
let t = Instant::now();
|
||||
while t.elapsed() < UP {
|
||||
if let Some(s) = reach() {
|
||||
return Ok(s);
|
||||
}
|
||||
if let Ok(Some(status)) = child.try_wait() {
|
||||
let tail = std::fs::read_to_string(&log).unwrap_or_default();
|
||||
return Err(format!("the service stopped ({status}):\n{}", tail.lines().rev().take(12).collect::<Vec<_>>().into_iter().rev().collect::<Vec<_>>().join("\n")));
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
}
|
||||
let _ = child.kill();
|
||||
Err(format!("the service didn't come up in {} s (see {})", UP.as_secs(), log.display()))
|
||||
}
|
||||
|
||||
/// A verb sent to the service, started if it isn't running; its progress printed as it comes
|
||||
pub(crate) fn call(args: &[String], cwd: &Path) -> (String, i32) {
|
||||
let stream = match reach() {
|
||||
Some(s) => Ok(s),
|
||||
None if args.first().is_some_and(|v| v == "stop") => return ("raea fingerprint: no service running".into(), 0),
|
||||
None => start(),
|
||||
};
|
||||
let mut s = match stream {
|
||||
Ok(s) => s,
|
||||
Err(e) => return (format!("raea fingerprint: {e}"), 1),
|
||||
};
|
||||
if writeln!(s, "{}", json!({"args": args, "cwd": cwd})).is_err() {
|
||||
return ("raea fingerprint: the service closed the connection".into(), 1);
|
||||
}
|
||||
for line in BufReader::new(s).lines() {
|
||||
let Ok(line) = line else { break };
|
||||
let v: Value = serde_json::from_str(&line).unwrap_or_default();
|
||||
if let Some(m) = v["say"].as_str() {
|
||||
eprintln!("{m}");
|
||||
} else if v.get("code").is_some() {
|
||||
return (v["out"].as_str().unwrap_or("").to_string(), v["code"].as_i64().unwrap_or(1) as i32);
|
||||
}
|
||||
}
|
||||
("raea fingerprint: the service ended without an answer (see ~/.raea/fingerprints/.serve.log)".into(), 1)
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
//! `raea fingerprint things FILE [--project P] [--json]` (docs/fingerprint.feature FP13a, FP13c): a piece's shots,
|
||||
//! their things (a render's layers, and every mark a person drew on a note of it in P's feed, P the folder it runs in
|
||||
//! by default) and the camera's path, with what floats, passes through, lurches or is empty
|
||||
//! (raea-sys-fingerprint-things). `--json` prints it all for `raea check --things`.
|
||||
|
||||
use crate::{flag, has};
|
||||
use anyhow::Result;
|
||||
use raea_sys_columns::Encoders;
|
||||
use raea_sys_fingerprint_things::things::{Mark, things};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub(crate) fn run(enc: &mut Encoders, args: &[String], cwd: &Path) -> Result<(String, i32)> {
|
||||
let file = cwd.join(args.first().filter(|a| !a.starts_with("--")).ok_or_else(|| anyhow::anyhow!("things FILE"))?);
|
||||
let project = flag(args, "--project").map_or_else(|| cwd.to_path_buf(), |p| cwd.join(p));
|
||||
let me = file.canonicalize().ok();
|
||||
let marks: Vec<Mark> = crate::notes::pinned(&project)
|
||||
.into_iter()
|
||||
.filter(|r| r.media.canonicalize().ok() == me)
|
||||
.filter_map(|r| Some(Mark { name: r.text.chars().take(40).collect(), t: r.t, a: (r.t - 1.0).max(0.0), b: r.to.unwrap_or(r.t + 1.0), region: r.region? }))
|
||||
.collect();
|
||||
let t = things(enc, &file, &marks)?;
|
||||
if has(args, "--json") {
|
||||
return Ok((serde_json::to_string_pretty(&t)?, 0));
|
||||
}
|
||||
let n: usize = t.shots.iter().map(|s| s.things.len()).sum();
|
||||
let mut out = format!("{}: {} shots, {n} things seen ({} marked), {} findings\n", PathBuf::from(&t.file).display(), t.shots.len(), marks.len(), t.issues.len());
|
||||
for i in &t.issues {
|
||||
out += &format!(" {:>6.1} s {} {}\n", i.at, i.rule, i.says);
|
||||
}
|
||||
Ok((out, 0))
|
||||
}
|
||||
@@ -0,0 +1,397 @@
|
||||
//! The verbs, run with the encoders loaded: new, bootstrap, teach and score; and report, which needs no encoders.
|
||||
|
||||
use crate::{Eval, at, flag, has, listed, named, words};
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use raea_sys_columns::{Encoders, FPS, media};
|
||||
use raea_sys_fingerprint::evidence::{Ledger, Row, features};
|
||||
use raea_sys_fingerprint::folder::{Folder, root};
|
||||
use raea_sys_fingerprint::inherit;
|
||||
use raea_sys_fingerprint_use::score::{Scored, clock, score, summary, timeline};
|
||||
use raea_sys_fingerprint_use::sheet::{Tick, sheet};
|
||||
use raea_sys_fingerprint::taxonomy::{Applies, Fingerprint, base, words_of};
|
||||
use raea_sys_fingerprint::words::Words;
|
||||
use crate::bootstrap;
|
||||
use raea_sys_fingerprint::{report_text, retrain};
|
||||
use serde_json::json;
|
||||
use std::path::Path;
|
||||
|
||||
/// The fingerprint a verb is about: --fp, else the one `new` made first, else "me"
|
||||
|
||||
/// A verb's answer and exit code
|
||||
pub(crate) fn run(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval, say: &mut dyn FnMut(String)) -> (String, i32) {
|
||||
let rest = &args[1..];
|
||||
let ran = match args[0].as_str() {
|
||||
"new" => new(enc, rest),
|
||||
"bootstrap" => boot(enc, rest, cwd, eval, say),
|
||||
"teach" => teach(enc, rest, cwd, eval),
|
||||
"approve" => approved(enc, rest, cwd, eval),
|
||||
"reembed" => reembedded(enc, rest, cwd, eval),
|
||||
"pair" | "versions" => paired(enc, args[0].as_str(), rest, cwd, eval),
|
||||
"learn-notes" => learned(enc, rest, cwd, eval),
|
||||
"move" => moved(enc, rest, eval),
|
||||
"postmortem" => crate::postmortem::run(enc, rest, cwd, eval),
|
||||
"things" => crate::things::run(enc, rest, cwd),
|
||||
"profile" => {
|
||||
let dir = crate::pick::chosen(rest, None).0;
|
||||
crate::profiles::make(enc, &dir, rest, cwd).map(|o| (o, 0))
|
||||
}
|
||||
"score" => scored(enc, rest, cwd, eval),
|
||||
v => Err(anyhow!("no verb {v}")),
|
||||
};
|
||||
ran.unwrap_or_else(|e| (format!("raea fingerprint {}: {e:#}", args[0]), 1))
|
||||
}
|
||||
|
||||
/// A new fingerprint as `new` makes it: raea's base axes, or the axes of the one it --extends, with --who and --about,
|
||||
/// and the kinds of piece and project tags it judges (--kinds, --tags, each comma-separated)
|
||||
pub(crate) fn shaped(short: &str, args: &[String], parent: Option<Fingerprint>) -> Fingerprint {
|
||||
let mut fp = base(short);
|
||||
if let Some(p) = parent {
|
||||
fp.axes = p.axes;
|
||||
fp.extends = Some(p.name);
|
||||
}
|
||||
fp.who = flag(args, "--who").map(str::to_string).or_else(|| std::env::var("USER").ok());
|
||||
fp.about = flag(args, "--about").map(str::trim).filter(|a| !a.is_empty()).map(str::to_string);
|
||||
let (kinds, tags) = (flag(args, "--kinds").map(words_of).unwrap_or_default(), flag(args, "--tags").map(words_of).unwrap_or_default());
|
||||
if !kinds.is_empty() || !tags.is_empty() {
|
||||
fp.applies = Some(Applies { kinds, tags });
|
||||
}
|
||||
fp
|
||||
}
|
||||
|
||||
fn new(enc: &mut Encoders, args: &[String]) -> Result<(String, i32)> {
|
||||
let n = *words(args).map_err(|e| anyhow!(e))?.first().ok_or_else(|| anyhow!("name it: raea fingerprint new NAME"))?;
|
||||
let dir = Folder::named(n);
|
||||
let short = dir.dir.file_name().map(|s| s.to_string_lossy().into_owned()).unwrap_or_else(|| n.into());
|
||||
let parent = match flag(args, "--extends") {
|
||||
Some(p) => Some(Folder::named(p).read(None).with_context(|| format!("--extends {p}"))?),
|
||||
None => None,
|
||||
};
|
||||
let from = parent.as_ref().map(|p| format!("{}'s axes", p.name)).unwrap_or_else(|| "raea's base taxonomy".into());
|
||||
let mut fp = shaped(&short, args, parent);
|
||||
fp.encoders = enc.pins();
|
||||
dir.create(&fp)?;
|
||||
let w = Words::build(enc, &fp)?;
|
||||
dir.write_words(&w)?;
|
||||
retrain(&dir, &fp, &w, &Ledger::default(), None)?;
|
||||
if !root().join("default").exists() && dir.dir.parent() == Some(root().as_path()) {
|
||||
std::fs::write(root().join("default"), &short)?;
|
||||
}
|
||||
Ok((
|
||||
format!(
|
||||
"made {}: {} axes from {from}, {} scoring from their words today (advice until they earn a gate)\n edit {} to add, remove or reword axes\n next: raea fingerprint bootstrap FILE... with your own finished work trains the mechanical axes",
|
||||
dir.dir.display(),
|
||||
fp.axes.len(),
|
||||
w.axes.len(),
|
||||
dir.ts().display()
|
||||
),
|
||||
0,
|
||||
))
|
||||
}
|
||||
|
||||
/// The fingerprint, its encoders checked against this machine's, and its words, made again when they changed
|
||||
/// The fingerprint a verb uses (pick.rs: --fp, else the one that judges the file), its axes with its parents', and its
|
||||
/// words
|
||||
pub(crate) fn open(enc: &mut Encoders, args: &[String], eval: Eval, file: Option<&Path>) -> Result<(Folder, Fingerprint, Words)> {
|
||||
let dir = crate::pick::chosen(args, file).0;
|
||||
let mut raw = dir.read(Some(eval))?;
|
||||
let here = enc.pins();
|
||||
if raw.encoders.is_empty() {
|
||||
raw.encoders = here;
|
||||
dir.rewrite(&raw)?;
|
||||
} else if here.iter().filter(|(k, v)| raw.encoders.get(*k) == Some(*v)).count() == raw.encoders.len() && raw.encoders != here {
|
||||
// an encoder added since (EmbeddingGemma 2, FP1b) doesn't change the ones it was trained on
|
||||
raw.encoders = here;
|
||||
dir.rewrite(&raw)?;
|
||||
} else if raw.encoders != here {
|
||||
bail!(
|
||||
"{} was trained on other encoders ({:?}) than this machine has ({:?}); its heads refuse these columns. `raea fingerprint reembed FOLDER...` moves its evidence to these, re-embedding the rows whose media it finds",
|
||||
dir.ts().display(),
|
||||
raw.encoders,
|
||||
here
|
||||
);
|
||||
}
|
||||
// a fingerprint that extends another judges with its parents' axes too (FP14b)
|
||||
let fp = inherit::axes(&raw, &inherit::parents(&raw, Some(eval)));
|
||||
let w = match dir.words().filter(|w| !w.stale(&fp)) {
|
||||
Some(w) => w,
|
||||
None => {
|
||||
let w = Words::build(enc, &fp)?;
|
||||
dir.write_words(&w)?;
|
||||
w
|
||||
}
|
||||
};
|
||||
// a shared fingerprint arrives with evidence and no heads: this machine trains its own (FP8a)
|
||||
if !dir.dir.join("heads.safetensors").is_file() {
|
||||
let l = dir.ledger()?;
|
||||
if !l.rows.is_empty() {
|
||||
retrain(&dir, &fp, &w, &l, None)?;
|
||||
}
|
||||
}
|
||||
Ok((dir, fp, w))
|
||||
}
|
||||
|
||||
fn boot(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval, say: &mut dyn FnMut(String)) -> Result<(String, i32)> {
|
||||
let (dir, fp, w) = open(enc, args, eval, None)?;
|
||||
let mut files = named(args, cwd)?;
|
||||
if let Some(list) = flag(args, "--from") {
|
||||
files.extend(listed(cwd, list)?);
|
||||
}
|
||||
if files.is_empty() {
|
||||
bail!("give it real finished work: raea fingerprint bootstrap FILE... or --from LIST (no placeholder footage)");
|
||||
}
|
||||
let per: usize = flag(args, "--per").map_or(Ok(10), str::parse).context("--per takes a count")?;
|
||||
let mut l = dir.ledger()?;
|
||||
let who = fp.who.clone().unwrap_or_else(|| "me".into());
|
||||
let made = bootstrap::rows(enc, &who, &files, per, &mut l, say)?;
|
||||
dir.write_ledger(&l)?;
|
||||
say(format!("{} windows from {} sources; measuring held out by source", made.windows, made.sources));
|
||||
let curves = bootstrap::curves(&fp, &l);
|
||||
let ws = bootstrap::word_scores(&l, &w);
|
||||
let patches = raea_sys_fingerprint_things::located::bootstrap(enc, &dir.dir, &files, per, say)?;
|
||||
let b = json!({"made": made, "per": per, "sources": files, "curves": curves, "words": ws, "patches": patches});
|
||||
retrain(&dir, &fp, &w, &l, Some(b))?;
|
||||
Ok((report_text(&dir.report().unwrap_or_default()), 0))
|
||||
}
|
||||
|
||||
/// The project a file belongs to: the folder holding .raea/project above it, else the folder it's in
|
||||
fn project_of(file: &Path) -> String {
|
||||
let mut d = file.parent();
|
||||
while let Some(p) = d {
|
||||
if p.join(".raea/project").exists() {
|
||||
return p.file_name().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
}
|
||||
d = p.parent();
|
||||
}
|
||||
file.parent().and_then(|p| p.file_name()).map(|s| s.to_string_lossy().into_owned()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// `approve`: approved work as clean rows on every axis (approve.rs, FP6a), then the heads retrained
|
||||
fn approved(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result<(String, i32)> {
|
||||
let first = words(args).map_err(|e| anyhow!(e))?.first().map(|f| at(cwd, f));
|
||||
let (dir, fp, w) = open(enc, args, eval, first.as_deref())?;
|
||||
let (mut out, _) = crate::approve::approve(enc, &dir, &fp, args, cwd, project_of)?;
|
||||
let tr = retrain(&dir, &fp, &w, &dir.ledger()?, None)?;
|
||||
out += &format!("{} axes gating\n", tr.heads.iter().filter(|h| h.state == "gating").count());
|
||||
Ok((out, 0))
|
||||
}
|
||||
|
||||
/// `reembed`: the evidence moved to this machine's encoders (reembed.rs, FP8c), the words remade and the heads retrained
|
||||
fn reembedded(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result<(String, i32)> {
|
||||
let dir = crate::pick::chosen(args, None).0;
|
||||
let raw = dir.read(Some(eval))?;
|
||||
let (fp, out) = crate::reembed::reembed(enc, &dir, raw, enc.pins(), args, cwd)?;
|
||||
let fp = inherit::axes(&fp, &inherit::parents(&fp, Some(eval)));
|
||||
let w = Words::build(enc, &fp)?;
|
||||
dir.write_words(&w)?;
|
||||
retrain(&dir, &fp, &w, &dir.ledger()?, None)?;
|
||||
Ok((out, 0))
|
||||
}
|
||||
|
||||
/// `pair` and `versions` (pairing.rs, FP6b, FP6c), then the heads retrained
|
||||
fn paired(enc: &mut Encoders, verb: &str, args: &[String], cwd: &Path, eval: Eval) -> Result<(String, i32)> {
|
||||
let first = words(args).map_err(|e| anyhow!(e))?.first().map(|f| at(cwd, f));
|
||||
let (dir, fp, w) = open(enc, args, eval, first.as_deref())?;
|
||||
let who = fp.who.clone().unwrap_or_else(|| "me".into());
|
||||
let mut l = dir.ledger()?;
|
||||
let out = if verb == "pair" { crate::pairing::pair(enc, &mut l, &who, args, cwd, project_of)? } else { crate::pairing::versions(enc, &mut l, &who, args, cwd, project_of)? };
|
||||
dir.write_ledger(&l)?;
|
||||
retrain(&dir, &fp, &w, &l, None)?;
|
||||
Ok((out, 0))
|
||||
}
|
||||
|
||||
/// `learn-notes [PROJECT]` (notes.rs, FP5a): checked readings as evidence in the fingerprint that judges the project
|
||||
/// (FP14d), then its heads retrained
|
||||
fn learned(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result<(String, i32)> {
|
||||
let (dir, fp, w) = open(enc, args, eval, Some(&crate::pick::piece_in(args, cwd)))?;
|
||||
let mut l = dir.ledger()?;
|
||||
let out = crate::notes::learn(enc, &dir, &mut l)?;
|
||||
dir.write_ledger(&l)?;
|
||||
retrain(&dir, &fp, &w, &l, None)?;
|
||||
Ok((out, 0))
|
||||
}
|
||||
|
||||
/// `move` (moving.rs, FP14d): a child's own labels up into a fingerprint it extends, then both retrained
|
||||
fn moved(enc: &mut Encoders, args: &[String], eval: Eval) -> Result<(String, i32)> {
|
||||
let (dir, fp, w) = open(enc, args, eval, None)?;
|
||||
let (to, out) = crate::moving::up(&dir, &dir.read(Some(eval))?, args, eval)?;
|
||||
retrain(&dir, &fp, &w, &dir.ledger()?, None)?;
|
||||
let (pd, pfp, pw) = open(enc, &["--fp".into(), to], eval, None)?;
|
||||
retrain(&pd, &pfp, &pw, &pd.ledger()?, None)?;
|
||||
Ok((out, 0))
|
||||
}
|
||||
|
||||
fn teach(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result<(String, i32)> {
|
||||
let file = at(cwd, words(args).map_err(|e| anyhow!(e))?.first().ok_or_else(|| anyhow!("which file?"))?);
|
||||
let (dir, fp, w) = open(enc, args, eval, Some(&file))?;
|
||||
let axis = flag(args, "--axis").ok_or_else(|| anyhow!("--axis A (or \"*\" for every axis)"))?;
|
||||
if axis != "*" && fp.axis(axis).is_none() {
|
||||
bail!("no axis {axis:?} in {}: its axes are {}", dir.ts().display(), fp.axes.iter().map(|a| a.name.as_str()).collect::<Vec<_>>().join(", "));
|
||||
}
|
||||
let t: f64 = flag(args, "--at").ok_or_else(|| anyhow!("--at SECONDS"))?.parse().context("--at takes seconds")?;
|
||||
let span: f64 = flag(args, "--span").map_or(Ok(2.0), str::parse).context("--span takes seconds")?;
|
||||
let region = flag(args, "--box").map(|b| -> Result<[f32; 4]> {
|
||||
let v: Vec<f32> = b.split(',').map(str::parse).collect::<Result<_, _>>().context("--box takes x0,y0,x1,y1 in 0-1")?;
|
||||
v.try_into().map_err(|_| anyhow!("--box takes four numbers"))
|
||||
});
|
||||
let c = enc.columns(&file)?;
|
||||
let a = (t - span / 2.0).clamp(0.0, (c.dur - span).max(0.0));
|
||||
let b = (a + span).min(c.dur);
|
||||
let bad = !has(args, "--good");
|
||||
let row = Row {
|
||||
media: c.media.clone(),
|
||||
a,
|
||||
b,
|
||||
axis: axis.into(),
|
||||
bad,
|
||||
weight: 1.0,
|
||||
who: fp.who.clone().unwrap_or_else(|| "me".into()),
|
||||
source: "teach".into(),
|
||||
project: flag(args, "--project").map_or_else(|| project_of(&file), str::to_string),
|
||||
kind: None,
|
||||
region: region.transpose()?,
|
||||
words: flag(args, "--words").map(str::to_string),
|
||||
at: 0,
|
||||
pin: None,
|
||||
};
|
||||
let mut l = dir.ledger()?;
|
||||
l.push(row, &features(&c, a, b));
|
||||
dir.write_ledger(&l)?;
|
||||
let tr = retrain(&dir, &fp, &w, &l, None)?;
|
||||
let h = tr.heads.iter().find(|h| h.axis == axis);
|
||||
let (p, n) = l.for_axis(axis).iter().fold((0, 0), |(p, n), &i| if l.rows[i].bad { (p + 1, n) } else { (p, n + 1) });
|
||||
Ok((
|
||||
format!(
|
||||
"taught {axis}: {} at {} in {}\n {axis} has {p} defect and {n} clean labels; its head: {}",
|
||||
if bad { "the defect" } else { "clean" },
|
||||
clock(t),
|
||||
file.display(),
|
||||
h.map_or("every axis's clean labels grew".to_string(), |h| format!("{} ({})", h.state, h.why))
|
||||
),
|
||||
0,
|
||||
))
|
||||
}
|
||||
|
||||
/// raea check's findings on the file, in seconds: (rule, from, to, what)
|
||||
fn checks(file: &Path) -> Vec<(String, f64, f64, String)> {
|
||||
let Ok(found) = raea_app_check::floor(&[file.display().to_string()], &[], &[]) else { return Vec::new() };
|
||||
found.into_iter().map(|f| {
|
||||
let (a, b) = f.frames.map_or((0.0, 0.0), |[a, b]| (a as f64 / 30.0, b as f64 / 30.0));
|
||||
(f.check, a, b, f.says)
|
||||
}).collect()
|
||||
}
|
||||
|
||||
/// A check wins over a head (FP4c): a moment on an axis a check measures is no gate unless the check found it too
|
||||
fn arbitrate(s: &mut Scored, fp: &Fingerprint, found: &[(String, f64, f64, String)]) {
|
||||
for m in &mut s.moments {
|
||||
let Some(rule) = fp.axis(&m.axis).and_then(|a| a.check.as_deref()) else { continue };
|
||||
let agrees = found.iter().any(|(r, a, b, _)| r == rule && *a <= m.b + 1.0 && *b >= m.a - 1.0);
|
||||
if !agrees {
|
||||
m.gating = false;
|
||||
m.state = format!("{}; the {rule} check found none", m.state);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn scored(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result<(String, i32)> {
|
||||
let file = at(cwd, words(args).map_err(|e| anyhow!(e))?.first().ok_or_else(|| anyhow!("which file?"))?);
|
||||
let (dir, fp, w) = open(enc, args, eval, Some(&file))?;
|
||||
let why = crate::pick::chosen(args, Some(&file)).1.map_or_else(|| "named with --fp, or the account's default".to_string(), |c| c.why);
|
||||
let c = enc.columns(&file)?;
|
||||
let trained = dir.trained()?.map(|(t, _)| t);
|
||||
let mut s = score(&fp, Some(&w), trained.as_ref(), &c, &file.display().to_string());
|
||||
let found = checks(&file);
|
||||
arbitrate(&mut s, &fp, &found);
|
||||
raea_sys_fingerprint_things::located::locate(enc, &file, &raea_sys_fingerprint_use::patch::load(&dir.dir), &mut s)?;
|
||||
// FP9a: each gating flag on the cut before, judged on this one, and its axis's disguises rerun on the fix
|
||||
let fixes = match flag(args, "--was") {
|
||||
Some(old) => {
|
||||
let was = at(cwd, old);
|
||||
let mut ws = score(&fp, Some(&w), trained.as_ref(), &enc.columns(&was)?, &was.display().to_string());
|
||||
arbitrate(&mut ws, &fp, &checks(&was));
|
||||
Some(raea_sys_fingerprint_use::fixed::fixes(&ws, &s, &fp, &dir.ledger()?, &c))
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let mut out = if has(args, "--json") {
|
||||
serde_json::to_string_pretty(&json!({"fingerprint": {"name": fp.name, "about": fp.about, "why": why}, "scored": s, "checks": found.iter().map(|(r, a, b, says)| json!({"check": r, "a": a, "b": b, "says": says})).collect::<Vec<_>>(), "fixes": fixes}))?
|
||||
} else if let Some(f) = &fixes {
|
||||
let mut t = format!("judged by {}: {why}\n", fp.name);
|
||||
t += &raea_sys_fingerprint_use::fixed::said(f);
|
||||
t += &summary(&s);
|
||||
t
|
||||
} else {
|
||||
let mut t = format!("judged by {}: {why}\n", fp.name);
|
||||
t += &summary(&s);
|
||||
t += &format!("checks: {}\n", if found.is_empty() { "no findings".to_string() } else { format!("{} findings", found.len()) });
|
||||
for (r, a, _, says) in &found {
|
||||
t += &format!(" {} {r}: {says}\n", clock(*a));
|
||||
}
|
||||
t
|
||||
};
|
||||
if has(args, "--timeline") {
|
||||
out += &timeline(&s);
|
||||
}
|
||||
if let Some(p) = flag(args, "--profile") {
|
||||
out += &crate::profiles::against(enc, &dir, p, &file)?.0;
|
||||
}
|
||||
if let Some(png) = flag(args, "--sheet") {
|
||||
let png = at(cwd, png);
|
||||
let frames: Vec<media::Rgb> = (0..12).filter_map(|i| media::frames(&file, FPS, c.dur * (i as f64 + 0.5) / 12.0, 0.25).ok()?.into_iter().next()).collect();
|
||||
let pcm = media::sound(&file, 16_000)?;
|
||||
let ticks: Vec<Tick> = found.iter().map(|(r, a, b, _)| Tick { a: *a, b: *b, what: r.clone() }).collect();
|
||||
sheet(&s, &frames, &pcm, &ticks, &|axis| fp.axis(axis).map(|a| a.modality), &png)?;
|
||||
out += &format!("sheet: {}\n", png.display());
|
||||
}
|
||||
let unfixed = fixes.iter().flatten().any(|f| f.verdict != "fixed");
|
||||
Ok((out, i32::from(unfixed || s.moments.iter().any(|m| m.gating))))
|
||||
}
|
||||
|
||||
/// `raea fingerprint report`: report.json, read; no encoders needed
|
||||
pub(crate) fn report_here(args: &[String]) -> i32 {
|
||||
let dir = crate::pick::chosen(args, None).0;
|
||||
match dir.report() {
|
||||
Some(r) if has(args, "--json") => {
|
||||
println!("{}", serde_json::to_string_pretty(&r).unwrap_or_default());
|
||||
0
|
||||
}
|
||||
Some(r) => {
|
||||
println!("{}", report_text(&r).trim_end());
|
||||
0
|
||||
}
|
||||
None => {
|
||||
eprintln!("raea fingerprint report: no report at {} (`raea fingerprint new NAME` makes one)", dir.dir.display());
|
||||
1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::shaped;
|
||||
use raea_sys_fingerprint::taxonomy::{Applies, base};
|
||||
|
||||
fn args(xs: &[&str]) -> Vec<String> {
|
||||
xs.iter().map(|x| x.to_string()).collect()
|
||||
}
|
||||
|
||||
/// FP14a: a new fingerprint says what it's for, and one that extends another starts from its axes
|
||||
#[test]
|
||||
fn a_new_fingerprint_says_what_its_for_and_what_it_builds_on() {
|
||||
let own = shaped("me", &args(&["me", "--who", "w"]), None);
|
||||
assert_eq!((own.about.as_deref(), own.extends.as_deref(), own.who.as_deref()), (None, None, Some("w")));
|
||||
assert_eq!(own.axes, base("me").axes);
|
||||
|
||||
let mut parent = base("me");
|
||||
parent.axes.truncate(2);
|
||||
parent.axes[0].words = vec!["a soft picture".into()];
|
||||
let ads = shaped("ads", &args(&["ads", "--about", " Short ads for one brand ", "--extends", "me"]), Some(parent.clone()));
|
||||
assert_eq!(ads.name, "ads");
|
||||
assert_eq!(ads.about.as_deref(), Some("Short ads for one brand"));
|
||||
assert_eq!(ads.extends.as_deref(), Some("me"));
|
||||
assert_eq!(ads.axes, parent.axes);
|
||||
assert_eq!(shaped("x", &args(&["x", "--about", " "]), None).about, None);
|
||||
assert_eq!(own.applies, None);
|
||||
let judged = shaped("ads", &args(&["ads", "--kinds", "ad, Playable", "--tags", "brand,"]), None);
|
||||
assert_eq!(judged.applies, Some(Applies { kinds: vec!["ad".into(), "playable".into()], tags: vec!["brand".into()] }));
|
||||
}
|
||||
}
|
||||
@@ -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,7 +1,7 @@
|
||||
//! The media verbs' command line (`raea media|ffmpeg|ffprobe`, and raea's shell, in process): the agent's media
|
||||
//! work on raea-media (lib.rs and its files), and an HTML composition's render (html.rs).
|
||||
//!
|
||||
//! media probe|still|sheet|audio|loudness|motion|cuts|freezes|proxy|trim|concat FILE ... media work, native (media help)
|
||||
//! media probe|still|sheet|audio|loudness|motion|cuts|freezes|proxy|lod|trim|concat FILE ... media work, native (media help)
|
||||
//! ffmpeg ARGS | ffprobe ARGS ffmpeg and ffprobe command lines read as the media verbs (no ffmpeg involved)
|
||||
//! render PAGE.html -o OUT.mp4|OUT.png|DIR [--at F,F] [--alpha] [--codec apple|soft|av1|ffmpeg] [--kbps K | --quality Q]
|
||||
//! shots [--size WxH] [--root DIR] plain HTML pages' first frames as PNGs, over white: stdin lines `PAGE\tOUT.png`,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
Loaded 100 of 1160 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user