mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-01 06:53:19 -10:00
Compare commits
95
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
028a2e2151 | ||
|
|
f4db12c1d0 | ||
|
|
cd159fe0be | ||
|
|
316b612d70 | ||
|
|
aa40a2fa86 | ||
|
|
48705982b6 | ||
|
|
7580433cd2 | ||
|
|
28f3fd814b | ||
|
|
1905dc723c | ||
|
|
c41dd64516 | ||
|
|
1fc3a07655 | ||
|
|
986bd33463 | ||
|
|
c41ec580a9 | ||
|
|
7e25dcc56e | ||
|
|
561e7a569c | ||
|
|
0649788f7f | ||
|
|
1a77da4980 | ||
|
|
1a913e6b06 | ||
|
|
7db0e7e149 | ||
|
|
ab63120653 | ||
|
|
8938819947 | ||
|
|
79cda1dc8c | ||
|
|
f0a266718e | ||
|
|
c8af179033 | ||
|
|
a0f6a95fe7 | ||
|
|
afaeaa0a7a | ||
|
|
65f2a6ae1e | ||
|
|
00deff035c | ||
|
|
7611a96e34 | ||
|
|
6fb27ef9e8 | ||
|
|
0c0de9b3d6 | ||
|
|
84f6c59dd0 | ||
|
|
96adb3ecfb | ||
|
|
4e12541984 | ||
|
|
4cc8f58e0a | ||
|
|
1873676251 | ||
|
|
374426411e | ||
|
|
e435bff43e | ||
|
|
4b2b39edd3 | ||
|
|
063ae93f30 | ||
|
|
2a63d75e1b | ||
|
|
2a005e0e30 | ||
|
|
04098af5af | ||
|
|
22834de9b1 | ||
|
|
300e094b9d | ||
|
|
7e214fedbb | ||
|
|
280437c111 | ||
|
|
11f28ffc52 | ||
|
|
107b591555 | ||
|
|
b7cc2694aa | ||
|
|
2bd30c5fad | ||
|
|
d169848689 | ||
|
|
0d92089f7d | ||
|
|
5885f86ff3 | ||
|
|
e02151cf49 | ||
|
|
49c2c96a1a | ||
|
|
346cacd71a | ||
|
|
ad766214e0 | ||
|
|
745c5f98c8 | ||
|
|
d36b0604bc | ||
|
|
03c2e2ee15 | ||
|
|
21859a5a31 | ||
|
|
f02348c397 | ||
|
|
64d97bac8f | ||
|
|
b9d1beaa2f | ||
|
|
b1a8d57616 | ||
|
|
9adc87dcd9 | ||
|
|
3a1cff770b | ||
|
|
09d87cfa1c | ||
|
|
afa6702c05 | ||
|
|
38f49d623f | ||
|
|
7ded6a7612 | ||
|
|
6416e4ec1b | ||
|
|
2556f42366 | ||
|
|
f2351359c8 | ||
|
|
7595c81782 | ||
|
|
1926af81a5 | ||
|
|
5d5da4f3d8 | ||
|
|
760d8e53c1 | ||
|
|
40757526f8 | ||
|
|
50a7e94f5e | ||
|
|
6735bd940f | ||
|
|
b250367b6c | ||
|
|
813bc24097 | ||
|
|
2127b369d3 | ||
|
|
5650d65c65 | ||
|
|
974148442e | ||
|
|
89fd926258 | ||
|
|
dd9be82976 | ||
|
|
784e156895 | ||
|
|
2161fa0ba0 | ||
|
|
e745f91ae4 | ||
|
|
a0f685b043 | ||
|
|
5c4ddb6989 | ||
|
|
17518a3ac1 |
No files matched your search
@@ -118,7 +118,12 @@ jobs:
|
||||
# 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-runtime-plugins -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
|
||||
# raea-bundle in a call of its own: Rolldown's crates turn on serde_json's arbitrary_precision, features unify
|
||||
# across one cargo call, and with it on an untagged enum can't read a number (raea-core-brief's make dials failed
|
||||
# here from 11-23 while passing alone). raea itself never links Rolldown: it loads it as a library at run time
|
||||
run: |
|
||||
cargo test --locked -p raea-runtime-plugins -p raea-io-media -p raea-core-fonts -p raea-native -p raea-core-brief -p raea-core-k -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
|
||||
cargo test --locked -p raea-bundle
|
||||
- name: Windows' and Linux's own (#169)
|
||||
# what a Windows or Linux user meets that no other step ran: QuickJS's Intl (raea-runtime-jsengine's
|
||||
# quickjs_formats_as_javascriptcore_does, on Linux), openh264 at --quality master (raea-io-soft), git found or
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
# Apple Silicon, Linux on x86_64 and Windows on x86_64 are built from the tag on GitHub's runners, packed by
|
||||
# tools/release.sh, checked by tools/release-check.sh, attested (anyone can check a download with
|
||||
# `gh attestation verify raea-VERSION-macos-arm64.tar.gz -R shinyobjectz/raea`) and attached to the tag's release.
|
||||
# Linux also packages and checks an AppImage from the same verified archive (tools/release-appimage.sh).
|
||||
# The skills gate reads the feed app, which is private, so it runs in a maintainer's checkout first
|
||||
# (tools/skills.sh check), and the tag names the commit it passed on; tools/release.sh checks the gate's inputs haven't
|
||||
# changed since (tools/release/skills-passed.sh):
|
||||
@@ -181,6 +182,11 @@ jobs:
|
||||
v=${TAG#v}
|
||||
if [ "$RUNNER_OS" = Linux ]; then xvfb-run -a -s "-screen 0 1280x1024x24" bash tools/release.sh "$v" ship HEAD
|
||||
else bash tools/release.sh "$v" ship HEAD; fi
|
||||
- name: Package and check the Linux AppImage
|
||||
if: runner.os == 'Linux'
|
||||
env:
|
||||
RAEA_CHECK_DIR: ${{ runner.temp }}/appimage-check
|
||||
run: xvfb-run -a -s "-screen 0 1280x1024x24" bash tools/release-appimage.sh "${TAG#v}" "dist/raea-${TAG#v}-linux-x86_64.tar.gz"
|
||||
# a failed check's own files (the app check's frames, every step's log), not the unpacked release
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: failure()
|
||||
@@ -189,6 +195,8 @@ jobs:
|
||||
path: |
|
||||
${{ runner.temp }}/release-check/app
|
||||
${{ runner.temp }}/release-check/**/*.log
|
||||
${{ runner.temp }}/appimage-check/app
|
||||
${{ runner.temp }}/appimage-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
|
||||
@@ -202,6 +210,10 @@ jobs:
|
||||
if: ${{ !inputs.dry_run }}
|
||||
with:
|
||||
subject-path: dist/raea-*.tar.gz
|
||||
- uses: actions/attest-build-provenance@v2
|
||||
if: ${{ runner.os == 'Linux' && !inputs.dry_run }}
|
||||
with:
|
||||
subject-path: dist/raea-*.AppImage
|
||||
- name: Attach to the release
|
||||
if: ${{ !inputs.dry_run }}
|
||||
env:
|
||||
@@ -209,11 +221,16 @@ jobs:
|
||||
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
|
||||
if [ "$RUNNER_OS" = Linux ]; then
|
||||
gh release upload "$TAG" dist/raea-*.AppImage dist/raea-*.AppImage.sha256 --clobber
|
||||
fi
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: ${{ inputs.dry_run }}
|
||||
with:
|
||||
name: dry-run-${{ runner.os }}
|
||||
path: dist/raea-*.tar.gz*
|
||||
path: |
|
||||
dist/raea-*.tar.gz*
|
||||
dist/raea-*.AppImage*
|
||||
retention-days: 3
|
||||
compression-level: 0
|
||||
|
||||
@@ -223,6 +240,9 @@ jobs:
|
||||
# (tools/release/win-bundle.sh), as Microsoft documents for app-local deployment.
|
||||
windows:
|
||||
runs-on: ${{ (vars.RELEASE_WINDOWS_RUNNER && fromJSON(vars.RELEASE_WINDOWS_RUNNER)) || 'windows-latest' }}
|
||||
# the signing identity's federated credential trusts this repository's environment "signing" and nothing else
|
||||
# (Azure app raea-release-signing); with no identity set there is no environment, and the zip is unsigned
|
||||
environment: ${{ vars.AZURE_SIGN_CLIENT_ID != '' && 'signing' || '' }}
|
||||
timeout-minutes: 350
|
||||
env:
|
||||
# the compile cache, as build's
|
||||
@@ -352,9 +372,24 @@ jobs:
|
||||
run: bash tools/release/lavapipe.sh
|
||||
- name: Where the skills gate passed
|
||||
run: bash tools/release/skills-passed.sh "$TAG" "${{ inputs.skills_passed }}"
|
||||
# raea's own Windows programs signed (#221), once the repository has the signing identity: the variables
|
||||
# AZURE_SIGN_CLIENT_ID, AZURE_SIGN_TENANT_ID and AZURE_SIGN_SUBSCRIPTION_ID name an Azure app whose federated
|
||||
# credential trusts this workflow and which holds the Artifact Signing Certificate Profile Signer role on the
|
||||
# account (no secret is stored: the job's own token is exchanged). Without them the zip is unsigned, as before
|
||||
- name: Sign in to Azure for signing
|
||||
if: ${{ vars.AZURE_SIGN_CLIENT_ID != '' }}
|
||||
uses: azure/login@v2
|
||||
with:
|
||||
client-id: ${{ vars.AZURE_SIGN_CLIENT_ID }}
|
||||
tenant-id: ${{ vars.AZURE_SIGN_TENANT_ID }}
|
||||
subscription-id: ${{ vars.AZURE_SIGN_SUBSCRIPTION_ID }}
|
||||
- name: jsign (signs raea's programs)
|
||||
if: ${{ vars.AZURE_SIGN_CLIENT_ID != '' }}
|
||||
run: choco install jsign -y --no-progress
|
||||
- name: Pack and check (tools/release.sh)
|
||||
env:
|
||||
RAEA_CHECK_DIR: ${{ runner.temp }}/release-check
|
||||
RAEA_WIN_SIGN: ${{ vars.AZURE_SIGN_CLIENT_ID != '' && '1' || '' }}
|
||||
run: bash tools/release.sh "${TAG#v}" target/dist HEAD
|
||||
# live play on Windows (PT20 left it unproven): bevy-ts's play cases, `play --offscreen` with an input script and
|
||||
# a snapshot's pixels probed, run by the raea just built; check.sh reads the pixels with ImageMagick, which the
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
# raea built natively for Windows on ARM (#82: a Snapdragon X runs the x64 build under emulation, and asked for its
|
||||
# own). GitHub's windows-11-arm runner builds what release.yml's windows job builds, for aarch64-pc-windows-msvc, runs
|
||||
# `raea --version`, packs and checks raea-VERSION-windows-arm64.zip with tools/release.sh (RAEA_WIN_ARCH=arm64)
|
||||
# without drawing (RAEA_CHECK_NO_GPU=1: WARP segfaults in Bevy's compute shaders here as on x64, and Mesa's lavapipe has
|
||||
# no ARM64 build; a Snapdragon PC is what draws, #82), and on a v* tag attaches it to that
|
||||
# release. It runs beside release.yml, not in it, so a release never waits on or fails with the ARM64 build; a
|
||||
# promoted release (release-go.sh) builds it again from the tag. install.ps1 takes it on an ARM64 PC when it's there.
|
||||
name: windows-arm
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
ref:
|
||||
description: "commit, branch or tag to build"
|
||||
required: false
|
||||
version:
|
||||
description: "the version the zip is named for (raea-VERSION-windows-arm64.zip)"
|
||||
required: false
|
||||
push:
|
||||
branches: [windows-arm64]
|
||||
tags: ["v*"]
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: windows-11-arm
|
||||
timeout-minutes: 350
|
||||
env:
|
||||
# the release builds' compile cache (tools/release/compile-cache.sh), under this OS and architecture's own prefix
|
||||
RELEASE_CACHE_ENDPOINT: ${{ secrets.RELEASE_CACHE_ENDPOINT }}
|
||||
AWS_ACCESS_KEY_ID: ${{ secrets.RELEASE_CACHE_KEY_ID }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ secrets.RELEASE_CACHE_SECRET }}
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ inputs.ref || github.sha }}
|
||||
submodules: true
|
||||
lfs: false
|
||||
- name: Toolchain (rust-toolchain.toml's pin)
|
||||
run: |
|
||||
if ! command -v rustup >/dev/null; then
|
||||
curl -fsSL --retry 3 -o "$RUNNER_TEMP/rustup-init.exe" https://static.rust-lang.org/rustup/dist/aarch64-pc-windows-msvc/rustup-init.exe
|
||||
"$RUNNER_TEMP/rustup-init.exe" -y --default-toolchain none --profile minimal
|
||||
echo "$USERPROFILE/.cargo/bin" >> "$GITHUB_PATH"
|
||||
export PATH="$USERPROFILE/.cargo/bin:$PATH"
|
||||
fi
|
||||
rustup show active-toolchain || rustup toolchain install
|
||||
rustc -vV
|
||||
# ring builds its aarch64 assembly with clang (and only clang) on Windows
|
||||
- name: clang (ring's assembly)
|
||||
run: |
|
||||
if ! command -v clang >/dev/null; then
|
||||
for d in "/c/Program Files/LLVM/bin" "/c/Program Files/Microsoft Visual Studio"/*/*/VC/Tools/Llvm/ARM64/bin; do
|
||||
[ -x "$d/clang.exe" ] && { echo "$d" >> "$GITHUB_PATH"; export PATH="$d:$PATH"; break; }
|
||||
done
|
||||
fi
|
||||
command -v clang >/dev/null || { winget install -e --id LLVM.LLVM --accept-source-agreements --accept-package-agreements --silent; echo "/c/Program Files/LLVM/bin" >> "$GITHUB_PATH"; export PATH="/c/Program Files/LLVM/bin:$PATH"; }
|
||||
clang --version
|
||||
- name: jq that writes LF
|
||||
run: |
|
||||
mkdir -p "$RUNNER_TEMP/jq"
|
||||
printf '#!/bin/bash\nexec "%s" -b "$@"\n' "$(command -v jq)" > "$RUNNER_TEMP/jq/jq"
|
||||
chmod +x "$RUNNER_TEMP/jq/jq"
|
||||
echo "$RUNNER_TEMP/jq" >> "$GITHUB_PATH"
|
||||
- uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: 1.4.2
|
||||
- name: The runtime's packages
|
||||
run: for d in sdk/react/js sdk/react/tw; do (cd "$d" && bun install --frozen-lockfile); done
|
||||
# (an sccache the action can't fetch for ARM64 Windows leaves the build uncached, as compile-cache.sh does)
|
||||
- name: Compile cache (sccache, as release.yml's)
|
||||
if: env.AWS_ACCESS_KEY_ID != ''
|
||||
continue-on-error: true
|
||||
uses: mozilla-actions/[email protected]
|
||||
- name: Use the compile cache
|
||||
if: env.AWS_ACCESS_KEY_ID != ''
|
||||
run: bash tools/release/compile-cache.sh
|
||||
- name: Build
|
||||
run: |
|
||||
feat=$(bash tools/bevy-plugins.sh features sdk/raea/bench/bevy-plugins)
|
||||
t() { s=$SECONDS; "$@"; echo "::notice::Windows ARM64 $(( (SECONDS - s) / 60 )) min: ${*:7}"; }
|
||||
t cargo build --profile dist --locked -p raea-cli --bin raea --no-default-features --features "$feat"
|
||||
t cargo build --profile dist --locked -p raea-rune-host
|
||||
t cargo build --profile dist --locked -p raea-page-host --features window
|
||||
t cargo build --profile dist --locked -p raea-perceive
|
||||
- name: What raea.exe is and imports
|
||||
run: |
|
||||
file target/dist/raea.exe || true
|
||||
dumpbin=$(ls "/c/Program Files/Microsoft Visual Studio"/*/*/VC/Tools/MSVC/*/bin/Hostarm64/arm64/dumpbin.exe 2>/dev/null | head -1)
|
||||
[ -n "$dumpbin" ] && "$dumpbin" -nologo -headers -dependents target/dist/raea.exe | grep -iE 'machine|\.dll$' | sed 's/^ *//' | tee -a "$GITHUB_STEP_SUMMARY" || true
|
||||
target/dist/raea.exe --version | tee -a "$GITHUB_STEP_SUMMARY"
|
||||
- name: Models (pinned by URL and sha256 in tools/release/models.tsv)
|
||||
run: |
|
||||
while IFS=$'\t' read -r path url sha; do
|
||||
case $path in ''|'#'*) continue ;; esac
|
||||
mkdir -p "$HOME/.local/share/raea-models/$(dirname "$path")"
|
||||
curl -fsSL "$url" -o "$HOME/.local/share/raea-models/$path"
|
||||
echo "$sha $HOME/.local/share/raea-models/$path" | sha256sum -c -
|
||||
done < <(tr -d '\r' < tools/release/models.tsv)
|
||||
# bin\ as release.yml's windows job fills it, with the ARM64 runtime, uv and DXC (RAEA_WIN_ARCH=arm64), then the
|
||||
# zip packed and checked by tools/release.sh as raea-VERSION-windows-arm64.zip. The skills gate is this commit's
|
||||
# (public raea has no feed app; cli.md is still checked against this build's help); nothing is drawn
|
||||
- name: Pack and check (tools/release.sh)
|
||||
env:
|
||||
RAEA_WIN_ARCH: arm64
|
||||
RAEA_CHECK_DIR: ${{ runner.temp }}/release-check
|
||||
RAEA_CHECK_NO_GPU: "1"
|
||||
run: |
|
||||
bash tools/release/onnxruntime.sh target/dist
|
||||
bash tools/release/win-bundle.sh target/dist
|
||||
v="${{ inputs.version }}"
|
||||
case $GITHUB_REF in
|
||||
refs/tags/v*)
|
||||
v=${v:-${GITHUB_REF_NAME#v}}
|
||||
# where the skills gate passed, as release.yml reads it (the tag's skills-passed line)
|
||||
eval "$(GITHUB_ENV= bash tools/release/skills-passed.sh "$GITHUB_REF_NAME" | grep '^RAEA_SKILLS_PASSED=')" ;;
|
||||
*) RAEA_SKILLS_PASSED=$(git rev-parse HEAD) ;;
|
||||
esac
|
||||
export RAEA_SKILLS_PASSED
|
||||
bash tools/release.sh "${v:-0.0.0-arm64}" target/dist HEAD
|
||||
# on a v* tag, beside release.yml's archives (the release made here if release.yml hasn't yet)
|
||||
- name: Attach to the release
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
pre=; case $GITHUB_REF_NAME in *-*) pre=--prerelease ;; esac
|
||||
gh release view "$GITHUB_REF_NAME" -R "$GITHUB_REPOSITORY" >/dev/null 2>&1 ||
|
||||
gh release create "$GITHUB_REF_NAME" -R "$GITHUB_REPOSITORY" $pre --title "raea ${GITHUB_REF_NAME#v}" --notes "Built by .github/workflows/release.yml; notes follow." ||
|
||||
gh release view "$GITHUB_REF_NAME" -R "$GITHUB_REPOSITORY" >/dev/null
|
||||
gh release upload "$GITHUB_REF_NAME" -R "$GITHUB_REPOSITORY" dist/raea-*-windows-arm64.zip dist/raea-*-windows-arm64.zip.sha256 --clobber
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: always()
|
||||
with:
|
||||
name: windows-arm64-zip
|
||||
path: dist/raea-*-windows-arm64.zip*
|
||||
retention-days: 7
|
||||
compression-level: 0
|
||||
if-no-files-found: ignore
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: always()
|
||||
with:
|
||||
name: windows-arm64-bins
|
||||
path: |
|
||||
target/dist/raea.exe
|
||||
target/dist/raea_bundle.dll
|
||||
target/dist/raea-rune-host.exe
|
||||
target/dist/raea-page-host.exe
|
||||
target/dist/raea-perceive.exe
|
||||
retention-days: 7
|
||||
if-no-files-found: ignore
|
||||
|
||||
# vendor/metis-sys's header change reaches release.yml's x64 build too (windows-latest's Visual Studio): metis-sys
|
||||
# alone, in a scratch crate, compiled there
|
||||
metis-x64:
|
||||
runs-on: windows-latest
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ inputs.ref || github.sha }}
|
||||
sparse-checkout: vendor/metis-sys
|
||||
- name: metis-sys on x64 MSVC
|
||||
run: |
|
||||
c="$RUNNER_TEMP/metis-x64"; mkdir -p "$c/src" && : > "$c/src/lib.rs"
|
||||
printf '[package]\nname = "metis-x64"\nversion = "0.0.0"\nedition = "2021"\n[dependencies]\nmetis-sys = { path = "%s" }\n[workspace]\n' "$(cygpath -m "$GITHUB_WORKSPACE/vendor/metis-sys")" > "$c/Cargo.toml"
|
||||
cl 2>&1 | head -1 || true
|
||||
cd "$c" && cargo build
|
||||
@@ -0,0 +1,55 @@
|
||||
# Code of conduct
|
||||
|
||||
raea's issues, pull requests, reviews and other project-managed community spaces
|
||||
should let people discuss and improve the work without harassment. This applies
|
||||
to maintainers, contributors and people using automated or AI-assisted tools.
|
||||
Participants remain responsible for the material they submit through those tools.
|
||||
|
||||
## Expected behavior
|
||||
|
||||
- Discuss the code, evidence and ideas respectfully. Technical disagreement is
|
||||
welcome; personal attacks and assumptions about another person's motives are not.
|
||||
- Give actionable feedback, accept corrections and respect requests to stop a
|
||||
conversation or move it out of a thread.
|
||||
- Make room for different experience levels, backgrounds and communication styles.
|
||||
- Respect privacy. Share only logs, screenshots and other information you have
|
||||
permission to publish, with credentials and personal information removed.
|
||||
|
||||
Harassment, discriminatory insults, threats, sexual harassment, unwanted repeated
|
||||
contact, disclosure of private information, deliberate disruption and retaliation
|
||||
against someone raising a concern are unacceptable.
|
||||
|
||||
## Reporting a concern
|
||||
|
||||
For content on GitHub, use the content menu's **Report content** action where it
|
||||
is available. Choose **Report to repository admins** if GitHub offers it.
|
||||
Maintainer reporting depends on repository settings and the reporter's access.
|
||||
For abuse covered by GitHub's rules, use **Report abuse to GitHub Support** or
|
||||
[GitHub's abuse-reporting route](https://docs.github.com/en/communities/maintaining-your-safety-on-github/reporting-abuse-or-spam).
|
||||
GitHub handles those reports under its own policies; it is not the project's
|
||||
appeal body for every technical or moderation disagreement.
|
||||
|
||||
A separate private maintainer inbox for conduct reports has not been designated
|
||||
in this repository. If GitHub's maintainer-reporting option is unavailable, ask
|
||||
for a private contact without posting the incident, personal information or
|
||||
accusations in a public issue. Maintainers can document an additional contact
|
||||
after confirming who will handle it. Use [the security policy](SECURITY.md) for vulnerabilities,
|
||||
not as a general conduct-report channel.
|
||||
|
||||
Include links, the relevant context and your preferred way to be contacted when
|
||||
reporting privately. Do not retaliate, publicly investigate the reporter or
|
||||
pressure someone to disclose an incident.
|
||||
|
||||
## Moderation
|
||||
|
||||
Repository maintainers may clarify expectations, ask participants to change
|
||||
behavior, close or remove disruptive content, restrict interactions, or block
|
||||
continued participation as appropriate to severity and repetition. A technical
|
||||
disagreement or a rejected contribution alone is not misconduct.
|
||||
|
||||
Maintainers should consider context and available evidence, protect sensitive
|
||||
information, explain decisions when doing so does not compromise privacy, and
|
||||
allow a participant to provide relevant additional context privately through the
|
||||
same reporting route. A maintainer involved in a concern should seek an uninvolved
|
||||
reviewer where one is available. This policy does not promise a response deadline
|
||||
or confidentiality beyond what the chosen reporting service and process provide.
|
||||
Generated
+51
-2
@@ -10263,8 +10263,6 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "metis-sys"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "769ee6be814b21c52afcc631f07051f578487d642f3e89a45f2a086fd94fffa9"
|
||||
dependencies = [
|
||||
"cc",
|
||||
]
|
||||
@@ -13896,6 +13894,9 @@ dependencies = [
|
||||
"raea-core-facts",
|
||||
"raea-core-review",
|
||||
"raea-io-home",
|
||||
"raea-runtime-cut-plan",
|
||||
"raea-runtime-goal-plan",
|
||||
"raea-runtime-lod-plan",
|
||||
"resvg 0.48.1",
|
||||
"serde_json",
|
||||
]
|
||||
@@ -13976,6 +13977,7 @@ dependencies = [
|
||||
"raea-core-scene",
|
||||
"raea-runtime-bundle",
|
||||
"raea-runtime-export",
|
||||
"raea-runtime-lod-plan",
|
||||
"raea-sys-contact",
|
||||
"raea-sys-light-meter",
|
||||
"raea-sys-stage",
|
||||
@@ -14042,6 +14044,7 @@ dependencies = [
|
||||
"anyhow",
|
||||
"cpal 0.15.3",
|
||||
"ort",
|
||||
"raea-io-trace",
|
||||
"raea-sys-ml",
|
||||
"raea-sys-speech",
|
||||
"serde_json",
|
||||
@@ -14804,7 +14807,9 @@ name = "raea-light"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"raea-core-facts",
|
||||
"raea-io-home",
|
||||
"raea-io-trace",
|
||||
"raea-runtime-bundle",
|
||||
"serde_json",
|
||||
]
|
||||
@@ -15063,6 +15068,7 @@ dependencies = [
|
||||
"raea-sys-engine-shaders",
|
||||
"raea-sys-post",
|
||||
"raea-sys-rt",
|
||||
"raea-sys-viewbox",
|
||||
"serde_json",
|
||||
"wgpu",
|
||||
]
|
||||
@@ -15289,6 +15295,15 @@ dependencies = [
|
||||
"raea-io-home",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-cut-plan"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"raea-core-brief",
|
||||
"raea-io-soft",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-dom"
|
||||
version = "0.1.0"
|
||||
@@ -15364,6 +15379,7 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"raea-core-facts",
|
||||
"raea-core-scene",
|
||||
"raea-runtime-lod-plan",
|
||||
"raea-sys-contact",
|
||||
"raea-sys-stage",
|
||||
"serde_json",
|
||||
@@ -15410,6 +15426,14 @@ dependencies = [
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-goal-plan"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"raea-core-brief",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-gpuframe"
|
||||
version = "0.1.0"
|
||||
@@ -15504,6 +15528,18 @@ dependencies = [
|
||||
"winit",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-lod-plan"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"dunce",
|
||||
"raea-core-facts",
|
||||
"raea-core-scene",
|
||||
"raea-sys-stage",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-look"
|
||||
version = "0.1.0"
|
||||
@@ -16145,6 +16181,7 @@ name = "raea-sys-framepass"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-sys-compose",
|
||||
"raea-sys-frame",
|
||||
"raea-sys-material",
|
||||
"raea-sys-sampler",
|
||||
@@ -16399,11 +16436,22 @@ dependencies = [
|
||||
"raea-io-home",
|
||||
"raea-io-media",
|
||||
"raea-io-trace",
|
||||
"raea-sys-mix-device",
|
||||
"raea-sys-mix-level",
|
||||
"raea-sys-tone",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-mix-device"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"audioadapter-buffers",
|
||||
"cpal 0.15.3",
|
||||
"firewheel",
|
||||
"raea-io-trace",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-mix-level"
|
||||
version = "0.1.0"
|
||||
@@ -16736,6 +16784,7 @@ name = "raea-sys-viewbox"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-sys-compose",
|
||||
"raea-sys-frame",
|
||||
]
|
||||
|
||||
|
||||
@@ -86,6 +86,7 @@ members = [
|
||||
"systems/tone",
|
||||
"systems/mix",
|
||||
"systems/mix/level",
|
||||
"systems/mix/device",
|
||||
"systems/ml",
|
||||
"systems/mlx",
|
||||
"systems/kimodo",
|
||||
@@ -193,6 +194,9 @@ members = [
|
||||
"runtime/canvas",
|
||||
"runtime/export",
|
||||
"runtime/endchecks",
|
||||
"runtime/lod-plan",
|
||||
"runtime/cut-plan",
|
||||
"runtime/goal-plan",
|
||||
"runtime/live",
|
||||
"runtime/page",
|
||||
"runtime/appscreen",
|
||||
@@ -343,6 +347,10 @@ split-debuginfo = "packed"
|
||||
[patch.crates-io]
|
||||
# the MP4 muxer, vendored
|
||||
muxide = { path = "vendor/muxide" }
|
||||
# metis-sys 0.3.2 (bevy_pbr's meshlets) with GKlib's own stdint.h and inttypes.h stand-ins used only before Visual
|
||||
# Studio 2013: Visual Studio 18's stdint.h types int_fast16_t differently, and every C file failed (raea#82; the change
|
||||
# is marked "raea:" in vendor/GKlib/gk_arch.h). Its test graphs, manual and programs are left out
|
||||
metis-sys = { path = "vendor/metis-sys" }
|
||||
# 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:")
|
||||
|
||||
@@ -32,10 +32,10 @@
|
||||
|
||||
---
|
||||
|
||||
> **0.1.6** (17 November 2026) is the latest release: the engine and the desktop app on macOS (Apple Silicon), Linux
|
||||
> (x86_64) and, newest and least tested, Windows 10 and 11 (x86_64). raea is young and moves fast, with a release most
|
||||
> days since 0.1.1 on 11 November: expect rough edges, and tell us what you hit in an
|
||||
> [issue](https://github.com/shinyobjectz/raea/issues), or from your agent with `raea bug`.
|
||||
> raea releases experimentally and often, so the newest release is always on
|
||||
> [Releases](https://github.com/shinyobjectz/raea/releases). The app is unstable for now, especially on Linux and
|
||||
> Windows: expect rough edges, and tell us what you hit in an [issue](https://github.com/shinyobjectz/raea/issues), or
|
||||
> from your agent with `raea bug`.
|
||||
|
||||
## The app
|
||||
|
||||
@@ -80,6 +80,13 @@ The installer puts the `raea` command under `~/.raea`, links it into `~/.local/b
|
||||
work. Run it again to update. The engine is free and needs no account. Tarballs and checksums are on the
|
||||
[releases page](https://github.com/shinyobjectz/raea/releases).
|
||||
|
||||
Linux release builds also package an x86_64 AppImage of the engine command and
|
||||
attach it and its SHA256 checksum beside the release archives.
|
||||
Make it executable with `chmod +x raea-*.AppImage`, then run
|
||||
`./raea-VERSION-linux-x86_64.AppImage --help` or pass the usual `raea` arguments.
|
||||
See [the AppImage release recipe](tools/release/README.md#linux-appimage) for build
|
||||
instructions, runtime requirements and running without FUSE.
|
||||
|
||||
On Windows 10 or 11, in PowerShell:
|
||||
|
||||
```powershell
|
||||
|
||||
@@ -240,6 +240,16 @@ fn check_one(tsx: &Path, id: Option<String>, rules: &[Rule], args: &[String], wh
|
||||
None => hows.iter().filter(|(_, h)| matches!(h, How::Named(n) if n.render && n.name != "text-read")).for_each(|(r, _)| needs(&mut waits, r)),
|
||||
}
|
||||
}
|
||||
// traced light held still (raea light steady): with the floor, a composition lit by Solari carries what its newest
|
||||
// hold of each frame found, kept in the project's record; with none yet, it waits for one
|
||||
if floor && traced(tsx) {
|
||||
let held = light_held(tsx, id.as_deref());
|
||||
if held.is_empty() {
|
||||
let c = id.as_ref().map(|i| format!(" --composition {i}")).unwrap_or_default();
|
||||
waits.push(("light-steady".into(), format!("a held frame of its traced light (raea light steady {}{c} --frame N -o DIR)", tsx.display())));
|
||||
}
|
||||
found.extend(held.into_iter().filter(|f| f.level != Level::Note));
|
||||
}
|
||||
// the project's own checks, in one run
|
||||
let mut files: Vec<PathBuf> = Vec::new();
|
||||
let mut plan = Vec::new();
|
||||
@@ -269,6 +279,46 @@ fn check_one(tsx: &Path, id: Option<String>, rules: &[Rule], args: &[String], wh
|
||||
Ok(Checked { file: tsx.to_path_buf(), id, found: finding::ranked(found), waits, render, shots, fps })
|
||||
}
|
||||
|
||||
/// Whether a composition is lit by traced light: its file, or a .tsx beside it or a folder down, names SolariLighting.
|
||||
fn traced(tsx: &Path) -> bool {
|
||||
let mut files = vec![tsx.to_path_buf()];
|
||||
let tsxs = |d: &Path| -> Vec<PathBuf> { std::fs::read_dir(d).into_iter().flatten().flatten().map(|e| e.path()).collect() };
|
||||
if let Some(dir) = tsx.parent() {
|
||||
files.extend(tsxs(dir).into_iter().flat_map(|p| if p.is_dir() { tsxs(&p) } else { vec![p] }).filter(|p| p.extension().is_some_and(|x| x == "tsx")));
|
||||
}
|
||||
for f in files {
|
||||
if let Ok(text) = std::fs::read_to_string(&f) {
|
||||
if text.contains("SolariLighting") {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// The findings of the newest hold of each frame of a composition (`raea light steady`), from its project's record.
|
||||
fn light_held(tsx: &Path, id: Option<&str>) -> Vec<Finding> {
|
||||
let Some(project) = dunce::canonicalize(tsx).ok().and_then(|t| record::up(t.parent()?, ".raea/project")) else { return Vec::new() };
|
||||
let of = record::rel(&project, tsx);
|
||||
let mut newest: std::collections::BTreeMap<i64, Vec<Finding>> = std::collections::BTreeMap::new();
|
||||
for e in record::read(&project) {
|
||||
if e.by != "raea light steady" || e.of != of {
|
||||
continue;
|
||||
}
|
||||
let mut mine = Vec::new();
|
||||
for f in e.findings {
|
||||
let mut about = f.about.iter().map(|a| a.name.as_str());
|
||||
if id.is_none_or(|id| about.any(|n| n == id)) {
|
||||
mine.push(f);
|
||||
}
|
||||
}
|
||||
if let Some(frame) = mine.first().and_then(|f| f.frames) {
|
||||
newest.insert(frame[0], mine);
|
||||
}
|
||||
}
|
||||
newest.into_values().flatten().collect()
|
||||
}
|
||||
|
||||
/// Where `f` is in `files`, added at the end when it isn't yet: the one run's checks, each file once.
|
||||
fn file_index(files: &mut Vec<PathBuf>, f: &Path) -> usize {
|
||||
if let Some(at) = files.iter().position(|x| x == f) {
|
||||
|
||||
@@ -58,7 +58,7 @@ fn brief_of(path: Option<&str>) -> Result<Value, String> {
|
||||
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
|
||||
let out = std::process::Command::new(exe).args(["spec", p, "--as", "brief"]).output().map_err(|e| e.to_string())?;
|
||||
let text = String::from_utf8_lossy(&out.stdout);
|
||||
let start = text.find('{').ok_or_else(|| format!("judge: {p} didn't read as a brief: {}", String::from_utf8_lossy(&out.stderr).lines().last().unwrap_or("")))?;
|
||||
let start = text.find('{').ok_or_else(|| format!("judge: {p} didn't read as a brief: {}", why_refused(&out)))?;
|
||||
let v: Value = serde_json::from_str(&text[start..]).map_err(|e| format!("judge: {p}: {e}"))?;
|
||||
Ok(v.get("brief").cloned().unwrap_or(v))
|
||||
}
|
||||
@@ -226,3 +226,10 @@ fn finish(args: &[String], kind: Option<&str>, dir: &Path, scores: serde_json::M
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
/// Why `raea spec` refused a brief, in its own words: its refusal is the last line it printed, on whichever stream
|
||||
/// (a REFUSED line goes to stdout, a thrown module's error to stderr). Reading stderr alone left the reason empty.
|
||||
pub fn why_refused(out: &std::process::Output) -> String {
|
||||
let last = |b: &[u8]| String::from_utf8_lossy(b).lines().rev().find(|l| !l.trim().is_empty()).map(|l| l.trim().trim_start_matches("REFUSED").trim().to_string());
|
||||
last(&out.stderr).or_else(|| last(&out.stdout)).unwrap_or_else(|| "raea spec printed nothing".into())
|
||||
}
|
||||
@@ -11,6 +11,12 @@ description = "raea make: a scene, kit or shot held to its frozen plan; what's m
|
||||
raea-core-brief = { path = "../../core/brief" }
|
||||
# the project's record of renders and checks, and the folder it lives in
|
||||
raea-core-facts = { path = "../../core/facts" }
|
||||
# the parts a render showed closer than their planned detail (MK24)
|
||||
raea-runtime-lod-plan = { path = "../../runtime/lod-plan" }
|
||||
# a cut job's gates: its client's brief as rules, held over the delivered files (MK25-MK27)
|
||||
raea-runtime-cut-plan = { path = "../../runtime/cut-plan" }
|
||||
# a goal job's gates: its commands and a fresh critic's verdict on its words (/goal)
|
||||
raea-runtime-goal-plan = { path = "../../runtime/goal-plan" }
|
||||
# the judge's rounds, passes and blocking defects, read as it keeps them
|
||||
raea-app-judge = { path = "../judge" }
|
||||
# the make questions, their calibrations and a sheet's ident, as raea ask keeps them (MK4)
|
||||
|
||||
@@ -85,7 +85,7 @@ pub fn floor_svg(m: &Make) -> Result<String, String> {
|
||||
fd * px / 2.0
|
||||
);
|
||||
s += &format!("<text x=\"{:.1}\" y=\"{:.1}\" font-size=\"{:.0}\" fill=\"#111\" text-anchor=\"middle\">{}</text>", sx(at[0]), sy(at[2]) - t * 0.25, t, esc(&o.label));
|
||||
s += &format!("<text x=\"{:.1}\" y=\"{:.1}\" font-size=\"{:.0}\" fill=\"#555\" text-anchor=\"middle\">{:.2} m</text>", sx(at[0]), sy(at[2]) + t * 0.9, t * 0.8, height(o));
|
||||
s += &format!("<text x=\"{:.1}\" y=\"{:.1}\" font-size=\"{:.0}\" fill=\"#555\" text-anchor=\"middle\">{:.2} m{}</text>", sx(at[0]), sy(at[2]) + t * 0.9, t * 0.8, height(o), o.lod.map(|l| format!(", LOD {l}")).unwrap_or_default());
|
||||
}
|
||||
s += &format!("<line x1=\"20\" y1=\"{0}\" x2=\"{1:.1}\" y2=\"{0}\" stroke=\"#111\" stroke-width=\"5\"/><text x=\"20\" y=\"{2:.0}\" font-size=\"{3:.0}\" fill=\"#111\">1 m</text>", h - 18, 20.0 + px, h as f64 - 26.0, t * 0.9);
|
||||
s += "</svg>";
|
||||
@@ -102,8 +102,10 @@ pub fn blockout_tsx(m: &Make) -> String {
|
||||
let h = height(o);
|
||||
let colour = if o.source == Some(Origin::Invented) { "#b4b0bd" } else { "#bdbdb8" };
|
||||
let a = -o.rot.unwrap_or(0.0).to_radians() / 2.0;
|
||||
let lod = o.lod.map(|l| format!(" lod={{{l}}}")).unwrap_or_default();
|
||||
boxes += &format!(
|
||||
" <Mesh3d transform={{Transform.fromXyz({:.3}, {:.3}, {:.3}).withRotation([0, {:.5}, 0, {:.5}])}}>\n <Cuboid half_size={{[{:.3}, {:.3}, {:.3}]}} />\n <StandardMaterial base_color=\"{colour}\" perceptual_roughness={{0.9}} />\n </Mesh3d>\n",
|
||||
" <Mesh3d name=\"{}\"{lod} transform={{Transform.fromXyz({:.3}, {:.3}, {:.3}).withRotation([0, {:.5}, 0, {:.5}])}}>\n <Cuboid half_size={{[{:.3}, {:.3}, {:.3}]}} />\n <StandardMaterial base_color=\"{colour}\" perceptual_roughness={{0.9}} />\n </Mesh3d>\n",
|
||||
o.id,
|
||||
at[0],
|
||||
at[1] + h / 2.0,
|
||||
at[2],
|
||||
|
||||
@@ -19,7 +19,8 @@ use std::path::{Path, PathBuf};
|
||||
use raea_core_brief::make::Make;
|
||||
use serde_json::Value;
|
||||
|
||||
pub const USAGE: &str = "raea make status [DIR] [--json] [--plan] (a scene, kit or shot held to its plan, `make` on brief.ts: what's missing, each gate (renders and checks, raea ask's calibrated questions, the critic on the kind's rubric), the judge's rounds, and whether it's done, decided in code; --plan writes the gates as check lines under the job's task in plan.org; the agent's Stop hook holds it there)
|
||||
pub const USAGE: &str = "raea make status [DIR] [--json] [--plan] (a scene, kit, shot, cut or goal held to its plan, `make` on brief.ts: what's missing, each gate (renders and checks, raea ask's calibrated questions, the critic on the kind's rubric), the judge's rounds, and whether it's done, decided in code; --plan writes the gates as check lines under the job's task in plan.org; the agent's Stop hook holds it there)
|
||||
raea make judge [DIR] [--by claude|kimi] (a goal job: a fresh critic, which only reads, judges each `says` rule; review/goal.judge.json)
|
||||
raea make plan [DIR] [--no-review] (the plan stop: review/plan/floor-plan.png, a grey-box blockout from the entrance and its review sheets, comparison.png beside reference 0)
|
||||
raea make refs [DIR] [--only ID,...] [--model M] [--dry] (a kit: every object's reference from the style images, in the plan's style, then review/refs.png; --dry quotes it)
|
||||
raea make sheet refs [DIR] (review/refs.png again: the style images, then every reference)
|
||||
@@ -58,7 +59,7 @@ pub fn read_make(brief: &Path) -> Result<Option<Make>, String> {
|
||||
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
|
||||
let out = std::process::Command::new(exe).arg("spec").arg(brief).args(["--as", "brief"]).env("RAEA_RECORD", "off").output().map_err(|e| e.to_string())?;
|
||||
let text = String::from_utf8_lossy(&out.stdout);
|
||||
let start = text.find('{').ok_or_else(|| format!("{} didn't read as a brief: {}", brief.display(), String::from_utf8_lossy(&out.stderr).lines().last().unwrap_or("")))?;
|
||||
let start = text.find('{').ok_or_else(|| format!("{} didn't read as a brief: {}", brief.display(), raea_app_judge::why_refused(&out)))?;
|
||||
let v: Value = serde_json::from_str(&text[start..]).map_err(|e| format!("{}: {e}", brief.display()))?;
|
||||
let b = v.get("brief").cloned().unwrap_or(v);
|
||||
match b.get("make") {
|
||||
@@ -88,7 +89,7 @@ pub fn status_of(brief: &Path, make: &Make) -> Value {
|
||||
let record = project.as_deref().map(raea_core_facts::record::read).unwrap_or_default();
|
||||
let (rounds, verdict, judged_at) = judged(dir);
|
||||
let ledger = asked::Ledger::read();
|
||||
let job = status::Job { make, dir, project: project.as_deref(), record: &record, rounds: &rounds, verdict: verdict.as_ref(), judged_at, ledger: &ledger, score_gates: raea_app_judge::kind_gates(status::kind_name(make.kind)) };
|
||||
let job = status::Job { make, dir, project: project.as_deref(), record: &record, rounds: &rounds, verdict: verdict.as_ref(), judged_at, ledger: &ledger, score_gates: raea_app_judge::kind_gates(make.kind.name()) };
|
||||
let mut s = status::status(&job);
|
||||
s["brief"] = Value::String(brief.display().to_string());
|
||||
s
|
||||
@@ -102,7 +103,7 @@ pub fn status_in(dir: &Path) -> Result<Option<Value>, String> {
|
||||
}
|
||||
|
||||
/// The flags that take a value: what follows them isn't a positional argument.
|
||||
const VALUED: [&str; 7] = ["--only", "--model", "--tripo", "--meshy", "--name", "--to", "--out"];
|
||||
const VALUED: [&str; 8] = ["--only", "--model", "--tripo", "--meshy", "--name", "--to", "--out", "--by"];
|
||||
|
||||
fn flag<'a>(args: &'a [String], k: &str) -> Option<&'a str> {
|
||||
args.iter().position(|a| a == k).and_then(|i| args.get(i + 1)).map(String::as_str)
|
||||
@@ -184,6 +185,7 @@ fn step(verb: &str, args: &[String]) -> Result<String, String> {
|
||||
pub fn cli(args: &[String]) -> Result<String, String> {
|
||||
match args.get(1).map(String::as_str) {
|
||||
Some("status") => {}
|
||||
Some("judge") => return job(&PathBuf::from(positional(args, 2).first().map_or(".", String::as_str))).and_then(|(b, m)| raea_runtime_goal_plan::judge(m.goal.as_ref().ok_or("raea make judge: the job isn't a goal({...})")?, b.parent().unwrap_or(Path::new(".")), flag(args, "--by").unwrap_or("claude")).map(|v| serde_json::to_string_pretty(&v).unwrap_or_default())),
|
||||
Some(v @ ("plan" | "refs" | "sheet" | "gen" | "pick-sheet" | "pick" | "prep" | "kit" | "framing" | "lenschart")) => return step(v, args),
|
||||
_ => return Err(USAGE.into()),
|
||||
}
|
||||
|
||||
+22
-16
@@ -1,8 +1,7 @@
|
||||
//! Whether a job is done (docs/make.feature MK1), from what's on disk and nothing the agent says: the deliverables, the
|
||||
//! notes, the record of renders and checks, and the judge's rounds. Pure over a `Job` so it is tested on fixtures.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::SystemTime;
|
||||
use std::{path::{Path, PathBuf}, time::SystemTime};
|
||||
|
||||
use raea_core_brief::make::{self, Make};
|
||||
use raea_core_facts::{Level, record::Entry};
|
||||
@@ -59,14 +58,6 @@ pub fn sheets(job: &Job) -> Vec<(&'static str, PathBuf)> {
|
||||
out.into_iter().filter(|(_, f)| f.is_file()).collect()
|
||||
}
|
||||
|
||||
pub(crate) fn kind_name(k: make::Kind) -> &'static str {
|
||||
match k {
|
||||
make::Kind::Scene => "scene",
|
||||
make::Kind::Kit => "kit",
|
||||
make::Kind::Shot => "shot",
|
||||
}
|
||||
}
|
||||
|
||||
/// When a file last changed, and that as seconds since 1970 (a record entry's clock).
|
||||
fn mtime(p: &Path) -> Option<SystemTime> {
|
||||
std::fs::metadata(p).ok()?.modified().ok()
|
||||
@@ -136,15 +127,22 @@ fn checks(job: &Job) -> Vec<Value> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// MK24: parts a composition's last render showed closer than planned, held until replanned or answered (raea-runtime-lod-plan)
|
||||
fn lods(job: &Job, notes: &str) -> Vec<Value> {
|
||||
let plans = job.make.objects.iter().any(|o| o.lod.is_some());
|
||||
let last = |c: &String| job.record.iter().rev().find(|e| e.of == job.project.map(|p| raea_core_facts::record::rel(p, &job.dir.join(c))).unwrap_or_else(|| c.clone()));
|
||||
job.make.compositions.iter().filter_map(|c| last(c).and_then(|l| raea_runtime_lod_plan::gate(c, &l.id, &l.findings, notes, plans)).map(|(clear, says)| gate("lod", Some(c), clear, says))).collect()
|
||||
}
|
||||
|
||||
/// Tier 3: a fresh critic has judged a round newer than the newest deliverable, and each blocking defect it named is
|
||||
/// fixed (the round passed) or answered in NOTES.md by its name. Its score gates once the judge is calibrated.
|
||||
fn critic(job: &Job, newest: Option<SystemTime>, notes: &str) -> Vec<Value> {
|
||||
let Some(last) = job.rounds.last() else {
|
||||
let kind = kind_name(job.make.kind);
|
||||
let kind = job.make.kind.name();
|
||||
let what = match job.make.kind {
|
||||
make::Kind::Kit => "raea render shared/components/KIT/lineup.tsx --review review/r1",
|
||||
make::Kind::Shot => "raea make framing --out review/r1",
|
||||
make::Kind::Scene => "raea render EDIT.tsx --review review/r1",
|
||||
make::Kind::Scene | make::Kind::Cut | make::Kind::Goal => "raea render EDIT.tsx --review review/r1",
|
||||
};
|
||||
return vec![gate("critic", None, false, format!("no round yet: {what}, then raea judge review/r1 --kind {kind} --by claude --brief brief.ts"))];
|
||||
};
|
||||
@@ -156,7 +154,7 @@ fn critic(job: &Job, newest: Option<SystemTime>, notes: &str) -> Vec<Value> {
|
||||
};
|
||||
out.push(gate("critic", None, fresh, if fresh { format!("round {} judged after the newest deliverable", job.rounds.len()) } else { "the newest deliverable came after the last round: review and judge it again".into() }));
|
||||
// the kind's own rubric (MK5): a round judged on another's doesn't count
|
||||
let kind = kind_name(job.make.kind);
|
||||
let kind = job.make.kind.name();
|
||||
if last["kind"].as_str() != Some(kind) {
|
||||
let dir = last["dir"].as_str().unwrap_or("review/rN");
|
||||
out.push(gate("rubric", None, false, format!("the last round wasn't judged on the {kind} rubric: raea judge {dir} --kind {kind} --by claude")));
|
||||
@@ -184,11 +182,18 @@ pub fn status(job: &Job) -> Value {
|
||||
}
|
||||
}
|
||||
let notes = notes_text(job.dir).unwrap_or_default();
|
||||
if !notes.to_lowercase().contains(&SKILL_HEADING.to_lowercase()) {
|
||||
if job.make.kind != make::Kind::Goal && !notes.to_lowercase().contains(&SKILL_HEADING.to_lowercase()) {
|
||||
missing.push(format!("NOTES.md with a \"{SKILL_HEADING}\" section (one line per thing that cost time; what the guide got wrong for this job)"));
|
||||
}
|
||||
let mut gates = checks(job);
|
||||
gates.extend(critic(job, newest, ¬es));
|
||||
gates.extend(lods(job, ¬es));
|
||||
// a cut job: its brief's rules over every delivered file (MK25-MK27), and the person's review its critic; a goal's
|
||||
let plan = |g: make::Gate| gate(g.name, g.of.as_deref(), g.clear, g.says);
|
||||
match (&job.make.cut, job.make.kind) {
|
||||
(Some(c), make::Kind::Cut) => gates.extend(raea_runtime_cut_plan::gates(c, job.dir).into_iter().map(plan)),
|
||||
(_, make::Kind::Goal) => gates.extend(job.make.goal.iter().flat_map(|g| raea_runtime_goal_plan::gates(g, job.dir)).map(plan)),
|
||||
_ => gates.extend(critic(job, newest, ¬es)),
|
||||
}
|
||||
let (asks, said) = crate::asked::gates(&sheets(job), job.ledger, ¬es);
|
||||
gates.extend(asks);
|
||||
let cap = job.make.rounds.unwrap_or(make::ROUNDS) as usize;
|
||||
@@ -211,6 +216,7 @@ pub fn status(job: &Job) -> Value {
|
||||
"gates": gates,
|
||||
"judge": {"rounds": job.rounds.len(), "cap": cap, "passesInARow": advice["passesInARow"], "changeApproach": advice["stall"], "again": advice["again"]},
|
||||
"plan": make::doctor(job.make),
|
||||
"files": {"deliverables": make::deliverables(job.make), "previews": make::previews(job.make)},
|
||||
"advice": said,
|
||||
"why": why,
|
||||
})
|
||||
@@ -235,6 +241,6 @@ pub fn text(s: &Value) -> String {
|
||||
t.push(format!(" {} {}{of}: {}", if g["clear"] == true { "ok " } else { "open" }, g["gate"].as_str().unwrap_or(""), g["says"].as_str().unwrap_or("")));
|
||||
}
|
||||
let j = &s["judge"];
|
||||
t.push(format!("judge: {} of {} rounds, {} passes in a row{}", j["rounds"], j["cap"], j["passesInARow"], if j["changeApproach"] == true { "; the same defect keeps coming back: change the approach for that part, not the dose" } else { "" }));
|
||||
if s["kind"] != "goal" { t.push(format!("judge: {} of {} rounds, {} passes in a row{}", j["rounds"], j["cap"], j["passesInARow"], if j["changeApproach"] == true { "; the same defect keeps coming back: change the approach for that part, not the dose" } else { "" })); }
|
||||
t.join("\n")
|
||||
}
|
||||
@@ -134,6 +134,22 @@ fn a_composition_needs_a_clean_check_newer_than_it() {
|
||||
assert!(s["gates"].to_string().contains("changed since"), "{s:#}");
|
||||
}
|
||||
|
||||
// MK24: a part a render showed closer than planned holds the job until it's replanned or answered in the notes
|
||||
#[test]
|
||||
fn a_part_seen_closer_than_planned_holds_the_job() {
|
||||
let d = dir("lod");
|
||||
delivered(&d);
|
||||
put(&d, "scene.tsx", "x");
|
||||
let mut make = kit();
|
||||
make.compositions = vec!["scene.tsx".into()];
|
||||
let future = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs() + 60;
|
||||
let entry: Entry = serde_json::from_value(json!({"id": "r1", "at": future, "by": "raea render", "of": "scene.tsx", "findings": [{"check": "lod-closer", "level": "warn", "about": [{"name": "kiosk"}], "says": "'kiosk' is planned at LOD 3", "by": "raea render"}]})).unwrap();
|
||||
let s = run(&make, &d, &[entry.clone()], &[round(true, 7.5, json!([]))], later());
|
||||
assert!(s["done"] == false && s["gates"].to_string().contains("seen closer than planned at r1: kiosk"), "{s:#}");
|
||||
put(&d, "NOTES.md", "- lod kiosk: one frame at the cut, left as a box\n## What the skill got wrong\n- nothing\n");
|
||||
assert_eq!(run(&make, &d, &[entry], &[round(true, 7.5, json!([]))], later())["done"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scene_wants_three_stills() {
|
||||
let d = dir("scene");
|
||||
|
||||
@@ -156,7 +156,7 @@ fn a_shot_frames_its_start_middle_and_end() {
|
||||
fn the_plan_draws_a_floor_plan_and_a_blockout() {
|
||||
let m: Make = read("make", r#"{"kind": "scene", "references": ["media/ref.png"], "objects": [
|
||||
{"id": "desk", "label": "Desk", "dims": [1.6, 0.8, 0.75], "at": [2, 0, 3], "rot": 90, "source": "reference", "hero": true},
|
||||
{"id": "plant", "label": "Plant", "h": 1.2, "at": [0.5, 0, 4], "source": "invented"},
|
||||
{"id": "plant", "label": "Plant", "h": 1.2, "at": [0.5, 0, 4], "source": "invented", "lod": 3},
|
||||
{"id": "pen", "label": "Pen", "max": 0.14}]}"#)
|
||||
.unwrap();
|
||||
let (placed, b) = crate::floor::extent(&m);
|
||||
@@ -172,6 +172,7 @@ fn the_plan_draws_a_floor_plan_and_a_blockout() {
|
||||
let t = crate::floor::blockout_tsx(&m);
|
||||
assert_eq!(t.matches("<Cuboid").count(), 3, "the floor and two boxes");
|
||||
assert!(t.contains("half_size={[0.800, 0.375, 0.400]}"), "{t}");
|
||||
assert!(t.contains("<Mesh3d name=\"plant\" lod={3} transform=") && svg.contains("1.20 m, LOD 3<"), "MK22, each box named with its planned detail: {t}");
|
||||
let none: Make = read("make", r#"{"kind": "scene", "objects": [{"id": "pen", "label": "Pen"}]}"#).unwrap();
|
||||
assert!(crate::floor::floor_svg(&none).unwrap_err().contains("no object has an `at`"));
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "raea scene lint|explain|light|stage: a composition's frames stepped without drawing and held to the contact, light and stage checks"
|
||||
description = "raea scene lint|explain|light|stage|lod: a composition's frames stepped without drawing and held to the contact, light and stage checks"
|
||||
|
||||
[dependencies]
|
||||
raea-runtime-bundle = { path = "../../runtime/bundle" }
|
||||
@@ -12,6 +12,8 @@ raea-runtime-export = { path = "../../runtime/export" }
|
||||
raea-sys-contact = { path = "../../systems/contact" }
|
||||
raea-sys-light-meter = { path = "../../systems/light-meter" }
|
||||
raea-sys-stage = { path = "../../systems/stage" }
|
||||
# each part's planned detail beside how large the frames show it (MK21, MK23)
|
||||
raea-runtime-lod-plan = { path = "../../runtime/lod-plan" }
|
||||
# its results as Findings (docs/direction.feature DR3)
|
||||
raea-core-facts = { path = "../../core/facts" }
|
||||
# camera clearance (MK16): the parts, their models' triangles, and the camera's point in space
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! `raea scene lint|explain|light|stage`: a composition's frames stepped without drawing and handed to raea-sys-contact
|
||||
//! `raea scene lint|explain|light|stage|lod`: a composition's frames stepped without drawing and handed to raea-sys-contact
|
||||
//! (what each part rests on, and parts that clip), raea-sys-light-meter (the light on a subject) and raea-sys-stage (3D
|
||||
//! type that can't be read, parts that snap, a camera that lurches, empty frames: docs/stage-guards.feature).
|
||||
//! type that can't be read, parts that snap, a camera that lurches, empty frames: docs/stage-guards.feature). `lod` is
|
||||
//! each part's planned detail beside how large the frames show it (docs/make.feature MK23).
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
@@ -10,9 +11,11 @@ use raea_runtime_export::{frame_of, items};
|
||||
// how near the camera passes to each solid part, every frame (`--clearance M`, MK16)
|
||||
pub mod clearance;
|
||||
mod light;
|
||||
// each part's planned detail beside how large the frames show it (MK23)
|
||||
pub mod lod;
|
||||
mod stage;
|
||||
|
||||
pub const USAGE: &str = "raea scene lint|explain|light|stage EDIT.tsx [--composition ID] [--frame N] [--part NAME] [--from N] [--to N] [--clearance M] [--json]";
|
||||
pub const USAGE: &str = "raea scene lint|explain|light|stage|lod EDIT.tsx [--composition ID] [--frame N] [--part NAME] [--from N] [--to N] [--clearance M] [--json]";
|
||||
|
||||
/// `raea scene lint|explain EDIT.tsx [--composition ID] [--frame N] [--json]`: the frame's parts measured
|
||||
/// (frame 0 by default). `lint` says the faults (errors fail it: floating, sunk, clipping; warnings: in the air,
|
||||
@@ -24,6 +27,7 @@ pub fn cli(args: &[String]) -> Result<String, String> {
|
||||
match mode {
|
||||
"light" => return light::cli(args),
|
||||
"stage" => return stage::cli(args),
|
||||
"lod" => return lod::cli(args),
|
||||
"lint" | "explain" => {}
|
||||
_ => return Err(usage.into()),
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
//! `raea scene lod EDIT.tsx [--composition ID] [--from N] [--to N] [--json]` (docs/make.feature MK23): every part's
|
||||
//! planned detail beside how large the frames show it. A part's plan is its own `lod` (0 the hero to 4 far), else its
|
||||
//! name's on the job's plan (`lod` on brief.ts's make objects); what a frame shows is how much of it the part's box
|
||||
//! spans (raea-runtime-lod-plan). The table lists the planned parts first, the ones seen closer than planned on top,
|
||||
//! then the parts nobody planned by how large they get, so a part forgotten since the plan was written is found by
|
||||
//! reading down it. A part seen two or more levels finer than planned fails it, as it fails a render.
|
||||
|
||||
use raea_core_facts::{Finding, Level, finding};
|
||||
use raea_runtime_lod_plan::{ordered, table};
|
||||
use serde_json::json;
|
||||
|
||||
pub(crate) fn cli(args: &[String]) -> Result<String, String> {
|
||||
let crate::stage::Stepped { items, nums, size: (w, h, fps), dir } = crate::stage::stepped(args, "raea scene lod EDIT.tsx [--composition ID] [--from N] [--to N] [--json]")?;
|
||||
let (first, last) = (nums[0], nums[nums.len() - 1]);
|
||||
let plan = raea_runtime_lod_plan::plan::lods(&dir);
|
||||
let mut unseen: Vec<String> = plan.keys().cloned().collect();
|
||||
let (seen, fs) = raea_runtime_lod_plan::lods(&items, &nums, w, h, fps, "raea scene lod", plan);
|
||||
let seen = ordered(seen);
|
||||
// a level the plan gives a name no part in these frames goes by holds nothing: said, so the part gets its name
|
||||
unseen.retain(|n| !seen.iter().any(|s| s.planned.is_some() && (s.name == *n || s.name.starts_with(&format!("{n} (lod ")))));
|
||||
unseen.sort();
|
||||
let text = if args.iter().any(|a| a == "--json") {
|
||||
let parts: Vec<_> = seen.iter().map(|s| json!({"part": s.name, "planned": s.planned, "seen": s.level(), "largest": s.finest.map(|f| f.1), "at": s.finest.map(|f| f.0), "frames": s.frames, "closer": s.closer})).collect();
|
||||
serde_json::to_string_pretty(&json!({"frames": [first, last], "parts": parts, "unseen": unseen, "findings": fs})).unwrap_or_default()
|
||||
} else {
|
||||
let levels = "levels, by how much of the frame a part spans: 0 hero 50%+, 1 featured 20%+, 2 dressing 8%+, 3 background 2%+, 4 far";
|
||||
let none = seen.iter().filter(|s| s.planned.is_none()).count();
|
||||
let missing = (!unseen.is_empty()).then(|| format!("planned in brief.ts, but no part of that name is in these frames (name the part as its object's id, or its plan holds nothing): {}", unseen.join(", ")));
|
||||
let sum = format!("frames {first} to {last}: {} parts, {none} with no plan; {}", seen.len(), finding::count(&fs));
|
||||
table(&seen).into_iter().chain(fs.iter().map(Finding::line)).chain(missing).chain([levels.to_string(), sum]).collect::<Vec<_>>().join("\n")
|
||||
};
|
||||
if fs.iter().any(|f| f.level == Level::Error) {
|
||||
println!("{text}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
Ok(text)
|
||||
}
|
||||
+23
-6
@@ -1,7 +1,7 @@
|
||||
//! `raea scene stage EDIT.tsx [--composition ID] [--from N] [--to N] [--json]`: every frame's scene stepped without
|
||||
//! drawing and held to the stage checks a render runs at its end (raea-sys-stage, docs/stage-guards.feature SG10-SG14):
|
||||
//! 3D type that can't be read, parts that snap, a camera that lurches or reverses, frames with nothing composed in
|
||||
//! them. Errors fail it, as they fail a render, so it's the cheap look before one. It lays out no page, so what the
|
||||
//! them, a part shown closer than its planned detail (MK21). Errors fail it, as they fail a render, so it's the cheap look before one. It lays out no page, so what the
|
||||
//! page holds waits for a render: its words over the parts (type-over-part), a Label's part as the shot's subject, and
|
||||
//! a frame its words or pictures fill, which reads empty here and is said as a warning, not failed (SG11).
|
||||
//! `--clearance M` holds the camera M metres off every solid part on every frame (0.45 for a carried camera, MK16).
|
||||
@@ -12,8 +12,16 @@ use raea_core_facts::{Level, finding};
|
||||
use raea_runtime_bundle::{bundle_composition, comp_opts, flag};
|
||||
use raea_runtime_export::{all_items, scene_frames_to};
|
||||
|
||||
pub(crate) fn cli(args: &[String]) -> Result<String, String> {
|
||||
let usage = "raea scene stage EDIT.tsx [--composition ID] [--from N] [--to N] [--clearance M] [--json]";
|
||||
/// A composition's frames stepped without drawing, for `stage` and `lod`: each frame's parts from --from to --to (every
|
||||
/// frame before is still stepped), their numbers, the frame's size and rate, and the composition's folder.
|
||||
pub(crate) struct Stepped {
|
||||
pub items: Vec<Vec<raea_core_scene::Item>>,
|
||||
pub nums: Vec<i64>,
|
||||
pub size: (u32, u32, f64),
|
||||
pub dir: std::path::PathBuf,
|
||||
}
|
||||
|
||||
pub(crate) fn stepped(args: &[String], usage: &str) -> Result<Stepped, String> {
|
||||
let Some(edit) = args.get(2) else { return Err(usage.into()) };
|
||||
let tsx = dunce::canonicalize(&std::path::PathBuf::from(edit)).map_err(|e| format!("{edit}: {e}"))?;
|
||||
let dir = tsx.parent().unwrap().to_path_buf();
|
||||
@@ -25,10 +33,19 @@ pub(crate) fn cli(args: &[String]) -> Result<String, String> {
|
||||
let _ = std::fs::remove_file(&js);
|
||||
let (frames, w, h, fps) = got?.ok_or("the composition has no 3D")?;
|
||||
let frames: Vec<_> = frames.into_iter().filter(|(f, _)| *f >= from && to.is_none_or(|t| *f <= t)).collect();
|
||||
let (Some(first), Some(last)) = (frames.first().map(|f| f.0), frames.last().map(|f| f.0)) else { return Err(format!("no frames from {from}")) };
|
||||
let nums: Vec<i64> = frames.iter().map(|(f, _)| *f).collect();
|
||||
let items = all_items(&frames);
|
||||
if frames.is_empty() {
|
||||
return Err(format!("no frames from {from}"));
|
||||
}
|
||||
Ok(Stepped { nums: frames.iter().map(|(f, _)| *f).collect(), items: all_items(&frames), size: (w, h, fps), dir })
|
||||
}
|
||||
|
||||
pub(crate) fn cli(args: &[String]) -> Result<String, String> {
|
||||
let Stepped { items, nums, size: (w, h, fps), dir } = stepped(args, "raea scene stage EDIT.tsx [--composition ID] [--from N] [--to N] [--clearance M] [--json]")?;
|
||||
let (first, last) = (nums[0], nums[nums.len() - 1]);
|
||||
let mut fs = raea_sys_stage::check(&items, &nums, w, h, fps, "raea scene stage");
|
||||
// and each part held to its planned detail (its own `lod`, or its name's on the plan above it: MK21), as a render does
|
||||
fs.extend(raea_runtime_lod_plan::lods(&items, &nums, w, h, fps, "raea scene stage", raea_runtime_lod_plan::plan::lods(&dir)).1.into_iter().filter(|f| f.check == "lod-closer"));
|
||||
fs = raea_core_facts::finding::ranked(fs);
|
||||
// the camera held off every solid part, when asked: the number after the flag, else a carried camera's 0.45 m
|
||||
if let Some(v) = flag(args, "--clearance") {
|
||||
let min = v.parse::<f32>().ok().filter(|m| *m >= 0.0).ok_or_else(|| format!("--clearance takes metres (0.45 for a carried camera), got {v:?}"))?;
|
||||
|
||||
@@ -12,6 +12,7 @@ path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
# Pocket TTS and its word clock
|
||||
raea-io-trace = { path = "../../io/trace" }
|
||||
raea-sys-speech = { path = "../../systems/speech" }
|
||||
# ort sessions the way raea builds them, and the model cache
|
||||
raea-sys-ml = { path = "../../systems/ml" }
|
||||
|
||||
@@ -108,7 +108,7 @@ pub fn microphone(tx: Sender<Vec<f32>>) -> anyhow::Result<cpal::Stream> {
|
||||
rs.push(&mono, &mut out);
|
||||
let _ = tx.send(out);
|
||||
};
|
||||
let bad = |e| eprintln!("raea voice: the microphone: {e}");
|
||||
let bad = raea_io_trace::once::said_once::<cpal::StreamError>("raea voice: the microphone");
|
||||
let stream = match cfg.sample_format() {
|
||||
cpal::SampleFormat::F32 => {
|
||||
dev.build_input_stream(&cfg.config(), move |d: &[f32], _: &cpal::InputCallbackInfo| take(mono(d, ch)), bad, None)
|
||||
@@ -242,7 +242,7 @@ impl Speaker {
|
||||
f.fill(ready.pop_front().unwrap_or(0.0));
|
||||
}
|
||||
};
|
||||
let stream = dev.build_output_stream(&cfg.config(), play, |e| eprintln!("raea voice: the speakers: {e}"), None).map_err(|e| anyhow!("the speakers didn't open: {e}"))?;
|
||||
let stream = dev.build_output_stream(&cfg.config(), play, raea_io_trace::once::said_once::<cpal::StreamError>("raea voice: the speakers"), None).map_err(|e| anyhow!("the speakers didn't open: {e}"))?;
|
||||
stream.play().map_err(|e| anyhow!("the speakers didn't start: {e}"))?;
|
||||
Ok(Speaker { line, rate, to, _stream: Some(stream) })
|
||||
}
|
||||
|
||||
Executable
+30
@@ -0,0 +1,30 @@
|
||||
#!/bin/bash
|
||||
# Two paint bugs, each held to what Chrome draws. Exits 1 on a failure.
|
||||
# #241 z.html: a stacking context's z-index: -1 child goes under its text. White pixels (the word) must be there:
|
||||
# before the fix the box covered the word and the frame had none.
|
||||
# #240 miter.html: a stroked rounded rect under a negative viewBox origin. Nothing blue left of the outline (x 0-60,
|
||||
# y 84-130: the outline starts at x 92), and the outline's top-left corner is round (dark at its square corner).
|
||||
# bench/paint-order/check.sh (RAEA_BIN: the raea to run, default target/release/raea)
|
||||
cd "$(dirname "$0")/../.." || exit 2
|
||||
BIN=${RAEA_BIN:-$PWD/target/release/raea}
|
||||
export RAEA_SIGN=0 RAEA_MARK=0 RAEA_EXPORT_CACHE=0
|
||||
OUT=$(mktemp -d "${TMPDIR:-/tmp}/raea-paint-order.XXXXXX")
|
||||
trap 'rm -rf "${OUT:?}"' EXIT
|
||||
status=0
|
||||
for p in z miter; do
|
||||
"$BIN" render "bench/paint-order/$p.html" -o "$OUT/$p.png" > "$OUT/$p.log" 2>&1 || { echo "FAIL render $p (log below)"; sed 's/^/ /' "$OUT/$p.log"; exit 1; }
|
||||
done
|
||||
# how many pixels of a region are near a colour
|
||||
count() { magick "$OUT/$1.png" -alpha off -crop "$2" +repage -fuzz "${4:-6}%" -fill black +opaque "$3" -fill white -opaque "$3" -colorspace Gray -format "%[fx:int(mean*w*h+0.5)]" info:; }
|
||||
white=$(count z 600x300+0+0 "#ffffff")
|
||||
(( white > 2000 )) || { echo "FAIL #241: $white white pixels, the word is under its z-index: -1 child"; status=1; }
|
||||
box=$(count z 600x300+0+0 "#10203C" 3)
|
||||
(( box > 3000 )) || { echo "FAIL #241: $box pixels of the box behind the word"; status=1; }
|
||||
bar=$(count miter 60x46+0+84 "#3c82f0")
|
||||
(( bar == 0 )) || { echo "FAIL #240: $bar blue pixels left of the outline (the miter join's bar)"; status=1; }
|
||||
corner=$(count miter 6x6+91+99 "#3c82f0")
|
||||
(( corner == 0 )) || { echo "FAIL #240: the outline's top-left corner is square ($corner blue pixels at its corner)"; status=1; }
|
||||
edge=$(count miter 200x6+400+97 "#3c82f0")
|
||||
(( edge > 300 )) || { echo "FAIL #240: the outline's top edge isn't drawn ($edge pixels)"; status=1; }
|
||||
[ $status = 0 ] && echo "PASS paint order: #241 text over a negative z-index child, #240 a miter join after an arc"
|
||||
exit $status
|
||||
@@ -0,0 +1,7 @@
|
||||
<!doctype html>
|
||||
<!-- #240: a thin rounded outline, nothing left of it (896 wide under a viewBox that starts at -20 drew a bar from x=0) -->
|
||||
<html><body style="margin:0;background:#111">
|
||||
<div data-composition-id="main" data-start="0" data-duration="1" data-width="1080" data-height="600" style="position:relative;width:1080px;height:600px;background:#111">
|
||||
<svg width="936" height="440" viewBox="-20 -20 936 440" style="position:absolute;left:72px;top:80px"><rect x="0" y="0" width="896" height="400" rx="24" fill="none" stroke="#3c82f0" stroke-width="3"/></svg>
|
||||
</div>
|
||||
</body></html>
|
||||
@@ -0,0 +1,7 @@
|
||||
<!doctype html>
|
||||
<!-- #241: white "Hollow" over a blue box that is its own z-index: -1 child -->
|
||||
<html><body style="margin:0;background:#111">
|
||||
<div data-composition-id="main" data-start="0" data-duration="1" data-width="600" data-height="300" style="position:relative;width:600px;height:300px;background:#111;display:flex;align-items:center;justify-content:center">
|
||||
<span style="position:relative;display:inline-block;z-index:1;color:#fff;font:700 80px sans-serif"><div style="position:absolute;inset:0;z-index:-1;background:#10203C;border:3px solid #3474D6"></div>Hollow</span>
|
||||
</div>
|
||||
</body></html>
|
||||
@@ -0,0 +1,242 @@
|
||||
//! A cut job's contract (docs/make.feature MK25): `make: cut({...})` on brief.ts, the client's brief made into rules
|
||||
//! before anything is planned or cut. A brief read as context gets lost (11-25, Shane, on StreetTalk's street interview
|
||||
//! ads: "you need to make the process of ingesting the brief more direct, or else it's just context that gets lost. It
|
||||
//! needs to be written as a brief typescript rule that is then enforced"). Every rule quotes the brief line it came
|
||||
//! from (`from`), and `raea make status` (apps/make cut.rs) finds each quote in the brief's text, so a rule can't be
|
||||
//! invented and a brief line can't drift; then it holds every delivered file to the rules, from what's on disk.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use ts_rs::TS;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
#[ts(optional_fields)]
|
||||
#[ts(rename = "MakeCut")]
|
||||
pub struct Cut {
|
||||
/// the brief as text, relative to brief.ts (`pdftotext -layout brief.pdf media/brief.txt`): every `from` is found in it
|
||||
pub brief: String,
|
||||
/// how many cuts the brief asks for; fewer planned is held open until an answered `open` item about "count" says why
|
||||
pub count: Option<Quoted<u32>>,
|
||||
/// a cut's length when its own `seconds` says none: [least, most]
|
||||
pub seconds: Option<[f64; 2]>,
|
||||
/// the formats every cut is delivered in when its own `formats` says none: "9:16", "16:9", "1:1", "4:5"
|
||||
#[serde(default)]
|
||||
#[ts(as = "Option<Vec<String>>", optional)]
|
||||
pub formats: Vec<String>,
|
||||
#[serde(default)]
|
||||
#[ts(as = "Option<Vec<CutPlan>>", optional)]
|
||||
pub cuts: Vec<CutPlan>,
|
||||
/// what is said or shown: in every cut unless `every: false` (then in one or more)
|
||||
#[serde(default)]
|
||||
#[ts(as = "Option<Vec<Phrase>>", optional)]
|
||||
pub say: Vec<Phrase>,
|
||||
/// what no cut says or shows: a banned claim, a word, a name
|
||||
#[serde(default)]
|
||||
#[ts(as = "Option<Vec<Phrase>>", optional)]
|
||||
pub never: Vec<Phrase>,
|
||||
/// the line every cut ends on, heard or on screen in its last `within` seconds
|
||||
pub cta: Option<Cta>,
|
||||
/// the brief's open items ([TO CONFIRM]): each holds the job open until it has an answer
|
||||
#[serde(default)]
|
||||
#[ts(as = "Option<Vec<Open>>", optional)]
|
||||
pub open: Vec<Open>,
|
||||
/// every face whole and every text big enough, by the frames check of each file (true when left out)
|
||||
pub frames: Option<bool>,
|
||||
}
|
||||
|
||||
/// A value with the brief's words for it.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
#[ts(rename = "MakeQuoted")]
|
||||
pub struct Quoted<T: TS> {
|
||||
pub value: T,
|
||||
/// the brief's own words, as they are in its text
|
||||
pub from: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
#[ts(optional_fields)]
|
||||
#[ts(rename = "MakeCutPlan")]
|
||||
pub struct CutPlan {
|
||||
/// [a-z0-9_], unique: each format lands as out/cuts/<id>_<W>x<H>.mp4 ("a1_s1_9x16.mp4")
|
||||
pub id: String,
|
||||
pub angle: Option<String>,
|
||||
/// solo or mashup
|
||||
pub kind: Option<String>,
|
||||
/// one of the brief's hook types ("Direct Problem", "Reaction")
|
||||
pub hook: Option<String>,
|
||||
/// captions, hook (a text hook) or none
|
||||
pub text: Option<String>,
|
||||
#[serde(default)]
|
||||
#[ts(as = "Option<Vec<String>>", optional)]
|
||||
pub formats: Vec<String>,
|
||||
pub seconds: Option<[f64; 2]>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
#[ts(optional_fields)]
|
||||
#[ts(rename = "MakePhrase")]
|
||||
pub struct Phrase {
|
||||
/// as it's said or shown; compared in lower case, by letters and digits ("24/7" and "24-7" are the same)
|
||||
pub text: String,
|
||||
pub from: String,
|
||||
/// `say` only: false when one cut saying it is enough
|
||||
pub every: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
#[ts(optional_fields)]
|
||||
#[ts(rename = "MakeCta")]
|
||||
pub struct Cta {
|
||||
pub text: String,
|
||||
pub from: String,
|
||||
/// the other lines a brief rotates (two host lines, a paid take's): any one lands it, each found in the brief
|
||||
#[serde(default)]
|
||||
#[ts(as = "Option<Vec<String>>", optional)]
|
||||
pub also: Vec<String>,
|
||||
/// how near the end it must land, in seconds (8 when left out)
|
||||
pub within: Option<f64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
#[ts(optional_fields)]
|
||||
#[ts(rename = "MakeOpen")]
|
||||
pub struct Open {
|
||||
pub question: String,
|
||||
pub from: String,
|
||||
/// what it decides: "count", "cta", "offer", a cut's id...
|
||||
pub about: Option<String>,
|
||||
/// the person's answer, as they gave it, and who gave it: until then the job can't be done
|
||||
pub answer: Option<String>,
|
||||
pub by: Option<String>,
|
||||
}
|
||||
|
||||
/// How near the end the CTA lands when the contract says nothing.
|
||||
pub const CTA_WITHIN: f64 = 8.0;
|
||||
|
||||
/// A format's frame shape, "9:16" -> (9, 16).
|
||||
pub fn ratio(f: &str) -> Option<(u32, u32)> {
|
||||
let (w, h) = f.split_once(':')?;
|
||||
Some((w.trim().parse().ok().filter(|&w| w > 0)?, h.trim().parse().ok().filter(|&h| h > 0)?))
|
||||
}
|
||||
|
||||
/// A cut's formats and its length: its own, else the contract's.
|
||||
pub fn formats<'a>(c: &'a Cut, p: &'a CutPlan) -> &'a [String] {
|
||||
if p.formats.is_empty() { &c.formats } else { &p.formats }
|
||||
}
|
||||
pub fn seconds(c: &Cut, p: &CutPlan) -> Option<[f64; 2]> {
|
||||
p.seconds.or(c.seconds)
|
||||
}
|
||||
|
||||
/// Where a cut's format lands, relative to the brief: out/cuts/a1_s1_9x16.mp4.
|
||||
pub fn file(p: &CutPlan, format: &str) -> String {
|
||||
format!("out/cuts/{}_{}.mp4", p.id, format.replace(':', "x"))
|
||||
}
|
||||
|
||||
/// Every file the contract asks for.
|
||||
pub fn deliverables(c: &Cut) -> Vec<String> {
|
||||
c.cuts.iter().flat_map(|p| formats(c, p).iter().map(move |f| file(p, f))).collect()
|
||||
}
|
||||
|
||||
/// Every `from` in the contract, with what it backs: the quotes `raea make status` finds in the brief's text.
|
||||
pub fn quotes(c: &Cut) -> Vec<(String, &str)> {
|
||||
let mut q: Vec<(String, &str)> = Vec::new();
|
||||
if let Some(n) = &c.count {
|
||||
q.push(("count".into(), &n.from));
|
||||
}
|
||||
for (what, list) in [("say", &c.say), ("never", &c.never)] {
|
||||
for p in list {
|
||||
q.push((format!("{what} \"{}\"", p.text), &p.from));
|
||||
}
|
||||
}
|
||||
if let Some(cta) = &c.cta {
|
||||
q.push(("cta".into(), &cta.from));
|
||||
for line in &cta.also {
|
||||
q.push((format!("cta \"{line}\""), line));
|
||||
}
|
||||
}
|
||||
for o in &c.open {
|
||||
q.push((format!("open \"{}\"", o.question), &o.from));
|
||||
}
|
||||
q
|
||||
}
|
||||
|
||||
/// What the contract lacks before it can be cut against, each with what to do.
|
||||
pub fn doctor(c: &Cut) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
if c.brief.trim().is_empty() {
|
||||
out.push("no `brief`: the brief as text beside brief.ts (pdftotext -layout BRIEF.pdf media/brief.txt), which every `from` quotes".into());
|
||||
}
|
||||
if c.cuts.is_empty() {
|
||||
out.push("no cuts: list every cut the brief asks for, with its id, angle, hook and formats".into());
|
||||
}
|
||||
if c.count.is_none() {
|
||||
out.push("no `count`: how many cuts the brief asks for, with its words".into());
|
||||
}
|
||||
if c.cta.is_none() {
|
||||
out.push("no `cta`: the line the brief says every cut ends on (or an `open` item asking for it)".into());
|
||||
}
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
for p in &c.cuts {
|
||||
if !seen.insert(p.id.as_str()) {
|
||||
out.push(format!("cut `{}` is listed twice", p.id));
|
||||
}
|
||||
if !crate::make::is_name(&p.id) {
|
||||
out.push(format!("cut `{}`: ids are [a-z0-9_], the file it lands as", p.id));
|
||||
}
|
||||
let fs = formats(c, p);
|
||||
if fs.is_empty() {
|
||||
out.push(format!("cut `{}` has no formats: give it `formats`, or the contract's", p.id));
|
||||
}
|
||||
for f in fs.iter().filter(|f| ratio(f).is_none()) {
|
||||
out.push(format!("cut `{}`: format `{f}` isn't W:H (\"9:16\", \"16:9\", \"1:1\", \"4:5\")", p.id));
|
||||
}
|
||||
match seconds(c, p) {
|
||||
None => out.push(format!("cut `{}` has no length: `seconds: [least, most]`, its own or the contract's", p.id)),
|
||||
Some([a, b]) if !(a > 0.0 && a <= b) => out.push(format!("cut `{}`: seconds [{a}, {b}] isn't [least, most]", p.id)),
|
||||
_ => {}
|
||||
}
|
||||
if let Some(t) = &p.text
|
||||
&& !matches!(t.as_str(), "captions" | "hook" | "none")
|
||||
{
|
||||
out.push(format!("cut `{}`: text is captions, hook or none, not `{t}`", p.id));
|
||||
}
|
||||
}
|
||||
for (what, from) in quotes(c) {
|
||||
if from.trim().is_empty() {
|
||||
out.push(format!("{what} has no `from`: the brief's own words for it"));
|
||||
}
|
||||
}
|
||||
for p in c.say.iter().chain(&c.never) {
|
||||
if norm(&p.text).is_empty() {
|
||||
out.push(format!("phrase `{}` has no letters or digits to find", p.text));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Text as it's compared: lower case, letters and digits, one space between words ("24/7" -> "24 7").
|
||||
pub fn norm(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
let mut gap = false;
|
||||
for ch in s.chars().flat_map(char::to_lowercase) {
|
||||
// a curly apostrophe or a plain one joins its word ("it's" is one word, "its" is another)
|
||||
if ch == '\'' || ch == '\u{2019}' {
|
||||
continue;
|
||||
}
|
||||
if ch.is_alphanumeric() {
|
||||
if gap && !out.is_empty() {
|
||||
out.push(' ');
|
||||
}
|
||||
gap = false;
|
||||
out.push(ch);
|
||||
} else {
|
||||
gap = true;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
//! A goal job's contract: `make: goal({...})` on brief.ts, the person's goal written as rules before the work starts
|
||||
//! (11-26, Shane: "we essentially just need to make sure that it can't stop unless all the goals pass, or all the rules
|
||||
//! in the brief"). `/goal` in raea.app and an agent's own goal are this: the goal in the person's words, then each
|
||||
//! thing that must hold, as a command that must pass, a file that must exist, or words a fresh critic must find true.
|
||||
//! `raea make status` (runtime/goal-plan) decides from them whether the agent may stop; the agent saying so never does.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use ts_rs::TS;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
#[ts(optional_fields)]
|
||||
#[ts(rename = "MakeGoal")]
|
||||
pub struct Goal {
|
||||
/// the goal as the person said it
|
||||
pub goal: String,
|
||||
/// what must hold before the agent may stop: every one, each checked in code or by a fresh critic
|
||||
#[serde(default)]
|
||||
#[ts(as = "Option<Vec<GoalRule>>", optional)]
|
||||
pub rules: Vec<GoalRule>,
|
||||
}
|
||||
|
||||
/// One thing that must hold. Exactly one of `run`, `file` or `says`.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
#[ts(optional_fields)]
|
||||
#[ts(rename = "MakeGoalRule")]
|
||||
pub struct GoalRule {
|
||||
/// a short name: [a-z0-9_], how status, the critic and NOTES.md name it
|
||||
pub id: String,
|
||||
/// a command that must exit 0, run in the brief's folder (`bun test`, `raea check edit.tsx`)
|
||||
pub run: Option<String>,
|
||||
/// the seconds `run` gets before it counts as failed (300 when left out)
|
||||
pub timeout: Option<u32>,
|
||||
/// a file that must exist, relative to the brief (`a|b`: either; `dir/`: three or more pictures in it)
|
||||
pub file: Option<String>,
|
||||
/// words that must be true of the work, judged by a fresh critic (`raea make judge`), never by the agent that did it
|
||||
pub says: Option<String>,
|
||||
}
|
||||
|
||||
/// What the goal's rules still lack, each with what to do. Empty when it's ready.
|
||||
pub fn doctor(g: &Goal) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
if g.goal.trim().is_empty() {
|
||||
out.push("no `goal`: the goal in the person's own words".into());
|
||||
}
|
||||
if g.rules.is_empty() {
|
||||
out.push("no `rules`: what must hold before you stop, each a `run` command, a `file` or words a critic judges (`says`)".into());
|
||||
}
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
for r in &g.rules {
|
||||
if !crate::make::is_name(&r.id) {
|
||||
out.push(format!("rule `{}`: ids are [a-z0-9_]", r.id));
|
||||
}
|
||||
if !seen.insert(r.id.as_str()) {
|
||||
out.push(format!("rule `{}` is listed twice", r.id));
|
||||
}
|
||||
let n = [r.run.is_some(), r.file.is_some(), r.says.is_some()].iter().filter(|x| **x).count();
|
||||
if n != 1 {
|
||||
out.push(format!("rule `{}` needs exactly one of `run`, `file` or `says` (it has {n})", r.id));
|
||||
}
|
||||
if r.timeout.is_some() && r.run.is_none() {
|
||||
out.push(format!("rule `{}` has a `timeout` but no `run`", r.id));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -4,6 +4,8 @@
|
||||
//! types (`declarations`), so what tsc checks is exactly what this crate reads.
|
||||
|
||||
pub mod brief;
|
||||
pub mod cut;
|
||||
pub mod goal;
|
||||
pub mod make;
|
||||
pub mod parts;
|
||||
pub mod script;
|
||||
@@ -39,6 +41,8 @@ pub fn declarations() -> String {
|
||||
taste::Taste, taste::TasteSection, taste::Rule, taste::RuleCheck, taste::RuleLevel, taste::Check,
|
||||
parts::Parts, parts::Concept, parts::Level, parts::Count, parts::Part,
|
||||
make::Make, make::Kind, make::Source, make::DialValue, make::Dial, make::Route, make::Origin, make::Pick, make::Object, make::Shot,
|
||||
cut::Cut, cut::Quoted<u32>, cut::CutPlan, cut::Phrase, cut::Cta, cut::Open,
|
||||
goal::Goal, goal::GoalRule,
|
||||
));
|
||||
out.join("\n\n") + "\n"
|
||||
}
|
||||
|
||||
+66
-1
@@ -19,6 +19,10 @@ pub enum Kind {
|
||||
Kit,
|
||||
/// stills or camera moves of a built scene, from words
|
||||
Shot,
|
||||
/// ads cut from footage to a client's brief: its deliverables, phrases, claims and CTA as rules (cut.rs, MK25)
|
||||
Cut,
|
||||
/// any other work held to a goal: commands that must pass, files that must exist, words a critic judges (goal.rs)
|
||||
Goal,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
|
||||
@@ -52,6 +56,15 @@ pub struct Make {
|
||||
pub deliverables: Vec<String>,
|
||||
/// the most critic rounds the job gets; at the cap it is delivered with what's still missing (8 by default)
|
||||
pub rounds: Option<u32>,
|
||||
/// a cut job's contract: the brief as rules (cut.rs)
|
||||
pub cut: Option<crate::cut::Cut>,
|
||||
/// a goal job's contract: the goal and its rules (goal.rs)
|
||||
pub goal: Option<crate::goal::Goal>,
|
||||
/// what the job shows but never delivers, relative to the brief (pictures, render tests, examples): each a file or a
|
||||
/// `dir/` (review/ and previews/ when left out). Deliverables are what it hands over; previews are how it got there
|
||||
#[serde(default)]
|
||||
#[ts(as = "Option<Vec<String>>", optional)]
|
||||
pub previews: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
|
||||
@@ -150,6 +163,10 @@ pub struct Object {
|
||||
pub at: Option<[f64; 3]>,
|
||||
pub rot: Option<f64>,
|
||||
pub hero: Option<bool>,
|
||||
/// how large it is planned to be seen, which is how much of it gets built: 0 the hero (half the frame or more),
|
||||
/// 1 featured (under 50%), 2 dressing (under 20%), 3 background (under 8%: a grey box reads), 4 far (under 2%: a
|
||||
/// silhouette). A render that shows it finer than this says so (`lod-closer`; `raea scene lod` lists every part)
|
||||
pub lod: Option<u8>,
|
||||
pub pick: Option<Pick>,
|
||||
/// what was fixed by script ("glass made transmissive, label kept opaque")
|
||||
#[serde(default)]
|
||||
@@ -182,12 +199,22 @@ pub struct Shot {
|
||||
pub fps: Option<f64>,
|
||||
}
|
||||
|
||||
impl Kind {
|
||||
/// as brief.ts writes it, and as raea judge's rubrics are named
|
||||
pub fn name(self) -> &'static str {
|
||||
// in the enum's order
|
||||
["scene", "kit", "shot", "cut", "goal"][self as usize]
|
||||
}
|
||||
}
|
||||
|
||||
/// Each kind's dials: what may be set, and what an unset one is read from the references as.
|
||||
pub fn dials(kind: Kind) -> &'static [&'static str] {
|
||||
match kind {
|
||||
Kind::Scene => &["density", "tidiness", "wear", "wetness", "time_of_day", "weather", "atmosphere", "power", "warmth", "look"],
|
||||
Kind::Kit => &["count", "variety", "detail", "wear", "wetness", "warmth", "look"],
|
||||
Kind::Shot => &["res", "seconds", "lens", "handheld", "look"],
|
||||
Kind::Cut => &["look"],
|
||||
Kind::Goal => &[],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -214,9 +241,22 @@ pub fn deliverables(m: &Make) -> Vec<String> {
|
||||
}
|
||||
// a shot is a still or a move, so either file answers; apps/make reads `a|b`
|
||||
Kind::Shot => m.shots.iter().map(|s| format!("out/shots/{0}.png|out/shots/{0}.mp4", s.name)).collect(),
|
||||
Kind::Cut => m.cut.as_ref().map(crate::cut::deliverables).unwrap_or_default(),
|
||||
// a goal's `file` rules
|
||||
Kind::Goal => m.goal.iter().flat_map(|g| &g.rules).filter_map(|r| r.file.clone()).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// What the job shows but doesn't deliver: the plan's own list, else review/ and previews/.
|
||||
pub fn previews(m: &Make) -> Vec<String> {
|
||||
if m.previews.is_empty() { vec!["review/".into(), "previews/".into()] } else { m.previews.clone() }
|
||||
}
|
||||
|
||||
/// A name a file lands as: [a-z0-9_], not empty.
|
||||
pub fn is_name(s: &str) -> bool {
|
||||
!s.is_empty() && s.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
|
||||
}
|
||||
|
||||
/// What the plan still lacks before it can be built against, each with what to do. Empty when it's ready.
|
||||
pub fn doctor(m: &Make) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
@@ -229,6 +269,18 @@ pub fn doctor(m: &Make) -> Vec<String> {
|
||||
Kind::Scene | Kind::Kit if m.objects.is_empty() => out.push("no objects: list every object with its real size and route".into()),
|
||||
_ => {}
|
||||
}
|
||||
match (&m.cut, m.kind) {
|
||||
(Some(c), Kind::Cut) => out.extend(crate::cut::doctor(c)),
|
||||
(None, Kind::Cut) => out.push("no `cut`: the brief as rules (count, cuts, say, never, cta, open), each quoting it".into()),
|
||||
(Some(_), k) => out.push(format!("`cut` is for a cut job, not a {k:?}: drop it, or make this `cut({{...}})`")),
|
||||
_ => {}
|
||||
}
|
||||
match (&m.goal, m.kind) {
|
||||
(Some(g), Kind::Goal) => out.extend(crate::goal::doctor(g)),
|
||||
(None, Kind::Goal) => out.push("no `goal`: the goal in the person's words and its `rules`".into()),
|
||||
(Some(_), k) => out.push(format!("`goal` is for a goal job, not a {k:?}: drop it, or make this `goal({{...}})`")),
|
||||
_ => {}
|
||||
}
|
||||
if m.kind == Kind::Kit && m.style.is_none() {
|
||||
out.push("no `style`: one paragraph (era, palette, materials, wear, one fictional maker) every reference carries".into());
|
||||
}
|
||||
@@ -240,6 +292,9 @@ pub fn doctor(m: &Make) -> Vec<String> {
|
||||
if o.h.is_none() && o.dims.is_none() && o.max.is_none() {
|
||||
out.push(format!("object `{}` has no size: give `h` (metres), `dims` for boxy things or `max` for flat ones", o.id));
|
||||
}
|
||||
if o.lod.is_some_and(|l| l > 4) {
|
||||
out.push(format!("object `{}` has lod {}: 0 (the hero, half the frame or more) to 4 (far, under 2% of it)", o.id, o.lod.unwrap_or(0)));
|
||||
}
|
||||
if o.route.is_none() && m.kind == Kind::Scene {
|
||||
out.push(format!("object `{}` has no route: solid, rule, gen, library or picture", o.id));
|
||||
}
|
||||
@@ -254,7 +309,7 @@ pub fn doctor(m: &Make) -> Vec<String> {
|
||||
if !names.insert(s.name.as_str()) {
|
||||
out.push(format!("shot `{}` is listed twice", s.name));
|
||||
}
|
||||
if !s.name.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_') {
|
||||
if !is_name(&s.name) {
|
||||
out.push(format!("shot `{}`: names are [a-z0-9_], the file it lands as", s.name));
|
||||
}
|
||||
if s.composition.is_none() {
|
||||
@@ -263,3 +318,13 @@ pub fn doctor(m: &Make) -> Vec<String> {
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// One gate as `raea make status` lists it: its name, the file, item or rule it's about, whether it's clear, and what
|
||||
/// it says. A cut's gates come from raea-runtime-cut-plan, a goal's from raea-runtime-goal-plan.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Gate {
|
||||
pub name: &'static str,
|
||||
pub of: Option<String>,
|
||||
pub clear: bool,
|
||||
pub says: String,
|
||||
}
|
||||
@@ -117,6 +117,17 @@ fn a_make_plan_reads_and_its_doctor_names_what_it_lacks() {
|
||||
assert!(want.contains(&"out/kit/phone/phone_lod1.glb".to_string()) && want.contains(&"out/kit/kit.json".to_string()), "{want:?}");
|
||||
}
|
||||
|
||||
// MK22: an object's planned detail, 0 (the hero) to 4 (far)
|
||||
#[test]
|
||||
fn an_object_plans_its_detail_and_the_doctor_holds_it_to_five_levels() {
|
||||
let m: make::Make = read("make", r#"{"kind": "scene", "objects": [
|
||||
{"id": "kiosk", "label": "Kiosk", "h": 2.4, "route": "solid", "lod": 3},
|
||||
{"id": "tower", "label": "Tower", "h": 40, "route": "picture", "lod": 7}]}"#).unwrap();
|
||||
assert_eq!(m.objects[0].lod, Some(3));
|
||||
let d = make::doctor(&m);
|
||||
assert!(d.iter().any(|x| x.contains("`tower` has lod 7")) && !d.iter().any(|x| x.contains("`kiosk`")), "{d:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shot_plan_wants_a_still_or_a_move_per_shot() {
|
||||
let m: make::Make = read("make", r#"{"kind": "shot", "shots": [{"name": "counter_push", "move": "push_in"}, {"name": "Bad Name"}]}"#).unwrap();
|
||||
|
||||
@@ -224,3 +224,131 @@ pub fn ray_tri(o: Vec3, d: Vec3, [a, b, c]: [Vec3; 3]) -> Option<f32> {
|
||||
let t = e2.dot(q) / det;
|
||||
(t >= 0.0).then_some(t)
|
||||
}
|
||||
|
||||
/// The part's lowest points (its feet): its vertices within a millimetre (or 2% of its height) of its lowest, and
|
||||
/// points across the faces lying there (a slab's corners overhang what holds it up; its middle doesn't), about 4 n at most.
|
||||
pub fn feet(p: &Part, n: usize) -> Vec<Vec3> {
|
||||
let tol = (0.02 * (p.hi.y - p.lo.y)).clamp(0.0005, 0.003);
|
||||
let low = |q: &Vec3| q.y <= p.lo.y + tol;
|
||||
let mut v: Vec<Vec3> = p.tris.iter().flatten().filter(|q| low(q)).copied().collect();
|
||||
let bases: Vec<&[Vec3; 3]> = p.tris.iter().filter(|t| t.iter().all(low)).collect();
|
||||
let area: f32 = bases.iter().map(|t| 0.5 * (t[1] - t[0]).cross(t[2] - t[0]).length()).sum();
|
||||
if area > 0.0 {
|
||||
// about n points over the base, spread by area
|
||||
let step = (area / n as f32).sqrt();
|
||||
for t in bases {
|
||||
let long = (t[1] - t[0]).length().max((t[2] - t[1]).length()).max((t[0] - t[2]).length());
|
||||
let m = ((long / step).ceil() as usize).clamp(1, 32);
|
||||
for i in 0..=m {
|
||||
for j in 0..=(m - i) {
|
||||
let (a, b) = (i as f32 / m as f32, j as f32 / m as f32);
|
||||
v.push(t[0] + (t[1] - t[0]) * a + (t[2] - t[0]) * b);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
v.sort_by(|a, b| (a.x, a.z, a.y).partial_cmp(&(b.x, b.z, b.y)).unwrap_or(std::cmp::Ordering::Equal));
|
||||
v.dedup_by(|a, b| (*a - *b).length() < 1e-4);
|
||||
if v.len() > 4 * n {
|
||||
let k = v.len() as f32 / (4 * n) as f32;
|
||||
v = (0..4 * n).map(|i| v[(i as f32 * k) as usize]).collect();
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// A wall, or a piece of one (the strip of wall over a window, the window in it): no thicker than WALL_THICK, at least
|
||||
/// WALL_WIDE across and WALL_TALL high (metres; the kitchen's strip over its back window is 9.6 cm).
|
||||
const WALL_THICK: f32 = 0.35;
|
||||
const WALL_WIDE: f32 = 0.8;
|
||||
const WALL_TALL: f32 = 0.05;
|
||||
/// Whether a part is a wall or a piece of one: thin, wide and high.
|
||||
pub fn wall(p: &Part) -> bool {
|
||||
let e = p.hi - p.lo;
|
||||
e.y >= WALL_TALL && e.x.min(e.z) <= WALL_THICK && e.x.max(e.z) >= WALL_WIDE
|
||||
}
|
||||
|
||||
/// A wall's face area, for which of two is set into the other.
|
||||
pub fn face(p: &Part) -> f32 {
|
||||
let e = p.hi - p.lo;
|
||||
e.y * e.x.max(e.z)
|
||||
}
|
||||
|
||||
/// Whether a part's own material gives off light (a lamp's panel, a neon tube): any of its emissive's red, green or
|
||||
/// blue above zero. A model's materials are in its file and aren't read here.
|
||||
pub fn glows(it: &Item) -> bool {
|
||||
it.material.as_ref().and_then(|m| m.props.get("emissive")).is_some_and(glows_in)
|
||||
}
|
||||
|
||||
fn above_zero(v: &Value) -> bool {
|
||||
v.as_f64().unwrap_or(0.0) > 0.0
|
||||
}
|
||||
|
||||
/// A colour as the SDK writes one: [r, g, b, a], { red, green, blue, alpha }, a tagged one ({ LinearRgba: {...} }) or a
|
||||
/// CSS string.
|
||||
fn glows_in(v: &Value) -> bool {
|
||||
match v {
|
||||
Value::Array(a) => a.iter().take(3).any(above_zero),
|
||||
Value::Object(o) => {
|
||||
let own = ["red", "green", "blue", "r", "g", "b"].iter().filter_map(|k| o.get(*k)).any(above_zero);
|
||||
own || o.values().any(|v| (v.is_object() || v.is_array()) && glows_in(v))
|
||||
}
|
||||
Value::String(c) => !matches!(c.trim_start_matches('#').to_ascii_lowercase().as_str(), "000" | "000000" | "black" | ""),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// How far from the scene a part is parked: a piece swaps a flipbook's frames (MALL RAT's fountain, 88 water models) by
|
||||
/// moving the ones not shown hundreds of metres away, where they lie in one another and read as faces fighting.
|
||||
const PARKED: f32 = 500.0;
|
||||
|
||||
/// The parts in the scene, without those parked far from it (further than PARKED from the median of every part's
|
||||
/// centre), each of those said once as not checked.
|
||||
pub fn unparked<T>(parts: Vec<Part>, items: Vec<T>, skipped: &mut Vec<String>) -> (Vec<Part>, Vec<T>) {
|
||||
if parts.len() < 3 {
|
||||
return (parts, items);
|
||||
}
|
||||
let mid = |k: usize| {
|
||||
let mut v: Vec<f32> = parts.iter().map(|p| ((p.lo + p.hi) * 0.5)[k]).collect();
|
||||
v.sort_by(f32::total_cmp);
|
||||
v[v.len() / 2]
|
||||
};
|
||||
let centre = Vec3::new(mid(0), mid(1), mid(2));
|
||||
let mut parked = 0;
|
||||
let kept: (Vec<Part>, Vec<T>) = parts.into_iter().zip(items).filter(|(p, _)| {
|
||||
let far = ((p.lo + p.hi) * 0.5).distance(centre) > PARKED;
|
||||
parked += far as usize;
|
||||
!far
|
||||
}).unzip();
|
||||
if parked > 0 {
|
||||
skipped.push(format!("{parked} part{} parked over {PARKED} m from the scene (a flipbook's frames not shown)", if parked == 1 { "" } else { "s" }));
|
||||
}
|
||||
kept
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_flipbooks_frames_parked_far_away_are_left_out() {
|
||||
let part = |name: &str, c: Vec3, s: Vec3| Part { label: name.into(), tris: Vec::new(), node: Vec::new(), nodes: Vec::new(), lo: c - s / 2.0, hi: c + s / 2.0, excused: false, moving: false };
|
||||
let mut parts = vec![part("floor", Vec3::ZERO, Vec3::new(20.0, 0.1, 20.0)), part("bench", Vec3::new(1.0, 0.3, 0.0), Vec3::new(1.5, 0.5, 0.4)), part("water0", Vec3::new(0.0, 0.5, 3.0), Vec3::ONE)];
|
||||
for i in 1..4 {
|
||||
parts.push(part(&format!("water{i}"), Vec3::new(0.0, -900.0, 3.0), Vec3::ONE));
|
||||
}
|
||||
let mut skipped = Vec::new();
|
||||
let (kept, _) = unparked(parts, vec![(); 6], &mut skipped);
|
||||
assert_eq!(kept.iter().map(|p| p.label.as_str()).collect::<Vec<_>>(), ["floor", "bench", "water0"]);
|
||||
assert!(skipped[0].starts_with("3 parts parked"), "{skipped:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_colour_with_any_light_in_it_glows() {
|
||||
use serde_json::json;
|
||||
assert!(glows_in(&json!({"red": 0.0, "green": 120.0, "blue": 0.0, "alpha": 1.0})));
|
||||
assert!(glows_in(&json!([2200.0, 120.0, 80.0, 1.0])));
|
||||
// black with an alpha of 1 doesn't
|
||||
assert!(!glows_in(&json!({"red": 0.0, "green": 0.0, "blue": 0.0, "alpha": 1.0})));
|
||||
assert!(!glows_in(&json!([0.0, 0.0, 0.0, 1.0])));
|
||||
}
|
||||
}
|
||||
+149
-14
@@ -22,7 +22,6 @@ struct Face {
|
||||
n: Vec3,
|
||||
d: f32,
|
||||
tri: [Vec3; 3],
|
||||
area: f32,
|
||||
}
|
||||
|
||||
fn face(t: &[Vec3; 3]) -> Option<Face> {
|
||||
@@ -32,7 +31,7 @@ fn face(t: &[Vec3; 3]) -> Option<Face> {
|
||||
return None;
|
||||
}
|
||||
let n = c / l;
|
||||
Some(Face { n, d: n.dot(t[0]), tri: *t, area: 0.5 * l })
|
||||
Some(Face { n, d: n.dot(t[0]), tri: *t })
|
||||
}
|
||||
|
||||
type Key = (i32, i32, i32, i64);
|
||||
@@ -46,11 +45,17 @@ fn near(k: Key) -> impl Iterator<Item = Key> {
|
||||
(-1..=1).flat_map(move |a| (-1..=1).flat_map(move |b| (-1..=1).flat_map(move |c| (-1..=1).map(move |e| (k.0 + a, k.1 + b, k.2 + c, k.3 + e as i64)))))
|
||||
}
|
||||
|
||||
/// A point of a plane with normal `n` as two numbers, in an orthonormal frame of the plane.
|
||||
fn flat_in(n: Vec3) -> impl Fn(Vec3) -> Vec2 {
|
||||
let u = n.any_orthonormal_vector();
|
||||
let v = n.cross(u);
|
||||
move |p| Vec2::new(p.dot(u), p.dot(v))
|
||||
}
|
||||
|
||||
/// Whether two coplanar faces overlap by more than INSIDE: separating axes in the plane, in an orthonormal frame.
|
||||
fn overlap(a: &Face, b: &Face) -> bool {
|
||||
let u = a.n.any_orthonormal_vector();
|
||||
let v = a.n.cross(u);
|
||||
let flat = |t: &[Vec3; 3]| t.map(|p| Vec2::new(p.dot(u), p.dot(v)));
|
||||
let point = flat_in(a.n);
|
||||
let flat = |t: &[Vec3; 3]| t.map(&point);
|
||||
let (p, q) = (flat(&a.tri), flat(&b.tri));
|
||||
for tri in [&p, &q] {
|
||||
for k in 0..3 {
|
||||
@@ -73,24 +78,119 @@ fn overlap(a: &Face, b: &Face) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// What two coplanar faces share: its area, and its middle. One triangle cut by the other's three edges.
|
||||
fn shared(a: &Face, b: &Face) -> (f32, Vec3) {
|
||||
// the same frame flat_in makes, to carry the middle back into the world
|
||||
let u = a.n.any_orthonormal_vector();
|
||||
let v = a.n.cross(u);
|
||||
let flat = flat_in(a.n);
|
||||
let mut poly: Vec<Vec2> = a.tri.iter().map(|p| flat(*p)).collect();
|
||||
let q = b.tri.map(flat);
|
||||
// b's winding in this frame, so its inside is on one known side of each edge
|
||||
let turn = (q[1] - q[0]).perp_dot(q[2] - q[0]).signum();
|
||||
for k in 0..3 {
|
||||
let (e0, e1) = (q[k], q[(k + 1) % 3]);
|
||||
let side = |p: Vec2| (e1 - e0).perp_dot(p - e0) * turn;
|
||||
let mut cut = Vec::with_capacity(poly.len() + 2);
|
||||
for i in 0..poly.len() {
|
||||
let (p0, p1) = (poly[i], poly[(i + 1) % poly.len()]);
|
||||
let (s0, s1) = (side(p0), side(p1));
|
||||
if s0 >= 0.0 {
|
||||
cut.push(p0);
|
||||
}
|
||||
if (s0 > 0.0 && s1 < 0.0) || (s0 < 0.0 && s1 > 0.0) {
|
||||
cut.push(p0 + (p1 - p0) * (s0 / (s0 - s1)));
|
||||
}
|
||||
}
|
||||
poly = cut;
|
||||
if poly.len() < 3 {
|
||||
return (0.0, Vec3::ZERO);
|
||||
}
|
||||
}
|
||||
let mut area = 0.0;
|
||||
let mut mid = Vec2::ZERO;
|
||||
for i in 1..poly.len() - 1 {
|
||||
let t = 0.5 * (poly[i] - poly[0]).perp_dot(poly[i + 1] - poly[0]).abs();
|
||||
area += t;
|
||||
mid += (poly[0] + poly[i] + poly[i + 1]) / 3.0 * t;
|
||||
}
|
||||
if area <= 0.0 {
|
||||
return (0.0, Vec3::ZERO);
|
||||
}
|
||||
let mid = mid / area;
|
||||
(area, u * mid.x + v * mid.y + a.n * a.d)
|
||||
}
|
||||
|
||||
fn same_plane(a: &Face, b: &Face) -> bool {
|
||||
a.n.dot(b.n) >= PARALLEL && (a.n.dot(b.tri[0]) - a.d).abs() <= PLANE
|
||||
}
|
||||
|
||||
/// One face over another: how many pairs, about how much area (the smaller face of each pair, summed: an upper
|
||||
/// bound), and where the first is. `b` None: within `a` itself.
|
||||
/// One face over another: how many pairs, the area they share, and the middle of the largest shared patch. `b` None: within `a` itself.
|
||||
pub fn overlaps(a: &[[Vec3; 3]], b: Option<&[[Vec3; 3]]>) -> Option<(usize, f32, Vec3)> {
|
||||
let o = sorted(a, b);
|
||||
o.fight.or(o.twins).or(o.bases)
|
||||
}
|
||||
|
||||
/// Faces in one plane over each other, by whether they show.
|
||||
#[derive(Default, Debug)]
|
||||
pub struct Overlaps {
|
||||
/// One face over a different one: the picture flickers between them.
|
||||
pub fight: Option<(usize, f32, Vec3)>,
|
||||
/// Between two parts, the same triangle in both (a slab built into two neighbouring chunks): nothing to see where
|
||||
/// they look alike, since either draws the same.
|
||||
pub twins: Option<(usize, f32, Vec3)>,
|
||||
/// Between two parts, faces looking straight down in the plane both parts stand on (two boxes on one floor, one
|
||||
/// set into the other): their undersides, which the floor hides.
|
||||
pub bases: Option<(usize, f32, Vec3)>,
|
||||
}
|
||||
|
||||
/// Corners this close (metres) are one corner.
|
||||
const CORNER: f32 = 0.0005;
|
||||
|
||||
fn twin(a: &Face, b: &Face) -> bool {
|
||||
a.tri.iter().all(|p| b.tri.iter().any(|q| p.distance(*q) <= CORNER))
|
||||
}
|
||||
|
||||
/// The lowest corner of a part's faces.
|
||||
fn low(faces: &[Face]) -> f32 {
|
||||
let mut y = f32::INFINITY;
|
||||
for f in faces {
|
||||
for p in &f.tri {
|
||||
y = y.min(p.y);
|
||||
}
|
||||
}
|
||||
y
|
||||
}
|
||||
|
||||
/// As `overlaps`, with the pairs that don't show kept apart (between two parts only: inside one model every pair counts).
|
||||
pub fn sorted(a: &[[Vec3; 3]], b: Option<&[[Vec3; 3]]>) -> Overlaps {
|
||||
if b.is_none() && a.len() > SELF_MAX {
|
||||
return None;
|
||||
return Overlaps::default();
|
||||
}
|
||||
let fa: Vec<Face> = a.iter().filter_map(face).collect();
|
||||
let fb: Vec<Face> = b.map(|b| b.iter().filter_map(face).collect()).unwrap_or_default();
|
||||
let others = if b.is_some() { &fb } else { &fa };
|
||||
let (low_a, low_b) = (low(&fa), low(&fb));
|
||||
let mut buckets: HashMap<Key, Vec<usize>> = HashMap::new();
|
||||
for (i, f) in others.iter().enumerate() {
|
||||
buckets.entry(key(f.n, f.d)).or_default().push(i);
|
||||
}
|
||||
let (mut count, mut area, mut at) = (0usize, 0f32, None);
|
||||
let mut out = Overlaps::default();
|
||||
// the largest patch each kind has seen, for where to point
|
||||
let mut most = [0.0f32; 3];
|
||||
let mut add = |kind: usize, to: &mut Option<(usize, f32, Vec3)>, f: &Face, g: &Face| {
|
||||
let (area, mid) = shared(f, g);
|
||||
if area <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let e = to.get_or_insert((0, 0.0, mid));
|
||||
e.0 += 1;
|
||||
e.1 += area;
|
||||
if area > most[kind] {
|
||||
most[kind] = area;
|
||||
e.2 = mid;
|
||||
}
|
||||
};
|
||||
for (i, f) in fa.iter().enumerate() {
|
||||
let mut seen: Vec<usize> = Vec::new();
|
||||
for k in near(key(f.n, f.d)) {
|
||||
@@ -102,14 +202,20 @@ pub fn overlaps(a: &[[Vec3; 3]], b: Option<&[[Vec3; 3]]>) -> Option<(usize, f32,
|
||||
seen.push(j);
|
||||
let g = &others[j];
|
||||
if same_plane(f, g) && overlap(f, g) {
|
||||
count += 1;
|
||||
area += f.area.min(g.area);
|
||||
at.get_or_insert((f.tri[0] + f.tri[1] + f.tri[2]) / 3.0);
|
||||
let y = f.tri[0].y;
|
||||
let base = b.is_some() && f.n.y <= -0.999 && (y - low_a).abs() <= 0.001 && (y - low_b).abs() <= 0.001;
|
||||
if base {
|
||||
add(0, &mut out.bases, f, g);
|
||||
} else if b.is_some() && twin(f, g) {
|
||||
add(1, &mut out.twins, f, g);
|
||||
} else {
|
||||
add(2, &mut out.fight, f, g);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
at.map(|at| (count, area, at))
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -127,7 +233,12 @@ mod tests {
|
||||
let floor = quad(0.0, -1.0, 1.0, true);
|
||||
let rug = quad(0.0001, 0.0, 0.5, true);
|
||||
let (n, area, _) = overlaps(&rug, Some(&floor)).expect("the rug's top fights the floor's");
|
||||
assert!(n >= 2 && area > 0.1, "{n} {area}");
|
||||
// the rug's whole top, 0.5 m², and no more (the floor's triangles are bigger); pointed at inside the rug
|
||||
let at = overlaps(&rug, Some(&floor)).unwrap().2;
|
||||
assert!(n >= 2 && (area - 0.5).abs() < 1e-4 && at.x > 0.0 && at.x < 0.5 && at.z > 0.0 && at.z < 1.0, "{n} {area} {at}");
|
||||
// a strip 2 mm wide along a metre: 20 cm²
|
||||
let (_, strip, _) = overlaps(&quad(0.0, 0.998, 2.0, true), Some(&floor)).expect("a strip over the floor's edge");
|
||||
assert!((strip - 0.002).abs() < 1e-5, "{strip}");
|
||||
// 1 cm above it, it doesn't
|
||||
assert!(overlaps(&quad(0.01, 0.0, 0.5, true), Some(&floor)).is_none());
|
||||
// back to back (a box resting on another: one top up, the other's bottom down) doesn't fight
|
||||
@@ -140,4 +251,28 @@ mod tests {
|
||||
assert_eq!(overlaps(&doubled, None).map(|o| o.0), Some(1));
|
||||
assert!(overlaps(&quad(0.5, 0.0, 1.0, true), None).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_faces_in_two_parts_and_undersides_on_one_floor_are_kept_apart_from_a_fight() {
|
||||
// a slab built into two chunks: the same triangles in both
|
||||
let slab = quad(8.8, 0.0, 4.0, true);
|
||||
let o = sorted(&slab, Some(&slab));
|
||||
assert!(o.fight.is_none() && o.twins.map(|t| t.0) == Some(2), "{o:?}");
|
||||
// a rug's top in the floor's is a different face over it: a fight
|
||||
let o = sorted(&quad(0.0001, 0.0, 0.5, true), Some(&quad(0.0, -1.0, 1.0, true)));
|
||||
assert!(o.fight.is_some() && o.twins.is_none() && o.bases.is_none(), "{o:?}");
|
||||
// a door set into a wall, both standing on the floor: their undersides overlap in the floor's plane
|
||||
let mut wall = quad(0.0, -1.0, 1.0, false);
|
||||
wall.extend(quad(2.0, -1.0, 1.0, true));
|
||||
let mut door = quad(0.0, -0.4, 0.4, false);
|
||||
door.extend(quad(1.0, -0.4, 0.4, true));
|
||||
let o = sorted(&door, Some(&wall));
|
||||
assert!(o.fight.is_none() && o.bases.is_some(), "{o:?}");
|
||||
// the same underside held up off the ground (a soffit under a beam's) still fights
|
||||
let mut beam = quad(2.0, -1.0, 1.0, false);
|
||||
beam.extend(quad(0.0, -1.0, 1.0, true));
|
||||
let mut soffit = quad(2.0, -0.4, 0.4, false);
|
||||
soffit.extend(quad(1.5, -0.4, 0.4, true));
|
||||
assert!(sorted(&soffit, Some(&beam)).fight.is_some());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
@spec
|
||||
Feature: raea cloud: a synced folder is pictured, understood, embedded and organized for the person
|
||||
Shane, 2026-11-24: "when i have a data sync, we should auto index/tag and relate them to the appropriate folders or
|
||||
have an ai agent or our ask/decision model api if available otherwise use their subscription agent and tag or
|
||||
auto-organize the assets or files or folders so we can help understand what purpose they are for and predict what
|
||||
they mean/do. also make sure we embed all the assets based on embedding type. this will mean if we have a client
|
||||
library, we want to relate a client based folder to that library, or if disorganized we go file by file."
|
||||
Later that day: "we should be able to pick a folder from a sync location and have all content when syncing
|
||||
auto-tagged and organized for the user", "make sure thumbnails are also generated correctly", and of the models:
|
||||
"isn't it running the models in modal?"
|
||||
|
||||
Today (11-24) a sync lists its folder through Composio and adds each file as a link item, all in one flat folder,
|
||||
named and typed from its name and mime type only. Search embeds words (Workers AI's bge-small) and nothing else; no
|
||||
file is tagged; pictures came from drive.google.com in the viewer's browser, so a viewer signed out of Google saw
|
||||
none. The first real client demo is StreetTalk's: workspace streettalk, its Main library's "raea test — StreetTalk
|
||||
samples (Nov 2026)" Drive folder (54 files: 47 videos, 6 documents, 1 picture) and three client libraries (Dutch,
|
||||
Elfster, The Body Shop), each with a Drive folder of its own.
|
||||
|
||||
Background:
|
||||
Given a workspace with Google Drive (or Box, Dropbox, Frame.io, Slack) connected through Composio
|
||||
And raea never moves, renames or deletes anything in the tool: organizing happens in raea's library only
|
||||
|
||||
Rule: a folder is picked, and its shape comes with it
|
||||
Scenario: IG1. A sync is a folder picked from the tool's own list
|
||||
When the person adds a sync and picks a folder from Drive's list (syncadd.js)
|
||||
Then the sync keeps the folder's id and its name; a folder typed as its id or its Drive link works the same,
|
||||
and is named for the folder on its first run (built 11-24: sync-run.ts driveId, NAME)
|
||||
Scenario: IG2. Subfolders come in as folders
|
||||
Given the picked folder holds subfolders ("Raw/Angle 1", "Finals")
|
||||
Then each becomes a library folder under the sync's folder, with the same name and nesting, and each file lands
|
||||
in its own; a file moved between subfolders in the tool moves in raea on the next run
|
||||
|
||||
Rule: every file has a picture anyone who can see the library sees
|
||||
Scenario: IG3. A synced file's picture is kept by raea
|
||||
When a run lists a file that has a picture in its tool (Drive's thumbnailLink; Box's and Dropbox's thumbnails)
|
||||
Then raea fetches it once at 640 px and keeps it in the workspace's own store (items.thumb, the API's signed
|
||||
thumb_src), 60 a run, a failed fetch tried again on the next run (built 11-24 for Drive)
|
||||
And the library's card shows it, with a play mark on a video; a tool's page address is never put in a <video>
|
||||
Scenario: IG4. A file with no picture in its tool gets one made
|
||||
Given a video, PDF or document the tool has no picture of
|
||||
Then a frame (a video's at 10% of its length), a first page or a typeset title card is made on Modal (IG8) and
|
||||
kept the same way
|
||||
|
||||
Rule: every file is understood
|
||||
Scenario: IG5. Each new file is read by its kind
|
||||
When a run brings files in
|
||||
Then each is read once per version (its tool's modified time or checksum): a picture by its picture; a video by
|
||||
its picture, frames at 10/50/90% and its words (transcribed); a document by its text (Drive exports Docs as
|
||||
text, PDFs are read); a sound by its words or, with none, what it sounds like
|
||||
And what it says about the file is kept on the item: a one-line description, tags (its kind: raw footage, b-roll,
|
||||
a final cut, a brief, a script, a logo, a voiceover, a reference; its subject; its client or brand; its format,
|
||||
9x16 or 16x9; its length), and for each tag who said it and why
|
||||
Scenario: IG6. raea's model reads first; the workspace's agent when there's none
|
||||
(built 11-24 with raea's model as a vision model on OpenRouter, tagger.ts: description, role, client, tags with
|
||||
why, on the item and its turbopuffer rows; raea ask's clef model takes its place when it's deployed)
|
||||
Given the workspace's plan has raea's ask model (raea ask, docs/ask.feature: clef-omni on the plan's pool)
|
||||
Then the files are read by it, batched, the spend on the pool
|
||||
Otherwise they are read by the workspace's own connected agent on raea cloud's box (Claude Code on its Claude, or
|
||||
Antigravity on its Google AI plan), as a background job that never takes a project's turn
|
||||
And with neither, files are tagged from their names, folders and types alone, and the library says how to get more
|
||||
Scenario: IG7. A person's correction wins
|
||||
When someone removes or changes a tag, or moves a file to another folder
|
||||
Then raea never puts it back, and the next files like it are read with that correction in the prompt
|
||||
|
||||
Rule: every file is embedded by its kind, once, into turbopuffer (Enterprise)
|
||||
Scenario: IG8. raea's own library indexer runs on Modal and writes to turbopuffer
|
||||
Then each file is indexed by the desktop's own indexer (apps/app host/library/index-file.ts, in the cloud
|
||||
indexer's image: EmbeddingGemma 2 for pictures, shots, sound and words, TransNetV2 cuts, Whisper; a document's
|
||||
text in windows), as a job on Modal (ingest.py index_job, any length), so a desktop's and the cloud's vectors
|
||||
compare; EmbeddingGemma 2 on a GPU (RAEA_INDEX_GPU=L4: fp16, CUDA 13) while there's work, else the CPU at q8
|
||||
And its rows go to turbopuffer in raea-api's layout, one namespace a workspace (raea-cloud-<workspace>.
|
||||
embeddinggemma-2@768), a row per segment and modality, replaced when the file is indexed again
|
||||
And only an Enterprise workspace is indexed in the cloud (raea cloud is Enterprise only, Shane 11-24); the raea
|
||||
app's Pro and Team plans embed on their own computers and keep their index in turbopuffer through raea-api,
|
||||
Free on the Mac
|
||||
(built 11-24: index-run.ts, tools/library-index cloud.ts, cloud-cli.ts, cloud-server.ts)
|
||||
Scenario: IG9. Search finds a file by what's in it
|
||||
(built 11-24: search.ts deep, turbopuffer's nearest segments, a hit's at {t0, t1})
|
||||
When the person searches "girl laughing on a street corner, vertical"
|
||||
Then the words are matched against pictures and frames (SigLIP's text tower), descriptions and transcripts, and
|
||||
tags, fused into one ranking; a hit says where in a video it is
|
||||
|
||||
Rule: the files are organized for the person
|
||||
Scenario: IG10. A folder about a client goes with that client's library
|
||||
Given a synced folder whose name, or most of whose files, are about one of the workspace's clients
|
||||
Then the sync is related to that client's library (or its files are, when the folder is the workspace's), shown
|
||||
with the reason ("47 of 54 files show The Body Shop's products"), and undone in one click
|
||||
Scenario: IG11. A disorganized folder is sorted file by file
|
||||
Given a folder of files with no useful subfolders
|
||||
Then raea proposes folders (by client, then by kind: Raw, B-roll, Finals, Briefs) with each file's place and
|
||||
reason, as one review the person accepts whole, or file by file; nothing moves until they do
|
||||
And once accepted, new files that fit are placed the same way on later runs
|
||||
|
||||
Rule: the person can see it working
|
||||
Scenario: IG12. The left panel says what a sync is doing
|
||||
Then a sync bringing files in turns in the left panel, on its row and its library's (built 11-24), then says
|
||||
"Reading 12 of 54" while files are read, and its card shows the tags as they come
|
||||
Scenario: IG13. Proven on StreetTalk's demo
|
||||
When StreetTalk's four Drive syncs run from empty
|
||||
Then every file has a picture, a description and tags; the three client folders are related to their client
|
||||
libraries; a search for a shot finds it by what's in it; and the run says its time and what it cost
|
||||
@@ -24,6 +24,8 @@ Feature: Make: scenes, kits and shots built to a frozen plan and held to a revie
|
||||
once each is calibrated on the person's labels; a fresh critic's fixes always (fixed or answered), its score
|
||||
once `raea judge calibrate` agrees with the person's eye.
|
||||
5. Every job ends with its notes, including what the skill got wrong for it, so the next job starts from them.
|
||||
6. Every object is planned at a level of detail, by how large it is meant to be seen, and every render says
|
||||
when a shot shows one closer than that (MK21-MK24).
|
||||
|
||||
Background:
|
||||
Given raea's scene loop as advice (sdk/guides/craft/bevy/scenes.md, from the 11-06 research): brief, routing,
|
||||
@@ -194,6 +196,128 @@ Feature: Make: scenes, kits and shots built to a frozen plan and held to a revie
|
||||
plan from the entrance (blockout.tsx, and `raea render --review` sheets of it) and puts the reference, the
|
||||
blockout and the floor plan on comparison.png, for the person to approve before anything is generated
|
||||
|
||||
Rule: planned detail (MK21-MK24)
|
||||
Shane, 2026-11-24: "define objects at an LOD level based on either us grayboxing or thinking of them as generally
|
||||
distant objects and alert agents when an LOD that was at 3 or 4 for example is now appearing in frame at LOD 2
|
||||
level or 1, or 0 ... helpful for planning objects as generally distant and unseen objects versus close ones and
|
||||
knowing if we forgot about something over time". A level is how large a part is planned to be seen, which is how
|
||||
much of it gets built; the frames are measured against it on every render, so a camera move added later, or a
|
||||
box that was meant to be replaced, is said the next time anything is drawn.
|
||||
|
||||
@done
|
||||
Scenario: MK21. A part shown closer than its planned detail is said
|
||||
Given a level is how much of the frame a part's box spans through the frame's camera, the larger of its width's
|
||||
and its height's share: 0 the hero (50% or more), 1 featured (20%), 2 dressing (8%), 3 background (2%), 4 far
|
||||
And a part's plan is its own `lod` (Mesh3d, Model, and every part inside an Entity with a transform or a Group
|
||||
that has one), else the `lod` of the plan's object of its name
|
||||
When a frame shows a planned part at a finer level than its plan (raea-runtime-lod-plan)
|
||||
Then the render's end checks, `raea scene stage` and `raea check --quick` say `lod-closer`: the part, its plan,
|
||||
the level it is seen at, how much of the frame it spans at its largest and on which frame, how many frames it
|
||||
is closer on, and the fix (build it for that level and plan it there, or keep the camera off it)
|
||||
And one level finer is a warning, two or more an error, which fails the render as any error does
|
||||
And a part out of the frame, behind the camera, or with another mesh's box across every line to it isn't seen;
|
||||
a part the camera stands in or beside is measured at its nearest point; RAEA_LOD_CHECK=0 leaves the check out
|
||||
|
||||
@needs:MK21 @done
|
||||
Scenario: MK22. The plan carries each object's level
|
||||
Given `lod: 0..4` on an object of `make` in brief.ts (core/brief make.rs; `doctor` refuses a level past 4)
|
||||
Then a render of a composition under that brief holds the parts named as the objects' ids to those levels
|
||||
(runtime/lod-plan plan.rs reads the brief only when its words plan a level, once a version)
|
||||
And `raea make plan` labels each footprint with its level and writes each grey box with its object's id as its
|
||||
name and its `lod`, so the blockout is held to the plan it draws
|
||||
|
||||
@needs:MK21 @done
|
||||
Scenario: MK23. `raea scene lod`: every part's plan beside what the frames show
|
||||
When `raea scene lod EDIT.tsx [--from N] [--to N] [--json]` steps the frames without drawing
|
||||
Then it lists every part: its planned level, the finest level a frame shows it at, how much of the frame it
|
||||
spans there, on which frame, and how many frames it is in; parts seen closer than planned first (the widest
|
||||
gap on top), then the rest of the planned, then the parts with no plan by how large they get
|
||||
And a planned part no frame shows as close as its plan says so (built finer than it is ever seen)
|
||||
And a level the plan gives a name that no part in the frames goes by is listed, since it holds nothing
|
||||
And it exits 1 when a part is seen two or more levels finer than planned
|
||||
|
||||
@needs:MK22 @done
|
||||
Scenario: MK24. A job is held at a part seen closer than planned
|
||||
Given a job whose composition's last render or check found `lod-closer`
|
||||
Then `raea make status` has a `lod` gate for that composition, open with the parts' names, until each is built
|
||||
for the level it is seen at and replanned, kept out of the camera's way, or answered in NOTES.md on a line
|
||||
with `lod` and its name; the Stop hook holds the agent there as at any open gate
|
||||
And a job that plans a level and whose render found none shows the gate clear
|
||||
|
||||
Rule: cuts from a client's brief (MK25-MK27)
|
||||
Shane, 11-25, on StreetTalk's street interview ads, cut by raea cloud agents from three clients' PDF briefs: "you
|
||||
need to make the process of ingesting the brief more direct, or else it's just context that gets lost. It needs to
|
||||
be written as a brief typescript rule that is then enforced ... I need raea make to be the standard". The agents had
|
||||
read the briefs and still shipped what a contract catches: held to one written from Elfster's brief, Gemini's four
|
||||
delivered solos (eight files) had "free, fun, and easy" missing from three, the CTA rewritten in one ("Download
|
||||
Elfster for free in the App Store") and missing from another, no frames check on any final file, and four of the
|
||||
ten cuts the brief asks for in its out/ folder.
|
||||
|
||||
@needs:MK0
|
||||
Scenario: MK25. The brief as rules: `make: cut({...})`
|
||||
Given a client's brief as text beside brief.ts (pdftotext -layout BRIEF.pdf media/brief.txt)
|
||||
When the agent writes `make: cut({ cut: {...} })` before it plans a single cut
|
||||
Then core/brief reads `cut` (cut.rs): `brief` (that text), `count` (how many cuts the brief asks for), `seconds`
|
||||
and `formats`, each cut (id, angle, solo or mashup, hook, captions or a text hook, its own formats and length),
|
||||
`say` (phrases every cut says or shows, or one cut with `every: false`), `never` (phrases no cut says or
|
||||
shows), `cta` (the line every cut ends on, within its last 8 s; `also`: the other lines a brief rotates, any
|
||||
one of which lands it, each found in the brief) and `open` (the brief's [TO CONFIRM] items)
|
||||
And every rule has `from`: the brief's own words for it
|
||||
And each cut lands at a fixed path, out/cuts/<id>_<W>x<H>.mp4 for each of its formats
|
||||
And `doctor` names what the contract still lacks: no count, no cta, an id that isn't [a-z0-9_], a format that
|
||||
isn't W:H, a cut with no length, a rule with no `from`
|
||||
|
||||
@needs:MK25
|
||||
Scenario: MK26. Held to the brief's own words, its count and its open items
|
||||
Given a cut contract
|
||||
Then `raea make status` finds every `from` in the brief's text, compared by letters and digits: a rule the brief
|
||||
doesn't say, or says in other words, holds the job ("quotes")
|
||||
And fewer cuts than `count` hold it, unless an `open` item about "count" has the person's answer ("count")
|
||||
And every `open` item without an answer holds it, so the agent stops at a review to ask ("open")
|
||||
|
||||
@needs:MK25
|
||||
Scenario: MK27. Every delivered file held to the rules, from what's on disk
|
||||
Given a cut's file at its path
|
||||
Then its shape and length are read from its own MP4 boxes, so a file re-encoded after its render is read as it is
|
||||
now ("shape")
|
||||
And its words must be heard after its last change (FILE.words.json, `raea words`), and in them or its render's
|
||||
text (FILE.render.json): every `say` phrase ("say"), no `never` phrase, with the second it's heard ("never"),
|
||||
and the CTA in its last `within` seconds, 85% of its words in order ("cta")
|
||||
And its frames check must have run after its last change (FILE.frames-check.json, `raea frames check`) with no
|
||||
error: no face cut by the frame or a seam, no text under the size floor ("frames")
|
||||
And the cut job has no critic tier yet: the person's review is its critic
|
||||
|
||||
Rule: any goal, held to rules (MK28-MK29)
|
||||
Shane, 11-26, asking whether raea make is just a version of /goal: "when we use these things, they should just
|
||||
probably be consolidated into one workflow, because in any case we'll have a goal or a brief or something that
|
||||
dictates what we need. And then we essentially just need to make sure that it can't stop unless all the goals pass,
|
||||
or all the rules in the brief". /goal in raea.app's chat let the agent end the loop by writing "GOAL MET"; a goal it
|
||||
can declare met is advice. So /goal and raea make are one loop: a goal is a fifth kind of job, its words become
|
||||
rules in brief.ts before the work starts, and only `raea make status` says it's met.
|
||||
|
||||
@needs:MK2
|
||||
Scenario: MK28. A goal as rules: `make: goal({...})`
|
||||
Given work that isn't a scene, kit, shot or cut (fix a bug, write a page, ship a change)
|
||||
When the agent writes `make: goal({ goal: "the person's words", rules: [...] })` before it starts
|
||||
Then core/brief reads `goal` (goal.rs): the goal as the person said it, and `rules`, each an id and exactly one of
|
||||
`run` (a command that must exit 0 in the brief's folder, within `timeout` seconds, 300 by default), `file` (a
|
||||
file that must exist: a deliverable) or `says` (words that must be true of the work)
|
||||
And `doctor` names what it lacks: no goal, no rules, an id that isn't [a-z0-9_] or is listed twice, a rule with
|
||||
none or more than one of run, file and says, a timeout with no run
|
||||
And a goal job needs no NOTES.md "What the skill got wrong" section (no skill made it) and has no render critic
|
||||
|
||||
@needs:MK28
|
||||
Scenario: MK29. Held by a command's exit and a fresh critic, never the agent's word
|
||||
Given a goal job
|
||||
Then `raea make status` runs every `run` rule at every status, the Stop hook's included, and holds the job on one
|
||||
that fails or outlives its timeout, with its exit code and last line ("run")
|
||||
And a `says` rule is clear only when review/goal.judge.json, written by `raea make judge [DIR] [--by claude|kimi]`
|
||||
(a fresh session that may only read: Read, Grep and Glob), found it true at a time no earlier than the work's
|
||||
newest file, the job's own review/, .raea/, NOTES.md, .git and node_modules left out, compared at whole seconds
|
||||
("says")
|
||||
And `file` rules are its deliverables, listed under missing
|
||||
And raea.app's /goal is this job: it writes the rules first, and only the status ends the loop
|
||||
|
||||
Rule: raea cloud (MK19-MK20)
|
||||
|
||||
@needs:MK2 @done
|
||||
|
||||
@@ -68,7 +68,7 @@ What's wrong before anyone watches it.
|
||||
| [`raea make`](make.md) | A scene, kit or shot made to its plan: the plan stop, the kit's references, generators, pick, prep and landing, a shot list's framing and lens charts, and whether it's done, decided in code; the agent's Stop hook holds it there. |
|
||||
| [`raea fingerprint`](fingerprint.md) | A person's sense of good work, learned on this Mac: axes with small heads over on-device encoders that score a render moment by moment and say what they can't judge yet. |
|
||||
| [`raea findings`](findings.md) | What each render and check found, read back from the project's record: fixed, new and carried since the one before. |
|
||||
| [`raea scene`](scene.md) | Find floating, sunk and clipping 3D parts, say what each part rests on, meter a shot's light, and hold every frame to the stage checks a render runs. |
|
||||
| [`raea scene`](scene.md) | Find floating, sunk and clipping 3D parts, say what each part rests on, meter a shot's light, hold every frame to the stage checks a render runs, and list each part's planned detail beside how large the frames show it. |
|
||||
| [`raea light`](light.md) | Measure a scene's light on each light path against its path-traced reference: distance in stops, the worst tile, flicker and cost. |
|
||||
| [`raea bench`](bench.md) | Each case on each denoiser against its converged truth: FLIP, RMSE, bias, flicker, blotches, lag after a disocclusion or a light going out, a frame's cost, and how many of MetalFX's numbers each meets. |
|
||||
| [`raea world`](world.md) | A frame as one world: its layers, text, 3D parts, camera, shots, clips, cues and lines as entities, queried across media. |
|
||||
|
||||
@@ -5,13 +5,18 @@ order: 44
|
||||
sources: ["apps/make/src/lib.rs", "apps/make/src/status.rs", "apps/make/src/asked.rs", "apps/make/src/plan.rs", "apps/make/src/kit.rs", "apps/make/src/kitout.rs", "apps/make/src/shots.rs", "apps/make/src/floor.rs", "apps/make/src/sheet.rs", "core/brief/src/make.rs", "apps/check/make/src/lib.rs"]
|
||||
---
|
||||
|
||||
`raea make status` reads the job on a project's brief.ts (`make: scene({...})`, `kit({...})` or `shot({...})` from
|
||||
`raea make status` reads the job on a project's brief.ts (`make: scene({...})`, `kit({...})`, `shot({...})`, `cut({...})` or `goal({...})` from
|
||||
`raea/brief`) and says what's still missing, from what's on disk and never from what the agent says:
|
||||
|
||||
- the kind's deliverables (a scene's three or more stills; a kit's GLB, LOD1 and thumbnail per object, its lineup
|
||||
and kit.json; a shot's still or move per shot), or the plan's own `deliverables`;
|
||||
- NOTES.md, ending with a "What the skill got wrong" section;
|
||||
- each composition the plan names has a render or check newer than it that found no error (the project's record);
|
||||
- no part is seen closer than its planned detail. An object's `lod` (0 the hero to 4 far; the levels are in
|
||||
[raea scene](scene.md)) says how large it is planned to be seen, so a grey box or a far backdrop is planned at 3
|
||||
or 4. A render that shows it two levels finer is an error, held by the line above; one level finer holds the job
|
||||
until the part is built for that level and replanned, the camera keeps off it, or NOTES.md answers it on a line
|
||||
with `lod` and its name. `raea scene lod` lists every part;
|
||||
- a fresh critic (`raea judge --kind KIND`) has judged a round newer than the newest deliverable on the job's own
|
||||
kind's rubric, and each blocking defect it named is fixed or answered in NOTES.md by its name; once the judge is
|
||||
calibrated against your eye, two passes in a row as well;
|
||||
@@ -21,6 +26,24 @@ sources: ["apps/make/src/lib.rs", "apps/make/src/status.rs", "apps/make/src/aske
|
||||
An answer counts for the sheet it was asked of, matched by the file's bytes, so a sheet rendered again is asked
|
||||
again.
|
||||
|
||||
A goal job (`goal({...})`, what raea.app's `/goal` writes) is any other work: the goal in your words and the rules
|
||||
that must hold before the agent stops. A `run` rule is a command that must exit 0 in the brief's folder (status runs
|
||||
it every time, 300 seconds unless its `timeout` says otherwise); a `file` rule is a deliverable; a `says` rule is
|
||||
words that must be true of the work, judged by a fresh critic that may only read: `raea make judge` asks one
|
||||
(`--by claude` or `kimi`) and keeps its verdict in review/goal.judge.json, and the rule clears only while that verdict
|
||||
is no older than the work's newest file. A goal job needs no NOTES.md section and has no render critic.
|
||||
|
||||
```ts
|
||||
make: goal({
|
||||
goal: "the export plays and the README says how to run it",
|
||||
rules: [
|
||||
{ id: "tests", run: "bun test" },
|
||||
{ id: "export", file: "out/final.mp4" },
|
||||
{ id: "readme", says: "README.md says how to install and run it, in order" },
|
||||
],
|
||||
}),
|
||||
```
|
||||
|
||||
`--plan` writes the gates as check lines under the job's own task in the project's plan.org, keeping the person's
|
||||
mark (DONE, DROPPED) and their own lines; the Stop hook runs it so.
|
||||
|
||||
@@ -75,7 +98,8 @@ raea make lenschart counter_push
|
||||
## Usage
|
||||
|
||||
```sh
|
||||
raea make status [DIR] [--json] [--plan] (a scene, kit or shot held to its plan, `make` on brief.ts: what's missing, each gate (renders and checks, raea ask's calibrated questions, the critic on the kind's rubric), the judge's rounds, and whether it's done, decided in code; --plan writes the gates as check lines under the job's task in plan.org; the agent's Stop hook holds it there)
|
||||
raea make status [DIR] [--json] [--plan] (a scene, kit, shot, cut or goal held to its plan, `make` on brief.ts: what's missing, each gate (renders and checks, raea ask's calibrated questions, the critic on the kind's rubric), the judge's rounds, and whether it's done, decided in code; --plan writes the gates as check lines under the job's task in plan.org; the agent's Stop hook holds it there)
|
||||
raea make judge [DIR] [--by claude|kimi] (a goal job: a fresh critic, which only reads, judges each `says` rule; review/goal.judge.json)
|
||||
raea make plan [DIR] [--no-review] (the plan stop: review/plan/floor-plan.png, a grey-box blockout from the entrance and its review sheets, comparison.png beside reference 0)
|
||||
raea make refs [DIR] [--only ID,...] [--model M] [--dry] (a kit: every object's reference from the style images, in the plan's style, then review/refs.png; --dry quotes it)
|
||||
raea make sheet refs [DIR] (review/refs.png again: the style images, then every reference)
|
||||
@@ -94,6 +118,7 @@ Headless: it needs nothing running and opens no window. Takes up to 5 arguments
|
||||
|
||||
| Flag | Takes | What it does |
|
||||
| --- | --- | --- |
|
||||
| `--by` | `claude\|kimi` | The critic `judge` asks, a fresh session that may only read (default `claude`). |
|
||||
| `--dry` | – | Quote the generation (refs, gen) and make nothing. |
|
||||
| `--json` | – | Print the status as JSON: missing, gates, judge, done, short and why. |
|
||||
| `--meshy` | `M` | The Meshy model for `gen` (default `fal:meshy/v7.1/image-to-3d`). |
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
---
|
||||
title: "raea scene"
|
||||
summary: "Find floating, sunk and clipping 3D parts, say what each part rests on, meter a shot's light, and hold every frame to the stage checks a render runs."
|
||||
summary: "Find floating, sunk and clipping 3D parts, say what each part rests on, meter a shot's light, hold every frame to the stage checks a render runs, and list each part's planned detail beside how large the frames show it."
|
||||
order: 47
|
||||
sources: ["apps/scene/src/lib.rs", "apps/scene/src/light.rs", "apps/scene/src/stage.rs", "systems/stage/src/lib.rs", "systems/stage/src/clearance.rs", "systems/contact/src/lint.rs", "systems/contact/src/zfight.rs"]
|
||||
sources: ["apps/scene/src/lib.rs", "apps/scene/src/light.rs", "apps/scene/src/stage.rs", "apps/scene/src/lod.rs", "runtime/lod-plan/src/lib.rs", "runtime/lod-plan/src/report.rs", "runtime/lod-plan/src/plan.rs", "systems/stage/src/lib.rs", "systems/stage/src/clearance.rs", "systems/contact/src/lint.rs", "systems/contact/src/zfight.rs"]
|
||||
---
|
||||
|
||||
`raea scene` steps a composition's frames and measures its 3D scene without rendering pictures. `lint` reports
|
||||
@@ -21,6 +21,28 @@ also holds the camera M metres off every solid part on every frame (0.45 for a c
|
||||
part it comes closer to, the frames and the nearest it gets, or that it's inside the part. Glass, decals, volumes and
|
||||
parts under 5 cm are passed over.
|
||||
|
||||
`lod` lists every part's planned detail beside what the frames show. A part's plan is how large it is meant to be
|
||||
seen, which is how much of it gets built:
|
||||
|
||||
| lod | for | across the frame |
|
||||
| --- | --- | --- |
|
||||
| 0 | the hero | 50% or more |
|
||||
| 1 | featured | 20% to 50% |
|
||||
| 2 | set dressing | 8% to 20% |
|
||||
| 3 | background: a grey box reads | 2% to 8% |
|
||||
| 4 | far: a silhouette | under 2% |
|
||||
|
||||
The plan is the part's own `lod` prop (`<Mesh3d lod={3}>`, `<Model lod={4}>`, or a parent `<Entity transform lod>`
|
||||
or `<Group lod>` for every part inside), else the `lod` of the object with the part's name in the job's plan (`make`
|
||||
on the brief.ts above the composition). What a frame shows is how much of it the part's box spans through that
|
||||
frame's camera, the larger of its width's and its height's share. The table puts parts seen closer than planned
|
||||
first, then the rest of the planned parts, then the parts nobody planned by how large they get, so a part forgotten
|
||||
since the plan was written is found by reading down it. Under it: each `lod-closer` finding, and any level the plan
|
||||
gives a name that no part in the frames goes by. A part seen one level finer than planned is a warning; two or more
|
||||
is an error, and `lod` exits 1. `raea render`, `raea scene stage` and `raea check --quick` say the same finding, and
|
||||
`raea make status` holds a job at it. A part hidden behind other meshes isn't counted as seen; RAEA_LOD_CHECK=0
|
||||
leaves the check out of a render.
|
||||
|
||||
```sh
|
||||
raea scene lint room.tsx
|
||||
raea scene explain room.tsx --frame 90 --json
|
||||
@@ -28,6 +50,7 @@ raea scene light room.tsx --part hero
|
||||
raea scene light film.tsx --composition shot1,shot2,shot3 # the light across the cuts
|
||||
raea scene stage film.tsx --from 1800 --to 2400 # the stage checks on 20 s of it
|
||||
raea scene stage walk.tsx --clearance 0.45 # and the camera kept off the set
|
||||
raea scene lod walk.tsx # every part's planned detail against the frames
|
||||
```
|
||||
|
||||
<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->
|
||||
@@ -36,7 +59,7 @@ raea scene stage walk.tsx --clearance 0.45 # and the camera
|
||||
|
||||
```sh
|
||||
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)
|
||||
raea scene lint|explain|light|stage EDIT.tsx [--composition ID] [--frame N] [--part NAME] [--from N] [--to N] [--clearance M] [--json] (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)
|
||||
raea scene lint|explain|light|stage|lod EDIT.tsx [--composition ID] [--frame N] [--part NAME] [--from N] [--to N] [--clearance M] [--json] (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)
|
||||
```
|
||||
|
||||
Headless: it needs nothing running and opens no window. Takes up to 2 arguments besides its flags.
|
||||
@@ -49,10 +72,10 @@ Headless: it needs nothing running and opens no window. Takes up to 2 arguments
|
||||
| `--clearance` | `M` | `stage`: every run of frames where the camera is nearer a solid part than M metres (0.45 carried, 0.15 on a rig). |
|
||||
| `--composition` | `ID` | Which composition to measure. `light` takes several, comma-separated, to compare the light across their cuts. |
|
||||
| `--frame` | `N` | The frame to measure (0 by default; `light` also takes `last`). |
|
||||
| `--from` | `N` | With `stage`: the first frame held to the checks (0 when left out). Every frame before it is still stepped, so a scene that builds over time is as it would render. |
|
||||
| `--json` | – | Print as JSON: `lint` its findings (check, level, the parts they are about, frames, says, measure, fix), `explain` every part with its support, gap and box. |
|
||||
| `--from` | `N` | With `stage` and `lod`: the first frame held to the checks (0 when left out). Every frame before it is still stepped, so a scene that builds over time is as it would render. |
|
||||
| `--json` | – | Print as JSON: `lint` its findings (check, level, the parts they are about, frames, says, measure, fix), `explain` every part with its support, gap and box, `lod` every part's row (planned, seen, largest, at, frames, closer), the plan's names no part goes by, and its findings. |
|
||||
| `--part` | `NAME` | With `light`: the part to meter, in place of the shot's subject. |
|
||||
| `--to` | `N` | With `stage`: the last frame held to the checks (the composition's last when left out). |
|
||||
| `--to` | `N` | With `stage` and `lod`: the last frame held to the checks (the composition's last when left out). |
|
||||
| `-o` | `DIR` | `export`: the folder scene.json is written to, with meshes/ and models/ beside it. |
|
||||
|
||||
<!-- generated:end -->
|
||||
|
||||
@@ -24,7 +24,7 @@ Headless: it needs nothing running and opens no window. Takes up to 2 arguments
|
||||
| `--duplex` | – | Listen all the time, with nothing taken out of the microphone's sound. For headphones: through speakers it hears itself and stops. |
|
||||
| `--fast` | – | With `--from`: read the recording as fast as it can be heard, not at the pace it was spoken. For tests. |
|
||||
| `--from` | `IN.wav` | A recording in the microphone's place. |
|
||||
| `--over` | – | Listen while it speaks, with its own voice taken out of the microphone's sound, so the person can talk over it through speakers. New: checked in a simulated room, not yet across real rooms. The first word or two said over it can be lost. |
|
||||
| `--over` | – | Listen while it speaks, with its own voice taken out of the microphone's sound, so the person can talk over it through speakers. Experimental, and raea.app doesn't use it. It works in a simulated room. In the one real room it was tried in (a wireless USB microphone and a Mac mini's speakers, 11-25) its own voice was never taken out well enough to be sure of, so nobody could talk over it and it behaved as without the flag: it never stopped itself by mistake either. |
|
||||
| `--pause` | `MS` | How long a silence ends the person's turn, in milliseconds. |
|
||||
| `--room` | `GAIN` | With `--from` and `--over`: a simulated room. What it says comes back into the recording at this gain (0.5 is a quiet room, 1.5 a loud one). |
|
||||
| `--to` | `OUT.wav` | A file in the speakers' place: everything it says is written there. |
|
||||
|
||||
@@ -279,6 +279,7 @@ hand-written element.
|
||||
| `scale` | `Vec3 \| number` | one number, or x, y and z |
|
||||
| `transform` | `{ translation?: Vec3; rotation?: [number, number, number, number]; scale?: Vec3 }` | Bevy's Transform (Transform.fromXyz(..).withRotation(..)), in place of position, rotation and scale: the entity is then a parent whose children (meshes, lights, models, other entities) move with it, as Bevy's ChildOf children do (the old Group) |
|
||||
| `pass` | `string` | with `transform`: the composition pass of every part inside that doesn't name its own (Mesh's `pass`) |
|
||||
| `lod` | `PlannedLod` | with `transform`: the planned detail of every part inside that plans none of its own, 0 (the hero) to 4 (far) |
|
||||
| `children` | `ReactNode` | its Bevy components (<BevyComponent>, or the generated wrappers in raea/bevy-own); with `transform`, also the parts it carries |
|
||||
|
||||
Used in: [ui/widgets/viewport_node](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/widgets/viewport_node.tsx), [3d/3d_shapes](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/3d/3d_shapes.tsx), [3d/atmospheric_fog](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/3d/atmospheric_fog.tsx), [3d/3d_scene](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/3d/3d_scene.tsx), [3d/parenting](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/3d/parenting.tsx), [stress_tests/many_foxes](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/stress_tests/many_foxes.tsx), [camera/projection_zoom](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/camera/projection_zoom.tsx), [animation/animated_transform](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/animation/animated_transform.tsx), and 5 more.
|
||||
@@ -554,6 +555,7 @@ Bevy: `bevy_pbr::mesh_material::MeshMaterial3d<raea_render::engine::look::LookMa
|
||||
| `scale` | `number \| Vec3` | one number, or x, y and z |
|
||||
| `allowOverlap` | `boolean` | it may pass through other parts on purpose (a blade into a body, a ghost through a wall): raea's clipping check leaves it out |
|
||||
| `posed` | `boolean` | set at an angle on purpose (a bowl knocked over, a mug on its side): `raea scene lint` doesn't call it tilted |
|
||||
| `floating` | `boolean` | it hangs in the air on purpose, touching nothing (a balloon, a sign on wires that aren't modelled): `raea scene lint` doesn't call it left in the air |
|
||||
| `animation` | `string \| number` | a clip to play: its name in the file, or its index |
|
||||
| `screens` | `ModelScreens` | live pictures on its materials, by the glTF material's name: `{ monitor_screen: <Screen resolution={[384, 272]}> <Game /></Screen> }` (or a bare `<Game />` for the defaults). Each mesh with that material shows the screen, the picture fitted to the mesh's texture coordinates and stood upright |
|
||||
| `hide` | `string[]` | nodes of the glTF hidden, by name (a robot's painted-on eyes under the screen that replaces them) |
|
||||
@@ -569,6 +571,7 @@ Bevy: `bevy_pbr::mesh_material::MeshMaterial3d<raea_render::engine::look::LookMa
|
||||
| `flat` | `boolean` | its surfaces without light: shape and colour alone, like a drawing (the site look keeps the light: its grain is made of it) |
|
||||
| `shadow` | `boolean` | false: its meshes cast no shadow (true by default) |
|
||||
| `detail` | `Detail` | where it's drawn: its distances or sizes on screen, cross-faded, and its shadow (Detail; raea-sys-lod) |
|
||||
| `lod` | `PlannedLod` | its planned detail, 0 (the hero) to 4 (far): how large it is meant to be seen. A render that shows it finer says so (`lod-closer`); a stand-in or a far backdrop is planned at 3 or 4 (PlannedLod) |
|
||||
| `receiveShadow` | `boolean` | false: no shadow falls on its meshes, its own included (true by default): a furry coat of many cards that would otherwise speckle itself in the shadow maps |
|
||||
| `pixelSize` | `number` | a cell's size in frame pixels for the pixel and site looks (6 by default) |
|
||||
| `edgeColor` | `string` | the pixel look's one-cell outline, a hex colour ("#000000" by default), or "none" |
|
||||
|
||||
@@ -30,10 +30,10 @@ See [Workspaces and projects](../../concepts/workspaces.md) for where each spec
|
||||
<!-- generated:begin by tools/manual-ref/sdk.ts from the SDK's exports and doc comments; edit outside this block -->
|
||||
|
||||
```ts
|
||||
import { brief, fingerprint, kit, parts } from "raea/brief"
|
||||
import { brief, cut, fingerprint, goal } from "raea/brief"
|
||||
```
|
||||
|
||||
`raea/brief` exports 8 functions, 34 types. Source: [sdk/raea/src/brief.ts](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/brief.ts).
|
||||
`raea/brief` exports 10 functions, 42 types. Source: [sdk/raea/src/brief.ts](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/brief.ts).
|
||||
|
||||
## Functions
|
||||
|
||||
@@ -46,6 +46,14 @@ the project's plan.org.
|
||||
function brief(b: Brief): Brief
|
||||
```
|
||||
|
||||
### `cut`
|
||||
|
||||
ads cut from footage to a client's brief: `cut: {...}` is the brief as rules, each quoting it
|
||||
|
||||
```ts
|
||||
function cut(m: Omit<Make, "kind">): Make
|
||||
```
|
||||
|
||||
### `fingerprint`
|
||||
|
||||
A fingerprint (fingerprint.ts): its axes and the encoders its heads were trained on.
|
||||
@@ -54,6 +62,16 @@ A fingerprint (fingerprint.ts): its axes and the encoders its heads were trained
|
||||
function fingerprint(f: Fingerprint): Fingerprint
|
||||
```
|
||||
|
||||
### `goal`
|
||||
|
||||
any other work held to a goal (`/goal`): the goal in the person's words and the rules that must hold before the agent
|
||||
stops, each a command that must pass (`run`), a file that must exist (`file`) or words a fresh critic judges
|
||||
(`says`, by `raea make judge`). `raea make status` holds the agent to every one.
|
||||
|
||||
```ts
|
||||
function goal({ goal, rules, ...m }: MakeGoal & Omit<Make, "kind" | "goal">): Make
|
||||
```
|
||||
|
||||
### `kit`
|
||||
|
||||
A kit: props in one style at real size (`style` is the paragraph every reference carries: era, palette, materials,
|
||||
@@ -205,6 +223,24 @@ type Line = { /** * a character, or "narrator" */ who: string, says: string, /**
|
||||
type Make = { kind: MakeKind, /** * the pictures the job answers to (paths beside the brief): what is in it and where for a scene, the style for a kit */ references?: Array<string>, /** * one paragraph every reference prompt carries: era, palette, materials, wear, and one fictional maker */ style?: string, /…
|
||||
```
|
||||
|
||||
### `MakeCta`
|
||||
|
||||
```ts
|
||||
type MakeCta = { text: string, from: string, /** * how near the end it must land, in seconds (8 when left out) */ within?: number, }
|
||||
```
|
||||
|
||||
### `MakeCut`
|
||||
|
||||
```ts
|
||||
type MakeCut = { /** * the brief as text, relative to brief.ts (`pdftotext -layout brief.pdf media/brief.txt`): every `from` is found in it */ brief: string, /** * how many cuts the brief asks for; fewer planned is held open until an answered `open` item about "count" says why */ count?: MakeQuoted<number>, /**…
|
||||
```
|
||||
|
||||
### `MakeCutPlan`
|
||||
|
||||
```ts
|
||||
type MakeCutPlan = { /** * [a-z0-9_], unique: each format lands as out/cuts/<id>_<W>x<H>.mp4 ("a1_s1_9x16.mp4") */ id: string, angle?: string, /** * solo or mashup */ kind?: string, /** * one of the brief's hook types ("Direct Problem", "Reaction") */ hook?: string, /** * captions, hook (a text hook) or none */ tex…
|
||||
```
|
||||
|
||||
### `MakeDial`
|
||||
|
||||
```ts
|
||||
@@ -217,10 +253,22 @@ type MakeDial = MakeDialValue | { value: MakeDialValue, source?: MakeSource, /**
|
||||
type MakeDialValue = number | string
|
||||
```
|
||||
|
||||
### `MakeGoal`
|
||||
|
||||
```ts
|
||||
type MakeGoal = { /** * the goal as the person said it */ goal: string, /** * what must hold before the agent may stop: every one, each checked in code or by a fresh critic */ rules?: Array<MakeGoalRule>, }
|
||||
```
|
||||
|
||||
### `MakeGoalRule`
|
||||
|
||||
```ts
|
||||
type MakeGoalRule = { /** * a short name: [a-z0-9_], how status, the critic and NOTES.md name it */ id: string, /** * a command that must exit 0, run in the brief's folder (`bun test`, `raea check edit.tsx`) */ run?: string, /** * the seconds `run` gets before it counts as failed (300 when left out) */ timeout?: num…
|
||||
```
|
||||
|
||||
### `MakeKind`
|
||||
|
||||
```ts
|
||||
type MakeKind = "scene" | "kit" | "shot"
|
||||
type MakeKind = "scene" | "kit" | "shot" | "cut" | "goal"
|
||||
```
|
||||
|
||||
### `MakeObject`
|
||||
@@ -229,18 +277,36 @@ type MakeKind = "scene" | "kit" | "shot"
|
||||
type MakeObject = { /** * snake_case, unique in the job */ id: string, label: string, /** * real height in metres */ h?: number, /** * [width, depth, height] in metres, for boxy things (generators invent depth) */ dims?: [number, number, number], /** * largest extent in metres, for things that lie flat (tools, pap…
|
||||
```
|
||||
|
||||
### `MakeOpen`
|
||||
|
||||
```ts
|
||||
type MakeOpen = { question: string, from: string, /** * what it decides: "count", "cta", "offer", a cut's id... */ about?: string, /** * the person's answer, as they gave it, and who gave it: until then the job can't be done */ answer?: string, by?: string, }
|
||||
```
|
||||
|
||||
### `MakeOrigin`
|
||||
|
||||
```ts
|
||||
type MakeOrigin = "reference" | "invented"
|
||||
```
|
||||
|
||||
### `MakePhrase`
|
||||
|
||||
```ts
|
||||
type MakePhrase = { /** * as it's said or shown; compared in lower case, by letters and digits ("24/7" and "24-7" are the same) */ text: string, from: string, /** * `say` only: false when one cut saying it is enough */ every?: boolean, }
|
||||
```
|
||||
|
||||
### `MakePick`
|
||||
|
||||
```ts
|
||||
type MakePick = { /** * "tripo-h31", "meshy", ... */ generator: string, /** * one line: why this one ("sharper dial numerals; Tripo fused the handset to the cradle") */ why: string, }
|
||||
```
|
||||
|
||||
### `MakeQuoted`
|
||||
|
||||
```ts
|
||||
type MakeQuoted = { value: T, /** * the brief's own words, as they are in its text */ from: string, }
|
||||
```
|
||||
|
||||
### `MakeRoute`
|
||||
|
||||
```ts
|
||||
|
||||
@@ -33,7 +33,7 @@ The composition, the app, and the specs and notes an agent writes.
|
||||
| --- | --- | --- |
|
||||
| [`raea`](raea.md) | The main entry: compositions, sequences, time, interpolation, springs, footage, sound and words. | 21 components, 9 hooks, 65 functions, 11 values, 109 types |
|
||||
| [`raea/app`](app.md) | The App, its plugins and schedules, and the registry a video's compositions are kept in. | 1 component, 1 hook, 5 functions, 3 classes, 17 values, 18 types |
|
||||
| [`raea/brief`](brief.md) | The specs an agent writes as data: brief, script, taste and an object's parts, checked against raea's schemas. | 8 functions, 34 types |
|
||||
| [`raea/brief`](brief.md) | The specs an agent writes as data: brief, script, taste and an object's parts, checked against raea's schemas. | 10 functions, 42 types |
|
||||
| [`raea/note`](note.md) | A person's note as a file in the project: their words kept as written, and the asks the agent restates it as. | 1 function, 4 types |
|
||||
|
||||
## Time and motion
|
||||
|
||||
@@ -207,6 +207,8 @@ raster-lit: Bevy 0.20's Solari can't trace it, unless `dynamic` gives a skinned
|
||||
| `primarySamples` | `number` | direct light samples at the camera's first hit, a pixel a frame (Bevy's 8). After MetalFX's denoiser 4 bought the window scene nothing over 8 and saved 1.5 ms at 1080p's pixels |
|
||||
| `secondarySamples` | `number` | direct light samples at each bounce (Bevy's 4) |
|
||||
| `firstBounce` | `number` | the chance a pixel traces its first bounce this frame, its light divided by it (Russian roulette): 0.5 halves the bounce's tracing, most of a dense forest's (1, every pixel every frame) |
|
||||
| `paths` | `number` | initial paths a pixel a frame (1 to 16, 1 by default): N cut the noise of one path N times, at N times its rays. A sunlit room seen through bounces (MALL RAT's court) needs 4 or more to hold still |
|
||||
| `firefly` | `number` | the firefly filter: a sample over this many times the mean of its 8x8 pixels is cut back to that after temporal reuse (off by default; 2 and up). One very bright sample otherwise lingers and spreads: a patch jumps brighter and takes a second to fall back. Lower holds stiller and loses more light (a room lit by small bulbs: 6 holds still and reads 0.3 stops darker, 12 half of both; 32 loses nothing and gains little) |
|
||||
| `cache` | `{ /** frames a cell's light is gathered over: steadier and slower to follow a change (B…` | Solari's world cache, the bounce light it keeps in cells across the scene |
|
||||
| `scale` | `number` | draw the view at this fraction of its size a side (a third to 1) and let MetalFX's temporal scaler bring it up to the full size, so a game traces fewer pixels: 0.67 traces 45% of them. On the Mac; elsewhere it draws at the full size and raea says so. 1 (or left out): the full size; RAEA_SOLARI_SCALE overrides it |
|
||||
| `denoise` | `boolean` | MetalFX's temporal denoiser on the lighting. false shows Solari's raw noise. Default true; RAEA_SOLARI_DENOISE=0 overrides it |
|
||||
@@ -215,11 +217,14 @@ raster-lit: Bevy 0.20's Solari can't trace it, unless `dynamic` gives a skinned
|
||||
| `emissive` | `"taa" \| "split" \| "mask"` | an emissive surface's own light: "taa" taken out before the denoiser and gathered over frames (RT11, RT32), "split" each frame's alone, "mask" left in for the denoiser. Default "taa"; RAEA_SOLARI_EMISSIVE overrides it |
|
||||
| `upscale` | `"one" \| "two"` | a view drawn small (scale below 1): denoised and brought up in "one" pass, or denoised small and scaled in "two". Default "one"; RAEA_SOLARI_UPSCALE overrides it |
|
||||
| `preexposure` | `number` | what MetalFX divides the light by before it denoises and multiplies it by after. Higher keeps more of a rare bright sample (a lamp found by one path in many) and lets more fireflies through: 1 kept 0.74 of the desk's light, 16 0.86, 64 0.91. Default 16; RAEA_METALFX_PREEXPOSURE overrides it |
|
||||
| `knee` | `number` | where the denoiser's soft knee starts, in its white (1 by default; 0 off). Light above it is denoised as its log and restored after, so a silhouette against bright sky or a lit doorway doesn't step with the camera's jitter. RAEA_METALFX_KNEE overrides it |
|
||||
| `late` | `boolean` | denoise after the forward meshes and the sky, so their edges are gathered over frames too instead of stepping with the camera's jitter. RAEA_SOLARI_DENOISE_LATE overrides it |
|
||||
| `aa` | `boolean` | jitter a full-size view too, so the denoiser anti-aliases its edges as it gathers frames. Default true; RAEA_SOLARI_AA=0 overrides it |
|
||||
| `jitter` | `"denoiser" \| "scaler" \| "both" \| "flip" \| "none"` | which of MetalFX's passes is told the camera's jitter: "denoiser", "scaler", "both", "flip" (the denoiser, negated), "none" (and the view isn't jittered). For A/Bs of RT9; default "denoiser"; RAEA_SOLARI_JITTER ("" the denoiser, "0" none) overrides it |
|
||||
| `emissiveSharpness` | `number` | how fast a sample's weight falls with its distance from a pixel's centre in the emission's history, exp(-k d²) in output pixels: lower is softer. Default 6; RAEA_EMIT_TAA_SHARP overrides it |
|
||||
| `jitterFrames` | `number` | the jitter's cycle at the full size, in frames: a view drawn at s of its size a side cycles through jitterFrames / s² offsets, and an emissive twig glimpsed through it may stay away that long. Default 8 (DLSS's) |
|
||||
| `dynamic` | `boolean` | the traced scene follows what moves (a trial, false by default): a skinned character's traced twin is posed each frame, so it casts traced shadows and bounces light. Decided as each mesh is first traced, so set it from the first frame. (A hidden part, or one a frame leaves out, leaves the traced scene with or without it.) |
|
||||
| `overscan` | `number` | overscan (off by default): the view is traced this much wider on every side (0.05 is a twentieth of its width and height) and the middle cropped back out, so the frame's border has light to gather from as the camera moves. For a moving shot whose edges crawl (`raea light steady` passing everywhere but the border). It costs (1 + 2 x overscan)² the tracing, the picture is drawn at 1 / (1 + 2 x overscan) of its size at most and brought up, and depth of field, motion blur and `--aov` read the wider view. Mac only (it rides MetalFX's denoiser) |
|
||||
| `constants` | `{ /** how far ReSTIR looks for a neighbour's light samples, pixels (30): smaller keeps …` | constants in Solari's and the denoiser's shaders, compiled in when the scene loads (a value changed later in the composition isn't drawn); each left out keeps the shader's own, given in brackets. <ShaderConstants> reaches the rest |
|
||||
|
||||
### `SpotLight`
|
||||
|
||||
@@ -114,7 +114,7 @@ One part, so a curve that grows is solid at every frame (never a chain of parts:
|
||||
| `normal` | `Vec3` | the way its face looks: the normal of the plane it lies in (left out: the plane of its points, else +z) |
|
||||
| `children` | `ReactNode` | its material (a white StandardMaterial when left out) |
|
||||
|
||||
Also takes the props of `MeshProps` (`animate`, `name`, `read`, `pass`, `quaternion`, `allowOverlap`, `posed`, `shape`, `driven`, `shadow`, `material`, `castShadow`, `surface`, `receiveShadow`, `attributes`, `compressed`, `layers`); `PointerHandlers3d` (`onClick`, `onDrag`, `onDragEnd`, `onDragEnter`, `onDragLeave`, `onDragOver`, `onDragStart`, `onDrop`, `onPointerDown`, `onPointerMove`, `onPointerUp`, `onPointerEnter`, `onPointerLeave`, `onPointerOver`, `onPointerOut`, `onWheel`); [`Mesh3dProps`](#mesh3dprops) (`visibility`, `transform`, `detail`).
|
||||
Also takes the props of `MeshProps` (`animate`, `name`, `read`, `pass`, `quaternion`, `allowOverlap`, `posed`, `floating`, `lod`, `shape`, `driven`, `shadow`, `material`, `castShadow`, `surface`, `receiveShadow`, `attributes`, `compressed`, `layers`); `PointerHandlers3d` (`onClick`, `onDrag`, `onDragEnd`, `onDragEnter`, `onDragLeave`, `onDragOver`, `onDragStart`, `onDrop`, `onPointerDown`, `onPointerMove`, `onPointerUp`, `onPointerEnter`, `onPointerLeave`, `onPointerOver`, `onPointerOut`, `onWheel`); [`Mesh3dProps`](#mesh3dprops) (`visibility`, `transform`, `detail`).
|
||||
|
||||
### `Mesh2d`
|
||||
|
||||
@@ -139,7 +139,7 @@ shadow="only" draws it with the shadow-only material (engine/render shadow_only.
|
||||
| `detail` | `Detail` | where it's drawn: its distances or sizes on screen, cross-faded, and its shadow (Detail; raea-sys-lod) |
|
||||
| `children` | `ReactNode` | its material and child entities |
|
||||
|
||||
Also takes the props of `MeshProps` (`animate`, `name`, `read`, `pass`, `quaternion`, `allowOverlap`, `posed`, `shape`, `driven`, `shadow`, `material`, `castShadow`, `surface`, `receiveShadow`, `attributes`, `compressed`, `layers`); `PointerHandlers3d` (`onClick`, `onDrag`, `onDragEnd`, `onDragEnter`, `onDragLeave`, `onDragOver`, `onDragStart`, `onDrop`, `onPointerDown`, `onPointerMove`, `onPointerUp`, `onPointerEnter`, `onPointerLeave`, `onPointerOver`, `onPointerOut`, `onWheel`).
|
||||
Also takes the props of `MeshProps` (`animate`, `name`, `read`, `pass`, `quaternion`, `allowOverlap`, `posed`, `floating`, `lod`, `shape`, `driven`, `shadow`, `material`, `castShadow`, `surface`, `receiveShadow`, `attributes`, `compressed`, `layers`); `PointerHandlers3d` (`onClick`, `onDrag`, `onDragEnd`, `onDragEnter`, `onDragLeave`, `onDragOver`, `onDragStart`, `onDrop`, `onPointerDown`, `onPointerMove`, `onPointerUp`, `onPointerEnter`, `onPointerLeave`, `onPointerOver`, `onPointerOut`, `onWheel`).
|
||||
|
||||
Used in: [ui/render_ui_to_texture](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/render_ui_to_texture.tsx), [ui/widgets/viewport_node](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/ui/widgets/viewport_node.tsx), [3d/fog](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/3d/fog.tsx), [3d/vertex_colors](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/3d/vertex_colors.tsx), [3d/rotate_environment_map](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/3d/rotate_environment_map.tsx), [3d/transparency_3d](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/3d/transparency_3d.tsx), [3d/spherical_area_lights](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/3d/spherical_area_lights.tsx), [3d/animated_material](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/3d/animated_material.tsx), and 54 more.
|
||||
|
||||
@@ -181,7 +181,7 @@ A line through points in 3D with a round section (a pipe, a wire): one mesh, dra
|
||||
| `radius` | `number` | its radius in metres (0.025) |
|
||||
| `sides` | `number` | sides around its section (12) |
|
||||
|
||||
Also takes the props of `MeshProps` (`animate`, `name`, `read`, `pass`, `quaternion`, `allowOverlap`, `posed`, `shape`, `driven`, `shadow`, `material`, `castShadow`, `surface`, `receiveShadow`, `attributes`, `compressed`, `layers`); `PointerHandlers3d` (`onClick`, `onDrag`, `onDragEnd`, `onDragEnter`, `onDragLeave`, `onDragOver`, `onDragStart`, `onDrop`, `onPointerDown`, `onPointerMove`, `onPointerUp`, `onPointerEnter`, `onPointerLeave`, `onPointerOver`, `onPointerOut`, `onWheel`); [`Mesh3dProps`](#mesh3dprops) (`visibility`, `transform`, `detail`).
|
||||
Also takes the props of `MeshProps` (`animate`, `name`, `read`, `pass`, `quaternion`, `allowOverlap`, `posed`, `floating`, `lod`, `shape`, `driven`, `shadow`, `material`, `castShadow`, `surface`, `receiveShadow`, `attributes`, `compressed`, `layers`); `PointerHandlers3d` (`onClick`, `onDrag`, `onDragEnd`, `onDragEnter`, `onDragLeave`, `onDragOver`, `onDragStart`, `onDrop`, `onPointerDown`, `onPointerMove`, `onPointerUp`, `onPointerEnter`, `onPointerLeave`, `onPointerOver`, `onPointerOut`, `onWheel`); [`Mesh3dProps`](#mesh3dprops) (`visibility`, `transform`, `detail`).
|
||||
|
||||
## Functions
|
||||
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
---
|
||||
title: "raea 0.1.10"
|
||||
version: "0.1.10"
|
||||
date: "2026-11-26"
|
||||
summary: "The app is raea cloud on your own computer, in the system's own window on the Mac, Windows and Linux. Publishing is a project's delivery, raea make holds a 3D scene to its plan, Solari's light boils less, and a long 3D film renders whole with each frame's own light."
|
||||
sources: ["https://github.com/shinyobjectz/raea/releases/tag/v0.1.10"]
|
||||
---
|
||||
|
||||
raea 0.1.10 makes the app raea cloud on your own computer. It is the same dashboard, with projects that run here on
|
||||
the AI you already use, in the system's own window on the Mac, Windows and Linux. A finished video is published from
|
||||
its project. In the engine, `raea make` holds a 3D scene, kit or shot to its plan until every check passes, Solari's
|
||||
light boils less and can be measured holding still, and a long 3D film that switches scenes renders whole with the
|
||||
same light as each frame alone.
|
||||
|
||||
**Get the app at [raea.io](https://raea.io)** (a Mac with Apple silicon, Windows 10 or 11, or Linux on x86_64).
|
||||
|
||||
The engine alone:
|
||||
|
||||
```sh
|
||||
curl -fsSL https://raea.io/install | sh
|
||||
```
|
||||
|
||||
On Windows, in PowerShell: `irm https://raea.io/install.ps1 | iex`.
|
||||
|
||||
## What changed since 0.1.9
|
||||
|
||||
### In the app
|
||||
|
||||
**The app is laid out like raea cloud.** Its rail is Inbox, Projects, Agents, Workflows, Libraries and Fingerprints,
|
||||
with your workspace above New, and Connections and Settings at the foot. Projects you start run on this computer, in a
|
||||
raea cloud of its own, on the AI you already use: Claude Code unless you pick another in Settings → General. Cloud
|
||||
workspaces sit in the same menu once you sign in. The first time it opens, the welcome and sign-in come first, then
|
||||
your projects, agents, library and fingerprints from the earlier app move in. The files are cloned, not copied, and the
|
||||
old folders are only read.
|
||||
|
||||
**In the system's own window.** The app now draws in the webview each system already has: WebKit on the Mac, WebView2
|
||||
on Windows and WebKitGTK on Linux. Links open in your browser, Copy reaches the clipboard, the folder chooser is the
|
||||
system's own on every system, and a `raea://` link brings the running app forward on Windows and Linux as on the Mac.
|
||||
|
||||
**Publishing is a project's delivery.** A workflow can end in a post: pick the accounts it posts to in its editor. When
|
||||
a project delivers its video, it waits in Needs you at Publish, with the caption its agent wrote and the account it
|
||||
goes to. Change the caption if you like, press Publish, and the project shows "Published" with the post's views once
|
||||
the network answers. On a plan that doesn't publish, Publish says which plan does and the project stays where it was.
|
||||
The separate Publishing page is gone.
|
||||
|
||||
**Ask a workflow to change.** In a workflow's editor, say what you want ("add a legal review before it posts") and
|
||||
your AI changes the workflow. When it needs to know more, it asks first.
|
||||
|
||||
**Agents and chats are one place.** Each agent is listed with its conversations under it, the busiest first. Click an
|
||||
agent to start a new chat with it, or its gear for its settings.
|
||||
|
||||
**The Inbox counts what you haven't seen.** Its number drops as cards come into view, and colour is kept for what needs
|
||||
you: what's running, done or stopped is grey.
|
||||
|
||||
**Projects belong to clients.** As in raea cloud, a project is filed under its client, and the client's board gathers
|
||||
its projects. Projects from the earlier app that sat inside another one join its client. In a terminal,
|
||||
`raea project new NAME --client CLIENT` names one, and `raea project tag --client CLIENT` changes it.
|
||||
|
||||
**`raea show` waits in your Inbox.** What an agent shows you from a terminal session is a card waiting for you, with
|
||||
its files, filed under its project's client. Your approval, or your notes and comments, go back to the session that
|
||||
asked.
|
||||
|
||||
**Mark up a picture.** The editor's picture toolbar has Pen (P), Arrow (A) and Box (B) beside Comment, in red, yellow
|
||||
or white, with Undo.
|
||||
|
||||
**A review link for work done here.** On Pro and Studio, a project in a workspace on this computer can hand out one of
|
||||
raea's review links for what it delivered.
|
||||
|
||||
**Ideate's voice is your raea plan's.** Talking an idea through in Ideate uses your plan's voice minutes: 30 a month on
|
||||
Pro, 300 on Studio, and no limit on Enterprise.
|
||||
|
||||
**Choose where your work is kept.** Settings → General → Where raea keeps your work: pick a folder on any drive, and from the next
|
||||
start raea keeps your work there, once what's already there has been copied and counted. The old folder stays as it
|
||||
was (#233).
|
||||
|
||||
**Light and dark.** The app follows your system, or stays light or dark: Settings → General → Theme.
|
||||
|
||||
### In the engine
|
||||
|
||||
**raea make.** `raea make status` holds a 3D scene, kit or shot written as `make` in a `brief.ts` to its plan: what's
|
||||
missing, each gate (its renders and checks, and raea ask's questions), and whether it's done. An agent's turn can't
|
||||
end until it is. Around it: `raea make plan` draws the floor plan and a grey-box blockout to review first, `raea make
|
||||
refs` makes every object's reference in one style, kits land as a component set with a lineup, and shots come from
|
||||
words or a path through the floor plan. A client's brief can be its rules (`make: cut({...})`), and each object and
|
||||
part can name its planned detail, from `lod={0}` (the hero) to `lod={4}` (far away), checked against how big it is on
|
||||
the frame.
|
||||
|
||||
**Solari's light boils less.** `<SolariLighting paths={N}>` starts N paths a pixel and merges them, which cuts the
|
||||
crawling patches on sunlit floors and reflections in held interiors by nearly half. `firefly={6}` cuts back a bright
|
||||
sample that stands far above its neighbours, and `overscan={0.05}` traces a little past the frame's edge so its border
|
||||
lights like its middle (on the Mac, where it rides the denoiser). Both are off unless set.
|
||||
|
||||
**Light you can measure holding still.** `raea render --hold FRAME` draws one frame again and again, and
|
||||
`raea light steady` says whether its light holds still, and if not, how it moves: settling, boiling, jitter or flicker.
|
||||
`raea light check` runs it on every traced scene.
|
||||
|
||||
**A 3D film renders whole.** In 0.1.9 a long film that switched scenes under Solari could draw its later shots darker
|
||||
than the same frames rendered alone: a part a scene had left stayed in the traced scene and kept shading the next one.
|
||||
It leaves now, and a film rendered whole matches each frame alone.
|
||||
|
||||
**raea render and raea scene check more.**
|
||||
- Words in the world that sit behind a part, so a viewer can't read them, are an error that names the part in front.
|
||||
Text3D is checked as RichText is.
|
||||
- A part a `<Label>` points at is the shot's subject: cutting it off at the frame's edge is an error.
|
||||
- A part left in the air touching nothing is an error in `raea scene lint`, unless it's marked `floating`.
|
||||
- A render whose shader didn't compile ends on an error, where before the frame came out without that pass.
|
||||
- `raea check`'s contrast reads a moving text where it is on its middle frame, not where it ends (#236).
|
||||
|
||||
**raea fix.** `raea fix "the error text"` looks a problem up before it's guessed at: what others found and did about
|
||||
the same symptom.
|
||||
|
||||
**raea/story.** A story as a typed program instead of a document: a premise, the values at stake, a cast with wants
|
||||
and needs, who knows what and when, and beats that each turn a value. It reads a story through twelve lenses (McKee,
|
||||
the Pixar spine, Campbell, Storynomics and others, plus a launch lens for product films), samples new stories from a
|
||||
seed, compiles to a `script.ts`, storylets, Ink or Yarn, and `raea check` holds a script's scenes to their beats.
|
||||
Measured against plain prompts, it works best as the editor of a draft rather than as the language a first draft is
|
||||
written in.
|
||||
|
||||
**New in raea render and raea media.**
|
||||
- `raea render --props JSON|FILE.json` hands a composition its inputs (`getInputProps()`), and `calculateMetadata` on
|
||||
a `<Composition>` sets its size and length from them (#176).
|
||||
- `raea render --scale S` draws a composition at S times its size: 0.5 for a quick look, 2 for a bigger master (#175).
|
||||
- `raea media share FILE -o OUT.mp4` makes the copy to send: any player takes it, and it's held to a bitrate (#219).
|
||||
|
||||
**The engine as a Linux AppImage.** Each release also carries `raea-VERSION-linux-x86_64.AppImage` and its checksum:
|
||||
make it executable and run it as `raea` (#226). The project has a [code of conduct](https://github.com/shinyobjectz/raea/blob/main/CODE_OF_CONDUCT.md) too
|
||||
(#228).
|
||||
|
||||
**Fixes.**
|
||||
- On Windows, a long chat scrolled in jerks, on fast graphics cards too (#215). In the system's own window a chat of
|
||||
160 turns scrolls at the display's rate, with or without the graphics card.
|
||||
- Two paint bugs, each held to what Chrome draws: a box behind a word with `z-index: -1` covered the word (#241), and
|
||||
a rounded rectangle's stroke could draw a bar across the page from its left edge at some widths (#240).
|
||||
- An Opus file couldn't be read back on Linux and Windows (#242).
|
||||
- A failing audio device printed its error on every callback, and on Linux the app's log reached 40 GB in two days.
|
||||
The error is said once, then how often it came back, and the app's log is kept to two files of 32 MB (#239).
|
||||
- An `<R3F>` over another layer cut a box out of the layer under it. The layer shows around the scene now (#235).
|
||||
- A WebM with alpha that another tool had remuxed drew opaque. Its alpha is read whatever the tag's case (#224).
|
||||
- `<Mix lufs>` could land a decibel off its target with flat-topped peaks. It lands on the target (#220).
|
||||
- `raea sounds get` of a second instrument into one folder replaced the first one's notes and licence. Each
|
||||
instrument keeps its own folder (#217).
|
||||
- `raea media sheet $FILES` in zsh, which passes every name as one argument, failed with "File name too long" (#218).
|
||||
- A song's bars are the same on every platform: a 12 ms difference between decoders moved them (#49).
|
||||
- A 3D scene with thousands of parts re-sent every part each frame. Parts whose props didn't change are skipped:
|
||||
a 3000-part scene went from 103 to 78 ms a frame (#160).
|
||||
- On Linux, signing in failed with "spawn /usr/bin/security ENOENT". The app keeps the sign-in in the desktop's
|
||||
keyring, or in a file only you can read where there is none (#216, #222).
|
||||
- `staticFile` from a composition in `compositions/` finds the project's `assets/`.
|
||||
- A composition with the word "import" in a comment above its imports failed before its first frame with "Can't find
|
||||
variable: raea". It renders.
|
||||
- A still of a page (`raea render --frame N`, or `--at` that doesn't start at 0) drew its CSS animations from the
|
||||
wrong time, so every animation showed its first keyframe. Each now runs from the composition's start, or from its
|
||||
own `<Sequence>`'s, as in the video.
|
||||
|
||||
**Known**
|
||||
- On Linux, raea needs a processor with AVX (most from 2011 on) and glibc 2.39 or newer (Ubuntu 24.04, Debian 13,
|
||||
Fedora 40 and later).
|
||||
- On Windows, TokenSynth runs on the CPU, so each note takes a minute or more to make.
|
||||
- A CSS transition that a style change starts depends on the frames before it, so a still of that frame shows it
|
||||
finished. Animate with `@keyframes` or `interpolate` for a still that matches the video.
|
||||
- A seek while a film plays in the timeline can show one frame from before the seek (about 33 ms) before it jumps.
|
||||
- Characters (the Character SDK) come in a later release.
|
||||
- R3F's pointer input has no double click yet, and touches don't arrive as pointers.
|
||||
- postprocessing's Outline, TextureEffect, DepthEffect and LUT1D, and TSL's OutlineNode, are skipped, with one
|
||||
warning that names them.
|
||||
- On a long held shot of an interior, Solari's light can still crawl in a few patches, most along the frame's edge.
|
||||
`raea light steady` shows where; `<SolariLighting overscan={0.05}>` lights the edge as it lights the middle (Mac
|
||||
only, about 1.2 times the tracing).
|
||||
- The Windows app and engine are unsigned, as before: Windows asks once whether to run them, and with Smart App
|
||||
Control on, the engine can't bundle a composition (#221).
|
||||
@@ -0,0 +1,81 @@
|
||||
---
|
||||
title: "raea 0.1.11"
|
||||
version: "0.1.11"
|
||||
date: "2026-11-26"
|
||||
summary: "A goal is a make job, judged by its own commands and a fresh critic. Live sound follows your output device, a picture taller than the GPU's largest texture draws, and Windows on ARM gets raea's installer and its own build. In the app, typing to Ideate answers with your own agent, there is one Settings page, and voice comes with Studio."
|
||||
sources: ["https://github.com/shinyobjectz/raea/releases/tag/v0.1.11"]
|
||||
---
|
||||
|
||||
raea 0.1.11 makes a goal something `raea make` holds an agent to: the goal's own commands and a critic that only
|
||||
reads decide when it's done, never the agent's word. Live sound now follows the output you're listening on, a very
|
||||
tall picture draws instead of being refused, and Windows on ARM PCs get raea's installer and a build of their own. In
|
||||
the app, typing to Ideate answers with the agent you connected, Settings are one page, and talking with Ideate comes
|
||||
with Studio.
|
||||
|
||||
**Get the app at [raea.io](https://raea.io)** (a Mac with Apple silicon, Windows 10 or 11, or Linux on x86_64).
|
||||
|
||||
The engine alone:
|
||||
|
||||
```sh
|
||||
curl -fsSL https://raea.io/install | sh
|
||||
```
|
||||
|
||||
On Windows, in PowerShell: `irm https://raea.io/install.ps1 | iex`.
|
||||
|
||||
## What changed since 0.1.10
|
||||
|
||||
**A goal is a make job.** Besides scenes, kits, shots and cuts, `make: goal({...})` in `brief.ts` is a fifth kind of
|
||||
job (MK28-MK29). Its rules are commands that must pass and things it must say, and `raea make judge` has a fresh
|
||||
critic, which only reads, judge each `says` rule into `review/goal.judge.json`. `raea make status` is the one judge
|
||||
of whether the goal is met.
|
||||
|
||||
**Cuts from a brief rotate their call to action.** A `cut` brief's `cta.also` lists the other lines a brief rotates,
|
||||
and each cut ends on one of them within its last 8 seconds (MK25).
|
||||
|
||||
**Live sound follows your output.** When the system's output changes (headphones, AirPods, a display) or the stream
|
||||
breaks, live sound reopens on the device in use instead of going quiet.
|
||||
|
||||
**A tall picture draws (#245).** A picture larger than the GPU's image atlas (a 1080 x 18000 site capture drawn 880
|
||||
wide) was refused with a message about a filtered layer. It is now decoded at a size that fits the atlas, which is
|
||||
16384 px a side even on a GPU that allows larger textures.
|
||||
|
||||
**Windows on ARM (#82).**
|
||||
- `irm https://raea.io/install.ps1 | iex` installs on an ARM64 PC: raea's ARM64 build when the release has one, else
|
||||
the x86_64 build, which Windows 11 on ARM runs emulated. Before, the installer refused ARM64 PCs.
|
||||
- raea is built natively for Windows on ARM (`raea-0.1.11-windows-arm64.zip`) when its build passes, beside the
|
||||
release's other archives.
|
||||
- On a Snapdragon PC, raea picks DirectX 12 for its Adreno GPU, where Vulkan drew 2D pages striped and with grey boxes
|
||||
behind fading text.
|
||||
|
||||
**In the app.**
|
||||
- Typing to Ideate answers with your own agent (Claude, Codex, or whichever you connected), named on screen while it
|
||||
thinks, and the conversation stays open instead of fading after a few seconds. raea's own voice model is only for
|
||||
speaking.
|
||||
- Talking with Ideate comes with Studio (300 minutes a month) and Enterprise (no limit). Free and Pro type.
|
||||
- Settings are one page: your workspace's sections, then this computer's (account, plan, sharing, general, storage
|
||||
and debugging), searched together.
|
||||
- Signing out on the Mac's workspace signs raea's account out, and the menu names the account you're in.
|
||||
- A review's player starts with sound, and remembers if you turn it off.
|
||||
- Every project has a canvas: deliverables, previews and the brief's frames, marked with a region or a point and a
|
||||
`#tag`, sent back as a note or as edits.
|
||||
- On Windows, Codex's shell commands run (#244). Codex's elevated sandbox waited on a Windows prompt or failed every
|
||||
call with "The tool call failed"; raea now starts it with Windows' unelevated sandbox, unless you set your own.
|
||||
|
||||
**raea cloud.**
|
||||
- Boxes move onto each new release, and each box build is stamped with the commit and files it came from.
|
||||
- An agent's errors go into its run's trace, a runaway render is stopped before it takes the box down, and an agent
|
||||
waiting on a long render keeps its connection.
|
||||
- A render sends a project's footage once, known by the file rather than its path.
|
||||
- `raea words` on a box transcribes with Whisper large-v3, and `raea frames check` measures what a cut's pictures get
|
||||
wrong (faces cut off, split frames that make no sense).
|
||||
- Google's AI signs in on the box, in a browser you work from the dashboard.
|
||||
|
||||
**Known**
|
||||
- The Windows on ARM build is checked in CI without drawing: GitHub's ARM64 runner has no GPU raea can draw on. A
|
||||
Snapdragon PC is where its pictures are checked. If something looks wrong, the x86_64 build still runs there, and
|
||||
`WGPU_BACKEND=vulkan` or `dx12` chooses the graphics API by hand.
|
||||
- The Windows app is unsigned, as before: Windows asks once whether to run it (#221).
|
||||
- On Linux, raea needs a processor with AVX (most from 2011 on) and glibc 2.39 or newer (Ubuntu 24.04, Debian 13,
|
||||
Fedora 40 and later).
|
||||
- A proxy set by an automatic configuration (PAC) file isn't read. If yours uses one, start raea with `HTTPS_PROXY`
|
||||
set.
|
||||
@@ -0,0 +1,283 @@
|
||||
# Solari, forked: where MALL RAT's frame time goes (11-25)
|
||||
|
||||
Measured on MALL RAT's own takes (Raea/anchor-tenant, `tools/solari-sweep.sh`, scored by `out/lab/pf/score.sh`): each
|
||||
lever moved alone from the take's settings, 240 frames, wall time a frame, scored SSIM/PSNR against the take as it
|
||||
renders (pf0) on the finished VHS look at 1440 x 1080. pfR is pf0 drawn again: its numbers are the noise floor (and wall
|
||||
time itself moves about 10% run to run). The sweep stopped partway: t8 has four levers.
|
||||
|
||||
| lever | t2 ms (pf0 204) | t2 ssim / psnr | t4 ms (pf0 82) | t4 ssim / psnr |
|
||||
|---|---|---|---|---|
|
||||
| pfR, the floor | 185 | 0.991 / 37.2 | 80 | 0.989 / 42.6 |
|
||||
| pfB, 1 bounce | 186 | 0.990 / 36.2 | **64** | 0.988 / 41.0 |
|
||||
| pfS, half the samples (8/4) | 194 | 0.988 / 32.6 | 75 | 0.987 / 40.5 |
|
||||
| pfF, firstBounce 0.5 | 161 | 0.989 / 35.8 | 61 | 0.984 / 38.8 |
|
||||
| pfC, Solari at 0.67 scale | 149 | 0.986 / 35.8 | 52 | 0.964 / 34.3 |
|
||||
| pfH, Solari at 0.5 | 154 | 0.984 / 35.1 | 33 | 0.959 / 35.0 |
|
||||
| pfT, Solari at 0.35 | 153 | 0.980 / 33.8 | 25 | 0.950 / 33.1 |
|
||||
| pfD, whole frame 720 x 540 | 180 | 0.983 / 33.4 | 25 | 0.967 / 34.2 |
|
||||
| pfE, whole frame 960 x 720 | 165 | **0.987 / 36.6** | **37** | **0.978 / 38.6** |
|
||||
|
||||
Solari's own GPU time (RAEA_SOLARI_TIMES) on t2: 18.5 ms at 0.5 scale (initial path 14.6, spatial and shade 2.7, world
|
||||
cache 1.1, light tiles 0.1), 31.7 ms at 960 x 720; by pixel count about 70 ms at full size.
|
||||
|
||||
## What it says
|
||||
|
||||
1. **t2 is not Solari's.** At 0.35 scale Solari takes 11 ms and the frame still takes 153. About 140 ms a frame in the
|
||||
mall court goes to the rest: the composition's scene each frame (hundreds of LOD pieces, 88 baked water frames, the
|
||||
arcade), raster, the look's FramePass chain and the encode. That is the biggest saving left, and it needs a CPU
|
||||
and GPU profile of one t2 frame (xctrace), not a Solari change.
|
||||
2. **Render the tape at 960 x 720.** The VHS look keeps about 320 x 240 a field, so the whole frame at 960 x 720 (pfE)
|
||||
is the best lever measured: t4 55% faster at SSIM 0.978, t2 about 15% faster, nearly at the floor. It beats scaling
|
||||
Solari alone (pfC) on both time and picture, because raster and the look shrink with it.
|
||||
3. **One bounce is free in picture.** pfB sits at the floor on all three takes and saves 20% on t4: the world cache
|
||||
already carries the light past the first bounce.
|
||||
4. **Fewer samples are not.** Halving spp saves little time (the cost is per pixel, not per sample, at these counts)
|
||||
and costs PSNR (t2 37.2 to 32.6). The other way round, the noise notes on v3 (21, 22) are answered with more samples
|
||||
on t5 and t8 only.
|
||||
5. t8's pfS and pfF score PSNR 19.8. Frame by frame it isn't a timing slip: pfS starts at 10 dB and climbs steadily to
|
||||
39 over the 240 frames (pfR holds 35-42 throughout). With fewer samples t8's light starts far off and takes about
|
||||
4 s to settle, most likely through its short world-cache life (`cache: { frames: 6 }`, set so the power cut drops
|
||||
the light at once). In a take with a short cache, cutting samples costs seconds of wrong light, not noise.
|
||||
|
||||
## The quality fix: light selection by power, not by count
|
||||
|
||||
`generate_random_light_sample` (scene/sampling.wesl) picks a light source uniformly: `light_id = rand_range_u(light_count)`,
|
||||
and every pdf divides by `light_count` (sampling.wesl 131-175, realtime/restir.wesl 330, realtime/initial_path.wesl 370).
|
||||
Each emissive mesh, each directional light and each sky portal is one source. So:
|
||||
- a dim exit sign gets as many samples as the sun, and a scene with 300 emissive pieces gives the sun 1/300 of them:
|
||||
noise where the sun matters (v3 notes 7, 21, 22);
|
||||
- a LOD swap or a set mounted mid-shot changes the count, so the sun's share jumps and the denoiser shows a one-frame
|
||||
2-5x brightness step (t2 v3: frames 1042, 2263, 3960, 4315, each a LOD swap). The composition now holds LOD levels a
|
||||
take and mounts sets for the whole take, which works round it, not through it.
|
||||
|
||||
Two ways to fix it in the fork, smallest first:
|
||||
- **A fixed share for the sky.** Directional lights and portals get a fixed probability q (0.5) split among them,
|
||||
emissive meshes share 1 - q. The count of emissive pieces then never moves the sun's share. Needs the two counts in
|
||||
a uniform and the sources kept in two runs (LightIndex's swap_remove keeps no order today), and the five pdf sites
|
||||
changed to read the share by kind.
|
||||
- **Power-weighted (an alias table).** Each source weighted by its power (emissive luminance x area; a directional
|
||||
light's illuminance; a portal's sky radiance x area), sampled in O(1) through an alias table rebuilt when the light
|
||||
set changes. GpuLightSource grows from {kind, id} to {kind, id, pmf, threshold, alias}. The emissive-hit pdf (MIS in
|
||||
the path tracer and initial_path) needs the hit's source pmf, so the instance needs its light index. ReSTIR DI's
|
||||
light tiles inherit it for free, since they draw from generate_random_light_sample.
|
||||
|
||||
Either needs a release build and a check on t2's four swap frames and t8; neither was built while MALL RAT v4 held the
|
||||
GPU.
|
||||
|
||||
## The splotches: the world cache's history, and a bake (11-25)
|
||||
|
||||
Shane on v4: "noisy splotchy thing in the lights and reflections ... it's definitely the world cache, can we bake it?"
|
||||
Each cell takes one bounce ray an update and blends it over a history capped at 32, but the adaptive cut
|
||||
(`alpha = |lum delta| / lum`, world_cache_update.wesl blend_new_samples) reads a cell's own noise as the light changing
|
||||
and holds the history near 10. Ten one-ray samples is the blotch: cell-sized patches that crawl.
|
||||
|
||||
Built in the fork (vendor/bevy_solari, uncommitted, lane solari-bake to come):
|
||||
- `world_cache_steady`: the blend keeps the whole history up to `cache.frames`, with no adaptive cut, and each update's
|
||||
ray seeded by the cell's sample count, so one cell's rays don't repeat. `cache.steady` in the SDK.
|
||||
- `world_cache_update_iterations`: N cache updates a frame. `cache.iterations` in the SDK.
|
||||
- `world_cache_keep`: no decay, so cells never die. `world_cache_save` / `world_cache_load`: the cache buffer
|
||||
written to a file (bake.rs: a copy to a MAP_READ buffer, mapped and written before the next frame's pipelines) or
|
||||
read into it and held (the whole world-cache stage skipped). `cache.bake: { iterations, save }` and
|
||||
`cache.load` in the SDK.
|
||||
|
||||
The bake doesn't fit. A cell's key holds its LOD band (stochastic between bands), its quantised position after a
|
||||
±half-cell jitter and a plane slice along the normal, so one surface seen from a moving camera makes many keys. With
|
||||
nothing decaying, t2's whole take filled all 2^20 slots, and so did each 6 s window of it (13 windows, each 100%).
|
||||
A cache that is full loses cells, and a loaded cache missing cells has holes. A bake would need larger cells, no
|
||||
jitter, or a cache sized to the take. So the live steady history is tried first: it gives the same convergence on
|
||||
the cells the camera sees (they are read each frame, so never die) with no file and no capacity limit. It costs a lag
|
||||
on light that moves, as long as the history: t8's power cut needs a short `frames`, as it has today.
|
||||
|
||||
## The cache's level does not drift: a pass's uniforms stood still (11-25)
|
||||
|
||||
An earlier reading here was wrong. The same t2 frame (1188) read 0.0189 cold at 1440 x 1080 and 0.0177 at 160 x 240,
|
||||
but 7x that inside the long view render and 0.2x inside the long meter render, and it looked as if the world cache's
|
||||
level depended on time and on how many pixels fed it. It doesn't. With the tape's exposure held constant, a 520-frame
|
||||
moving run and a held frame agree (ratio 1.04), at any size.
|
||||
|
||||
What moved was the passes over the frame. A video's 3D is made live, and when a part is dropped mid-render the live
|
||||
rows move up; a <FramePass>'s and a <Compute>'s `follow` found their row by the order the scene opened with, so from
|
||||
the first drop on they read another row and kept the uniforms they opened with. The view's exposure stayed at its
|
||||
first value (64 against 7.6 at t2's frame 720), the meter's passes kept their first camera, and the auto-exposure
|
||||
built on that meter set the final 14 to 40x too bright: Shane's overexposed daylight. Fixed in the engine
|
||||
(engine/render spawn.rs `name_rows`; docs/shaders.feature SH6). After it, t2's meter reads 3 to 4.6x higher than
|
||||
before, a held meter frame and the moving one agree (0.89), and the take's white share fell from a median of 19.9%
|
||||
to 3.7%.
|
||||
|
||||
How it was found, for the next time a sequence and a still disagree: hold the frame (`raea render --hold N:40`) and
|
||||
compare it with frame N of the sequence; then make one input constant at a time (here the exposure uniform) until
|
||||
they agree. The frame-purity check (`raea render`, every 300th frame drawn again alone) catches this class, and
|
||||
MALL RAT renders with it off (RAEA_FRAME_PURE=0), because Solari's history makes a still differ from a sequence anyway.
|
||||
|
||||
## What fixes the patches, measured (11-25)
|
||||
|
||||
The patches are **boiling**, the industry's word for denoised traced light's soft patches crawling over still surfaces
|
||||
(NRD, RTXDI, GI-1.0, the ReSTIR papers, Lumen). raea now uses it (docs/skills.glossary.md, the Solari guide's "Boiling");
|
||||
`raea light steady`'s blotch is its size in one held frame.
|
||||
|
||||
What others do about it that raea hasn't tried yet:
|
||||
- a longer denoiser history: NRD says history "can be bumped up to 60 frames relatively safely" to suppress residual
|
||||
boiling, and Lumen's guides raise `MaxFramesAccumulated` (10 -> 16) before adding rays. MetalFX's history is the
|
||||
next lever here;
|
||||
- blue-noise sampling (NRD: "reduced residual boiling in areas with acceptable sampling quality"), against Solari's white
|
||||
hash noise;
|
||||
- a larger ReSTIR temporal cap with decorrelating mutations (Sawhney et al. 2024: boiling from hard indirect light is
|
||||
resolved by a greater M cap, and mutations remove the blotches a larger cap brings), or RTXDI's boiling filter
|
||||
(which loses energy);
|
||||
- for an offline render, a noise pattern held still across frames (Octane's "static noise"): a held shot can't boil,
|
||||
though its grain stops moving.
|
||||
|
||||
Measured with `raea light steady` (frame held, its light's movement over time; limit 1.5% blotch, worst tile 4.5%) on
|
||||
MALL RAT t2 frame 1188 (150 held, 75 measured), and the bench kitchen (STEADY 0.63 today). t2's runs of one setup spread
|
||||
by 0.1-0.4, so each setup that matters was run twice.
|
||||
|
||||
| setup on t2 | blotch | verdict |
|
||||
|---|---|---|
|
||||
| today (1 path, ReSTIR, live cache) | 2.84-3.09 | fails |
|
||||
| the controls: raster, and the look's passes off | 0.0, 3.04 | the patches are Solari's |
|
||||
| world cache baked and frozen | 2.55 | the cache is not the main cause |
|
||||
| denoiser off / its guides off | grain 17.6, 2.9 | MetalFX passes the patches, doesn't make them |
|
||||
| ReSTIR off; its confidence cap 32; spatial radius 8 | 2.13; 3.03; 2.98 | ReSTIR adds, its settings don't fix |
|
||||
| 2x/4x direct-light samples; 64 small emissives removed; light selection by a sky share | no change | not the direct light |
|
||||
| denoiser and ReSTIR off, cache frozen: the raw light | 98% per-pixel grain, white in space and time | one path's bounce has a sd as large as its mean |
|
||||
| **paths 4 / 8** (new: N initial paths a pixel, RIS-merged) | **1.89 / 2.10** | halves it |
|
||||
| paths 8 + frozen cache | 1.45, 1.53 | on the line |
|
||||
| paths 8 + steady cache (1024 history, 8 updates) | 1.65, 1.69 | |
|
||||
| paths 4-8 + steady + still-camera query (no jitter, one LOD) | 1.66-1.88 | no better |
|
||||
| paths 8, ReSTIR off, steady / frozen | 1.60, 1.69 / 1.54 | |
|
||||
| paths 8 + frozen, camera jitter off | 1.31 (the one pass) | jitter isn't the floor |
|
||||
|
||||
Bias: the kitchen's mean at 4 paths against 1 is +0.0015 stops (per-pixel median 0); with the steady cache and still
|
||||
query +0.0013. Glade's moving shot (the still query off while it moves): flicker 0.708 against 0.702. Cost on t2: a
|
||||
150-frame hold 50 s at 1 path, 82-94 s at 4, 112 s at 8; glade 1.72 -> 2.47 s a still at 4.
|
||||
|
||||
So: `paths` is the lever that ships (default 1; MALL RAT's takes set it). It takes t2 from about 3.0 to 1.6-1.9, which
|
||||
still fails the gate. The rest is the world cache: a frozen one reads 0.1-0.3 lower than any live one at the same paths,
|
||||
and the live cache made to converge (steady history, more updates, the still-camera query) doesn't close the gap. Left
|
||||
for the next release: a cache that converges like the frozen one (cells kept for a held shot without the 2^20 overflow:
|
||||
a bigger or per-take cache, or ReSTIR GI's reservoirs carrying the cache's light), then t2 again.
|
||||
|
||||
Built in the fork, all off unless asked: `paths` (SolariLighting::paths_per_pixel, RAEA_SOLARI_PATHS), `cache.steady`
|
||||
and `cache.iterations`, the still-camera query (with `cache.steady`, RAEA_SOLARI_STEADY=1), `cache.bake`/`cache.load`
|
||||
(experimental: a whole take overflows 2^20 cells), light selection by a fixed sky share (RAEA_SOLARI_SKY_SHARE, 0 =
|
||||
upstream), ReSTIR's spatial radius (RAEA_SOLARI_SPATIAL_RADIUS, 30).
|
||||
|
||||
## Telling the movement apart, and what each kind was (11-25, afternoon)
|
||||
|
||||
`raea light steady` now tells the kinds of movement in a held frame apart (engine/light/src/kinds.rs). It
|
||||
reads each 32 px square over the last 75 held frames and splits its light four ways:
|
||||
- **settling**: the square's straight-line trend over the window. The light is still building, which a real render's
|
||||
lead-in covers. It's reported as "unsettled" over p95 5%, not failed;
|
||||
- **boiling**: what's left once the trend is removed, where it's slow (lag-1 correlation 0.5 or more);
|
||||
- **jitter**: what repeats on a 2-16 frame cycle, the camera's sub-pixel jitter showing through;
|
||||
- **flicker**: what is fast with no cycle, such as a firefly, a sparkle in a reflection, or two faces at one depth.
|
||||
|
||||
Each kind has its own limit: boiling rms 1.5% with its worst square under three times that, jitter and flicker worst
|
||||
5%, and drift 0.05 stops. steady-kinds.png maps them: red is jitter or flicker, green is boiling, blue is settling.
|
||||
Before, a single number mixed them, and the fixes differ.
|
||||
|
||||
What each turned out to be on MALL RAT:
|
||||
|
||||
| hold | before | change | after |
|
||||
|---|---|---|---|
|
||||
| t1 1699 (silhouettes against the sky) | jitter worst 73%, all 3.73 | the denoiser after the sky and forward meshes (`late`) | jitter worst 3.8%, all 0.76: STEADY |
|
||||
| t2 1188 (the court, 4 paths) | jitter worst 10% on the shop signs | `late` + emissive "taa" | jitter 0.09%, worst 2.8% |
|
||||
| t2 1188 | boiling 1.27%, worst 5-7% at the frame's right edge | ReSTIR's spatial neighbours reflected back into the frame, not clamped to its border (restir.wesl) | boiling 1.21%, worst 4.25%: STEADY (t1 425: 0.58) |
|
||||
| kitchen | 0.63 all, grain 1.38 | `late` | 0.40 all, grain 0.55 |
|
||||
|
||||
- **The edges stepping with the jitter: the sky and forward meshes were drawn after the denoiser.** MetalFX ran
|
||||
before Bevy's main opaque pass (metalfx.rs `denoise`). That pass then drew the Environment's background and every
|
||||
forward mesh with the jittered camera, and nothing resolved them. Each silhouette against the sky stepped a pixel
|
||||
a frame on the 8-frame Halton cycle. `SolariSettings.late` (TSX `late`, RAEA_SOLARI_DENOISE_LATE) runs it after
|
||||
the main pass instead. The guides pass already marks a pixel with no G-buffer (sky, forward meshes) undenoised
|
||||
(mask 1) but still gathered.
|
||||
- **The shop signs' edges: MALL RAT's `emissive="split"`** puts each emitter's light back after the denoiser frame by
|
||||
frame, so emissive edges keep the jitter. The default "taa" mode gathers them over frames.
|
||||
- **A soft knee around MetalFX** (`knee`, RAEA_METALFX_KNEE; logarithmic above the white at preexposure/16) was
|
||||
tried first, on the theory that the resolve averaged bright edges in linear light. It changed nothing at t1 1699
|
||||
(73% either way), because the sky wasn't going through the resolve at all. It keeps the kitchen's mean within
|
||||
0.004 stops. It's kept for now, default 1.
|
||||
- **Not the cache's update rate or cell life.** Every cell updated every frame (`cache.updates` 2,000,000) read 1.98
|
||||
and 1.88 against 1.89. Cells kept for 600 frames unqueried (`cache.life`, RAEA_SOLARI_CELL_LIFE) read 1.34 against
|
||||
1.27. A 600-frame hold settles by about frame 300-450, but over a longer window the boiling reads higher, so the
|
||||
detector now fixes its window at 75 frames.
|
||||
- **Offline, a 64-frame average of a frozen cache's frames reads 0.50**, the kitchen's level. Of a live cache's, it
|
||||
reads no better than as rendered. So what boils is slow: the light wanders over tens of frames, longer than
|
||||
MetalFX's history.
|
||||
|
||||
## Fireflies that linger, the frame's border, and dark squares (11-25, evening)
|
||||
|
||||
A baseline of every MALL RAT take at three frames (27 holds) had the frame-wide boiling under 1.5% on all but one,
|
||||
and still failed most of them on a single worst square of 5 to 25%. Three different things were in that number.
|
||||
|
||||
- **A firefly that lingers.** A hot square's level is flat for 40 frames, jumps 30% in one frame, and takes about 30
|
||||
frames to fall back. One very bright sample (a bounce landing beside a small lamp) gets a large weight, temporal
|
||||
reuse keeps it, and spatial reuse spreads it to its neighbours. Whether a hold passed depended on whether one
|
||||
landed in its 75 frames: t7 187 read 0.88% (worst 10.1%) and, minutes later with nothing changed, 0.39% (worst
|
||||
2.0%). The party room (t5 1440), lit by small bulbs, has them all the time. This is the case RTXDI's boiling filter
|
||||
is for, and ReSTIR PT Enhanced (2026) describes the cause. raea's version is `SolariLighting.firefly_cap` (TSX
|
||||
`firefly`, RAEA_SOLARI_FIREFLY): after temporal reuse, a reservoir whose contribution is over N times the mean of
|
||||
its 8x8 block has its weight cut to that (restir.wesl, a `var<workgroup>` array and a barrier). On t5 1440:
|
||||
|
||||
| firefly | boiling | worst square | frame's mean |
|
||||
|---|---|---|---|
|
||||
| off | 1.63% | 7.4% | 0 stops |
|
||||
| 32 | 1.42% | 4.9% | -0.003 |
|
||||
| 12 | 1.06% | 6.3% | -0.15 |
|
||||
| 6 | 0.73% | 3.0% | -0.29: STEADY |
|
||||
| 3 | 0.69% | 3.9% | -0.38 |
|
||||
|
||||
It costs the light those samples carried, so it is off by default and a composition asks for it. Cutting the
|
||||
sample's confidence, not its weight (ReSTIR PT Enhanced's adaptive cap), lost nearly as much light (-0.22 at 6) and
|
||||
held less still (0.89%).
|
||||
- **The frame's border boils more, in a band as wide as the spatial reuse radius.** By distance from the border, in
|
||||
8 px steps: 0.94, 0.79, 0.67, 0.62, 0.57, then 0.5 from 48 px in (t7 187). A border pixel has half a disc of
|
||||
neighbours to reuse from. Reflecting the neighbours into the frame helped the first few pixels (above); permuting
|
||||
the 3 px border strip that `permute_pixel` leaves unpermuted changed nothing (kept, it is harmless). What production
|
||||
renderers do is overscan: render a margin and crop it. raea has no overscan yet.
|
||||
- **Dark squares read high as a plain ratio.** The detector divided each square's deviation by its level, so the
|
||||
darkest corners led (12% of nearly nothing). The eye's contrast threshold is constant in bright light (Weber) and
|
||||
rises as the square root of falling luminance in dim light (de Vries-Rose; Barten's model has both). kinds.rs now
|
||||
divides by sqrt(level x 0.05) below a level of 0.05 (linear; about 5 cd/m2 on a 100 cd/m2 display). t5 1440 read
|
||||
2.03% before and 1.59% after on the same frames.
|
||||
|
||||
What was looked up and already there: the world cache's lookups are jittered in the tangent plane (GI-1.0 and
|
||||
world-space ReSTIR name hash-cell blotches and this cure), and its blend is the adaptive one (Boissé's, in Bevy 0.18).
|
||||
|
||||
For moving shots, ReVQ (No-Reference Rendered Video Quality Assessment, arXiv 2510.13349) is the design to follow:
|
||||
windows of 5 frames warped onto their last with motion vectors, pixels without a correspondence masked, differences
|
||||
over spans of 1 to 4 frames. A first try that chained 32 frames of motion vectors read 10% on a clean shot from the
|
||||
warp's own error.
|
||||
|
||||
With the firefly filter at 6 on every take, 19 of 24 holds read STEADY (8 of 22 before). What was left, by cause:
|
||||
|
||||
- **Emitters thinner than a pixel flickered: the emitter history's clamp.** MALL RAT's ceiling tubes seen edge-on are
|
||||
1 to 3 px tall and changed shape every frame (t6 211 and t8 204: jitter 7.7% and 7.0% in their squares). With the
|
||||
history always taken (RAEA_EMIT_TAA_DEBUG=3) the jitter read 0.01%. emit_taa.wgsl held a still pixel's history
|
||||
inside the range of this frame's samples about it, so a lamp switched off goes dark at once; a tube that some of the
|
||||
jitter's positions miss altogether was cut to black on those frames. Eased (a quarter of the way to those bounds a
|
||||
frame) both holds read STEADY (jitter 2.2% and 1.2%), but lightbench's orb switched off then left +2.52 stops on its
|
||||
tile where it left +0.17 (RT32). Eased only where the history is thin (dark two pixels to both sides, across or
|
||||
down) the tubes read 3.6% and 2.1% and the orb +0.30, its rim. Two stricter tests of "thin" kept the rim out and
|
||||
lost the tubes (5.2 to 6.5%). So the engine's default is as it was (STILL_HOLD 1) and MALL RAT asks for it
|
||||
(`constants={{ emissiveClamp: { stillHold: 0.25 } }}`); the fix for every scene is a count, kept with the history,
|
||||
of the frames a pixel was missed. A softer gather kernel made it worse (11 to 13% at emissiveSharpness 3 and 1.5).
|
||||
- **The border** (above): t3 1320's wall at the frame's right edge is lit in 8 px blocks that change each frame, and
|
||||
the corner squares of t5 900 and the court boil past the worst-square limit on some runs. Overscan
|
||||
(docs/raytracing.feature RT40) is built, off by default: `<SolariLighting overscan={k}>` (RAEA_SOLARI_OVERSCAN) widens
|
||||
the camera's sub view by k a side (raea-sys-viewbox), the main pass draws that at 1 / (1 + 2k) of the view's size at
|
||||
most, MetalFX's denoiser brings it up to a texture (1 + 2k) the view's size, the emission goes back in there, and the
|
||||
middle is copied over the colour; FramePass's depth() and normal() read the middle of the wider prepass (and now read
|
||||
the right texels under a render scale below 1, which they didn't). Measured 11-25: lightbench's window draws the
|
||||
same picture with and without it (no shift, no zoom, mean difference 0.006). t3 1320 held: jitter's worst square
|
||||
16.06% without, 5.61% at 0.05 and 6.07% at 0.08 (limit 5), boiling's worst 2.32%, 3.51% and 6.1%. So it takes most
|
||||
of the border's share away and no margin clears this hold: what's left in the last two columns isn't the border.
|
||||
- A hold near the limit passes on one run and fails on the next (t2 922 and t2 2304 failed in the baseline and read
|
||||
STEADY minutes later): what's left there is chance, a firefly landing in the 75 frames or not.
|
||||
|
||||
The moving detector (scratch moving3.py, ReVQ's design on raea's own motion vectors and depth) reads 0.5% a frame on
|
||||
the court's door swing where the 32-frame chain read 10%, and tells one path a pixel from four (worst square 9.3%
|
||||
against 5.8% over 4 frames). It did not tell `late` and emissive "taa" from the settings before them on that shot,
|
||||
which has no sky edge or sign in it and whose light changes as the doors open. It needs a moving shot under steady
|
||||
light to be judged on before it gates anything.
|
||||
|
||||
@@ -13,3 +13,7 @@ serde_json = "1"
|
||||
raea-runtime-bundle = { path = "../../runtime/bundle" }
|
||||
# the home folder on every OS (HOME, then USERPROFILE)
|
||||
raea-io-home = { path = "../../io/home" }
|
||||
# a held frame's findings kept in its project's record, where raea check and raea findings read them
|
||||
raea-core-facts = { path = "../../core/facts" }
|
||||
# the record's UTC stamp, as raea render's
|
||||
raea-io-trace = { path = "../../io/trace" }
|
||||
@@ -0,0 +1,176 @@
|
||||
//! What moves in a held frame, told apart (steady.rs measures how much). One number hid four things that have
|
||||
//! different causes and different fixes (MALL RAT, 11-25: take 1 failed on edges, take 2 on patches):
|
||||
//!
|
||||
//! - **settling**: a square whose level climbs or falls steadily through the window. The light is still building (a
|
||||
//! world cache lit a ray a cell a frame takes hundreds of frames in a closed court): hold longer before measuring,
|
||||
//! and give a render the same lead-in.
|
||||
//! - **boiling**: a square that wanders slowly about its level (each frame close to the last: lag-1 correlation over
|
||||
//! SLOW). Traced light's patches: too few rays behind a denoiser. More paths, a cache that converges.
|
||||
//! - **jitter**: a square that repeats on a short cycle (the camera's sub-pixel jitter is 8 frames long). An edge the
|
||||
//! temporal resolve isn't holding: a silhouette against the sky or a clipped-bright doorway steps a pixel a frame.
|
||||
//! Doors, walls and beams look as if they shake.
|
||||
//! - **flicker**: fast and without a cycle. A firefly, a sparkle in a reflection, two faces fighting for one depth.
|
||||
//!
|
||||
//! Each is each LARGE square's deviation in time over its mean, with its straight-line trend taken out first, counted
|
||||
//! to the kind the square's own series shows, and reported as the rms over every lit square (the others counting as
|
||||
//! zero, so the four add in squares to the whole), with the worst square and where it is.
|
||||
|
||||
use crate::metric::Luma;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
/// A square whose deviation is under this (a fraction of its level) isn't moving: no kind.
|
||||
const QUIET: f64 = 0.0015;
|
||||
/// Lag-1 correlation from which a square's movement is slow.
|
||||
const SLOW: f64 = 0.5;
|
||||
/// The correlation with itself a cycle later from which a square repeats.
|
||||
const REPEATS: f64 = 0.6;
|
||||
/// The longest cycle looked for, frames (the jitter's is 8; a 16-frame sequence is the longest raea uses).
|
||||
const CYCLE: usize = 16;
|
||||
|
||||
/// Below this level (linear, a twentieth of white: about 5 cd/m2 on a 100 cd/m2 display) a change shows less than its
|
||||
/// ratio to the level says. The eye's contrast threshold is constant in bright light (Weber) and rises as the square
|
||||
/// root of falling luminance in dim light (de Vries-Rose; Barten's contrast sensitivity model has both). Measured as a
|
||||
/// plain ratio, MALL RAT's worst squares were its darkest corners (t5 1440, t8 510: 12% and 6% of nearly nothing).
|
||||
const DIM: f64 = 0.05;
|
||||
|
||||
/// The level a square's deviation is a fraction of: its mean in bright light, and sqrt(mean x DIM) below DIM, so a
|
||||
/// dark square's movement counts by how much of it shows.
|
||||
pub fn shown_level(mean: f64, lit: f64) -> f64 {
|
||||
let m = mean.max(lit);
|
||||
if m >= DIM { m } else { (m * DIM).sqrt() }
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Debug)]
|
||||
pub enum Kind {
|
||||
Still,
|
||||
Boiling,
|
||||
Jitter,
|
||||
Flicker,
|
||||
}
|
||||
|
||||
/// One square's series read: its kind, its deviation over its level (trend out), its trend across the window over its
|
||||
/// level, and the cycle it repeats on (0: none).
|
||||
pub fn read(series: &[f64], lit: f64) -> (Kind, f64, f64, usize) {
|
||||
let n = series.len();
|
||||
let mean = series.iter().sum::<f64>() / n as f64;
|
||||
let mid = (n as f64 - 1.0) / 2.0;
|
||||
let slope = series.iter().enumerate().map(|(t, v)| (t as f64 - mid) * v).sum::<f64>() / (0..n).map(|t| (t as f64 - mid).powi(2)).sum::<f64>().max(1e-12);
|
||||
let r: Vec<f64> = series.iter().enumerate().map(|(t, v)| v - mean - slope * (t as f64 - mid)).collect();
|
||||
let var = r.iter().map(|v| v * v).sum::<f64>() / n as f64;
|
||||
let level = shown_level(mean, lit);
|
||||
let (dev, trend) = (var.sqrt() / level, slope.abs() * (n as f64 - 1.0) / level);
|
||||
if dev < QUIET {
|
||||
return (Kind::Still, dev, trend, 0);
|
||||
}
|
||||
// the series against itself p frames later, as a correlation
|
||||
let corr = |p: usize| r[p..].iter().zip(&r).map(|(a, b)| a * b).sum::<f64>() / (n - p) as f64 / var.max(1e-18);
|
||||
let slow = corr(1) >= SLOW;
|
||||
let (mut cycle, mut best) = (0, 0.0);
|
||||
for p in 2..=CYCLE.min(n / 3) {
|
||||
let c = corr(p);
|
||||
if c > best {
|
||||
(cycle, best) = (p, c);
|
||||
}
|
||||
}
|
||||
if !slow && best >= REPEATS {
|
||||
(Kind::Jitter, dev, trend, cycle)
|
||||
} else if slow {
|
||||
(Kind::Boiling, dev, trend, 0)
|
||||
} else {
|
||||
(Kind::Flicker, dev, trend, 0)
|
||||
}
|
||||
}
|
||||
|
||||
/// The kinds of a window of held frames: the report's fields, and a picture at the frame's size (red: jitter and
|
||||
/// flicker, green: boiling, blue: settling; each white at `shown` percent).
|
||||
pub fn kinds(frames: &[Luma], k: usize, lit: f64, shown: f64) -> (Value, image::RgbImage) {
|
||||
let blocks: Vec<Luma> = frames.iter().map(|f| f.blocks(k)).collect();
|
||||
let (w, h) = (blocks[0].w, blocks[0].h);
|
||||
let pct = |v: f64| (v * 1e4).round() / 100.0;
|
||||
let mut sums = [0.0f64; 4];
|
||||
let mut counts = [0usize; 4];
|
||||
let mut worst = [(0.0f64, 0usize); 4];
|
||||
let mut cycles = vec![0usize; CYCLE + 1];
|
||||
let (mut trends, mut lit_n) = (Vec::new(), 0usize);
|
||||
let mut px = vec![[0u8; 3]; w * h];
|
||||
let level = |v: f64| (v * 100.0 / shown * 255.0).min(255.0) as u8;
|
||||
for i in 0..w * h {
|
||||
let series: Vec<f64> = blocks.iter().map(|b| b.y[i] as f64).collect();
|
||||
if series.iter().sum::<f64>() / series.len() as f64 <= lit {
|
||||
continue;
|
||||
}
|
||||
lit_n += 1;
|
||||
let (kind, dev, trend, cycle) = read(&series, lit);
|
||||
trends.push(trend);
|
||||
let j = kind as usize;
|
||||
sums[j] += dev * dev;
|
||||
counts[j] += 1;
|
||||
if dev > worst[j].0 {
|
||||
worst[j] = (dev, i);
|
||||
}
|
||||
cycles[cycle] += usize::from(kind == Kind::Jitter);
|
||||
px[i] = match kind {
|
||||
Kind::Still => [0, 0, level(trend)],
|
||||
Kind::Boiling => [0, level(dev), level(trend)],
|
||||
Kind::Jitter | Kind::Flicker => [level(dev), 0, level(trend)],
|
||||
};
|
||||
}
|
||||
trends.sort_by(|a, b| a.total_cmp(b));
|
||||
let at = |q: f64| trends.get(((trends.len() as f64 - 1.0) * q).round() as usize).copied().unwrap_or(0.0);
|
||||
let one = |j: usize| json!({ "rms": pct((sums[j] / lit_n.max(1) as f64).sqrt()), "squares": counts[j], "worst": pct(worst[j].0), "worst_at": [worst[j].1 % w * k, worst[j].1 / w * k] });
|
||||
let cycle = cycles.iter().enumerate().max_by_key(|c| *c.1).filter(|c| *c.1 > 0).map_or(0, |c| c.0);
|
||||
let report = json!({
|
||||
"boiling": one(Kind::Boiling as usize), "jitter": one(Kind::Jitter as usize), "flicker": one(Kind::Flicker as usize),
|
||||
"cycle": cycle, "settling": { "median": pct(at(0.5)), "p95": pct(at(0.95)) },
|
||||
});
|
||||
let picture = image::RgbImage::from_fn((w * k) as u32, (h * k) as u32, |x, y| image::Rgb(px[y as usize / k * w + x as usize / k]));
|
||||
(report, picture)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn rnd(seed: &mut u32) -> f64 {
|
||||
*seed = seed.wrapping_mul(1664525).wrapping_add(1013904223);
|
||||
(*seed >> 8) as f64 / (1u32 << 24) as f64 * 2.0 - 1.0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_kind_of_movement_is_told_from_the_others() {
|
||||
let mut s = 3u32;
|
||||
// a level that climbs 10% and nothing else: still, with its trend
|
||||
let climb: Vec<f64> = (0..75).map(|t| 0.3 * (1.0 + 0.1 * t as f64 / 74.0)).collect();
|
||||
let (kind, dev, trend, _) = read(&climb, 0.004);
|
||||
assert_eq!(kind, Kind::Still);
|
||||
assert!(dev < 1e-6 && (trend - 0.0952).abs() < 0.01, "{dev} {trend}");
|
||||
// a slow wander: each frame a small step from the last
|
||||
let mut v = 0.0;
|
||||
let wander: Vec<f64> = (0..75).map(|_| { v = 0.92 * v + 0.01 * rnd(&mut s); 0.3 * (1.0 + v) }).collect();
|
||||
assert_eq!(read(&wander, 0.004).0, Kind::Boiling);
|
||||
// the jitter's cycle: eight levels, again and again, with a little grain on top
|
||||
let phase = [7.5, 1.7, 2.6, 10.4, 1.7, 5.6, 11.3, 1.7];
|
||||
let cycle: Vec<f64> = (0..75).map(|t| 0.02 * phase[t % 8] * (1.0 + 0.02 * rnd(&mut s))).collect();
|
||||
let (kind, dev, _, p) = read(&cycle, 0.004);
|
||||
assert_eq!((kind, p), (Kind::Jitter, 8));
|
||||
assert!(dev > 0.5, "{dev}");
|
||||
// new every frame: flicker
|
||||
let fast: Vec<f64> = (0..75).map(|_| 0.3 * (1.0 + 0.05 * rnd(&mut s))).collect();
|
||||
assert_eq!(read(&fast, 0.004).0, Kind::Flicker);
|
||||
// and a climb under a wander is still boiling, its trend kept apart
|
||||
let both: Vec<f64> = wander.iter().enumerate().map(|(t, v)| v + 0.03 * t as f64 / 74.0).collect();
|
||||
let (kind, _, trend, _) = read(&both, 0.004);
|
||||
assert_eq!(kind, Kind::Boiling);
|
||||
assert!(trend > 0.05, "{trend}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dark_squares_movement_counts_for_less_than_its_ratio() {
|
||||
let mut s = 5u32;
|
||||
let series = |level: f64, s: &mut u32| -> Vec<f64> { (0..75).map(|_| level * (1.0 + 0.05 * rnd(s))).collect() };
|
||||
let (lit, dark) = (read(&series(0.3, &mut s), 0.004).1, read(&series(0.005, &mut s), 0.004).1);
|
||||
// the same 5% ratio: counted whole at a lit level, and by sqrt(0.005 / 0.05) at a dark one
|
||||
assert!((dark / lit - (0.005f64 / 0.05).sqrt()).abs() < 0.05, "{dark} {lit}");
|
||||
assert_eq!(shown_level(0.05, 0.004), 0.05);
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@
|
||||
//! live stage, 1920x1080 by default) }.
|
||||
|
||||
pub mod metric;
|
||||
mod kinds;
|
||||
pub mod steady;
|
||||
|
||||
use raea_runtime_bundle::{flag, R};
|
||||
@@ -114,9 +115,10 @@ pub fn render_with(scene: &Scene, label: &str, env: &[(&str, String)], at: &[i64
|
||||
let run = cmd
|
||||
.args(["render", &scene.file, "--composition", &scene.composition, "--at", &at.join(","), "-o"])
|
||||
.arg(format!("{}/", out.display()))
|
||||
// a light check measures light, not placement: a set's clip (11-24: FLOOR3's fit-2 1 cm into grid-bay) is the
|
||||
// set's to fix and stays in its record, but doesn't stop the measure
|
||||
.args(["--despite", "clips", "raea light check measures light, not placement"])
|
||||
// a light check measures light, not placement or camera: a set's clip (11-24: FLOOR3's fit-2 1 cm into
|
||||
// grid-bay) and a contact sheet's cuts read as a lurching camera (11-25: gambit-street refused, every scene
|
||||
// after it unmeasured) are the piece's to fix and stay in its record, but don't stop the measure
|
||||
.args(["--despite", "all", "raea light check measures light, not placement or camera"])
|
||||
.output()
|
||||
.map_err(|e| e.to_string())?;
|
||||
if !run.status.success() {
|
||||
@@ -351,7 +353,7 @@ pub fn light(args: &[String]) -> R<String> {
|
||||
// won't be the same the next time
|
||||
let moved: Vec<String> = reports.iter().flat_map(|r| r["paths"].as_object().into_iter().flatten().filter(|(_, p)| p["steady"]["steady"] == json!(false)).map(|(path, p)| format!("{} on {path}: {}", r["name"].as_str().unwrap_or(""), steady::line(&p["steady"])))).collect();
|
||||
if !moved.is_empty() {
|
||||
return Err(format!("{said}\nthe light doesn't hold still ({}). {}", moved.join("; "), steady::WHY));
|
||||
return Err(format!("{said}\nthe light boils ({}). {}", moved.join("; "), steady::WHY));
|
||||
}
|
||||
Ok(said)
|
||||
}
|
||||
|
||||
+101
-11
@@ -35,6 +35,15 @@ const MAX: f64 = 1.5;
|
||||
const MAX_ENERGY: f64 = 0.25;
|
||||
/// How far the held frame's level may move between the first and the last quarter of the measured frames, in stops.
|
||||
const MAX_DRIFT: f64 = 0.05;
|
||||
/// The frames measured: the last WINDOW of a hold (or its second half, if that's shorter). Fixed, because a slow
|
||||
/// wander reads larger over a longer window, so two holds of different lengths wouldn't compare.
|
||||
const WINDOW: usize = 75;
|
||||
/// What the worst square that moves with the jitter, or flickers, may show, percent: an edge stepping a pixel a frame
|
||||
/// reads 20 to 70; a resolved one under 2.
|
||||
const MAX_FAST: f64 = 5.0;
|
||||
/// The trend across the window a hold's squares may still have (the 95th percentile), percent: over it the light was
|
||||
/// still building when it was measured, and what reads as boiling is partly that.
|
||||
const MAX_SETTLING: f64 = 5.0;
|
||||
|
||||
/// Each square's mean and deviation in time over `frames`, side `k`: (w, h, [(mean, deviation / mean)]).
|
||||
fn squares(frames: &[Luma], k: usize) -> (usize, usize, Vec<(f64, f64)>) {
|
||||
@@ -57,7 +66,7 @@ fn rms(v: impl Iterator<Item = f64>) -> f64 {
|
||||
}
|
||||
|
||||
/// The measure of held frames (the module's doc), and steady.png's picture: the large squares' deviation.
|
||||
pub fn measure(frames: &[Luma]) -> R<(Value, image::GrayImage)> {
|
||||
pub fn measure(frames: &[Luma]) -> R<(Value, image::GrayImage, image::RgbImage)> {
|
||||
if frames.len() < 8 {
|
||||
return Err(format!("{} held frames: 8 at least say whether the light holds still", frames.len()));
|
||||
}
|
||||
@@ -85,12 +94,14 @@ pub fn measure(frames: &[Luma]) -> R<(Value, image::GrayImage)> {
|
||||
let level = |f: &[Luma]| f.iter().map(|f| f.y.iter().map(|&v| v as f64).sum::<f64>() / f.y.len().max(1) as f64).sum::<f64>() / f.len() as f64;
|
||||
let q = (frames.len() / 4).max(1);
|
||||
let drift = (level(&frames[frames.len() - q..]).max(1e-6) / level(&frames[..q]).max(1e-6)).log2();
|
||||
let (kinds, kinds_map) = crate::kinds::kinds(frames, LARGE, LIT, MAX_SHOWN);
|
||||
let report = json!({
|
||||
"kinds": kinds,
|
||||
"drift": (drift * 1e3).round() / 1e3,
|
||||
"frames": frames.len(), "blotch": pct(blotch), "grain": pct(grain), "spread": ((blotch / grain.max(1e-9)) * 100.0).round() / 100.0,
|
||||
"worst": pct(worst.0), "worst_at": [worst.1, worst.2], "lit": ((large.iter().filter(lit).count() as f64 / large.len().max(1) as f64) * 100.0).round() / 100.0,
|
||||
});
|
||||
Ok((report, map))
|
||||
Ok((report, map, kinds_map))
|
||||
}
|
||||
|
||||
/// The PNG frames of a folder, in order.
|
||||
@@ -141,12 +152,26 @@ pub fn report(dir: &Path, max: Option<f64>) -> R<Value> {
|
||||
let max = max.unwrap_or(MAX);
|
||||
// the second half: the first is the light building from nothing, which a render's lead-in covers
|
||||
let files = held(dir)?;
|
||||
let frames: Vec<Luma> = files[files.len() / 2..].iter().map(|p| metric::load(p)).collect::<R<_>>()?;
|
||||
let (mut report, map) = measure(&frames)?;
|
||||
let frames: Vec<Luma> = files[files.len() - WINDOW.min(files.len() - files.len() / 2)..].iter().map(|p| metric::load(p)).collect::<R<_>>()?;
|
||||
let (mut report, map, kinds_map) = measure(&frames)?;
|
||||
let png = dir.join("steady.png");
|
||||
map.save(&png).map_err(|e| format!("{}: {e}", png.display()))?;
|
||||
let kinds_png = dir.join("steady-kinds.png");
|
||||
kinds_map.save(&kinds_png).map_err(|e| format!("{}: {e}", kinds_png.display()))?;
|
||||
let get = |k: &str| report[k].as_f64().unwrap_or(0.0);
|
||||
let ok = get("blotch") <= max && get("worst") <= max * 3.0 && get("drift").abs() <= MAX_DRIFT;
|
||||
let kind = |k: &str, f: &str| report["kinds"][k][f].as_f64().unwrap_or(0.0);
|
||||
// each kind against its own limit, and what failed named: the fixes differ
|
||||
let mut failed: Vec<&str> = Vec::new();
|
||||
if kind("boiling", "rms") > max || kind("boiling", "worst") > max * 3.0 { failed.push("boiling"); }
|
||||
if kind("jitter", "worst") > MAX_FAST { failed.push("jitter"); }
|
||||
if kind("flicker", "worst") > MAX_FAST { failed.push("flicker"); }
|
||||
if get("drift").abs() > MAX_DRIFT { failed.push("drift"); }
|
||||
let ok = failed.is_empty();
|
||||
let unsettled = kind("settling", "p95") > MAX_SETTLING;
|
||||
let failed: Vec<String> = failed.into_iter().map(String::from).collect();
|
||||
report["failed"] = json!(failed);
|
||||
report["unsettled"] = json!(unsettled);
|
||||
report["kinds_picture"] = json!(kinds_png);
|
||||
report["max"] = json!(max);
|
||||
report["max_drift"] = json!(MAX_DRIFT);
|
||||
report["steady"] = json!(ok);
|
||||
@@ -157,14 +182,74 @@ pub fn report(dir: &Path, max: Option<f64>) -> R<Value> {
|
||||
|
||||
/// A report as one line.
|
||||
pub fn line(r: &Value) -> String {
|
||||
let k = &r["kinds"];
|
||||
let one = |name: &str| format!("{name} {}% (worst {}% at {},{})", k[name]["rms"], k[name]["worst"], k[name]["worst_at"][0], k[name]["worst_at"][1]);
|
||||
format!(
|
||||
"drift {} stops (max {}), blotch {}% (max {}), worst {}% at {},{}, grain {}%, spread {} over {} held frames; {}",
|
||||
r["drift"], r["max_drift"], r["blotch"], r["max"], r["worst"], r["worst_at"][0], r["worst_at"][1], r["grain"], r["spread"], r["frames"], r["picture"].as_str().unwrap_or("")
|
||||
"{}{}, {}{}, {}, settling {}% (p95 {}%){}, drift {} stops (max {}); all movement {}% (blotch), grain {}%, spread {} over {} held frames; {}",
|
||||
one("boiling"), format_args!(" (max {})", r["max"]), one("jitter"), if k["cycle"].as_u64().unwrap_or(0) > 0 { format!(" on a {}-frame cycle", k["cycle"]) } else { String::new() }, one("flicker"),
|
||||
k["settling"]["median"], k["settling"]["p95"], if r["unsettled"] == json!(true) { " STILL SETTLING: hold longer (--frames) before reading the rest" } else { "" },
|
||||
r["drift"], r["max_drift"], r["blotch"], r["grain"], r["spread"], r["frames"], r["kinds_picture"].as_str().unwrap_or("")
|
||||
)
|
||||
}
|
||||
|
||||
/// What a light that doesn't hold still is told.
|
||||
pub const WHY: &str = "Patches this size are light built over frames that hasn't settled: on Solari the world cache, ReSTIR's reuse or the denoiser. Hold the frame with each switched off in turn (cache.steady or a baked cache, RAEA_SOLARI_DENOISE=0, RAEA_SOLARI_PSR=0) to see which; DIR/render.log holds what each render said";
|
||||
/// What a held frame that moves is told, by what moved.
|
||||
pub fn why(r: &Value) -> String {
|
||||
let failed: Vec<&str> = r["failed"].as_array().map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default();
|
||||
let mut says: Vec<String> = Vec::new();
|
||||
if failed.contains(&"boiling") || failed.contains(&"drift") { says.push(WHY.to_string()); }
|
||||
if failed.contains(&"jitter") { says.push("Jitter: squares that repeat on a short cycle are edges stepping with the camera's sub-pixel jitter, which the temporal resolve should have held: a silhouette against the sky or a clipped-bright opening. Hold it with RAEA_SOLARI_AA=0 to confirm (it goes), then keep the bright side under the resolve's range (exposure, the sky's level) or report it".to_string()); }
|
||||
if failed.contains(&"flicker") { says.push("Flicker: fast and without a cycle is a firefly, a sparkle in a reflection or two faces at one depth: look at the worst square in steady-kinds.png (red), and run raea scene lint for faces in one plane".to_string()); }
|
||||
says.join(" ")
|
||||
}
|
||||
|
||||
/// What a light that boils is told (boiling: the trade's word for low-frequency patches that crawl on a held frame).
|
||||
pub const WHY: &str = "Boiling: patches this size are light built over frames that hasn't settled. On Solari, paths (SolariLighting paths={4}) first, then the world cache, ReSTIR's reuse or the denoiser. Hold the frame with each switched off in turn (cache.steady or a baked cache, RAEA_SOLARI_DENOISE=0, RAEA_SOLARI_PSR=0) to see which; DIR/render.log holds what each render said";
|
||||
|
||||
/// The check a held frame's findings carry in the project's record, which `raea check` reads for a traced composition.
|
||||
pub const CHECK: &str = "light-steady";
|
||||
|
||||
/// A held frame's report as findings, one a kind that failed: about the composition, on the frame held.
|
||||
pub fn findings(r: &Value, composition: Option<&str>, frame: i64) -> Vec<raea_core_facts::Finding> {
|
||||
use raea_core_facts::{Finding, Level};
|
||||
let k = &r["kinds"];
|
||||
let num = |v: &Value| v.as_f64().unwrap_or(0.0);
|
||||
let at = |name: &str| format!("{},{}", k[name]["worst_at"][0], k[name]["worst_at"][1]);
|
||||
let mut out = Vec::new();
|
||||
let mut push = |kind: &str, level: Level, says: String, value: f64, limit: f64, fix: &str| {
|
||||
let mut f = Finding::new(CHECK, level, says, "raea light steady").frames(frame, frame + 1).measure(kind, value, "%", Some(limit)).fix(fix);
|
||||
if let Some(c) = composition {
|
||||
f = f.about(c, None);
|
||||
}
|
||||
out.push(f);
|
||||
};
|
||||
let failed: Vec<&str> = r["failed"].as_array().map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default();
|
||||
let max = num(&r["max"]);
|
||||
if failed.contains(&"boiling") {
|
||||
push("boiling", Level::Error, format!("the light boils on frame {frame} held: {}% (worst square {}% at {}; max {max}, worst {})", k["boiling"]["rms"], k["boiling"]["worst"], at("boiling"), max * 3.0), num(&k["boiling"]["worst"]), max * 3.0, WHY);
|
||||
}
|
||||
if failed.contains(&"jitter") {
|
||||
push("jitter", Level::Error, format!("edges step with the camera's jitter on frame {frame} held: worst square {}% at {} on a {}-frame cycle (max {MAX_FAST})", k["jitter"]["worst"], at("jitter"), k["cycle"]), num(&k["jitter"]["worst"]), MAX_FAST, "an edge against the sky, a forward mesh or an emitter left out of the denoiser's history: SolariLighting late and emissive=\"taa\" (the Solari guide)");
|
||||
}
|
||||
if failed.contains(&"flicker") {
|
||||
push("flicker", Level::Error, format!("a square flickers on frame {frame} held: {}% at {} (max {MAX_FAST})", k["flicker"]["worst"], at("flicker")), num(&k["flicker"]["worst"]), MAX_FAST, "a firefly, a sparkle in a reflection or two faces in one plane: look at the square in steady-kinds.png, and run raea scene lint for faces in one plane");
|
||||
}
|
||||
if failed.contains(&"drift") {
|
||||
push("drift", Level::Error, format!("the held frame's light drifts {} stops (max {MAX_DRIFT})", r["drift"]), num(&r["drift"]).abs(), MAX_DRIFT, WHY);
|
||||
}
|
||||
if failed.is_empty() {
|
||||
push("steady", Level::Note, format!("the light holds still on frame {frame} held: {}", line(r)), num(&r["blotch"]), max, "");
|
||||
}
|
||||
if r["unsettled"] == json!(true) {
|
||||
push("settling", Level::Note, format!("the light was still building on frame {frame} held (settling p95 {}%): hold longer, or give the shot a lead-in", k["settling"]["p95"]), num(&k["settling"]["p95"]), MAX_SETTLING, "a still lead-in before the shot, as long as the hold took to settle");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A held frame's findings kept in `file`'s project's record (nothing outside a project).
|
||||
fn keep(file: &str, out: &Path, r: &Value, composition: Option<&str>, frame: i64) {
|
||||
let stamp = raea_io_trace::utc(std::time::SystemTime::now()).1;
|
||||
raea_core_facts::record::keep("raea light steady", Path::new(file), Some(out), &findings(r, composition, frame), Vec::new(), &stamp);
|
||||
}
|
||||
|
||||
pub fn steady(args: &[String]) -> R<String> {
|
||||
let first = args.first().ok_or(format!("usage: {USAGE}"))?;
|
||||
@@ -179,6 +264,10 @@ pub fn steady(args: &[String]) -> R<String> {
|
||||
out
|
||||
};
|
||||
let mut r = report(&dir, max)?;
|
||||
let held_frame = flag(args, "--frame").and_then(|f| f.parse::<i64>().ok());
|
||||
if let (false, Some(f)) = (Path::new(first).is_dir(), held_frame) {
|
||||
keep(first, dir.parent().unwrap_or(&dir), &r, flag(args, "--composition").as_deref(), f);
|
||||
}
|
||||
// --run M: the frame cold against the same frame at the end of M frames played up to it. A cache that gains or
|
||||
// loses energy over minutes (MALL RAT's court, 11-24: 7 times brighter inside the long render) shows here and not
|
||||
// in a hold
|
||||
@@ -201,9 +290,9 @@ pub fn steady(args: &[String]) -> R<String> {
|
||||
}
|
||||
std::fs::write(dir.join("steady.json"), serde_json::to_string_pretty(&r).unwrap_or_default()).map_err(|e| e.to_string())?;
|
||||
let said = format!("energy {} stops after {m} frames against the frame cold (max {MAX_ENERGY}), {}", r["energy"], line(&r));
|
||||
return if r["steady"] == json!(true) { Ok(format!("STEADY {said}")) } else { Err(format!("the light doesn't hold still: {said}. {WHY}")) };
|
||||
return if r["steady"] == json!(true) { Ok(format!("STEADY {said}")) } else { Err(format!("the held frame moves ({}): {said}. {}", r["failed"].as_array().map(|a| a.iter().filter_map(Value::as_str).collect::<Vec<_>>().join(", ")).unwrap_or_default(), why(&r))) };
|
||||
}
|
||||
if r["steady"] == json!(true) { Ok(format!("STEADY {}", line(&r))) } else { Err(format!("the light doesn't hold still: {}. {WHY}", line(&r))) }
|
||||
if r["steady"] == json!(true) { Ok(format!("STEADY {}", line(&r))) } else { Err(format!("the held frame moves ({}): {}. {}", r["failed"].as_array().map(|a| a.iter().filter_map(Value::as_str).collect::<Vec<_>>().join(", ")).unwrap_or_default(), line(&r), why(&r))) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -231,6 +320,7 @@ mod tests {
|
||||
#[test]
|
||||
fn grain_is_steady_and_blotches_are_not() {
|
||||
let still = measure(&frames(0.0, 0.0)).unwrap().0;
|
||||
assert_eq!(still["kinds"]["boiling"]["rms"], 0.0);
|
||||
assert_eq!(still["blotch"], 0.0);
|
||||
assert_eq!(still["drift"], 0.0);
|
||||
// a light that doubles over the held frames: about 0.8 of a stop between the first and the last quarter
|
||||
|
||||
@@ -11,6 +11,8 @@ description = "raea-render's ray tracing: Bevy's Solari for a scene whose camera
|
||||
raea-io-trace = { path = "../../../io/trace" }
|
||||
# the jitter's Halton places (a facility of raea-sys-post's steady)
|
||||
raea-sys-post = { path = "../../../systems/post" }
|
||||
# Overscan, the camera's wider view (the denoiser crops it back)
|
||||
raea-sys-viewbox = { path = "../../../systems/viewbox" }
|
||||
serde_json = "1"
|
||||
# its own wgpu shaders read from a project's engine-shaders/ or the checkout (RAEA_ENGINE_SHADERS), as the embedded ones
|
||||
raea-sys-engine-shaders = { path = "../../../systems/engine-shaders" }
|
||||
|
||||
@@ -18,6 +18,16 @@ const HISTORY_CAP: f32 = 16.0;
|
||||
// a still pixel's history held within what's about it now, its darkest and brightest times these
|
||||
const STILL_LOW: f32 = 0.95;
|
||||
const STILL_HIGH: f32 = 1.05;
|
||||
// how far a still pixel's history goes toward those bounds a frame where it's thin (THIN). At 1, the default, it's held
|
||||
// to them at once, and an emitter under a pixel tall, which some of the jitter's positions miss altogether, is cut to
|
||||
// black on those frames and built again on the others: MALL RAT's ceiling tubes seen edge-on changed shape every frame
|
||||
// (raea light steady: jitter 7% and 8% in their squares, 0.01% with the history always taken). At a quarter
|
||||
// (<SolariLighting constants={{ emissiveClamp: { stillHold: 0.25 } }} />) they read 2.1% and 3.6%, and a 30000-nit
|
||||
// orb switched off leaves its rim behind: +0.30 stops on its tile against +0.17, +0.26 eight frames on (lightbench
|
||||
// window-still-off-q against -one). So it's a scene's choice until a pixel can count the frames it was missed
|
||||
const STILL_HOLD: f32 = 1.0;
|
||||
// a history counts as thin where the brighter of its two sides, two pixels off, is under this much of it
|
||||
const THIN: f32 = 0.25;
|
||||
// a moving pixel's history held under this many times the brightest about it, plus this
|
||||
const MOVING_GAIN: f32 = 4.0;
|
||||
const MOVING_FLOOR: f32 = 0.02;
|
||||
@@ -190,7 +200,23 @@ fn restore_taa(@builtin(global_invocation_id) id: vec3<u32>) {
|
||||
// them (a lamp switched off goes dark at once, rim and all, not over a second)
|
||||
let reach = select(1.5, 1.05, still);
|
||||
if (hd.b * reach >= zlo && hd.a <= zhi * reach && params[0].w != 3.0) {
|
||||
hrgb = clamped;
|
||||
// eased only where the history is a thin line or a point: an emitter under a pixel wide is all the jitter can miss outright. A lamp's or an orb's
|
||||
// face and rim have light to one side, and go dark at once (RT32: eased everywhere, a 30000-nit orb
|
||||
// switched off left +2.5 stops on its tile for 8 frames and +0.8 at 16; eased on thin histories, +0.30
|
||||
// against +0.17 clamped at once, the orb's rim where it's dark to both sides)
|
||||
var hold = 1.0;
|
||||
if (still) {
|
||||
let px = 2.0 / out_size;
|
||||
let lw = vec3<f32>(0.2126, 0.7152, 0.0722);
|
||||
let l0 = dot(hrgb, lw) * THIN;
|
||||
let lx = max(dot(textureSampleLevel(hist_in, hist_sampler, was + vec2<f32>(px.x, 0.0), 0.0).rgb, lw), dot(textureSampleLevel(hist_in, hist_sampler, was - vec2<f32>(px.x, 0.0), 0.0).rgb, lw));
|
||||
let ly = max(dot(textureSampleLevel(hist_in, hist_sampler, was + vec2<f32>(0.0, px.y), 0.0).rgb, lw), dot(textureSampleLevel(hist_in, hist_sampler, was - vec2<f32>(0.0, px.y), 0.0).rgb, lw));
|
||||
// stricter tests of "thin" kept the orb's rim out (+0.18 by the second frame) and lost the tubes:
|
||||
// a line alike along itself, 5.2 and 5.8%; a ring of eight with each lit place lit across, 6.2 and
|
||||
// 6.5% (the tubes hang in rows, so a tube's neighbours light one side of it)
|
||||
if (min(lx, ly) < l0) { hold = STILL_HOLD; }
|
||||
}
|
||||
hrgb = mix(hrgb, clamped, hold);
|
||||
dbg_f += 8.0;
|
||||
}
|
||||
}
|
||||
@@ -232,5 +258,5 @@ fn restore_taa(@builtin(global_invocation_id) id: vec3<u32>) {
|
||||
textureStore(color, p, vec4<f32>(weight, hist.a / HISTORY_CAP, f32(hist.a > 0.0), c.a));
|
||||
return;
|
||||
}
|
||||
textureStore(color, p, vec4<f32>(c.rgb + e, c.a));
|
||||
textureStore(color, p, vec4<f32>(uncompress(c.rgb) + e, c.a));
|
||||
}
|
||||
@@ -58,6 +58,16 @@ pub struct SolariSettings {
|
||||
/// what MetalFX divides the colour by before it denoises and multiplies it by after: bright light kept, at the cost
|
||||
/// of fireflies past 16 (metalfx.rs pre_exposure; RAEA_METALFX_PREEXPOSURE)
|
||||
pub preexposure: f32,
|
||||
/// where the denoiser's soft knee starts, in its white (the colour at `preexposure / 16`); 0 turns it off
|
||||
/// (RAEA_METALFX_KNEE). Above it a pixel's light goes in as its log: W (1 + ln(m / W)), its colour scaled to match,
|
||||
/// and comes out undone after the denoiser. MetalFX averages a silhouette against bright sky or a lit doorway in
|
||||
/// linear light, so its jittered edge pixel swung with the sky's share, 8 frames a cycle (MALL RAT t1 frame 1699:
|
||||
/// steady 3.72, 0.81 with the jitter off). Light under the knee is untouched, so it isn't biased
|
||||
pub knee: f32,
|
||||
/// a full-size view denoised after the main pass instead of before it, so the sky and the forward meshes (drawn
|
||||
/// there, with the jittered camera) are gathered over frames too and their edges stop stepping with the jitter
|
||||
/// (metalfx.rs denoise_late; RAEA_SOLARI_DENOISE_LATE)
|
||||
pub late: bool,
|
||||
/// a full-size view jittered too, so the denoiser anti-aliases its edges as it gathers frames (RAEA_SOLARI_AA=0)
|
||||
pub aa: bool,
|
||||
/// which of MetalFX's passes is told the jitter: "" the denoiser, "scaler", "both", "flip", "0" none (and none is
|
||||
@@ -74,6 +84,11 @@ pub struct SolariSettings {
|
||||
/// the traced scene follows what moves: a skinned mesh's traced twin posed each frame (RT5, a trial;
|
||||
/// RAEA_SOLARI_DYNAMIC). A hidden part leaves the traced scene with or without it (SG9)
|
||||
pub dynamic: bool,
|
||||
/// overscan: the main pass draws this much of the view more on every side (0.05 is a twentieth), and the denoiser
|
||||
/// crops the middle back out, so the light at the frame's border has neighbours and history to gather from as the
|
||||
/// camera moves (RT40; RAEA_SOLARI_OVERSCAN). 0, the default, is off. The view then draws at 1 / (1 + 2 x overscan)
|
||||
/// of its size at most and is brought up; with the denoiser off, or `upscale` "two", it does nothing
|
||||
pub overscan: f32,
|
||||
}
|
||||
|
||||
impl Default for SolariSettings {
|
||||
@@ -85,11 +100,14 @@ impl Default for SolariSettings {
|
||||
emissive: "taa".into(),
|
||||
upscale: "one".into(),
|
||||
preexposure: 16.0,
|
||||
knee: 1.0,
|
||||
late: false,
|
||||
aa: true,
|
||||
jitter: String::new(),
|
||||
emissive_sharpness: 6.0,
|
||||
jitter_frames: 8.0,
|
||||
dynamic: false,
|
||||
overscan: 0.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,6 +59,7 @@ pub(crate) fn add(app: &mut App) {
|
||||
};
|
||||
core.add_systems(denoise.after(solari).before(main_opaque_pass_3d).in_set(Core3dSystems::MainPass));
|
||||
core.add_systems(denoise_up.before(super::upscale::upscale).in_set(Core3dSystems::EarlyPostProcess));
|
||||
core.add_systems(denoise_late.before(super::upscale::upscale).in_set(Core3dSystems::EarlyPostProcess));
|
||||
// Solari's own guides (primary surface replacement: a mirror's pixel takes what it reflects, and a glossy one is as
|
||||
// far off as what it reflects, RT34), written for every view; a view's `guides` and `reflection_depth` choose whether
|
||||
// its denoiser reads them
|
||||
@@ -88,13 +89,15 @@ struct View {
|
||||
/// the split emission's history (RAEA_SOLARI_EMISSIVE=taa, emit_taa.rs)
|
||||
taa: Option<super::emit_taa::History>,
|
||||
fresh: bool,
|
||||
/// overscan: the output is wider than the colour, and `run` copies its middle over once the emission is back in
|
||||
cropped: bool,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Kit {
|
||||
/// the guides (and the emissive out), the emissive back in, from this frame or gathered over frames (emit_taa.rs),
|
||||
/// and the sampler that reads the gathered emission's history
|
||||
pipeline: Option<(wgpu::ComputePipeline, wgpu::ComputePipeline, wgpu::ComputePipeline, wgpu::Sampler, wgpu::ComputePipeline)>,
|
||||
pipeline: Option<(wgpu::ComputePipeline, wgpu::ComputePipeline, wgpu::ComputePipeline, wgpu::Sampler, wgpu::ComputePipeline, wgpu::ComputePipeline)>,
|
||||
views: HashMap<Entity, View>,
|
||||
off: bool,
|
||||
}
|
||||
@@ -161,7 +164,7 @@ impl View {
|
||||
mask: texture(dev, size, wgpu::TextureFormat::R32Float, guide, "metalfx denoise strength"),
|
||||
out: texture(dev, out_size, wgpu::TextureFormat::Rgba16Float, guide | U::RENDER_ATTACHMENT | U::COPY_SRC, "metalfx output"),
|
||||
taa: taa.then(|| super::emit_taa::History::new(dev, out_size)),
|
||||
fresh: true,
|
||||
fresh: true, cropped: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -204,15 +207,30 @@ impl View {
|
||||
s.setShouldResetHistory(reset || self.fresh);
|
||||
matrices(s, view.world_from_view.to_matrix().inverse(), view.clip_from_view);
|
||||
s.encodeToCommandBuffer(cb);
|
||||
let blit = cb.blitCommandEncoder().ok_or("no blit encoder")?;
|
||||
let o = MTLOrigin { x: 0, y: 0, z: 0 };
|
||||
let size = MTLSize { width: self.out_size.x as _, height: self.out_size.y as _, depth: 1 };
|
||||
blit.copyFromTexture_sourceSlice_sourceLevel_sourceOrigin_sourceSize_toTexture_destinationSlice_destinationLevel_destinationOrigin(&out, 0, 0, o, size, &color, 0, 0, o);
|
||||
blit.endEncoding();
|
||||
if !self.cropped {
|
||||
let blit = cb.blitCommandEncoder().ok_or("no blit encoder")?;
|
||||
let o = MTLOrigin { x: 0, y: 0, z: 0 };
|
||||
let size = MTLSize { width: self.out_size.x as _, height: self.out_size.y as _, depth: 1 };
|
||||
blit.copyFromTexture_sourceSlice_sourceLevel_sourceOrigin_sourceSize_toTexture_destinationSlice_destinationLevel_destinationOrigin(&out, 0, 0, o, size, &color, 0, 0, o);
|
||||
blit.endEncoding();
|
||||
}
|
||||
}
|
||||
self.fresh = false;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Overscan: the `full` middle of the wider output, from `at`, over the colour.
|
||||
fn crop_onto(&self, cb: &ProtocolObject<dyn MTLCommandBuffer>, color: &wgpu::Texture, at: UVec2, full: UVec2) -> Result<(), &'static str> {
|
||||
let (out, color) = (mtl(&self.out).ok_or("a texture isn't a Metal one")?, mtl(color).ok_or("a texture isn't a Metal one")?);
|
||||
unsafe {
|
||||
let blit = cb.blitCommandEncoder().ok_or("no blit encoder")?;
|
||||
let from = MTLOrigin { x: at.x as _, y: at.y as _, z: 0 };
|
||||
let size = MTLSize { width: full.x as _, height: full.y as _, depth: 1 };
|
||||
blit.copyFromTexture_sourceSlice_sourceLevel_sourceOrigin_sourceSize_toTexture_destinationSlice_destinationLevel_destinationOrigin(&out, 0, 0, from, size, &color, 0, 0, MTLOrigin { x: 0, y: 0, z: 0 });
|
||||
blit.endEncoding();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// worldToViewMatrix and viewToClipMatrix, simd_float4x4 properties objc2-metal-fx leaves out (no simd types in
|
||||
@@ -240,7 +258,7 @@ fn matrices(s: &ProtocolObject<dyn MTLFXTemporalDenoisedScaler>, world_to_view:
|
||||
}
|
||||
}
|
||||
|
||||
type Viewed = (&'static ViewTarget, &'static ViewPrepassTextures, &'static ExtractedView, &'static ExtractedCamera, &'static SolariLighting, Option<&'static MainPassResolutionOverride>, Option<&'static TemporalJitter>, Has<super::upscale::Upscaled>, Option<&'static SolariGuideTextures>, Option<&'static super::SolariSettings>);
|
||||
type Viewed = (&'static ViewTarget, &'static ViewPrepassTextures, &'static ExtractedView, &'static ExtractedCamera, &'static SolariLighting, Option<&'static MainPassResolutionOverride>, Option<&'static TemporalJitter>, Has<super::upscale::Upscaled>, Option<&'static SolariGuideTextures>, Option<&'static super::SolariSettings>, Option<&'static raea_sys_viewbox::Overscan>);
|
||||
|
||||
/// Before the forward meshes: a view at its full size, or one drawn small whose settings upscale in "two" (its corner).
|
||||
/// Each view's settings go into the run's trace here, once and on a change.
|
||||
@@ -250,8 +268,23 @@ fn denoise(view: ViewQuery<Viewed>, device: Res<RenderDevice>, mut kit: Local<Ki
|
||||
let st = super::settings::of(item.9);
|
||||
let scale = item.5.map_or(1.0, |p| p.0.x as f32 / item.0.main_texture().width() as f32);
|
||||
super::settings::record(entity, &st, scale, &mut seen);
|
||||
// a view drawn small is denoised and brought up in one pass, unless its upscale is "two"
|
||||
if !st.denoise || (item.7 && st.upscale != "two") {
|
||||
// a view drawn small is denoised and brought up in one pass, unless its upscale is "two"; one whose settings say
|
||||
// `late` after the forward meshes and the sky (denoise_late)
|
||||
if !st.denoise || (item.7 && st.upscale != "two") || (st.late && !item.7) {
|
||||
return;
|
||||
}
|
||||
run(entity, item, &st, &device, &mut kit, &mut ctx, false);
|
||||
}
|
||||
|
||||
/// After the main pass: a view at its full size whose settings say `late`, so the sky and the forward meshes, drawn with
|
||||
/// the jittered camera after Solari, are gathered over frames with the rest. Drawn after the denoiser, they kept the
|
||||
/// jitter: a silhouette against the sky stepped a pixel a frame on its 8-frame cycle (MALL RAT t1 frame 1699, steady's
|
||||
/// jitter worst square 73%)
|
||||
fn denoise_late(view: ViewQuery<Viewed>, device: Res<RenderDevice>, mut kit: Local<Kit>, mut ctx: RenderContext) {
|
||||
let entity = view.entity();
|
||||
let item = view.into_inner();
|
||||
let st = super::settings::of(item.9);
|
||||
if !st.denoise || item.7 || !st.late {
|
||||
return;
|
||||
}
|
||||
run(entity, item, &st, &device, &mut kit, &mut ctx, false);
|
||||
@@ -268,7 +301,7 @@ fn denoise_up(view: ViewQuery<Viewed>, device: Res<RenderDevice>, mut kit: Local
|
||||
run(entity, item, &st, &device, &mut kit, &mut ctx, true);
|
||||
}
|
||||
|
||||
type Item<'a> = (&'a ViewTarget, &'a ViewPrepassTextures, &'a ExtractedView, &'a ExtractedCamera, &'a SolariLighting, Option<&'a MainPassResolutionOverride>, Option<&'a TemporalJitter>, bool, Option<&'a SolariGuideTextures>, Option<&'a super::SolariSettings>);
|
||||
type Item<'a> = (&'a ViewTarget, &'a ViewPrepassTextures, &'a ExtractedView, &'a ExtractedCamera, &'a SolariLighting, Option<&'a MainPassResolutionOverride>, Option<&'a TemporalJitter>, bool, Option<&'a SolariGuideTextures>, Option<&'a super::SolariSettings>, Option<&'a raea_sys_viewbox::Overscan>);
|
||||
|
||||
/// The guides from the G-buffer and the emissive out, at the main pass's size; MetalFX's denoiser, out to the whole
|
||||
/// view when `up`; its output over the colour and the emissive back in.
|
||||
@@ -276,7 +309,7 @@ fn run(entity: Entity, item: Item, st: &super::SolariSettings, device: &RenderDe
|
||||
if kit.off {
|
||||
return;
|
||||
}
|
||||
let (target, pre, ext, cam, solari, part, jitter, _, guides, _) = item;
|
||||
let (target, pre, ext, cam, solari, part, jitter, _, guides, _, over) = item;
|
||||
// Solari wrote its guides for every view; this one reads them unless its settings say the G-buffer's
|
||||
let guides = guides.filter(|_| st.guides);
|
||||
let (Some(depth), Some(motion), Some(gbuf)) = (pre.depth.as_ref(), pre.motion_vectors.as_ref(), pre.deferred.as_ref()) else { return };
|
||||
@@ -286,7 +319,12 @@ fn run(entity: Entity, item: Item, st: &super::SolariSettings, device: &RenderDe
|
||||
let color: &wgpu::Texture = target.main_texture();
|
||||
let full = UVec2::new(color.width(), color.height());
|
||||
let size = part.map_or(full, |p| p.0);
|
||||
let out_size = if up { full } else { size };
|
||||
// overscan: the main pass drew the view wider, so the denoised frame is wider than the colour, and its middle is
|
||||
// what the colour takes (below)
|
||||
let k = if up { raea_sys_viewbox::Overscan::drawn(over) } else { 0.0 };
|
||||
let wide = (full.as_vec2() * (1.0 + 2.0 * k)).round().as_uvec2();
|
||||
let crop = (k > 0.0).then(|| (wide - full) / 2);
|
||||
let out_size = if !up { size } else if crop.is_some() { wide } else { full };
|
||||
let jitter = jitter.map_or(Vec2::ZERO, |j| -j.offset * super::upscale::jitter_gain(&st.jitter, true, true));
|
||||
let dev = device.wgpu_device().clone();
|
||||
// with Solari's guides, the denoiser's depth is theirs: a mirror's pixel as far off as what it reflects, so when what
|
||||
@@ -302,12 +340,13 @@ fn run(entity: Entity, item: Item, st: &super::SolariSettings, device: &RenderDe
|
||||
}
|
||||
Err(e) => {
|
||||
kit.off = true;
|
||||
super::upscale::NO_DENOISER.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
eprintln!("raea: <SolariLighting>: no MetalFX denoiser ({e}); the lighting draws un-denoised (docs/raytracing.feature RT4)");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
let (pipeline, restore, restore_taa, hist_sampler, pipeline_psr) = kit
|
||||
let (pipeline, restore, restore_taa, hist_sampler, pipeline_psr, expand) = kit
|
||||
.pipeline
|
||||
.get_or_insert_with(|| {
|
||||
// read from a project's engine-shaders/ or the checkout when one has them (docs/nobuild.feature NB5b)
|
||||
@@ -316,18 +355,19 @@ fn run(entity: Entity, item: Item, st: &super::SolariSettings, device: &RenderDe
|
||||
let source = format!("{guides}{taa}");
|
||||
let module = dev.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("metalfx guides"), source: wgpu::ShaderSource::Wgsl(source.into()) });
|
||||
let make = |entry: &str| dev.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some("metalfx guides"), layout: None, module: &module, entry_point: Some(entry), compilation_options: Default::default(), cache: None });
|
||||
(make("main"), make("restore"), make("restore_taa"), super::emit_taa::sampler(&dev), make("main_psr"))
|
||||
(make("main"), make("restore"), make("restore_taa"), super::emit_taa::sampler(&dev), make("main_psr"), make("expand"))
|
||||
})
|
||||
.clone();
|
||||
let color_view = color.create_view(&Default::default());
|
||||
let back = ext.world_from_view.back();
|
||||
let reset = solari.reset || kit.views.get(&entity).is_none_or(|v| v.fresh);
|
||||
// the jitter's cycle at this render scale, how long a twig glimpsed through it can stay away (emit_taa.wgsl)
|
||||
let cycle = super::upscale::cycle(size.x as f32 / full.x as f32, st.jitter_frames) as f32;
|
||||
let words: [f32; 16] = [cam.exposure, if split { 1.0 } else { 0.0 }, if reset { 1.0 } else { 0.0 }, super::emit_taa::debug(), out_size.x as f32, out_size.y as f32, size.x as f32, size.y as f32, back.x, back.y, back.z, st.emissive_sharpness, jitter.x, jitter.y, cycle, 0.0];
|
||||
let cycle = super::upscale::cycle(size.x as f32 / out_size.x.max(full.x) as f32, st.jitter_frames) as f32;
|
||||
let words: [f32; 16] = [cam.exposure, if split { 1.0 } else { 0.0 }, if reset { 1.0 } else { 0.0 }, super::emit_taa::debug(), out_size.x as f32, out_size.y as f32, size.x as f32, size.y as f32, back.x, back.y, back.z, st.emissive_sharpness, jitter.x, jitter.y, cycle, st.knee.max(0.0) * st.preexposure / 16.0];
|
||||
let bytes: Vec<u8> = words.iter().flat_map(|w| w.to_ne_bytes()).collect();
|
||||
let params = wgpu::util::DeviceExt::create_buffer_init(&dev, &wgpu::util::BufferInitDescriptor { label: Some("metalfx params"), contents: &bytes, usage: wgpu::BufferUsages::UNIFORM });
|
||||
let v = kit.views.get_mut(&entity).unwrap();
|
||||
v.cropped = crop.is_some();
|
||||
let views = [&v.diffuse, &v.specular, &v.normal, &v.rough].map(|t| t.create_view(&Default::default()));
|
||||
let mut entries = vec![wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&*gbuf.texture.default_view) }];
|
||||
for (i, tv) in views.iter().enumerate() {
|
||||
@@ -368,6 +408,9 @@ fn run(entity: Entity, item: Item, st: &super::SolariSettings, device: &RenderDe
|
||||
})
|
||||
};
|
||||
ctx.add_command_buffer(raw.finish());
|
||||
// overscan: the emission goes back into the denoiser's wider output, whose middle the colour then takes
|
||||
let out_view = v.out.create_view(&Default::default());
|
||||
let color_view = if crop.is_some() { out_view } else { color_view };
|
||||
// the emissive back in, after the denoiser's command buffer (add_command_buffer flushed the encoder before it)
|
||||
if split {
|
||||
let mut entries = vec![
|
||||
@@ -391,6 +434,31 @@ fn run(entity: Entity, item: Item, st: &super::SolariSettings, device: &RenderDe
|
||||
pass.dispatch_workgroups(out_size.x.div_ceil(8), out_size.y.div_ceil(8), 1);
|
||||
}
|
||||
}
|
||||
// the knee undone where no `restore` ran (emissive "mask")
|
||||
if !split && st.knee > 0.0 {
|
||||
let entries = [
|
||||
wgpu::BindGroupEntry { binding: 5, resource: wgpu::BindingResource::TextureView(&color_view) },
|
||||
wgpu::BindGroupEntry { binding: 6, resource: params.as_entire_binding() },
|
||||
];
|
||||
let bind = dev.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("metalfx knee undone"), layout: &expand.get_bind_group_layout(0), entries: &entries });
|
||||
let mut pass = ctx.command_encoder().begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("metalfx knee undone"), timestamp_writes: None });
|
||||
pass.set_pipeline(&expand);
|
||||
pass.set_bind_group(0, &bind, &[]);
|
||||
pass.dispatch_workgroups(out_size.x.div_ceil(8), out_size.y.div_ceil(8), 1);
|
||||
}
|
||||
// the middle of the wider output over the colour: a raw blit as the denoiser's own (the colour has no COPY_DST for
|
||||
// wgpu's), in a command buffer after the emission's (add_command_buffer flushes the encoder before it)
|
||||
let mut done = done;
|
||||
if let (Some(at), true) = (crop, done.is_ok()) {
|
||||
let mut raw = dev.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("metalfx overscan crop") });
|
||||
done = unsafe {
|
||||
raw.as_hal_mut::<Metal, _, _>(|e| match e.and_then(|e| e.raw_command_buffer()) {
|
||||
Some(cb) => v.crop_onto(cb, color, at, full),
|
||||
None => Err("wgpu gave no Metal command buffer"),
|
||||
})
|
||||
};
|
||||
ctx.add_command_buffer(raw.finish());
|
||||
}
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
super::upscale::DENOISED.store(done.is_ok(), Relaxed);
|
||||
super::upscale::DENOISING.store(done.is_ok(), Relaxed);
|
||||
@@ -399,6 +467,7 @@ fn run(entity: Entity, item: Item, st: &super::SolariSettings, device: &RenderDe
|
||||
}
|
||||
if let Err(e) = done {
|
||||
kit.off = true;
|
||||
super::upscale::NO_DENOISER.store(true, Relaxed);
|
||||
eprintln!("raea: <SolariLighting>: the MetalFX denoiser stopped ({e}); the lighting draws un-denoised");
|
||||
}
|
||||
}
|
||||
@@ -22,12 +22,28 @@
|
||||
@group(0) @binding(5) var color: texture_storage_2d<rgba16float, read_write>;
|
||||
// [0].x: the camera's exposure, .y: 1 to split all emission out (RAEA_SOLARI_EMISSIVE=split); [1]: the output's size
|
||||
// and the input's (the corner of the colour the main pass drew); [2].xyz: the camera's back, world-space; [3].xy: the
|
||||
// jitter MetalFX is told, in input pixels
|
||||
// jitter MetalFX is told, in input pixels, .w: where the soft knee starts in the colour (0: none; SolariSettings.knee)
|
||||
@group(0) @binding(6) var<uniform> params: array<vec4<f32>, 4>;
|
||||
// the emission `main` took out of the colour, at the input's size, for `restore` to put back
|
||||
@group(0) @binding(7) var emit: texture_storage_2d<rgba16float, read_write>;
|
||||
// MetalFX's denoise strength mask: 1 leaves a pixel undenoised
|
||||
@group(0) @binding(8) var mask: texture_storage_2d<r32float, write>;
|
||||
// The soft knee (SolariSettings.knee): above W a pixel's light m (its largest channel) goes in as W (1 + ln(m / W)),
|
||||
// which meets the line at W with the same slope, and its colour is scaled to match; `expand` undoes it after the
|
||||
// denoiser. Logarithmic rather than Reinhard's m / (1 + m): its half floats keep a bright pixel's light to about 0.5%,
|
||||
// where Reinhard's curve crowds every highlight just under its ceiling and loses them
|
||||
fn compress(c: vec3<f32>) -> vec3<f32> {
|
||||
let w = params[3].w;
|
||||
let m = max(c.r, max(c.g, c.b));
|
||||
if (w <= 0.0 || m <= w) { return c; }
|
||||
return c * (w * (1.0 + log(m / w)) / m);
|
||||
}
|
||||
fn uncompress(c: vec3<f32>) -> vec3<f32> {
|
||||
let w = params[3].w;
|
||||
let m = max(c.r, max(c.g, c.b));
|
||||
if (w <= 0.0 || m <= w) { return c; }
|
||||
return c * (w * exp(min(m / w - 1.0, 80.0)) / m);
|
||||
}
|
||||
fn rgb9e5(v: u32) -> vec3<f32> {
|
||||
let scale = exp2(f32(i32(extractBits(v, 27u, 5u)) - 15 - 9));
|
||||
return vec3<f32>(f32(extractBits(v, 0u, 9u)), f32(extractBits(v, 9u, 9u)), f32(extractBits(v, 18u, 9u))) * scale;
|
||||
@@ -84,6 +100,7 @@ fn sky(p: vec2<i32>) {
|
||||
textureStore(rough, p, vec4<f32>(1.0, 0.0, 0.0, 0.0));
|
||||
textureStore(emit, p, vec4<f32>(0.0));
|
||||
textureStore(mask, p, vec4<f32>(1.0, 0.0, 0.0, 0.0));
|
||||
textureStore(color, p, vec4<f32>(compress(c), textureLoad(color, p).a));
|
||||
}
|
||||
fn store(p: vec2<i32>, g: vec4<u32>, s: Surface) {
|
||||
textureStore(normal, p, vec4<f32>(s.normal, 0.0));
|
||||
@@ -95,7 +112,7 @@ fn store(p: vec2<i32>, g: vec4<u32>, s: Surface) {
|
||||
if (params[0].y > 0.5) {
|
||||
let taken = min(e, c.rgb);
|
||||
textureStore(diffuse, p, vec4<f32>(s.diffuse, 1.0));
|
||||
textureStore(color, p, vec4<f32>(c.rgb - taken, c.a));
|
||||
textureStore(color, p, vec4<f32>(compress(c.rgb - taken), c.a));
|
||||
textureStore(emit, p, vec4<f32>(taken, 0.0));
|
||||
textureStore(mask, p, vec4<f32>(0.0));
|
||||
return;
|
||||
@@ -104,6 +121,7 @@ fn store(p: vec2<i32>, g: vec4<u32>, s: Surface) {
|
||||
let share = dot(e, luma) / max(dot(c.rgb, luma), 1e-4);
|
||||
textureStore(diffuse, p, vec4<f32>(min(s.diffuse + e / (vec3<f32>(1.0) + e), vec3<f32>(1.0)), 1.0));
|
||||
textureStore(mask, p, vec4<f32>(smoothstep(0.3, 0.7, share), 0.0, 0.0, 0.0));
|
||||
textureStore(color, p, vec4<f32>(compress(c.rgb), c.a));
|
||||
}
|
||||
@compute @workgroup_size(8, 8, 1)
|
||||
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
|
||||
@@ -142,5 +160,14 @@ fn restore(@builtin(global_invocation_id) id: vec3<u32>) {
|
||||
let t = q - floor(q);
|
||||
let e = mix(mix(emitted(i), emitted(i + vec2<i32>(1, 0)), t.x), mix(emitted(i + vec2<i32>(0, 1)), emitted(i + vec2<i32>(1, 1)), t.x), t.y);
|
||||
let c = textureLoad(color, p);
|
||||
textureStore(color, p, vec4<f32>(c.rgb + e, c.a));
|
||||
textureStore(color, p, vec4<f32>(uncompress(c.rgb) + e, c.a));
|
||||
}
|
||||
// the knee undone, with no emission to put back (emissive "mask"): run after the denoiser whenever `restore` isn't
|
||||
@compute @workgroup_size(8, 8, 1)
|
||||
fn expand(@builtin(global_invocation_id) id: vec3<u32>) {
|
||||
let size = vec2<u32>(params[1].xy);
|
||||
if (id.x >= size.x || id.y >= size.y) { return; }
|
||||
let p = vec2<i32>(id.xy);
|
||||
let c = textureLoad(color, p);
|
||||
textureStore(color, p, vec4<f32>(uncompress(c.rgb), c.a));
|
||||
}
|
||||
@@ -13,10 +13,13 @@ struct Overrides {
|
||||
emissive: Option<String>,
|
||||
upscale: Option<String>,
|
||||
preexposure: Option<f32>,
|
||||
knee: Option<f32>,
|
||||
late: Option<bool>,
|
||||
aa: Option<bool>,
|
||||
jitter: Option<String>,
|
||||
emissive_sharpness: Option<f32>,
|
||||
dynamic: Option<bool>,
|
||||
overscan: Option<f32>,
|
||||
}
|
||||
|
||||
fn overrides() -> &'static Overrides {
|
||||
@@ -33,10 +36,13 @@ fn overrides() -> &'static Overrides {
|
||||
emissive: var("RAEA_SOLARI_EMISSIVE").filter(|v| matches!(v.as_str(), "taa" | "split" | "mask")),
|
||||
upscale: var("RAEA_SOLARI_UPSCALE").filter(|v| matches!(v.as_str(), "one" | "two")),
|
||||
preexposure: num("RAEA_METALFX_PREEXPOSURE"),
|
||||
late: switch("RAEA_SOLARI_DENOISE_LATE"),
|
||||
knee: if var("RAEA_METALFX_KNEE").as_deref() == Some("0") { Some(0.0) } else { num("RAEA_METALFX_KNEE") },
|
||||
aa: switch("RAEA_SOLARI_AA"),
|
||||
jitter: var("RAEA_SOLARI_JITTER"),
|
||||
emissive_sharpness: num("RAEA_EMIT_TAA_SHARP"),
|
||||
dynamic: switch("RAEA_SOLARI_DYNAMIC"),
|
||||
overscan: var("RAEA_SOLARI_OVERSCAN").and_then(|v| v.parse::<f32>().ok()).filter(|v| (0.0..=0.25).contains(v)),
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -51,10 +57,13 @@ pub(crate) fn of(s: Option<&SolariSettings>) -> SolariSettings {
|
||||
if let Some(v) = &o.emissive { s.emissive = v.clone(); }
|
||||
if let Some(v) = &o.upscale { s.upscale = v.clone(); }
|
||||
if let Some(v) = o.preexposure { s.preexposure = v; }
|
||||
if let Some(v) = o.knee { s.knee = v; }
|
||||
if let Some(v) = o.late { s.late = v; }
|
||||
if let Some(v) = o.aa { s.aa = v; }
|
||||
if let Some(v) = &o.jitter { s.jitter = v.clone(); }
|
||||
if let Some(v) = o.emissive_sharpness { s.emissive_sharpness = v; }
|
||||
if let Some(v) = o.dynamic { s.dynamic = v; }
|
||||
if let Some(v) = o.overscan { s.overscan = v; }
|
||||
s
|
||||
}
|
||||
|
||||
@@ -66,9 +75,12 @@ const VARS: &[(&str, &str)] = &[
|
||||
("RAEA_SOLARI_EMISSIVE", "emissive"),
|
||||
("RAEA_SOLARI_UPSCALE", "upscale"),
|
||||
("RAEA_METALFX_PREEXPOSURE", "preexposure"),
|
||||
("RAEA_METALFX_KNEE", "knee"),
|
||||
("RAEA_SOLARI_DENOISE_LATE", "late"),
|
||||
("RAEA_SOLARI_AA", "aa"),
|
||||
("RAEA_SOLARI_JITTER", "jitter"),
|
||||
("RAEA_SOLARI_DYNAMIC", "dynamic"),
|
||||
("RAEA_SOLARI_OVERSCAN", "overscan"),
|
||||
("RAEA_EMIT_TAA_SHARP", "emissiveSharpness"),
|
||||
("RAEA_SOLARI_SCALE", "scale"),
|
||||
];
|
||||
@@ -89,7 +101,7 @@ pub(crate) fn record(view: Entity, s: &SolariSettings, scale: f32, seen: &mut Ha
|
||||
"view": view.to_bits(),
|
||||
"denoise": s.denoise, "guides": s.guides, "reflection_depth": s.reflection_depth, "emissive": s.emissive,
|
||||
"upscale": s.upscale, "preexposure": s.preexposure, "aa": s.aa, "jitter": s.jitter,
|
||||
"emissive_sharpness": s.emissive_sharpness, "jitter_frames": s.jitter_frames, "dynamic": s.dynamic, "scale": (f64::from(scale) * 1000.0).round() / 1000.0,
|
||||
"emissive_sharpness": s.emissive_sharpness, "jitter_frames": s.jitter_frames, "dynamic": s.dynamic, "overscan": s.overscan, "scale": (f64::from(scale) * 1000.0).round() / 1000.0,
|
||||
"env": env.iter().map(|(n, v, _)| format!("{n}={v}")).collect::<Vec<_>>(),
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -41,18 +41,49 @@ static NONE: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// After app.finish(): the jitter and the main pass's size in the main world, the scaler after the main pass.
|
||||
pub(crate) fn add(app: &mut App) {
|
||||
app.add_systems(PostUpdate, jitter);
|
||||
app.add_systems(PostUpdate, (jitter, widen.before(raea_sys_viewbox::tag_row_view).before(bevy::camera::CameraUpdateSystems)));
|
||||
let Some(r) = app.get_sub_app_mut(RenderApp) else { return };
|
||||
r.add_systems(ExtractSchedule, extract).add_systems(Core3d, upscale.in_set(Core3dSystems::EarlyPostProcess));
|
||||
}
|
||||
|
||||
/// The fraction of the view's size a side its main pass draws at, 1/3 to 1: RAEA_SOLARI_SCALE on a Solari camera, else
|
||||
/// its RenderScale; 1 where there's no scaler.
|
||||
fn scale(rs: Option<&RenderScale>, solari: bool) -> f32 {
|
||||
fn scale(rs: Option<&RenderScale>, solari: bool, k: f32) -> f32 {
|
||||
static FORCED: std::sync::OnceLock<Option<f32>> = std::sync::OnceLock::new();
|
||||
let forced = *FORCED.get_or_init(|| std::env::var("RAEA_SOLARI_SCALE").ok().and_then(|v| v.parse::<f32>().ok()));
|
||||
let s = if solari && let Some(f) = forced { f } else { rs.map_or(1.0, |r| r.scale) };
|
||||
if NONE.load(Ordering::Relaxed) || !s.is_finite() || s >= 0.999 { 1.0 } else { s.clamp(1.0 / 3.0, 1.0) }
|
||||
let s = if NONE.load(Ordering::Relaxed) || !s.is_finite() || s >= 0.999 { 1.0 } else { s.clamp(1.0 / 3.0, 1.0) };
|
||||
// overscan: the wider main pass has to fit the view's textures
|
||||
if k > 0.0 { s.min(1.0 / (1.0 + 2.0 * k)) } else { s }
|
||||
}
|
||||
|
||||
/// The denoiser stopped (metalfx.rs): nothing crops a wider view back, so no view is drawn wider.
|
||||
pub(crate) static NO_DENOISER: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// A Solari camera's overscan as it applies: its settings', where the denoiser brings the view up in one pass (it does
|
||||
/// the cropping); none otherwise.
|
||||
fn overscan(solari: bool, st: &super::SolariSettings) -> f32 {
|
||||
if !solari || !st.denoise || st.upscale == "two" || NONE.load(Ordering::Relaxed) || NO_DENOISER.load(Ordering::Relaxed) || !st.overscan.is_finite() {
|
||||
return 0.0;
|
||||
}
|
||||
st.overscan.clamp(0.0, 0.25)
|
||||
}
|
||||
|
||||
/// Each Solari camera's Overscan from its settings, for the view it draws (raea-sys-viewbox widens it).
|
||||
#[allow(clippy::type_complexity)]
|
||||
fn widen(mut cmd: Commands, cams: Query<(Entity, Has<SolariLighting>, Option<&super::SolariSettings>, Option<&raea_sys_viewbox::Overscan>), With<Camera3d>>) {
|
||||
for (e, solari, st, has) in &cams {
|
||||
let k = overscan(solari, &super::settings::of(st));
|
||||
match (k > 0.0, has) {
|
||||
(true, has) if has.map(|o| o.margin) != Some(k) => {
|
||||
cmd.entity(e).insert(raea_sys_viewbox::Overscan { margin: k, drawn: 0.0 });
|
||||
}
|
||||
(false, Some(_)) => {
|
||||
cmd.entity(e).remove::<raea_sys_viewbox::Overscan>();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The denoiser ran on the view this frame (metalfx.rs sets it; the scaler, after it, reads and clears it).
|
||||
@@ -94,10 +125,10 @@ pub(crate) fn cycle(s: f32, frames: f32) -> u32 {
|
||||
/// gathers frames: photo 2's frame 95 had stepped edges held still, and jittered it came 15.9 -> 15.6 off the path
|
||||
/// tracer.
|
||||
#[allow(clippy::type_complexity)]
|
||||
fn jitter(mut cmd: Commands, frame: Res<FrameCount>, mut cams: Query<(Entity, Option<&RenderScale>, Has<SolariLighting>, Option<&mut TemporalJitter>, Has<Jittered>, Option<&super::SolariSettings>), With<Camera3d>>) {
|
||||
for (e, rs, solari, j, mine, st) in &mut cams {
|
||||
let s = scale(rs, solari);
|
||||
fn jitter(mut cmd: Commands, frame: Res<FrameCount>, mut cams: Query<(Entity, Option<&RenderScale>, Has<SolariLighting>, Option<&mut TemporalJitter>, Has<Jittered>, Option<&super::SolariSettings>, Option<&raea_sys_viewbox::Overscan>), With<Camera3d>>) {
|
||||
for (e, rs, solari, j, mine, st, over) in &mut cams {
|
||||
let st = super::settings::of(st);
|
||||
let s = scale(rs, solari, raea_sys_viewbox::Overscan::drawn(over));
|
||||
if s < 1.0 || (solari && st.aa && st.denoise && DENOISING.load(Ordering::Relaxed)) {
|
||||
let n = cycle(s, st.jitter_frames);
|
||||
let i = frame.0 % n + 1;
|
||||
@@ -120,16 +151,24 @@ fn jitter(mut cmd: Commands, frame: Res<FrameCount>, mut cams: Query<(Entity, Op
|
||||
pub(crate) struct Upscaled;
|
||||
|
||||
/// Each drawn-small camera's main pass size onto its view; taken off when its scale goes back to 1.
|
||||
fn extract(mut cmd: Commands, cams: Extract<Query<(RenderEntity, &Camera, Option<&RenderScale>, Has<SolariLighting>), With<Camera3d>>>, upscaled: Query<(), With<Upscaled>>) {
|
||||
for (re, cam, rs, solari) in &cams {
|
||||
let s = scale(rs, solari);
|
||||
#[allow(clippy::type_complexity)]
|
||||
fn extract(mut cmd: Commands, cams: Extract<Query<(RenderEntity, &Camera, Option<&RenderScale>, Has<SolariLighting>, Option<&raea_sys_viewbox::Overscan>), With<Camera3d>>>, upscaled: Query<(), With<Upscaled>>) {
|
||||
for (re, cam, rs, solari, over) in &cams {
|
||||
// as wide as the camera's view was drawn (raea-sys-viewbox's tag_row_view): the main pass matches that
|
||||
let k = raea_sys_viewbox::Overscan::drawn(over);
|
||||
let s = scale(rs, solari, k);
|
||||
match cam.physical_viewport_size() {
|
||||
Some(size) if s < 1.0 && cam.is_active => {
|
||||
let part = (size.as_vec2() * s).round().as_uvec2().max(UVec2::ONE);
|
||||
let part = (size.as_vec2() * s * (1.0 + 2.0 * k)).round().as_uvec2().clamp(UVec2::ONE, size);
|
||||
cmd.entity(re).insert((MainPassResolutionOverride(part), Upscaled));
|
||||
if k > 0.0 {
|
||||
cmd.entity(re).insert(raea_sys_viewbox::Overscan { margin: k, drawn: k });
|
||||
} else {
|
||||
cmd.entity(re).remove::<raea_sys_viewbox::Overscan>();
|
||||
}
|
||||
}
|
||||
_ if upscaled.contains(re) => {
|
||||
cmd.entity(re).remove::<(MainPassResolutionOverride, Upscaled)>();
|
||||
cmd.entity(re).remove::<(MainPassResolutionOverride, Upscaled, raea_sys_viewbox::Overscan)>();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
@@ -126,6 +126,9 @@ pub fn apply_rows(world: &mut World, dir: &Path, rows: &[Tup]) -> Result<bool, S
|
||||
}
|
||||
}
|
||||
}
|
||||
if world.resource::<FrameRows>().cols.id.len() != store::rows(world).len() {
|
||||
name_rows(world);
|
||||
}
|
||||
// a <BevyComponent> or <BevyResource> whose value a live frame changed (or a new one): set on its part
|
||||
plugins::apply_live_rows(world, &reflected)?;
|
||||
// a mesh spawned here with a shader over its surface: put on now that this frame's rows are in (scene3d's
|
||||
@@ -169,10 +172,27 @@ pub fn remove_rows_from(world: &mut World, rows: &[(String, String)]) -> Result<
|
||||
// the rows after a dropped one moved up: their places again, from the store's order
|
||||
let ix: bevy::ecs::entity::EntityHashMap<usize> = store::rows(world).iter().enumerate().map(|(r, &e)| (e, r)).collect();
|
||||
world.resource_mut::<FrameRows>().ix = ix;
|
||||
name_rows(world);
|
||||
}
|
||||
if gone.is_empty() { Ok(()) } else { Err(gone.join("; ")) }
|
||||
}
|
||||
|
||||
/// The frame's row names (`cols.kind`, `cols.id`) as the store holds its rows now. A live scene's rows move up when one
|
||||
/// before them is dropped and new ones join at the end, and a <FramePass>'s or a <Compute>'s `follow` finds its row
|
||||
/// by `cols.id`: left as the scene opened, a pass read another row from the first drop on and kept the uniforms it
|
||||
/// opened with for the rest of a video (11-25: MALL RAT's exposure stood still, its daylight blown out).
|
||||
fn name_rows(world: &mut World) {
|
||||
let (mut kinds, mut ids) = (Vec::<String>::new(), Vec::<String>::new());
|
||||
for &e in store::rows(world).iter() {
|
||||
if let Some(k) = store::key(world, e) {
|
||||
kinds.push(k.kind.clone());
|
||||
ids.push(k.id.clone());
|
||||
}
|
||||
}
|
||||
let mut fr = world.resource_mut::<FrameRows>();
|
||||
(fr.cols.kind, fr.cols.id) = (kinds.into(), ids.into());
|
||||
}
|
||||
|
||||
/// Where a plain App's 3D camera draws when its camera row arrives through apply_rows (an Engine's draws into its frame).
|
||||
#[derive(Resource, Clone)]
|
||||
pub struct SceneTarget {
|
||||
@@ -382,3 +402,23 @@ pub(crate) fn spawn_3d(world: &mut World, e: Entity, t: &Tup, inserted: &[Tup],
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_live_rows_name_follows_the_rows_dropped_before_it() {
|
||||
let row = |kind: &str, id: &str, k: f64| Tup { kind: kind.into(), id: id.into(), vals: [("k".into(), V::N(k))].into() };
|
||||
let mut s = store::Store::new(&[row("mesh", "a", 0.0), row("mesh", "b", 1.0), row("frame_pass", "frame_pass0", 2.0)]);
|
||||
let mut fr = FrameRows::new(store::rows(&s.world).iter().enumerate().map(|(r, &e)| (e, r)).collect());
|
||||
fr.cols = s.gather();
|
||||
fr.live = Some(s.tups().into_iter().map(|t| t.vals).collect());
|
||||
s.world.insert_resource(fr);
|
||||
remove_rows_from(&mut s.world, &[("mesh".into(), "a".into())]).unwrap();
|
||||
// the pass's row is one place up, and found there by its name (a FramePass's `follow`)
|
||||
let fr = s.world.resource::<FrameRows>();
|
||||
let r = fr.cols.id.iter().position(|i| i == "frame_pass0").unwrap();
|
||||
assert_eq!((r, fr.at(r, "k")), (1, Some(V::N(2.0))));
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,8 @@ pub fn device() -> Result<Handles, String> {
|
||||
/// Intel's and AMD's PCI vendor ids, as DXGI and Vulkan report them.
|
||||
const INTEL: u32 = 0x8086;
|
||||
const AMD: u32 = 0x1002;
|
||||
/// Qualcomm's (Adreno, on a Windows on ARM PC): DXGI reports "QCOM" as its vendor, some drivers 0x5143
|
||||
const QUALCOMM: [u32; 2] = [0x4D4F_4351, 0x5143];
|
||||
|
||||
/// Whether the shared device runs on DX12 alone: on Windows, when WGPU_BACKEND isn't set and DX12 lists Intel's or
|
||||
/// AMD's own hardware among its GPUs (`dx12`: each one's vendor and kind; WARP, Windows' software DirectX, is a Cpu),
|
||||
@@ -41,10 +43,12 @@ const AMD: u32 = 0x1002;
|
||||
/// 0.1.3's app crashed before its window in AMD's OpenGL driver (atio6axx.dll, 0xc0000005) on a laptop with an AMD
|
||||
/// 780M beside an RTX 5060, under wgpu's every-backend default and under Vulkan alike (#155); both ran with
|
||||
/// WGPU_BACKEND=dx12. On that laptop DX12's high-performance pick is the NVIDIA GPU, so the rule looks at every GPU,
|
||||
/// not the pick. A PC with only NVIDIA's GPUs, a PC with no GPU, a Mac or Linux, and a WGPU_BACKEND someone set
|
||||
/// not the pick. A Snapdragon PC's Adreno too (#82): under Vulkan Vello's 2D pages came out striped and with grey boxes
|
||||
/// behind fading text on an Adreno X1-85, and on DX12 they were clean. A PC with only NVIDIA's GPUs, a PC with no GPU,
|
||||
/// a Mac or Linux, and a WGPU_BACKEND someone set
|
||||
/// (Windows' check sets vulkan, for lavapipe) keep wgpu's own pick.
|
||||
pub fn dx12_first(windows: bool, env: Option<wgpu::Backends>, dx12: &[(u32, wgpu::DeviceType)]) -> bool {
|
||||
windows && env.is_none() && dx12.iter().any(|&(vendor, kind)| matches!(vendor, INTEL | AMD) && kind != wgpu::DeviceType::Cpu)
|
||||
windows && env.is_none() && dx12.iter().any(|&(vendor, kind)| (matches!(vendor, INTEL | AMD) || QUALCOMM.contains(&vendor)) && kind != wgpu::DeviceType::Cpu)
|
||||
}
|
||||
|
||||
/// The backends every wgpu instance of raea's asks for (the shared device's, Bevy's own when it isn't there, systems/k's
|
||||
@@ -147,6 +151,8 @@ mod tests {
|
||||
assert!(dx12_first(true, None, &[(AMD, igpu), (0x10de, dgpu), warp]), "#155: an AMD 780M beside an RTX 5060 (DX12 picks the NVIDIA)");
|
||||
assert!(dx12_first(true, None, &[(0x10de, dgpu), (AMD, igpu)]), "the same laptop listed NVIDIA first");
|
||||
assert!(dx12_first(true, None, &[(AMD, dgpu)]), "an AMD Radeon card");
|
||||
assert!(dx12_first(true, None, &[(0x4D4F_4351, igpu), warp]), "#82: a Snapdragon's Adreno (DXGI's QCOM)");
|
||||
assert!(dx12_first(true, None, &[(0x5143, igpu)]), "#82: an Adreno reported by its PCI id");
|
||||
assert!(dx12_first(true, None, &[(INTEL, igpu), (0x10de, dgpu)]), "an Intel laptop with an NVIDIA GPU");
|
||||
assert!(!dx12_first(true, Some(Backends::VULKAN), &[(INTEL, igpu)]), "WGPU_BACKEND=vulkan is kept");
|
||||
assert!(!dx12_first(true, Some(Backends::DX12), &[(AMD, igpu)]), "WGPU_BACKEND set: wgpu's own read of it");
|
||||
|
||||
+7
-1
@@ -11,5 +11,11 @@ raea-io-codec = { path = "../codec", features = ["mux"] }
|
||||
raea-io-soft = { path = "../soft" }
|
||||
muxide = "0.2"
|
||||
# from the v1.1.0 tag: the crates.io package leaves out src/arm/asm-offsets.h, which its arm assembly includes
|
||||
rav1d = { git = "https://github.com/memorysafety/rav1d", tag = "v1.1.0" }
|
||||
rav1d = { git = "https://github.com/memorysafety/rav1d", tag = "v1.1.0", default-features = false, features = ["bitdepth_8", "bitdepth_16"] }
|
||||
rav1e = { version = "0.8", default-features = false, features = ["threading"] }
|
||||
|
||||
# rav1d's assembly everywhere but Windows on ARM (#82): there its arm64 .S files are GNU syntax, which MSVC's cl.exe
|
||||
# skips (the link then fails), and building them with clang-cl instead breaks metis-sys's GKlib headers. The Rust and
|
||||
# C paths decode the same frames, slower.
|
||||
[target.'cfg(not(all(windows, target_arch = "aarch64")))'.dependencies]
|
||||
rav1d = { git = "https://github.com/memorysafety/rav1d", tag = "v1.1.0", features = ["asm", "asm_arm64_dotprod", "asm_arm64_i8mm", "asm_arm64_sve2"] }
|
||||
+33
-2
@@ -35,7 +35,7 @@ pub fn decode_audio_symphonia(path: &Path) -> R<Audio> {
|
||||
.find(|t| t.codec_params.sample_rate.is_some())
|
||||
.ok_or("no audio track")?
|
||||
.clone();
|
||||
let mut dec = symphonia::default::get_codecs()
|
||||
let mut dec = crate::opusdec::codecs()
|
||||
.make(&track.codec_params, &DecoderOptions::default())
|
||||
.map_err(|e| format!("symphonia: {e}"))?;
|
||||
let mut rate = track.codec_params.sample_rate.unwrap_or(0);
|
||||
@@ -129,7 +129,7 @@ pub fn decode_audio_window_symphonia(path: &Path, start: f64, secs: f64) -> R<Au
|
||||
.map_err(|e| format!("symphonia: {e}"))?;
|
||||
let mut format = probed.format;
|
||||
let track = format.tracks().iter().find(|t| t.codec_params.sample_rate.is_some()).ok_or("no audio track")?.clone();
|
||||
let mut dec = symphonia::default::get_codecs().make(&track.codec_params, &DecoderOptions::default()).map_err(|e| format!("symphonia: {e}"))?;
|
||||
let mut dec = crate::opusdec::codecs().make(&track.codec_params, &DecoderOptions::default()).map_err(|e| format!("symphonia: {e}"))?;
|
||||
let rate = track.codec_params.sample_rate.unwrap_or(0);
|
||||
if rate == 0 {
|
||||
return Err(format!("{}: the sound track has no sample rate", path.display()));
|
||||
@@ -356,3 +356,34 @@ mod window_tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod opus_tests {
|
||||
use raea_io_codec::Audio;
|
||||
|
||||
/// Opus packets as this backend writes them decode back here (#242: no decoder took them, so raea's own MP4s read
|
||||
/// as silent off the Mac): a 440 Hz tone, mono and stereo, comes back at its length and its level.
|
||||
#[test]
|
||||
fn opus_written_here_reads_back() {
|
||||
for channels in [1usize, 2] {
|
||||
let tone: Vec<f32> = (0..48_000).map(|i| 0.5 * (i as f32 * 440.0 * std::f32::consts::TAU / 48_000.0).sin()).collect();
|
||||
let a = Audio { rate: 48_000, channels: vec![tone; channels] };
|
||||
let packets = super::opus_packets(&a).unwrap();
|
||||
let mut dec = crate::packets::AudioPacketDecoder::new("opus", None, 48_000, channels as u32).unwrap();
|
||||
let mut out = vec![Vec::new(); channels];
|
||||
for (_, p) in &packets {
|
||||
let (rate, planes) = dec.decode(p).unwrap();
|
||||
assert_eq!(rate, 48_000);
|
||||
assert_eq!(planes.len(), channels);
|
||||
for (o, p) in out.iter_mut().zip(&planes) {
|
||||
o.extend_from_slice(p);
|
||||
}
|
||||
}
|
||||
let n = out[0].len();
|
||||
assert!((47_000..=49_500).contains(&n), "{channels} channel(s): {n} samples back from 48000");
|
||||
// past the coder's start, the tone's level (0.5 peak is 0.354 RMS)
|
||||
let rms = (out[0][4800..n - 4800].iter().map(|v| v * v).sum::<f32>() / (n - 9600) as f32).sqrt();
|
||||
assert!((rms - 0.354).abs() < 0.03, "{channels} channel(s): RMS {rms}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,8 @@
|
||||
mod audio;
|
||||
#[cfg(feature = "h264")]
|
||||
mod h264;
|
||||
/// Opus read back (libopus) as a Symphonia decoder, and the registry every decoder here is made from
|
||||
mod opusdec;
|
||||
/// packet-level audio decoding (Symphonia), for coders handed packets
|
||||
pub mod packets;
|
||||
mod probe;
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
//! Opus read back (libopus), as a Symphonia decoder: Symphonia's MP4 reader finds an Opus track and has no decoder for
|
||||
//! it, so the MP4s this backend writes itself (H.264 + Opus) came back without their sound wherever no platform reader
|
||||
//! stood in front (raea #242: on Windows `raea media probe` listed no audio and `raea media share` wrote a silent copy).
|
||||
//! `codecs()` is Symphonia's registry with this one added; every decoder here is made from it.
|
||||
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
|
||||
use symphonia::core::audio::{AsAudioBufferRef, AudioBuffer, AudioBufferRef, Channels, Signal, SignalSpec};
|
||||
use symphonia::core::codecs::{CODEC_TYPE_OPUS, CodecDescriptor, CodecParameters, CodecRegistry, Decoder, DecoderOptions, FinalizeResult};
|
||||
use symphonia::core::errors::{Result, decode_error, unsupported_error};
|
||||
use symphonia::core::formats::Packet;
|
||||
use symphonia::core::support_codec;
|
||||
|
||||
/// Opus always decodes at 48 kHz, and a packet holds at most 120 ms of it
|
||||
const RATE: u32 = 48_000;
|
||||
const MAX_FRAMES: usize = 5760;
|
||||
|
||||
pub struct OpusDecoder {
|
||||
params: CodecParameters,
|
||||
/// (behind a lock only because a Symphonia decoder must be Sync, which libopus's state isn't: one caller at a time)
|
||||
dec: Mutex<opus::Decoder>,
|
||||
channels: usize,
|
||||
pcm: Vec<f32>,
|
||||
buf: AudioBuffer<f32>,
|
||||
}
|
||||
|
||||
/// Symphonia's own codecs and Opus.
|
||||
pub fn codecs() -> &'static CodecRegistry {
|
||||
static ALL: OnceLock<CodecRegistry> = OnceLock::new();
|
||||
ALL.get_or_init(|| {
|
||||
let mut r = CodecRegistry::new();
|
||||
symphonia::default::register_enabled_codecs(&mut r);
|
||||
r.register_all::<OpusDecoder>();
|
||||
r
|
||||
})
|
||||
}
|
||||
|
||||
/// How many channels an Opus track has: its identification header's count (OpusHead, as an MP4's dOps box and an Ogg
|
||||
/// stream's first packet both carry it: 8 bytes of magic, a version, the count), else what the container said.
|
||||
fn channel_count(p: &CodecParameters) -> usize {
|
||||
let head = p.extra_data.as_deref().filter(|d| d.len() > 9 && d.starts_with(b"OpusHead")).map(|d| d[9] as usize);
|
||||
let said = p.channels.map(|c| c.count()).or(p.channel_layout.map(|l| l.into_channels().count()));
|
||||
head.or(said).unwrap_or(2)
|
||||
}
|
||||
|
||||
impl Decoder for OpusDecoder {
|
||||
fn try_new(params: &CodecParameters, _: &DecoderOptions) -> Result<Self> {
|
||||
if params.codec != CODEC_TYPE_OPUS {
|
||||
return unsupported_error("opus: not an Opus track");
|
||||
}
|
||||
// mono and stereo (what raea writes, and nearly every Opus file): a surround stream is several coupled streams
|
||||
// under a mapping, which this isn't
|
||||
let (channels, layout, how) = match channel_count(params) {
|
||||
1 => (1, Channels::FRONT_LEFT, opus::Channels::Mono),
|
||||
2 => (2, Channels::FRONT_LEFT | Channels::FRONT_RIGHT, opus::Channels::Stereo),
|
||||
_ => return unsupported_error("opus: more than two channels"),
|
||||
};
|
||||
let dec = match opus::Decoder::new(RATE, how) {
|
||||
Ok(d) => d,
|
||||
Err(_) => return unsupported_error("opus: the decoder didn't start"),
|
||||
};
|
||||
let mut params = params.clone();
|
||||
params.with_sample_rate(RATE).with_channels(layout);
|
||||
Ok(OpusDecoder { params, dec: Mutex::new(dec), channels, pcm: vec![0.0; MAX_FRAMES * channels], buf: AudioBuffer::new(MAX_FRAMES as u64, SignalSpec::new(RATE, layout)) })
|
||||
}
|
||||
|
||||
fn supported_codecs() -> &'static [CodecDescriptor] {
|
||||
&[support_codec!(CODEC_TYPE_OPUS, "opus", "Opus")]
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
if let Ok(d) = self.dec.get_mut() {
|
||||
let _ = d.reset_state();
|
||||
}
|
||||
}
|
||||
|
||||
fn codec_params(&self) -> &CodecParameters {
|
||||
&self.params
|
||||
}
|
||||
|
||||
fn decode(&mut self, packet: &Packet) -> Result<AudioBufferRef<'_>> {
|
||||
self.buf.clear();
|
||||
let n = match self.dec.get_mut().map(|d| d.decode_float(packet.buf(), &mut self.pcm, false)) {
|
||||
Ok(Ok(n)) => n,
|
||||
_ => return decode_error("opus: a packet didn't decode"),
|
||||
};
|
||||
self.buf.render_reserved(Some(n));
|
||||
for c in 0..self.channels {
|
||||
for (o, i) in self.buf.chan_mut(c).iter_mut().zip(self.pcm.iter().skip(c).step_by(self.channels)) {
|
||||
*o = *i;
|
||||
}
|
||||
}
|
||||
Ok(self.buf.as_audio_buffer_ref())
|
||||
}
|
||||
|
||||
fn finalize(&mut self) -> FinalizeResult {
|
||||
FinalizeResult::default()
|
||||
}
|
||||
|
||||
fn last_decoded(&self) -> AudioBufferRef<'_> {
|
||||
self.buf.as_audio_buffer_ref()
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Packet-level audio decoding (Symphonia), for coders handed compressed packets one at a time: AAC (with its
|
||||
//! AudioSpecificConfig), MP3, FLAC, PCM, as Symphonia reads them. Planar f32 out.
|
||||
//! AudioSpecificConfig), MP3, FLAC, PCM, as Symphonia reads them, and Opus (opusdec.rs). Planar f32 out.
|
||||
|
||||
use symphonia::core::audio::{AudioBufferRef, Signal};
|
||||
use symphonia::core::codecs::{CodecParameters, Decoder, DecoderOptions};
|
||||
@@ -19,7 +19,8 @@ fn codec_type(codec: &str) -> R<symphonia::core::codecs::CodecType> {
|
||||
"mp4a" | "aac" => CODEC_TYPE_AAC,
|
||||
"mp3" => CODEC_TYPE_MP3,
|
||||
"flac" => CODEC_TYPE_FLAC,
|
||||
o => return Err(format!("{o}: audio decodes here as aac, mp3 or flac")),
|
||||
"opus" => CODEC_TYPE_OPUS,
|
||||
o => return Err(format!("{o}: audio decodes here as aac, mp3, flac or opus")),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -37,7 +38,7 @@ impl AudioPacketDecoder {
|
||||
} {
|
||||
p.with_channel_layout(layout);
|
||||
}
|
||||
let dec = symphonia::default::get_codecs().make(&p, &DecoderOptions::default()).map_err(|e| format!("symphonia: {e}"))?;
|
||||
let dec = crate::opusdec::codecs().make(&p, &DecoderOptions::default()).map_err(|e| format!("symphonia: {e}"))?;
|
||||
Ok(AudioPacketDecoder { dec, ts: 0 })
|
||||
}
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ use std::time::{Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub mod once;
|
||||
mod crash;
|
||||
mod look;
|
||||
mod props;
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
//! An error that repeats, said once (#239): a failing audio device calls its stream's error callback without pause.
|
||||
|
||||
/// A device's error said once, then only how often it came back (at its 10th, 100th, ... time, and never more than once
|
||||
/// a second): a failing ALSA device calls a stream's error callback without pause, and every call printed a line: #239's
|
||||
/// app.log reached 40 GB of one line in two days.
|
||||
pub fn said_once<E: std::fmt::Display>(what: &'static str) -> impl FnMut(E) + Send + 'static {
|
||||
let mut seen = Repeats::default();
|
||||
move |e| {
|
||||
let m = e.to_string();
|
||||
match seen.hit(&m, std::time::Instant::now()) {
|
||||
Some(1) => eprintln!("{what}: {m}"),
|
||||
Some(n) => eprintln!("{what}: {m} ({n} times now)"),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Which of an error's repeats get said: `hit` answers with the count to print, or nothing.
|
||||
#[derive(Default)]
|
||||
struct Repeats {
|
||||
last: String,
|
||||
n: u64,
|
||||
next: u64,
|
||||
at: Option<std::time::Instant>,
|
||||
}
|
||||
|
||||
impl Repeats {
|
||||
fn hit(&mut self, m: &str, now: std::time::Instant) -> Option<u64> {
|
||||
if m != self.last || self.n == 0 {
|
||||
(self.last, self.n, self.next) = (m.to_string(), 0, 1);
|
||||
}
|
||||
self.n += 1;
|
||||
let soon = self.at.is_some_and(|t| now.duration_since(t).as_secs() < 1);
|
||||
if self.n < self.next || (soon && self.n > 1) {
|
||||
return None;
|
||||
}
|
||||
self.next = self.n.saturating_mul(10);
|
||||
self.at = Some(now);
|
||||
Some(self.n)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::Repeats;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// #239: half a billion repeats of one ALSA error were half a billion lines. Two days of them are a handful.
|
||||
#[test]
|
||||
fn a_repeating_error_is_a_handful_of_lines() {
|
||||
let (mut r, t0) = (Repeats::default(), Instant::now());
|
||||
// 5,000 a second for a minute
|
||||
let said = (0..300_000u64).filter(|i| r.hit("alsa::poll() returned POLLERR", t0 + Duration::from_micros(i * 200)).is_some()).count();
|
||||
assert!(said <= 8, "{said} lines for 300,000 repeats");
|
||||
assert_eq!(Repeats::default().hit("x", t0), Some(1), "the first is always said");
|
||||
// another error is said at once, when a second has gone by
|
||||
assert_eq!(r.hit("the device went away", t0 + Duration::from_secs(120)), Some(1));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "raea-runtime-cut-plan"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "A cut job held to its client's brief: every rule quoting the brief, the count and open items, and each delivered file's shape, words heard, banned phrases, CTA and frames check, from what's on disk (docs/make.feature MK25-MK27)"
|
||||
|
||||
[dependencies]
|
||||
# the contract: `make: cut({...})` on brief.ts
|
||||
raea-core-brief = { path = "../../core/brief" }
|
||||
# a delivered file's size and length from its header boxes, the media never read
|
||||
raea-io-soft = { path = "../../io/soft" }
|
||||
serde_json = "1"
|
||||
@@ -0,0 +1,265 @@
|
||||
//! A cut job's gates (docs/make.feature MK25-MK27): the brief as rules (`make: cut({...})`, core/brief cut.rs), held
|
||||
//! from what's on disk. The quotes: every rule's `from` is in the brief's text. The count: as many cuts as the brief
|
||||
//! asks for, or an answer saying why not. The open items: each answered. Then each delivered file: its shape and
|
||||
//! length; its words, heard after its last change (FILE.words.json, `raea words`), with every `say` phrase heard or
|
||||
//! shown, no `never` phrase in its words or its text, and the CTA in its last seconds; and its frames check, run after
|
||||
//! its last change (FILE.frames-check.json, `raea frames check`), with no face cut and no text too small.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use raea_core_brief::cut::{self, Cut, norm};
|
||||
use serde_json::Value;
|
||||
|
||||
/// One gate as `raea make status` lists it (a goal's are the same kind)
|
||||
pub use raea_core_brief::make::Gate;
|
||||
|
||||
fn gate(name: &'static str, of: Option<&str>, clear: bool, says: String) -> Gate {
|
||||
Gate { name, of: of.map(str::to_string), clear, says }
|
||||
}
|
||||
|
||||
/// A delivered file's width, height and seconds, from its header boxes (io/soft's probe: the media isn't read, and a
|
||||
/// file re-encoded after its render is read as it is now).
|
||||
fn shape(f: &Path) -> Option<(u32, u32, f64)> {
|
||||
raea_io_soft::probe(f).ok().map(|p| (p.width.round() as u32, p.height.round() as u32, p.secs))
|
||||
}
|
||||
|
||||
/// A report beside the file (FILE.words.json, FILE.frames-check.json), read when it's newer than the file (a report
|
||||
/// from before the last change says nothing about it now): Ok(json), or Err(why not).
|
||||
fn fresh(f: &Path, ext: &str, run: &str) -> Result<Value, String> {
|
||||
let r = f.with_extension(ext);
|
||||
let changed = |p: &Path| -> Option<std::time::SystemTime> { p.metadata().ok()?.modified().ok() };
|
||||
let Some(at) = changed(&r) else { return Err(format!("never run: {run}")) };
|
||||
if changed(f).is_some_and(|m| m > at) {
|
||||
return Err(format!("the file changed after it: {run} again"));
|
||||
}
|
||||
std::fs::read_to_string(&r).ok().and_then(|s| serde_json::from_str(&s).ok()).ok_or_else(|| format!("{} isn't JSON: {run} again", r.display()))
|
||||
}
|
||||
|
||||
/// What a file says: its heard words with their times in seconds (`raea words`: start/end, or start_ms/end_ms).
|
||||
fn heard(words: &Value) -> Vec<(String, f64, f64)> {
|
||||
let list = words.as_array().or_else(|| words["words"].as_array()).cloned().unwrap_or_default();
|
||||
list.iter()
|
||||
.filter_map(|w| {
|
||||
let t = norm(w["text"].as_str().or_else(|| w["word"].as_str())?);
|
||||
let at = |k: &str| w[k].as_f64().or(w[format!("{k}_ms")].as_f64().map(|ms| ms * 0.001));
|
||||
let s = at("start")?;
|
||||
let e = at("end").unwrap_or(s);
|
||||
(!t.is_empty()).then_some((t, s, e))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// What a file shows: each text of its render manifest (FILE.render.json) and the second it's first on screen.
|
||||
fn shown(manifest: &Value) -> Vec<(String, f64)> {
|
||||
let fps = manifest["fps"].as_f64().filter(|f| *f > 0.0).unwrap_or(30.0);
|
||||
let mut out: Vec<(String, f64)> = Vec::new();
|
||||
for fr in manifest["frames"].as_array().into_iter().flatten() {
|
||||
let at = fr["frame"].as_f64().unwrap_or(0.0) / fps;
|
||||
for t in fr["text"].as_array().into_iter().flatten() {
|
||||
let s = norm(t["text"].as_str().unwrap_or(""));
|
||||
if !s.is_empty() && t["opacity"].as_f64().unwrap_or(1.0) > 0.05 && !out.iter().any(|(o, _)| *o == s) {
|
||||
out.push((s, at));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `phrase` in `text` as whole words.
|
||||
fn has(text: &str, phrase: &str) -> bool {
|
||||
!phrase.is_empty() && format!(" {text} ").contains(&format!(" {phrase} "))
|
||||
}
|
||||
|
||||
/// `got`'s words with each compound the brief writes as one word joined back ("wish list" heard, "Wishlist" written),
|
||||
/// each with the index of its first word in `got`.
|
||||
fn joined<'a>(got: &[&'a str], want: &[&str]) -> Vec<(String, usize)> {
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < got.len() {
|
||||
let k = (2..=3).rev().find(|&k| i + k <= got.len() && want.contains(&got[i..i + k].concat().as_str())).unwrap_or(1);
|
||||
out.push((got[i..i + k].concat(), i));
|
||||
i += k;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Where `phrase` (normalised) is first said in `got`: the index of its first word. Its words in order, compounds
|
||||
/// joined, each at most `gap` words after the one before (1: word for word; people say "it's free, it's fun, and it's
|
||||
/// easy" for "free, fun, and easy", which a gap of 2 takes and a reordered "fun, free, and easy" doesn't).
|
||||
fn said_at(got: &[&str], phrase: &str, gap: usize) -> Option<usize> {
|
||||
let want: Vec<&str> = phrase.split(' ').filter(|w| !w.is_empty()).collect();
|
||||
let got = joined(got, &want);
|
||||
(0..got.len()).find(|&s| {
|
||||
if want.is_empty() || got[s].0 != want[0] {
|
||||
return false;
|
||||
}
|
||||
let mut at = s;
|
||||
want[1..].iter().all(|w| match (at + 1..(at + 1 + gap).min(got.len())).find(|&j| got[j].0 == *w) {
|
||||
Some(j) => {
|
||||
at = j;
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
})
|
||||
})
|
||||
.map(|s| got[s].1)
|
||||
}
|
||||
|
||||
/// How far apart a `say` phrase's words may be heard.
|
||||
const SAY_GAP: usize = 2;
|
||||
|
||||
/// The share of `want`'s words that `got` has in order (longest common subsequence): a CTA heard with a word misheard
|
||||
/// still lands.
|
||||
fn in_order(want: &[&str], got: &[&str]) -> f64 {
|
||||
if want.is_empty() {
|
||||
return 1.0;
|
||||
}
|
||||
let mut row = vec![0usize; got.len() + 1];
|
||||
for w in want {
|
||||
let mut prev = 0;
|
||||
for (j, g) in got.iter().enumerate() {
|
||||
let keep = row[j + 1];
|
||||
row[j + 1] = if w == g { prev + 1 } else { row[j + 1].max(row[j]) };
|
||||
prev = keep;
|
||||
}
|
||||
}
|
||||
row[got.len()] as f64 / want.len() as f64
|
||||
}
|
||||
|
||||
/// How much of the CTA a run of words must have, in order.
|
||||
const CTA_SHARE: f64 = 0.85;
|
||||
|
||||
/// One delivered file's gates: shape, words (say, never, cta) and frames.
|
||||
fn file_gates(c: &Cut, plan: &cut::CutPlan, format: &str, f: &Path, rel: &str, said: &mut Vec<(usize, String)>) -> Vec<Gate> {
|
||||
let mut out = Vec::new();
|
||||
let shape = shape(f);
|
||||
match (shape, cut::ratio(format), cut::seconds(c, plan)) {
|
||||
(None, ..) => out.push(gate("shape", Some(rel), false, "not an MP4 or MOV with a video track".into())),
|
||||
(Some((w, h, secs)), Some((rw, rh)), len) => {
|
||||
let mut wrong = Vec::new();
|
||||
let (want, got) = (rw as f64 / rh as f64, w as f64 / h.max(1) as f64);
|
||||
if (got / want - 1.0).abs() > 0.02 {
|
||||
wrong.push(format!("{w}x{h} isn't {format}"));
|
||||
}
|
||||
if let Some([a, b]) = len
|
||||
&& (secs + 0.05 < a || secs > b + 0.05)
|
||||
{
|
||||
wrong.push(format!("{secs:.1} s isn't {a}-{b} s"));
|
||||
}
|
||||
out.push(gate("shape", Some(rel), wrong.is_empty(), if wrong.is_empty() { format!("{w}x{h}, {secs:.1} s") } else { wrong.join("; ") }));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
// what it says and shows
|
||||
match fresh(f, "words.json", &format!("raea words {rel}")) {
|
||||
Err(why) => out.push(gate("words", Some(rel), false, why)),
|
||||
Ok(w) => {
|
||||
let words = heard(&w);
|
||||
let spoken: Vec<&str> = words.iter().map(|(t, ..)| t.as_str()).collect();
|
||||
let screen = std::fs::read_to_string(f.with_extension("render.json")).ok().and_then(|s| serde_json::from_str::<Value>(&s).ok()).map(|m| shown(&m)).unwrap_or_default();
|
||||
let on_screen = |s: &str, p: &str, gap| said_at(&s.split(' ').collect::<Vec<_>>(), p, gap).is_some();
|
||||
let on = |p: &str| said_at(&spoken, p, SAY_GAP).is_some() || screen.iter().any(|(s, _)| on_screen(s, p, SAY_GAP));
|
||||
let missing: Vec<&str> = c.say.iter().filter(|p| p.every != Some(false) && !on(&norm(&p.text))).map(|p| p.text.as_str()).collect();
|
||||
said.extend(c.say.iter().enumerate().filter(|(_, p)| on(&norm(&p.text))).map(|(i, _)| (i, rel.to_string())));
|
||||
out.push(gate("say", Some(rel), missing.is_empty(), if missing.is_empty() { format!("says all {} of its phrases", c.say.iter().filter(|p| p.every != Some(false)).count()) } else { format!("never says or shows: {}", missing.iter().map(|m| format!("\"{m}\"")).collect::<Vec<_>>().join(", ")) }));
|
||||
let banned: Vec<String> = c
|
||||
.never
|
||||
.iter()
|
||||
.filter_map(|p| {
|
||||
let n = norm(&p.text);
|
||||
if let Some(i) = said_at(&spoken, &n, 1) {
|
||||
return Some(format!("\"{}\" heard at {:.1} s (brief: {})", p.text, words[i].1, p.from));
|
||||
}
|
||||
screen.iter().find(|(s, _)| on_screen(s, &n, 1)).map(|(_, at)| format!("\"{}\" on screen at {at:.1} s (brief: {})", p.text, p.from))
|
||||
})
|
||||
.collect();
|
||||
out.push(gate("never", Some(rel), banned.is_empty(), if banned.is_empty() { "says and shows none of the banned phrases".into() } else { banned.join("; ") }));
|
||||
if let Some(cta) = &c.cta {
|
||||
let within = cta.within.unwrap_or(cut::CTA_WITHIN);
|
||||
let end = shape.map(|s| s.2).or_else(|| words.last().map(|w| w.2)).unwrap_or(0.0);
|
||||
let last: Vec<&str> = words.iter().filter(|w| w.2 >= end - within).map(|w| w.0.as_str()).collect();
|
||||
// the share of a line's words, in order, in `got`; the best of the brief's lines
|
||||
let share = |line: &str, got: &[&str]| {
|
||||
let want_s = norm(line);
|
||||
let want: Vec<&str> = want_s.split(' ').collect();
|
||||
let j = joined(got, &want);
|
||||
in_order(&want, &j.iter().map(|(w, _)| w.as_str()).collect::<Vec<_>>())
|
||||
};
|
||||
let lines: Vec<&str> = std::iter::once(cta.text.as_str()).chain(cta.also.iter().map(String::as_str)).collect();
|
||||
// the line heard most, the first of equals (none when no line's words were heard)
|
||||
let heard: Vec<_> = lines.iter().map(|l| share(l, &last)).collect();
|
||||
let heard_share = heard.iter().copied().fold(0.0, f64::max);
|
||||
let best = lines.iter().zip(&heard).find(|(_, h)| heard_share > 0.0 && **h == heard_share).map_or("", |(l, _)| *l);
|
||||
let on_screen = screen.iter().any(|(s, at)| *at >= end - within && lines.iter().any(|l| share(l, &s.split(' ').collect::<Vec<_>>()) >= CTA_SHARE));
|
||||
let ok = heard_share >= CTA_SHARE || on_screen;
|
||||
let says = match (ok, on_screen) {
|
||||
(true, true) => "ends on the CTA (on screen)".to_string(),
|
||||
(true, false) => format!("ends on the CTA (heard: \"{best}\")"),
|
||||
_ => format!("no CTA in its last {within:.0} s ({:.0}% of the nearest one's words heard there): \"{}\"", heard_share * 100.0, if best.is_empty() { &cta.text } else { best }),
|
||||
};
|
||||
out.push(gate("cta", Some(rel), ok, says));
|
||||
}
|
||||
}
|
||||
}
|
||||
// faces whole, text big enough: the frames check of the file as it is now
|
||||
if c.frames != Some(false) {
|
||||
match fresh(f, "frames-check.json", &format!("raea frames check {rel}")) {
|
||||
Err(why) => out.push(gate("frames", Some(rel), false, why)),
|
||||
Ok(r) => {
|
||||
let errors: Vec<&str> = r["findings"].as_array().into_iter().flatten().filter(|x| x["level"] == "error").filter_map(|x| x["says"].as_str()).collect();
|
||||
out.push(gate("frames", Some(rel), errors.is_empty(), match errors.as_slice() {
|
||||
[] => "no face cut, no text too small".into(),
|
||||
[one] => one.to_string(),
|
||||
many => format!("{} errors, first: {}", many.len(), many[0]),
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The cut job's gates over its brief folder `dir`.
|
||||
pub fn gates(c: &Cut, dir: &Path) -> Vec<Gate> {
|
||||
let mut out = Vec::new();
|
||||
// the quotes: each rule is backed by the brief's own words
|
||||
match std::fs::read_to_string(dir.join(&c.brief)) {
|
||||
Err(_) => out.push(gate("quotes", None, false, format!("no brief text at {}: pdftotext -layout BRIEF.pdf {}", c.brief, c.brief))),
|
||||
Ok(t) => {
|
||||
let text = norm(&t);
|
||||
let unfound: Vec<String> = cut::quotes(c).into_iter().filter(|(_, from)| !has(&text, &norm(from))).map(|(what, from)| format!("{what} (\"{}\")", from.chars().take(60).collect::<String>())).collect();
|
||||
out.push(gate("quotes", None, unfound.is_empty(), if unfound.is_empty() { format!("all {} rules quote the brief", cut::quotes(c).len()) } else { format!("not in the brief's text, word for word: {}", unfound.join("; ")) }));
|
||||
}
|
||||
}
|
||||
let answered = |about: &str| c.open.iter().any(|o| o.about.as_deref() == Some(about) && o.answer.as_deref().is_some_and(|a| !a.trim().is_empty()));
|
||||
if let Some(n) = &c.count {
|
||||
let have = c.cuts.len() as u32;
|
||||
let ok = have >= n.value || answered("count");
|
||||
out.push(gate("count", None, ok, if have >= n.value { format!("{have} cuts planned; the brief asks for {}", n.value) } else if ok { format!("{have} of the brief's {} cuts, as answered", n.value) } else { format!("{have} cuts planned; the brief asks for {} (\"{}\"): plan them, or add an `open` item about \"count\" and get it answered", n.value, n.from) }));
|
||||
}
|
||||
for o in &c.open {
|
||||
let ok = o.answer.as_deref().is_some_and(|a| !a.trim().is_empty());
|
||||
out.push(gate("open", o.about.as_deref(), ok, if ok { format!("{} -> {}{}", o.question, o.answer.as_deref().unwrap_or(""), o.by.as_deref().map(|b| format!(" ({b})")).unwrap_or_default()) } else { format!("unanswered: {} (brief: \"{}\"): ask at the review, then write the answer and who gave it", o.question, o.from) }));
|
||||
}
|
||||
let mut said: Vec<(usize, String)> = Vec::new();
|
||||
for p in &c.cuts {
|
||||
for fmt in cut::formats(c, p) {
|
||||
let rel = cut::file(p, fmt);
|
||||
let f = dir.join(&rel);
|
||||
if f.is_file() {
|
||||
out.extend(file_gates(c, p, fmt, &f, &rel, &mut said));
|
||||
}
|
||||
}
|
||||
}
|
||||
// a phrase one cut is enough for
|
||||
for (i, p) in c.say.iter().enumerate() {
|
||||
if p.every != Some(false) {
|
||||
continue;
|
||||
}
|
||||
let by = said.iter().find_map(|(j, f)| (*j == i).then_some(f));
|
||||
out.push(gate("say-once", None, by.is_some(), if let Some(f) = by { format!("\"{}\" in {f}", p.text) } else { format!("no cut says or shows \"{}\" (brief: \"{}\")", p.text, p.from) }));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,199 @@
|
||||
//! A cut job held to its brief (MK25-MK27): the contract's doctor, the quotes, the count and open items, and each
|
||||
//! delivered file's shape, words and frames. The delivered file is raea's 3 s 320x180 test clip.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
use raea_core_brief::{cut, make::Make, read};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::{Gate, gates};
|
||||
|
||||
const CLIP: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../../engine/rune/media/tests/fixtures/clip.mp4");
|
||||
|
||||
fn dir(name: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("raea-cut-plan-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
fn put(d: &Path, rel: &str, bytes: &[u8]) -> PathBuf {
|
||||
let p = d.join(rel);
|
||||
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
std::fs::write(&p, bytes).unwrap();
|
||||
p
|
||||
}
|
||||
|
||||
/// `p` as changed `secs` from now (a report written after its video is newer than it)
|
||||
fn touch(p: &Path, secs: i64) {
|
||||
let t = if secs >= 0 { SystemTime::now() + Duration::from_secs(secs as u64) } else { SystemTime::now() - Duration::from_secs((-secs) as u64) };
|
||||
std::fs::File::options().write(true).open(p).unwrap().set_modified(t).unwrap();
|
||||
}
|
||||
|
||||
const BRIEF: &str = "Deliverables: 10 total videos (4 solos / 1 mashup per angle).\nUse the phrase \"free, fun, and easy.\"\nDon't let it read as White Elephant.\nEnd on the CTA: \"Make your Wishlist and organize your Gift Exchange on Elfster. It's free.\"\nCTV specs from the client [TO CONFIRM]\n";
|
||||
|
||||
fn contract(extra: &str) -> Make {
|
||||
read(
|
||||
"make",
|
||||
&format!(
|
||||
r#"{{"kind": "cut", "cut": {{"brief": "media/brief.txt", "count": {{"value": 2, "from": "10 total videos"}}, "seconds": [2, 4], "formats": ["16:9"],
|
||||
"cuts": [{{"id": "a1_s1", "angle": "1", "hook": "Direct Problem", "text": "captions"}}, {{"id": "a1_s2"}}],
|
||||
"say": [{{"text": "free, fun, and easy", "from": "Use the phrase \"free, fun, and easy.\""}}],
|
||||
"never": [{{"text": "white elephant", "from": "Don't let it read as White Elephant."}}],
|
||||
"cta": {{"text": "Make your Wishlist and organize your Gift Exchange on Elfster. It's free.", "from": "End on the CTA"}}{extra}}}}}"#
|
||||
),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn run(m: &Make, d: &Path) -> Vec<Gate> {
|
||||
gates(m.cut.as_ref().unwrap(), d)
|
||||
}
|
||||
|
||||
fn named<'a>(g: &'a [Gate], name: &str) -> Vec<&'a Gate> {
|
||||
g.iter().filter(|g| g.name == name).collect()
|
||||
}
|
||||
|
||||
fn of(g: &[Gate], name: &str, file: &str) -> Gate {
|
||||
g.iter().find(|g| g.name == name && g.of.as_deref() == Some(file)).unwrap_or_else(|| panic!("no {name} gate of {file}")).clone()
|
||||
}
|
||||
|
||||
/// Words said evenly from 0.5 s, one every 0.6 s, as `raea words` writes them.
|
||||
fn words(line: &str) -> String {
|
||||
let w: Vec<Value> = line.split_whitespace().enumerate().map(|(i, t)| json!({"text": t, "start": 0.5 + i as f64 * 0.6, "end": 0.8 + i as f64 * 0.6})).collect();
|
||||
serde_json::to_string(&w).unwrap()
|
||||
}
|
||||
|
||||
/// A delivered file (the test clip) with its words and frames check written after it.
|
||||
fn deliver(d: &Path, file: &str, said: &str, frame_errors: &[&str]) {
|
||||
let f = put(d, file, &std::fs::read(CLIP).unwrap());
|
||||
touch(&f, -60);
|
||||
let stem = file.trim_end_matches(".mp4");
|
||||
put(d, &format!("{stem}.words.json"), words(said).as_bytes());
|
||||
let findings: Vec<Value> = frame_errors.iter().map(|e| json!({"level": "error", "kind": "face-cut", "says": e})).collect();
|
||||
put(d, &format!("{stem}.frames-check.json"), json!({"findings": findings}).to_string().as_bytes());
|
||||
}
|
||||
|
||||
const GOOD: &str = "So it draws the names for you it's free fun and easy to set up and everyone makes a wishlist so nobody draws their own name ever again Make your Wishlist and organize your Gift Exchange on Elfster It's free";
|
||||
const S1: &str = "out/cuts/a1_s1_16x9.mp4";
|
||||
const S2: &str = "out/cuts/a1_s2_16x9.mp4";
|
||||
|
||||
#[test]
|
||||
fn the_contract_is_read_and_doctored() {
|
||||
let m = contract("");
|
||||
assert_eq!(m.kind, raea_core_brief::make::Kind::Cut);
|
||||
assert_eq!(raea_core_brief::make::deliverables(&m), vec![S1, S2]);
|
||||
assert!(raea_core_brief::make::doctor(&m).is_empty(), "{:?}", raea_core_brief::make::doctor(&m));
|
||||
let bad: Make = read("make", r#"{"kind": "cut", "cut": {"brief": "b.txt", "cuts": [{"id": "A-1", "formats": ["tall"], "text": "both"}], "say": [{"text": "x", "from": ""}]}}"#).unwrap();
|
||||
let d = raea_core_brief::make::doctor(&bad).join("\n");
|
||||
for want in ["no `count`", "no `cta`", "ids are [a-z0-9_]", "isn't W:H", "no length", "captions, hook or none", "has no `from`"] {
|
||||
assert!(d.contains(want), "{want} in\n{d}");
|
||||
}
|
||||
let none: Make = read("make", r#"{"kind": "cut"}"#).unwrap();
|
||||
assert!(raea_core_brief::make::doctor(&none).iter().any(|x| x.contains("no `cut`")));
|
||||
assert_eq!(cut::norm("24/7 Virtual Vet Care. It’s free!"), "24 7 virtual vet care its free");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_rule_quotes_the_brief() {
|
||||
let d = dir("quotes");
|
||||
assert!(named(&run(&contract(""), &d), "quotes")[0].says.contains("no brief text"));
|
||||
put(&d, "media/brief.txt", BRIEF.as_bytes());
|
||||
assert!(named(&run(&contract(""), &d), "quotes")[0].clear);
|
||||
// a rule the brief doesn't say, or says in other words, is held
|
||||
let invented = contract(r#", "open": [{"question": "Which code?", "from": "the offer is PETS99"}]"#);
|
||||
let g = run(&invented, &d);
|
||||
assert!(!named(&g, "quotes")[0].clear);
|
||||
assert!(named(&g, "quotes")[0].says.contains("Which code?"), "{:?}", named(&g, "quotes"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_count_and_open_items_hold_the_job() {
|
||||
let d = dir("count");
|
||||
put(&d, "media/brief.txt", BRIEF.as_bytes());
|
||||
let mut m = contract("");
|
||||
m.cut.as_mut().unwrap().count.as_mut().unwrap().value = 10;
|
||||
assert!(!named(&run(&m, &d), "count")[0].clear);
|
||||
let mut asked = contract(r#", "open": [{"question": "Only 2 interviews came: cut 2?", "from": "10 total videos", "about": "count"}]"#);
|
||||
asked.cut.as_mut().unwrap().count.as_mut().unwrap().value = 10;
|
||||
let g = run(&asked, &d);
|
||||
assert!(!named(&g, "count")[0].clear, "an open item without its answer doesn't excuse the count");
|
||||
assert!(named(&g, "open")[0].says.starts_with("unanswered"));
|
||||
let o = &mut asked.cut.as_mut().unwrap().open[0];
|
||||
o.answer = Some("yes, the 2 we have".into());
|
||||
o.by = Some("Shane".into());
|
||||
let g = run(&asked, &d);
|
||||
assert!(named(&g, "count")[0].clear && named(&g, "open")[0].clear);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_delivered_cut_is_held_to_its_words_shape_and_frames() {
|
||||
let d = dir("files");
|
||||
put(&d, "media/brief.txt", BRIEF.as_bytes());
|
||||
let m = contract("");
|
||||
deliver(&d, S1, GOOD, &[]);
|
||||
deliver(&d, S2, GOOD, &[]);
|
||||
let g = run(&m, &d);
|
||||
assert!(g.iter().all(|g| g.clear), "{g:#?}");
|
||||
assert_eq!(of(&g, "shape", S1).says, "320x180, 3.0 s");
|
||||
// a banned phrase heard, the CTA cut, a phrase missing, a face cut
|
||||
deliver(&d, S2, "we did a white elephant swap last year and it was chaos so we tried something new", &["a face is cut by the left edge from 4.0 s to 5.5 s"]);
|
||||
let g = run(&m, &d);
|
||||
assert!(of(&g, "never", S2).says.contains("\"white elephant\" heard at 2.3 s"), "{:?}", of(&g, "never", S2));
|
||||
assert!(!of(&g, "say", S2).clear && !of(&g, "cta", S2).clear);
|
||||
assert!(of(&g, "frames", S2).says.contains("left edge"));
|
||||
// a report from before the file's last change says nothing about it now
|
||||
touch(&d.join(S1), 60);
|
||||
let g = run(&m, &d);
|
||||
assert!(of(&g, "words", S1).says.contains("changed after it"), "{:?}", of(&g, "words", S1));
|
||||
assert!(of(&g, "frames", S1).says.contains("changed after it"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_wrong_shape_is_named() {
|
||||
let d = dir("shape");
|
||||
put(&d, "media/brief.txt", BRIEF.as_bytes());
|
||||
let mut m = contract("");
|
||||
let p = &mut m.cut.as_mut().unwrap().cuts[0];
|
||||
p.formats = vec!["9:16".into()];
|
||||
p.seconds = Some([20.0, 30.0]);
|
||||
deliver(&d, "out/cuts/a1_s1_9x16.mp4", GOOD, &[]);
|
||||
let says = of(&run(&m, &d), "shape", "out/cuts/a1_s1_9x16.mp4").says;
|
||||
assert!(says.contains("320x180 isn't 9:16") && says.contains("3.0 s isn't 20-30 s"), "{says}");
|
||||
put(&d, "out/cuts/a1_s1_9x16.mp4", b"not a video");
|
||||
assert!(!of(&run(&m, &d), "shape", "out/cuts/a1_s1_9x16.mp4").clear);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn heard_the_way_people_say_it() {
|
||||
// Gemini's Elfster A1 solo (11-25): the transcript splits "Wishlist" and the speaker fills the phrase out
|
||||
let d = dir("said");
|
||||
put(&d, "media/brief.txt", BRIEF.as_bytes());
|
||||
let m = contract("");
|
||||
let line = "so it draws the names for you and everyone gets a gift they want It's free it's fun and it's easy so set it up tonight with your whole family Make your wish list and organize your gift exchange on Elfster It's free";
|
||||
deliver(&d, S1, line, &[]);
|
||||
let g = run(&m, &d);
|
||||
assert!(of(&g, "say", S1).clear, "{:?}", of(&g, "say", S1));
|
||||
assert!(of(&g, "cta", S1).clear, "{:?}", of(&g, "cta", S1));
|
||||
// the brief's order is the phrase: "fun, free and easy" isn't it
|
||||
deliver(&d, S1, &line.replace("It's free it's fun", "It's fun it's free"), &[]);
|
||||
assert!(!of(&run(&m, &d), "say", S1).clear);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rotated_cta_lands_on_any_of_its_lines() {
|
||||
// Dutch's hosts rotate "See a vet today at Dutch.com." and "Download the Dutch app and book a call for your dog or cat."
|
||||
let brief = format!("{BRIEF}\"See a vet today at Dutch.com.\"\n");
|
||||
let d = dir("rotated");
|
||||
put(&d, "media/brief.txt", brief.as_bytes());
|
||||
let mut m = contract("");
|
||||
m.cut.as_mut().unwrap().cta.as_mut().unwrap().also = vec!["See a vet today at Dutch.com.".into()];
|
||||
deliver(&d, S1, "it draws the names it's free fun and easy so See a vet today at Dutch com", &[]);
|
||||
let g = run(&m, &d);
|
||||
assert!(of(&g, "cta", S1).clear, "{:?}", of(&g, "cta", S1));
|
||||
assert!(named(&g, "quotes")[0].clear, "{:?}", named(&g, "quotes"));
|
||||
// a rotated line the brief doesn't have is held like any other rule
|
||||
m.cut.as_mut().unwrap().cta.as_mut().unwrap().also.push("Book now at Dutch.com".into());
|
||||
assert!(!named(&run(&m, &d), "quotes")[0].clear);
|
||||
}
|
||||
@@ -11,4 +11,6 @@ raea-core-scene = { path = "../../core/scene" }
|
||||
raea-core-facts = { path = "../../core/facts" }
|
||||
raea-sys-contact = { path = "../../systems/contact" }
|
||||
raea-sys-stage = { path = "../../systems/stage" }
|
||||
# each part held to its planned detail (MK21)
|
||||
raea-runtime-lod-plan = { path = "../lod-plan" }
|
||||
serde_json = "1"
|
||||
@@ -2,6 +2,8 @@
|
||||
//! clipping check (raea-sys-contact; RAEA_CLIP_CHECK=0 skips it), the staging (raea-sys-stage; RAEA_STAGE_CHECK=0) and
|
||||
//! the manifest's word on the parts (raea_sys_stage::Mounts) keep of them, and let go, so a long render never holds its
|
||||
//! frames' parts for its checks. raea-runtime-export hands each frame in as it's drawn, and a still's at its end.
|
||||
//! With them, each part held to its planned detail (raea-runtime-lod-plan; RAEA_LOD_CHECK=0 skips it): its own `lod`, else
|
||||
//! its name's on the plan above the composition (its plan.rs: `lod` on the brief's make objects, MK22).
|
||||
|
||||
use raea_core_facts::Finding;
|
||||
use raea_core_scene::Item;
|
||||
@@ -10,6 +12,7 @@ use serde_json::Value;
|
||||
pub struct EndChecks {
|
||||
clip: Option<raea_sys_contact::Clipping>,
|
||||
stage: Option<raea_sys_stage::Staging>,
|
||||
lod: Option<raea_runtime_lod_plan::Lods>,
|
||||
mounts: raea_sys_stage::Mounts,
|
||||
any: bool,
|
||||
parts: usize,
|
||||
@@ -19,7 +22,8 @@ impl EndChecks {
|
||||
pub fn new(w: u32, h: u32, fps: f64) -> EndChecks {
|
||||
let on = |k: &str| std::env::var(k).as_deref() != Ok("0");
|
||||
let (clip, stage) = (on("RAEA_CLIP_CHECK").then(|| raea_sys_contact::Clipping::new(w, h, fps)), on("RAEA_STAGE_CHECK").then(|| raea_sys_stage::Staging::new(w, h, fps)));
|
||||
EndChecks { clip, stage, mounts: raea_sys_stage::Mounts::new(w, h), any: false, parts: 0 }
|
||||
let lod = on("RAEA_LOD_CHECK").then(|| raea_runtime_lod_plan::Lods::new(w, h, fps, raea_runtime_lod_plan::plan::here(), false));
|
||||
EndChecks { clip, stage, lod, mounts: raea_sys_stage::Mounts::new(w, h), any: false, parts: 0 }
|
||||
}
|
||||
|
||||
/// The next frame (its number, `frame`): its parts, and its page where the manifest has it.
|
||||
@@ -31,6 +35,9 @@ impl EndChecks {
|
||||
if let Some(s) = &mut self.stage {
|
||||
s.push(frame, its, page);
|
||||
}
|
||||
if let Some(l) = &mut self.lod {
|
||||
l.push(frame, its);
|
||||
}
|
||||
self.mounts.push(frame, its);
|
||||
}
|
||||
|
||||
@@ -47,9 +54,39 @@ impl EndChecks {
|
||||
mark("end checks: clipping");
|
||||
found.extend(self.stage.map_or_else(Vec::new, raea_sys_stage::Staging::told));
|
||||
mark("end checks: staging");
|
||||
// parts shown closer than their planned detail, said as the staging's are
|
||||
let closer = self.lod.map_or_else(Vec::new, |l| l.findings(raea_sys_stage::BY));
|
||||
closer.iter().for_each(|f| eprintln!("raea: {}", f.line()));
|
||||
raea_core_facts::finding::said(&closer);
|
||||
found.extend(closer);
|
||||
// the clipping check's solids, kept for the process, aren't needed again by a render
|
||||
raea_sys_contact::forget();
|
||||
mark("end checks: done, their solids let go");
|
||||
(found, Some(seen))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
|
||||
fn item(kind: &'static str, props: Value, shape: Option<&str>) -> Item {
|
||||
Item { kind, props: Arc::new(props.as_object().cloned().unwrap_or_default()), shape: shape.map(Arc::from), at: None, material: None, world: Default::default() }
|
||||
}
|
||||
|
||||
// MK21: a render's end checks say a part shown closer than its planned detail, with its other findings
|
||||
#[test]
|
||||
fn a_render_says_a_part_shown_closer_than_its_planned_detail() {
|
||||
let frame = |z: f32, lod: u8| vec![item("camera", json!({"position": [0.0, 0.0, z], "lookAt": [0, 0, 0], "fov": 50}), None), item("mesh", json!({"name": "kiosk", "lod": lod}), Some("box(1, 1, 1)"))];
|
||||
let run = |z: f32, lod: u8| {
|
||||
let mut e = EndChecks::new(1280, 720, 30.0);
|
||||
e.push(0, &frame(z, lod), None);
|
||||
e.told(|_| {}).0.into_iter().filter(|f| f.check == "lod-closer").collect::<Vec<_>>()
|
||||
};
|
||||
let found = run(2.0, 4);
|
||||
assert_eq!((found.len(), found[0].level, found[0].by.as_str()), (1, raea_core_facts::Level::Error, "raea render"), "{found:?}");
|
||||
assert!(run(2.0, 0).is_empty() && run(80.0, 4).is_empty(), "a hero up close and a far part far away are as planned");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "raea-runtime-goal-plan"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "A goal job held to its rules: commands that must pass, and words a fresh critic must find true after the work's last change (make: goal({...}), /goal)"
|
||||
|
||||
[dependencies]
|
||||
# the contract: `make: goal({...})` on brief.ts
|
||||
raea-core-brief = { path = "../../core/brief" }
|
||||
serde_json = "1"
|
||||
@@ -0,0 +1,205 @@
|
||||
//! A goal job's gates (`make: goal({...})` on brief.ts, core/brief goal.rs): the person's goal held as rules, from what's
|
||||
//! on disk and what a fresh critic said, never from the agent that did the work. `/goal` in raea.app and an agent's own
|
||||
//! goal are this one loop (11-26, Shane: "it can't stop unless all the goals pass").
|
||||
//! run the command exits 0 in the brief's folder, within its timeout (run again at every status)
|
||||
//! file the file exists: a deliverable, so `raea make status` lists it under missing, not here
|
||||
//! says a fresh critic (`raea make judge`) found it true of the work, after the work's last change
|
||||
//! The critic's verdict is review/goal.judge.json: {at, by, rules: {ID: {pass, why}}}.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, Instant, SystemTime};
|
||||
|
||||
use raea_core_brief::goal::Goal;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// One gate as `raea make status` lists it (a cut's are the same kind): `of` is the rule it's about
|
||||
pub use raea_core_brief::make::Gate;
|
||||
|
||||
fn gate(name: &'static str, of: &str, clear: bool, says: String) -> Gate {
|
||||
Gate { name, of: Some(of.to_string()), clear, says }
|
||||
}
|
||||
|
||||
/// Where the critic's verdict is kept, beside the brief.
|
||||
pub const VERDICT: &str = "review/goal.judge.json";
|
||||
/// The seconds a `run` rule gets when it names none.
|
||||
pub const TIMEOUT: u32 = 300;
|
||||
|
||||
/// Folders that aren't the work: what the job writes about itself, and what tools keep.
|
||||
const NOT_WORK: [&str; 7] = ["review", ".git", "node_modules", ".raea", "target", ".cache", ".raea-cloud"];
|
||||
|
||||
/// When the work last changed: the newest file under DIR, its own bookkeeping left out (a bounded walk).
|
||||
pub fn newest(dir: &Path) -> Option<SystemTime> {
|
||||
let mut best: Option<SystemTime> = None;
|
||||
let mut stack = vec![dir.to_path_buf()];
|
||||
let mut seen = 0usize;
|
||||
while let Some(d) = stack.pop() {
|
||||
for e in std::fs::read_dir(&d).into_iter().flatten().flatten() {
|
||||
seen += 1;
|
||||
if seen > 20_000 {
|
||||
return best;
|
||||
}
|
||||
let p = e.path();
|
||||
let name = e.file_name().to_string_lossy().to_string();
|
||||
let Ok(t) = e.file_type() else { continue };
|
||||
if t.is_dir() {
|
||||
if !(d == dir && NOT_WORK.contains(&name.as_str())) && name != "node_modules" && name != ".git" {
|
||||
stack.push(p);
|
||||
}
|
||||
} else if t.is_file() && name != "NOTES.md" {
|
||||
if let Ok(m) = e.metadata().and_then(|m| m.modified()) {
|
||||
best = Some(best.map_or(m, |b| b.max(m)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
/// A command run in DIR through the system shell, stopped at its timeout: (passed, its last words).
|
||||
pub fn run(cmd: &str, dir: &Path, secs: u32) -> (bool, String) {
|
||||
let mut c = if cfg!(windows) {
|
||||
let mut c = std::process::Command::new("cmd");
|
||||
c.args(["/C", cmd]);
|
||||
c
|
||||
} else {
|
||||
let mut c = std::process::Command::new("sh");
|
||||
c.args(["-c", cmd]);
|
||||
c
|
||||
};
|
||||
let out = std::env::temp_dir().join(format!("raea-goal-{}-{}.log", std::process::id(), Instant::now().elapsed().as_nanos()));
|
||||
let Ok(log) = std::fs::File::create(&out) else { return (false, "couldn't make a log file for it".into()) };
|
||||
let Ok(err) = log.try_clone() else { return (false, "couldn't make a log file for it".into()) };
|
||||
let child = c.current_dir(dir).stdin(std::process::Stdio::null()).stdout(log).stderr(err).spawn();
|
||||
let mut child = match child {
|
||||
Ok(ch) => ch,
|
||||
Err(e) => return (false, format!("couldn't start it: {e}")),
|
||||
};
|
||||
let until = Instant::now() + Duration::from_secs(secs as u64);
|
||||
let status = loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(s)) => break Some(s),
|
||||
Ok(None) if Instant::now() >= until => {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
break None;
|
||||
}
|
||||
Ok(None) => std::thread::sleep(Duration::from_millis(100)),
|
||||
Err(_) => break None,
|
||||
}
|
||||
};
|
||||
let text = std::fs::read_to_string(&out).unwrap_or_default();
|
||||
let _ = std::fs::remove_file(&out);
|
||||
let last = text.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("").trim();
|
||||
let last: String = last.chars().take(200).collect();
|
||||
match status {
|
||||
Some(s) if s.success() => (true, "passes".into()),
|
||||
Some(s) => (false, format!("exits {}{}", s.code().map_or("by a signal".into(), |c| c.to_string()), if last.is_empty() { String::new() } else { format!(": {last}") })),
|
||||
None => (false, format!("still running after {secs} s: stopped (give the rule a longer `timeout`, or make it quicker)")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The critic's verdict, when there is one.
|
||||
pub fn verdict(dir: &Path) -> Option<Value> {
|
||||
serde_json::from_str(&std::fs::read_to_string(dir.join(VERDICT)).ok()?).ok()
|
||||
}
|
||||
|
||||
/// Every rule's gate but `file` rules (deliverables: status lists them as missing).
|
||||
pub fn gates(g: &Goal, dir: &Path) -> Vec<Gate> {
|
||||
let says: Vec<_> = g.rules.iter().filter(|r| r.says.is_some()).collect();
|
||||
let v = if says.is_empty() { None } else { verdict(dir) };
|
||||
let judged = v.as_ref().and_then(|v| v["at"].as_u64()).map(|s| SystemTime::UNIX_EPOCH + Duration::from_secs(s));
|
||||
let changed = if says.is_empty() { None } else { newest(dir) };
|
||||
// at whole seconds, as the verdict keeps its time: work saved in the second the critic was asked counts as judged
|
||||
let secs = |t: SystemTime| t.duration_since(SystemTime::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
|
||||
let fresh = match (judged, changed) {
|
||||
(Some(j), Some(c)) => secs(j) >= secs(c),
|
||||
(Some(_), None) => true,
|
||||
_ => false,
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for r in &g.rules {
|
||||
if let Some(cmd) = &r.run {
|
||||
let (ok, said) = run(cmd, dir, r.timeout.unwrap_or(TIMEOUT));
|
||||
out.push(gate("run", &r.id, ok, if ok { format!("`{cmd}` passes") } else { format!("`{cmd}` {said}") }));
|
||||
} else if r.says.is_some() {
|
||||
let one = v.as_ref().map(|v| &v["rules"][&r.id]);
|
||||
let (clear, said) = match one {
|
||||
None => (false, "not judged yet: raea make judge".to_string()),
|
||||
Some(Value::Null) => (false, "the last judging didn't cover it: raea make judge".to_string()),
|
||||
Some(_) if !fresh => (false, "the work changed after the critic judged it: raea make judge again".to_string()),
|
||||
Some(x) if x["pass"] == true => (true, format!("a fresh critic found it true: {}", x["why"].as_str().unwrap_or(""))),
|
||||
Some(x) => (false, format!("a fresh critic found it not true yet: {}", x["why"].as_str().unwrap_or(""))),
|
||||
};
|
||||
out.push(gate("says", &r.id, clear, said));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// What the critic is asked: the goal, each `says` rule by id, and the answer's shape. It reads; it changes nothing.
|
||||
pub fn prompt(g: &Goal, dir: &Path) -> String {
|
||||
let rules: Vec<String> = g.rules.iter().filter_map(|r| r.says.as_ref().map(|s| format!("- {}: {s}", r.id))).collect();
|
||||
format!(
|
||||
"You are a fresh critic. You did none of this work and owe it nothing. The work is in {d}: read whatever you need \
|
||||
there (its files, its renders, NOTES.md), and change nothing.\n\nThe goal, as the person said it: {goal}\n\nFor each rule \
|
||||
below, decide whether it is true of the work as it is on disk now. Count it true only when you have seen it hold; if you \
|
||||
can't tell, it isn't true yet. Say why in one sentence, naming what you looked at.\n\n{rules}\n\nAnswer last with one JSON \
|
||||
object and nothing after it: {{\"rules\": {{\"ID\": {{\"pass\": true, \"why\": \"...\"}}}}}}",
|
||||
d = dir.display(),
|
||||
goal = g.goal,
|
||||
rules = rules.join("\n")
|
||||
)
|
||||
}
|
||||
|
||||
/// The verdict: the object around the text's last `"rules"` key (a critic may think aloud, or quote the shape, first).
|
||||
pub fn last_verdict(text: &str) -> Option<Value> {
|
||||
let key = text.rfind("\"rules\"")?;
|
||||
// the nearest brace before the key opens the verdict
|
||||
let open = text[..key].rfind('{')?;
|
||||
let v: Value = serde_json::Deserializer::from_str(&text[open..]).into_iter::<Value>().next()?.ok()?;
|
||||
v["rules"].is_object().then_some(v)
|
||||
}
|
||||
|
||||
/// The critics `raea make judge` can ask, each a fresh session that may only read.
|
||||
pub const BY: [&str; 2] = ["claude", "kimi"];
|
||||
|
||||
/// One fresh critic over the goal's `says` rules: its verdict kept at review/goal.judge.json, stamped with when it was
|
||||
/// asked (so work changed while it judged counts as changed after). Returns the verdict.
|
||||
pub fn judge(g: &Goal, dir: &Path, by: &str) -> Result<Value, String> {
|
||||
if !g.rules.iter().any(|r| r.says.is_some()) {
|
||||
return Err("raea make judge: the goal has no `says` rules; its `run` and `file` rules are checked by raea make status".into());
|
||||
}
|
||||
let asked = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
|
||||
let p = prompt(g, dir);
|
||||
let mut cmd = match by {
|
||||
"claude" => {
|
||||
let mut c = std::process::Command::new("claude");
|
||||
c.args(["-p", &p, "--allowedTools", "Read Grep Glob", "--output-format", "json"]);
|
||||
c
|
||||
}
|
||||
"kimi" => {
|
||||
let mut c = std::process::Command::new("kimi");
|
||||
c.args(["-p", &p]);
|
||||
c
|
||||
}
|
||||
o => return Err(format!("raea make judge: --by {o}: the critics are {}", BY.join(", "))),
|
||||
};
|
||||
let out = cmd.current_dir(dir).stdin(std::process::Stdio::null()).output().map_err(|e| format!("raea make judge: couldn't run {by}: {e} (is its CLI installed and signed in?)"))?;
|
||||
let text = String::from_utf8_lossy(&out.stdout).to_string();
|
||||
// claude's json output is {result: "..."}; kimi's is the words
|
||||
let words = serde_json::from_str::<Value>(&text).ok().and_then(|v| v["result"].as_str().map(String::from)).unwrap_or(text);
|
||||
let tail = &words[words.floor_char_boundary(words.len().saturating_sub(300))..];
|
||||
let mut v = last_verdict(&words).ok_or_else(|| format!("raea make judge: {by} answered no verdict: {}", tail.trim()))?;
|
||||
v["at"] = json!(asked);
|
||||
v["by"] = json!(by);
|
||||
v["goal"] = json!(g.goal);
|
||||
let file: PathBuf = dir.join(VERDICT);
|
||||
if let Some(parent) = file.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| format!("raea make judge: {}: {e}", parent.display()))?;
|
||||
}
|
||||
std::fs::write(&file, serde_json::to_string_pretty(&v).unwrap_or_default()).map_err(|e| format!("raea make judge: {}: {e}", file.display()))?;
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,84 @@
|
||||
use super::*;
|
||||
use raea_core_brief::goal::{Goal, GoalRule};
|
||||
|
||||
fn rule(id: &str) -> GoalRule {
|
||||
GoalRule { id: id.into(), run: None, timeout: None, file: None, says: None }
|
||||
}
|
||||
|
||||
fn tmp(name: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("raea-goal-plan-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_command_passes_or_says_why() {
|
||||
let d = tmp("run");
|
||||
let g = Goal { goal: "tests pass".into(), rules: vec![GoalRule { run: Some("true".into()), ..rule("ok") }, GoalRule { run: Some("echo broke; exit 3".into()), ..rule("bad") }] };
|
||||
let gs = gates(&g, &d);
|
||||
assert_eq!(gs.len(), 2);
|
||||
assert!(gs[0].clear, "{gs:?}");
|
||||
assert!(!gs[1].clear);
|
||||
assert!(gs[1].says.contains("exits 3") && gs[1].says.contains("broke"), "{}", gs[1].says);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_command_past_its_timeout_fails() {
|
||||
let d = tmp("slow");
|
||||
let (ok, said) = run("sleep 5", &d, 1);
|
||||
assert!(!ok);
|
||||
assert!(said.contains("still running after 1 s"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn words_need_a_fresh_critic() {
|
||||
let d = tmp("says");
|
||||
std::fs::write(d.join("work.txt"), "the work").unwrap();
|
||||
let g = Goal { goal: "a friendly reply".into(), rules: vec![GoalRule { says: Some("the reply is friendly".into()), ..rule("friendly") }] };
|
||||
// never judged
|
||||
let gs = gates(&g, &d);
|
||||
assert!(!gs[0].clear && gs[0].says.contains("raea make judge"), "{gs:?}");
|
||||
// judged after the work, and found true
|
||||
let later = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs() + 5;
|
||||
std::fs::create_dir_all(d.join("review")).unwrap();
|
||||
let v = json!({"at": later, "by": "claude", "rules": {"friendly": {"pass": true, "why": "it says hello warmly"}}});
|
||||
std::fs::write(d.join(VERDICT), v.to_string()).unwrap();
|
||||
assert!(gates(&g, &d)[0].clear);
|
||||
// the critic's own file doesn't count as the work changing
|
||||
assert!(newest(&d).unwrap() < SystemTime::UNIX_EPOCH + Duration::from_secs(later));
|
||||
// judged before the work changed: stale
|
||||
let earlier = json!({"at": 1, "rules": {"friendly": {"pass": true, "why": ""}}});
|
||||
std::fs::write(d.join(VERDICT), earlier.to_string()).unwrap();
|
||||
let gs = gates(&g, &d);
|
||||
assert!(!gs[0].clear && gs[0].says.contains("changed after"), "{gs:?}");
|
||||
// judged and found not true
|
||||
let no = json!({"at": later, "rules": {"friendly": {"pass": false, "why": "it is curt"}}});
|
||||
std::fs::write(d.join(VERDICT), no.to_string()).unwrap();
|
||||
let gs = gates(&g, &d);
|
||||
assert!(!gs[0].clear && gs[0].says.contains("it is curt"), "{gs:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_rules_are_left_to_the_deliverables() {
|
||||
let d = tmp("file");
|
||||
let g = Goal { goal: "an export".into(), rules: vec![GoalRule { file: Some("out/final.mp4".into()), ..rule("export") }] };
|
||||
assert!(gates(&g, &d).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_verdict_is_the_last_json_with_rules() {
|
||||
let t = "the shape is {\"rules\": {\"ID\": ...}} so: {\"x\": 1} then {\"rules\": {\"a\": {\"pass\": true, \"why\": \"seen\"}}}";
|
||||
assert_eq!(last_verdict(t).unwrap()["rules"]["a"]["pass"], true);
|
||||
assert!(last_verdict("no json here").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_rules_are_doctored() {
|
||||
let g = Goal { goal: "".into(), rules: vec![GoalRule { run: Some("x".into()), says: Some("y".into()), ..rule("Two") }, rule("two")] };
|
||||
let d = raea_core_brief::goal::doctor(&g);
|
||||
assert!(d.iter().any(|l| l.contains("no `goal`")), "{d:?}");
|
||||
assert!(d.iter().any(|l| l.contains("`Two`: ids are")), "{d:?}");
|
||||
assert!(d.iter().any(|l| l.contains("exactly one") && l.contains("it has 2")), "{d:?}");
|
||||
assert!(d.iter().any(|l| l.contains("`two` needs exactly one") && l.contains("it has 0")), "{d:?}");
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "raea-runtime-lod-plan"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "Planned detail held to the frame: a part planned as a grey box or as far away (lod 0 the hero to 4 far) that a shot shows closer than its plan, the levels a job's plan gives its objects, the gate a job is held at and raea scene lod's table (docs/make.feature MK21-MK24)"
|
||||
|
||||
[dependencies]
|
||||
raea-core-scene = { path = "../../core/scene" }
|
||||
# its results as Findings (docs/direction.feature DR3)
|
||||
raea-core-facts = { path = "../../core/facts" }
|
||||
# the frame's camera, a part's box and what stands in front of it
|
||||
raea-sys-stage = { path = "../../systems/stage" }
|
||||
# the brief above a composition, found as raea make finds it (MK22)
|
||||
dunce = "1"
|
||||
bevy = { version = "=0.20.0", default-features = false, features = ["std"] }
|
||||
serde_json = "1"
|
||||
@@ -0,0 +1,304 @@
|
||||
//! raea-runtime-lod-plan (docs/make.feature MK21), planned detail held to the frame: a part planned as a grey box or as something far away (`lod` on the part,
|
||||
//! or on its object in the plan, `make` on brief.ts) that a shot then shows closer than its plan. A plan's level is how
|
||||
//! large the part is meant to be seen, 0 (the hero, half the frame or more) to 4 (far, under 2% of it); a frame's level
|
||||
//! is how large the part's box is on screen through that frame's camera. A part seen finer than planned was built for
|
||||
//! a distance the camera no longer keeps: a warning one level finer, an error two or more. It reads the scene, not the
|
||||
//! pixels: a part behind others is passed over only when every line from the camera to it crosses another mesh's box
|
||||
//! (a hollow shape's box hides more than the shape does, so a part behind one may be missed; one in the open never is).
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
|
||||
use bevy::math::Vec3;
|
||||
use raea_core_facts::{Finding, Level};
|
||||
use raea_core_scene::base_ident;
|
||||
use serde_json::Value;
|
||||
|
||||
use raea_core_scene::Item;
|
||||
use raea_sys_stage::{View, called, corners, crossing, model_box, own_box, see_through};
|
||||
|
||||
// the levels a job's plan gives its objects (`lod` on brief.ts's make objects, MK22)
|
||||
pub mod plan;
|
||||
// the gate a job is held at, and the table `raea scene lod` prints
|
||||
mod report;
|
||||
pub use report::{gate, held, ordered, table};
|
||||
|
||||
/// The coarsest level: far, a silhouette.
|
||||
pub const COARSEST: u8 = 4;
|
||||
/// SPANS[k]: a part across this share of the frame or more (the larger of its width's and its height's) is seen at
|
||||
/// level k; under the last it is at level 4. Unity's and Unreal's levels switch on the same measure, size on screen.
|
||||
pub const SPANS: [f32; 4] = [0.5, 0.2, 0.08, 0.02];
|
||||
/// What each level is for.
|
||||
pub const NAMES: [&str; 5] = ["hero", "featured", "dressing", "background", "far"];
|
||||
|
||||
/// The level a part across `span` of the frame is seen at.
|
||||
pub fn level(span: f32) -> u8 {
|
||||
SPANS.iter().position(|s| span >= *s).unwrap_or(SPANS.len()) as u8
|
||||
}
|
||||
|
||||
/// A level in words: "LOD 3 (background, under 8% of the frame)".
|
||||
pub fn words(l: u8) -> String {
|
||||
let l = l.min(COARSEST) as usize;
|
||||
let size = if l == 0 { format!("{:.0}% of the frame or more", SPANS[0] * 100.0) } else { format!("under {:.0}% of the frame", SPANS[l - 1] * 100.0) };
|
||||
format!("LOD {l} ({}, {size})", NAMES[l])
|
||||
}
|
||||
|
||||
/// A part's planned level: its own `lod`, else its name's in the plan.
|
||||
fn planned(it: &Item, plan: &HashMap<String, u8>) -> Option<u8> {
|
||||
let own = it.props.get("lod").and_then(Value::as_f64).filter(|l| *l >= 0.0).map(|l| (l as u8).min(COARSEST));
|
||||
own.or_else(|| plan.get(base_ident(it)).copied())
|
||||
}
|
||||
|
||||
/// How much of the frame a part's box spans through `v` (the larger of its width's and its height's share, 1 at
|
||||
/// most), and the box's corners; None when its size isn't known or none of it is in the frame.
|
||||
fn span(it: &Item, v: &View, boxes: &mut HashMap<String, Option<(Vec3, Vec3)>>) -> Option<(f32, [Vec3; 8])> {
|
||||
let (lo, hi) = match it.kind {
|
||||
"mesh" => own_box(it, boxes)?,
|
||||
"model" => model_box(it, boxes)?,
|
||||
_ => return None,
|
||||
};
|
||||
let pts = corners(&it.world, lo, hi);
|
||||
if let Some(b) = v.bounds(pts) {
|
||||
return (v.share(b) > 0.0).then(|| (((b[2] - b[0]) / v.w).max((b[3] - b[1]) / v.h).min(1.0), pts));
|
||||
}
|
||||
// across the camera's plane: the camera is in it or beside it, so it is measured at its nearest point
|
||||
let near = it.world.transform_point3(it.world.inverse().transform_point3(v.eye).clamp(lo, hi));
|
||||
if near.distance(v.eye) < 1e-4 {
|
||||
return Some((1.0, pts));
|
||||
}
|
||||
let [x, y, depth] = v.project(near)?;
|
||||
(x >= 0.0 && x <= v.w && y >= 0.0 && y <= v.h).then(|| (((pts[7] - pts[0]).length() * v.focal / depth / v.h).min(1.0), pts))
|
||||
}
|
||||
|
||||
/// Whether other parts stand between the camera and all of a part: its box's middle and eight points halfway out to
|
||||
/// its corners, each behind a mesh's box the line passes right through (not one the camera or the point is inside: a
|
||||
/// room round either hides nothing). Models never hide: a file's box is mostly air.
|
||||
fn hidden(its: &[Item], me: usize, pts: &[Vec3; 8], eye: Vec3, boxes: &mut HashMap<String, Option<(Vec3, Vec3)>>) -> bool {
|
||||
let mid = pts.iter().copied().sum::<Vec3>() / 8.0;
|
||||
let targets: Vec<Vec3> = std::iter::once(mid).chain(pts.iter().map(|p| mid + (*p - mid) * 0.5)).collect();
|
||||
let mut others = Vec::new();
|
||||
for (j, it) in its.iter().enumerate() {
|
||||
if j == me || it.kind != "mesh" || it.at.is_some() || see_through(it) {
|
||||
continue;
|
||||
}
|
||||
if let Some((lo, hi)) = own_box(it, boxes) {
|
||||
others.push((it.world.inverse(), lo, hi));
|
||||
}
|
||||
}
|
||||
targets.iter().all(|p| others.iter().any(|(inv, lo, hi)| crossing(inv.transform_point3(eye), inv.transform_point3(*p), *lo, *hi).is_some_and(|(t0, t1)| t0 > 0.0 && t1 < 1.0)))
|
||||
}
|
||||
|
||||
/// What the frames showed of one part.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Seen {
|
||||
pub name: String,
|
||||
pub planned: Option<u8>,
|
||||
/// how many frames it was in
|
||||
pub frames: usize,
|
||||
/// where it was largest: the frame's number, and the share of the frame it spanned there
|
||||
pub finest: Option<(i64, f32)>,
|
||||
/// how many frames showed it finer than planned
|
||||
pub closer: usize,
|
||||
}
|
||||
|
||||
impl Seen {
|
||||
/// The finest level it was seen at.
|
||||
pub fn level(&self) -> Option<u8> {
|
||||
self.finest.map(|(_, s)| level(s))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Part {
|
||||
planned: Option<u8>,
|
||||
frames: usize,
|
||||
/// its largest: (frame, span)
|
||||
finest: Option<(i64, f32)>,
|
||||
/// the frames it was seen finer than planned: (frame, span)
|
||||
closer: Vec<(i64, f32)>,
|
||||
}
|
||||
|
||||
/// Each frame as it comes: per part, how often it was in the frame, where it was largest, and the frames it was seen
|
||||
/// finer than its plan. A render keeps only the parts with a plan; `every` keeps all (`raea scene lod`'s table).
|
||||
pub struct Lods {
|
||||
plan: HashMap<String, u8>,
|
||||
every: bool,
|
||||
w: u32,
|
||||
h: u32,
|
||||
fps: f64,
|
||||
boxes: HashMap<String, Option<(Vec3, Vec3)>>,
|
||||
parts: BTreeMap<String, Part>,
|
||||
}
|
||||
|
||||
impl Lods {
|
||||
/// For frames w x h at `fps`. `plan` is the levels the job's plan gives its objects, by name (`lod` on brief.ts's
|
||||
/// make objects); a part's own `lod` comes first.
|
||||
pub fn new(w: u32, h: u32, fps: f64, plan: HashMap<String, u8>, every: bool) -> Lods {
|
||||
Lods { plan, every, w, h, fps: fps.max(1.0), boxes: HashMap::new(), parts: BTreeMap::new() }
|
||||
}
|
||||
|
||||
/// The next frame's parts, through its camera.
|
||||
pub fn push(&mut self, frame: i64, its: &[Item]) {
|
||||
if self.plan.is_empty() && !self.every && !its.iter().any(|it| it.props.contains_key("lod")) {
|
||||
return;
|
||||
}
|
||||
let Some(v) = View::of(its, self.w, self.h) else { return };
|
||||
for (j, it) in its.iter().enumerate() {
|
||||
if !matches!(it.kind, "mesh" | "model") || it.at.is_some() {
|
||||
continue;
|
||||
}
|
||||
let plan = planned(it, &self.plan);
|
||||
if plan.is_none() && !self.every {
|
||||
continue;
|
||||
}
|
||||
let Some((s, pts)) = span(it, &v, &mut self.boxes) else { continue };
|
||||
let closer = plan.is_some_and(|p| level(s) < p);
|
||||
if closer && hidden(its, j, &pts, v.eye, &mut self.boxes) {
|
||||
continue;
|
||||
}
|
||||
// parts of one name planned apart (two crates, one a hero) are told apart
|
||||
let mut name = called(it);
|
||||
if self.parts.get(&name).is_some_and(|p| p.planned != plan) {
|
||||
name = format!("{name} (lod {})", plan.map_or("none".into(), |p| p.to_string()));
|
||||
}
|
||||
let part = self.parts.entry(name).or_default();
|
||||
part.planned = plan;
|
||||
part.frames += 1;
|
||||
if part.finest.is_none_or(|(_, best)| s > best) {
|
||||
part.finest = Some((frame, s));
|
||||
}
|
||||
if closer {
|
||||
part.closer.push((frame, s));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the frames showed of each part, by name.
|
||||
pub fn seen(&self) -> Vec<Seen> {
|
||||
self.parts.iter().map(|(name, p)| Seen { name: name.clone(), planned: p.planned, frames: p.frames, finest: p.finest, closer: p.closer.len() }).collect()
|
||||
}
|
||||
|
||||
/// One finding a part seen finer than planned, worst first: where it was largest, and for how long.
|
||||
pub fn findings(&self, by: &str) -> Vec<Finding> {
|
||||
let mut out = Vec::new();
|
||||
for (name, p) in &self.parts {
|
||||
let (Some(plan), Some(&(first, _)), Some(&(last, _))) = (p.planned, p.closer.first(), p.closer.last()) else { continue };
|
||||
let Some(&(at, s)) = p.closer.iter().max_by(|a, b| a.1.total_cmp(&b.1)) else { continue };
|
||||
let seen = level(s);
|
||||
let lasts = if p.closer.len() == 1 { "on one frame".to_string() } else { format!("on {} frames ({:.1} s)", p.closer.len(), p.closer.len() as f64 / self.fps) };
|
||||
let says = format!("'{name}' is planned at {} and is seen at {}: across {:.0}% of the frame at frame {at}, closer than planned {lasts}", words(plan), words(seen), s * 100.0);
|
||||
let fix = format!("build it for LOD {seen} and plan it there (lod={{{seen}}} on the part, or `lod: {seen}` on its object in brief.ts), or keep the camera off it");
|
||||
let level = if plan - seen >= 2 { Level::Error } else { Level::Warn };
|
||||
out.push(Finding::new("lod-closer", level, says, by).frames(first, last + 1).about(name.clone(), None).measure("span", (s * 100.0) as f64, "% of the frame", Some((SPANS[plan as usize - 1] * 100.0) as f64)).fix(fix));
|
||||
}
|
||||
raea_core_facts::finding::ranked(out)
|
||||
}
|
||||
}
|
||||
|
||||
/// Every part of the frames against its planned detail (`all[k]` is frame `frames[k]`'s parts): each part's row, and a
|
||||
/// finding a part seen finer than planned.
|
||||
pub fn lods(all: &[Vec<Item>], frames: &[i64], w: u32, h: u32, fps: f64, by: &str, plan: HashMap<String, u8>) -> (Vec<Seen>, Vec<Finding>) {
|
||||
let mut l = Lods::new(w, h, fps, plan, true);
|
||||
for (k, its) in all.iter().enumerate() {
|
||||
l.push(frames[k], its);
|
||||
}
|
||||
(l.seen(), l.findings(by))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use bevy::math::Mat4;
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
|
||||
fn item(kind: &'static str, props: Value, world: Mat4) -> Item {
|
||||
Item { kind, props: Arc::new(props.as_object().cloned().unwrap_or_default()), shape: None, at: None, material: None, world }
|
||||
}
|
||||
|
||||
/// A camera at `eye` looking at `at`, 50 degrees.
|
||||
fn cam(eye: [f32; 3], at: [f32; 3]) -> Item {
|
||||
item("camera", json!({"position": eye, "lookAt": at, "fov": 50}), Mat4::IDENTITY)
|
||||
}
|
||||
|
||||
/// a 1 m cube at `at`, with these props
|
||||
fn cube(props: Value, at: [f32; 3]) -> Item {
|
||||
let mut it = item("mesh", props, Mat4::from_translation(Vec3::from(at)));
|
||||
it.shape = Some(Arc::from("box(1, 1, 1)"));
|
||||
it
|
||||
}
|
||||
|
||||
fn run(frames: Vec<Vec<Item>>, plan: &[(&str, u8)]) -> (Vec<Seen>, Vec<Finding>) {
|
||||
let nums: Vec<i64> = (0..frames.len() as i64).collect();
|
||||
lods(&frames, &nums, 1920, 1080, 30.0, "test", plan.iter().map(|(n, l)| (n.to_string(), *l)).collect())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_level_is_how_much_of_the_frame_a_part_spans() {
|
||||
assert_eq!([0.9, 0.5, 0.3, 0.1, 0.05, 0.01].map(level), [0, 0, 1, 2, 3, 4]);
|
||||
assert_eq!(words(3), "LOD 3 (background, under 8% of the frame)");
|
||||
assert_eq!(words(0), "LOD 0 (hero, 50% of the frame or more)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_far_part_the_camera_comes_up_to_is_said_with_where_and_how_close() {
|
||||
// planned far (4); the camera dollies from 60 m to 2 m
|
||||
let frames: Vec<Vec<Item>> = [60.0, 30.0, 8.0, 2.0].iter().map(|z| vec![cam([0.0, 0.0, *z], [0.0, 0.0, 0.0]), cube(json!({"name": "crate", "lod": 4}), [0.0, 0.0, 0.0])]).collect();
|
||||
let (seen, found) = run(frames, &[]);
|
||||
assert_eq!((seen[0].planned, seen[0].level(), seen[0].closer), (Some(4), Some(0), 3), "{seen:?}");
|
||||
assert_eq!(seen[0].finest.map(|f| f.0), Some(3));
|
||||
let f = &found[0];
|
||||
assert_eq!((f.check.as_str(), f.level, f.frames), ("lod-closer", Level::Error, Some([1, 4])), "{f:?}");
|
||||
assert!(f.says.starts_with("'crate' is planned at LOD 4 (far, under 2% of the frame) and is seen at LOD 0 (hero") && f.says.contains("at frame 3, closer than planned on 3 frames (0.1 s)"), "{}", f.says);
|
||||
assert!(f.fix.as_deref().unwrap().contains("lod={0}"), "{:?}", f.fix);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_level_finer_warns_and_a_part_at_its_plan_says_nothing() {
|
||||
// a 1 m cube 5 m off a 50 degree lens is about 23% of the frame's height: level 1
|
||||
let scene = |lod: u8| vec![vec![cam([0.0, 0.0, 5.5], [0.0, 0.0, 0.0]), cube(json!({"name": "crate", "lod": lod}), [0.0, 0.0, 0.0])]];
|
||||
assert!(run(scene(1), &[]).1.is_empty() && run(scene(0), &[]).1.is_empty());
|
||||
assert_eq!(run(scene(2), &[]).1[0].level, Level::Warn);
|
||||
assert_eq!(run(scene(3), &[]).1[0].level, Level::Error);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_plan_names_a_part_and_its_own_lod_wins() {
|
||||
let scene = |props: Value| vec![vec![cam([0.0, 0.0, 3.0], [0.0, 0.0, 0.0]), cube(props, [0.0, 0.0, 0.0])]];
|
||||
let (seen, found) = run(scene(json!({"name": "kiosk"})), &[("kiosk", 3)]);
|
||||
assert_eq!((seen[0].planned, found.len()), (Some(3), 1));
|
||||
assert!(run(scene(json!({"name": "kiosk", "lod": 0})), &[("kiosk", 3)]).1.is_empty(), "the part's own level is the newer word");
|
||||
// a part with no plan is never a finding; the table still has its row, and a render doesn't keep it
|
||||
let (seen, found) = run(scene(json!({"name": "other"})), &[("kiosk", 3)]);
|
||||
assert_eq!((seen[0].planned, seen[0].level(), found.len()), (None, Some(1), 0));
|
||||
let mut l = Lods::new(1920, 1080, 30.0, HashMap::from([("kiosk".to_string(), 3)]), false);
|
||||
l.push(0, &scene(json!({"name": "other"}))[0]);
|
||||
assert!(l.seen().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_part_out_of_frame_behind_the_camera_or_behind_a_wall_is_not_seen() {
|
||||
let far = |at: [f32; 3]| cube(json!({"name": "crate", "lod": 4}), at);
|
||||
// beside the frame, and behind the camera
|
||||
assert!(run(vec![vec![cam([0.0, 0.0, 3.0], [0.0, 0.0, 0.0]), far([40.0, 0.0, 0.0])]], &[]).1.is_empty());
|
||||
assert!(run(vec![vec![cam([0.0, 0.0, 3.0], [0.0, 0.0, 0.0]), far([0.0, 0.0, 9.0])]], &[]).1.is_empty());
|
||||
// a wall wider than it between the two hides it; a post narrower than it doesn't
|
||||
let mut wall = cube(json!({"name": "wall"}), [0.0, 0.0, 1.5]);
|
||||
wall.world = Mat4::from_translation(Vec3::new(0.0, 0.0, 1.5)) * Mat4::from_scale(Vec3::new(6.0, 6.0, 0.2));
|
||||
assert!(run(vec![vec![cam([0.0, 0.0, 3.0], [0.0, 0.0, 0.0]), far([0.0, 0.0, 0.0]), wall.clone()]], &[]).1.is_empty());
|
||||
wall.world = Mat4::from_translation(Vec3::new(0.0, 0.0, 1.5)) * Mat4::from_scale(Vec3::new(0.1, 6.0, 0.1));
|
||||
assert_eq!(run(vec![vec![cam([0.0, 0.0, 3.0], [0.0, 0.0, 0.0]), far([0.0, 0.0, 0.0]), wall]], &[]).1.len(), 1);
|
||||
// a room round both hides nothing
|
||||
let mut room = cube(json!({"name": "room"}), [0.0, 0.0, 0.0]);
|
||||
room.world = Mat4::from_scale(Vec3::splat(20.0));
|
||||
assert_eq!(run(vec![vec![cam([0.0, 0.0, 3.0], [0.0, 0.0, 0.0]), far([0.0, 0.0, 0.0]), room]], &[]).1.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_camera_inside_or_beside_a_part_sees_it_at_its_nearest() {
|
||||
// a 30 m hall the camera stands in, planned as background
|
||||
let mut hall = cube(json!({"name": "hall", "lod": 3}), [0.0, 0.0, 0.0]);
|
||||
hall.world = Mat4::from_scale(Vec3::new(30.0, 4.0, 30.0));
|
||||
let (seen, found) = run(vec![vec![cam([0.0, 0.0, 3.0], [0.0, 0.0, 0.0]), hall]], &[]);
|
||||
assert_eq!((seen[0].level(), found[0].level), (Some(0), Level::Error));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
//! The levels a job's plan gives its objects (docs/make.feature MK22): `lod` on the objects of `make` in the brief.ts
|
||||
//! at or above a composition, inside its raea project. Read only when the brief's words hold a `lod` at all, since
|
||||
//! reading it runs the module (`raea spec brief.ts --as brief`, a child process: this crate carries no TS engine);
|
||||
//! read once a brief's version a process. A brief that doesn't load plans nothing: a render never fails on it.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::time::SystemTime;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
/// The last brief read: its path, when it last changed, and its levels.
|
||||
static READ: Mutex<Option<(PathBuf, Option<SystemTime>, HashMap<String, u8>)>> = Mutex::new(None);
|
||||
|
||||
/// The composition a command was given: its first word naming a .tsx or .jsx file (`raea render EDIT.tsx ...`).
|
||||
pub fn composition(words: impl IntoIterator<Item = String>) -> Option<PathBuf> {
|
||||
for w in words {
|
||||
if w.ends_with(".tsx") || w.ends_with(".jsx") {
|
||||
return Some(PathBuf::from(w));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The plan's levels for the composition this process was asked to render, read from its own command line: a render's
|
||||
/// end checks are made deep in the export, which isn't told where the composition is. None when it names none.
|
||||
pub fn here() -> HashMap<String, u8> {
|
||||
let dir = composition(std::env::args().skip(1)).and_then(|c| std::path::absolute(c).ok()).and_then(|c| c.parent().map(Path::to_path_buf));
|
||||
dir.map(|d| lods(&d)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The brief.ts at or above `dir` in its project whose words plan a level.
|
||||
fn brief(dir: &Path) -> Option<PathBuf> {
|
||||
let dir = dunce::canonicalize(dir).ok()?;
|
||||
let project = raea_core_facts::record::up(&dir, ".raea/project");
|
||||
for d in dir.ancestors() {
|
||||
let p = d.join("brief.ts");
|
||||
if p.is_file() {
|
||||
return std::fs::read_to_string(&p).is_ok_and(|t| t.contains("lod")).then_some(p);
|
||||
}
|
||||
if project.as_deref() == Some(d) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The levels in a brief as `raea spec --as brief` prints it: each of make's objects with a `lod`, by its id.
|
||||
pub fn of_brief(v: &Value) -> HashMap<String, u8> {
|
||||
let b = v.get("brief").unwrap_or(v);
|
||||
let objects = b["make"]["objects"].as_array().into_iter().flatten();
|
||||
objects.filter_map(|o| Some((o["id"].as_str()?.to_string(), o["lod"].as_u64()?.min(crate::COARSEST as u64) as u8))).collect()
|
||||
}
|
||||
|
||||
/// The plan's levels for a composition in `dir`: object id to level, empty when no brief above it plans any.
|
||||
pub fn lods(dir: &Path) -> HashMap<String, u8> {
|
||||
let Some(brief) = brief(dir) else { return HashMap::new() };
|
||||
let changed = std::fs::metadata(&brief).and_then(|m| m.modified()).ok();
|
||||
if let Some((p, at, plan)) = READ.lock().unwrap().as_ref() {
|
||||
if *p == brief && *at == changed {
|
||||
return plan.clone();
|
||||
}
|
||||
}
|
||||
let read = || {
|
||||
let out = std::process::Command::new(std::env::current_exe().ok()?).arg("spec").arg(&brief).args(["--as", "brief"]).env("RAEA_RECORD", "off").output().ok()?;
|
||||
let text = String::from_utf8_lossy(&out.stdout);
|
||||
Some(of_brief(&serde_json::from_str(&text[text.find('{')?..]).ok()?))
|
||||
};
|
||||
let plan = read().unwrap_or_default();
|
||||
*READ.lock().unwrap() = Some((brief, changed, plan.clone()));
|
||||
plan
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn a_briefs_objects_with_a_level_are_the_plan() {
|
||||
let v = json!({"brief": {"make": {"kind": "scene", "objects": [{"id": "kiosk", "lod": 3}, {"id": "desk"}, {"id": "sign", "lod": 9}]}}});
|
||||
let plan = of_brief(&v);
|
||||
assert_eq!((plan.len(), plan["kiosk"], plan["sign"]), (2, 3, 4));
|
||||
assert!(of_brief(&json!({"title": "no job"})).is_empty());
|
||||
// as `raea spec brief.ts --as brief` prints it: the brief itself, every field given, a level left out null
|
||||
let printed = json!({"title": "Kiosk square", "make": {"kind": "scene", "objects": [{"id": "kiosk", "lod": 3, "hero": null}, {"id": "desk", "lod": null}]}});
|
||||
assert_eq!(of_brief(&printed), HashMap::from([("kiosk".to_string(), 3)]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_composition_is_the_commands_first_tsx() {
|
||||
let words = |w: &[&str]| composition(w.iter().map(|s| s.to_string()));
|
||||
assert_eq!(words(&["render", "shots/walk.tsx", "-o", "out/walk.mp4"]), Some(PathBuf::from("shots/walk.tsx")));
|
||||
assert_eq!(words(&["check", "out/walk.mp4"]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_with_no_brief_planning_a_level_plans_nothing() {
|
||||
let d = std::env::temp_dir().join(format!("raea-lod-plan-{}", std::process::id()));
|
||||
std::fs::create_dir_all(d.join(".raea")).unwrap();
|
||||
std::fs::write(d.join(".raea/project"), "").unwrap();
|
||||
assert!(lods(&d).is_empty());
|
||||
std::fs::write(d.join("brief.ts"), "export default brief({ title: \"x\" })").unwrap();
|
||||
assert!(brief(&d).is_none(), "a brief whose words plan no level isn't run");
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
//! What is said of planned detail once the frames are read: the parts a job is held at (`raea make status`'s lod gate,
|
||||
//! MK24) and the table `raea scene lod` prints (MK23).
|
||||
|
||||
use raea_core_facts::Finding;
|
||||
|
||||
use crate::{Seen, level};
|
||||
|
||||
/// Of a render's or check's findings, the parts seen closer than planned (`lod-closer`), and those of them not yet
|
||||
/// answered in the job's notes: a line of NOTES.md with `lod` and the part's name answers it.
|
||||
pub fn held<'a>(findings: &'a [Finding], notes: &str) -> (Vec<&'a str>, Vec<&'a str>) {
|
||||
let answered = |name: &str| notes.lines().any(|l| l.to_lowercase().contains("lod") && l.contains(name));
|
||||
let name = |f: &'a Finding| (f.check == "lod-closer").then(|| f.about.first()).flatten().map(|a| a.name.as_str());
|
||||
let closer: Vec<&str> = findings.iter().filter_map(name).collect();
|
||||
let open = closer.iter().copied().filter(|n| !answered(n)).collect();
|
||||
(closer, open)
|
||||
}
|
||||
|
||||
/// A composition's lod gate, from the findings of its last render or check (the record's entry `id`): whether it is
|
||||
/// clear and what it says, None when the job plans no level and the render found none. Two levels finer is an error,
|
||||
/// which the checks gate holds until it's fixed; one level finer is held here until the part is replanned and rendered
|
||||
/// again, or answered in the notes.
|
||||
pub fn gate(of: &str, id: &str, findings: &[Finding], notes: &str, plans: bool) -> Option<(bool, String)> {
|
||||
let (closer, open) = held(findings, notes);
|
||||
if open.is_empty() {
|
||||
return (plans || !closer.is_empty()).then(|| (true, format!("no part closer than its planned detail left unanswered at {id}")));
|
||||
}
|
||||
Some((false, format!("seen closer than planned at {id}: {}. Build each for the level it's seen at and plan it there (`lod` on its object in brief.ts or on the part), keep the camera off it, or answer in NOTES.md on a line with `lod` and its name; raea scene lod {of} lists every part", open.join(", "))))
|
||||
}
|
||||
|
||||
/// What a row says of its part: closer than planned, never as close as planned, or as planned.
|
||||
fn verdict(s: &Seen) -> &'static str {
|
||||
match (s.planned, s.level()) {
|
||||
(Some(p), Some(l)) if l < p => "CLOSER than planned",
|
||||
(Some(p), Some(l)) if l > p => "never this close: planned finer than any frame shows it",
|
||||
(Some(_), _) => "as planned",
|
||||
(None, _) => "no plan",
|
||||
}
|
||||
}
|
||||
|
||||
/// The rows in reading order: seen closer than planned (the widest gap first), the rest of the planned, then the
|
||||
/// unplanned, each by how large it gets.
|
||||
pub fn ordered(mut seen: Vec<Seen>) -> Vec<Seen> {
|
||||
let gap = |s: &Seen| s.planned.zip(s.level()).map_or(0, |(p, l)| p.saturating_sub(l));
|
||||
let size = |s: &Seen| s.finest.map_or(0.0, |f| f.1);
|
||||
seen.sort_by(|a, b| (gap(b), b.planned.is_some()).cmp(&(gap(a), a.planned.is_some())).then(size(b).total_cmp(&size(a))).then(a.name.cmp(&b.name)));
|
||||
seen
|
||||
}
|
||||
|
||||
/// The table: a row a part, its plan beside the finest level a frame showed it at, how much of the frame it spanned
|
||||
/// there, at which frame, and how many frames it was in.
|
||||
pub fn table(seen: &[Seen]) -> Vec<String> {
|
||||
let mut t = vec![format!("{:<32} {:>7} {:>5} {:>7} {:>7} {:>7} ", "part", "planned", "seen", "largest", "at", "frames")];
|
||||
let n = |l: Option<u8>| l.map_or("-".into(), |l| l.to_string());
|
||||
for s in seen {
|
||||
let (at, span) = s.finest.map_or(("-".into(), "-".into()), |(f, sp)| (f.to_string(), format!("{:.0}%", sp * 100.0)));
|
||||
t.push(format!("{:<32} {:>7} {:>5} {:>7} {:>7} {:>7} {}", s.name.chars().take(32).collect::<String>(), n(s.planned), n(s.finest.map(|f| level(f.1))), span, at, s.frames, verdict(s)));
|
||||
}
|
||||
t
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use raea_core_facts::Level;
|
||||
|
||||
fn row(name: &str, planned: Option<u8>, span: f32) -> Seen {
|
||||
Seen { name: name.into(), planned, frames: 10, finest: Some((4, span)), closer: 0 }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_table_reads_closer_than_planned_first_then_planned_then_the_rest_by_size() {
|
||||
let rows = ordered(vec![row("floor", None, 1.0), row("desk", Some(0), 0.6), row("kiosk", Some(3), 0.3), row("tower", Some(4), 0.05), row("lamp", None, 0.1), row("phone", Some(0), 0.04)]);
|
||||
assert_eq!(rows.iter().map(|r| r.name.as_str()).collect::<Vec<_>>(), ["kiosk", "tower", "desk", "phone", "floor", "lamp"]);
|
||||
let t = table(&rows);
|
||||
assert!(t[1].starts_with("kiosk") && t[1].ends_with("CLOSER than planned"), "{}", t[1]);
|
||||
assert!(t[3].ends_with("as planned"), "{}", t[3]);
|
||||
assert!(t[4].ends_with("never this close: planned finer than any frame shows it"), "{}", t[4]);
|
||||
assert!(t[5].ends_with("no plan"), "{}", t[5]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_part_seen_closer_is_held_until_a_notes_line_with_lod_and_its_name_answers_it() {
|
||||
let closer = |name: &str| Finding::new("lod-closer", Level::Warn, format!("'{name}' is planned at LOD 3"), "raea render").about(name, None);
|
||||
let fs = [closer("kiosk"), Finding::new("clips", Level::Error, "the mug is in the desk", "raea render").about("mug", None), closer("tower")];
|
||||
assert_eq!(held(&fs, ""), (vec!["kiosk", "tower"], vec!["kiosk", "tower"]));
|
||||
// a line about the part that isn't about its detail answers nothing
|
||||
assert_eq!(held(&fs, "the kiosk is fine\n- LOD tower: one frame at the cut").1, ["kiosk"]);
|
||||
assert!(held(&fs, "- lod kiosk and tower: left as boxes, the cut hides them").1.is_empty());
|
||||
// the gate: open with the parts named, clear once answered, and absent from a job that plans and found nothing
|
||||
let open = gate("scene.tsx", "r1", &fs, "", false).unwrap();
|
||||
assert!(!open.0 && open.1.starts_with("seen closer than planned at r1: kiosk, tower.") && open.1.ends_with("raea scene lod scene.tsx lists every part"), "{open:?}");
|
||||
assert_eq!(gate("scene.tsx", "r1", &fs, "lod kiosk, tower: boxes", false).map(|g| g.0), Some(true));
|
||||
assert_eq!((gate("scene.tsx", "r1", &[], "", false), gate("scene.tsx", "r1", &[], "", true).map(|g| g.0)), (None, Some(true)));
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -32,7 +32,7 @@ curl -H "authorization: Bearer $RAEA_CLOUD_TOKEN" localhost:8080/v1/health
|
||||
`AGENTS` takes any ids the [ACP registry](https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json)
|
||||
lists, several at once: `kimi-code`, `claude-acp`, `codex-acp`, `gemini`, `opencode`, `goose`, ... Each is installed
|
||||
from its registry entry (npm at the registry's version, or its Linux archive checked by sha256), and raea's skill is
|
||||
installed for it on every start. `RAEA_AGENT` picks the default; a socket can name another (`?agent=`).
|
||||
installed for it on every start. A socket names its agent (`?agent=`); `RAEA_AGENT` names one for sockets that don't. With neither, there is no agent: the box never picks one itself.
|
||||
`RAEA_AGENT_CMD` runs an agent the registry doesn't list, by its command line.
|
||||
|
||||
Signing the agent in:
|
||||
|
||||
+250
-30
@@ -10,6 +10,9 @@
|
||||
# GET /v1/jobs/ID/media with media=1: the job's media outputs [{path, oid, size}],
|
||||
# left out of /out
|
||||
# POST /v1/jobs/ID/media {objects: [{path, oid, href, header}]} PUTs each to its signed URL in R2 (farm_media.py)
|
||||
# POST /v1/blobs/have {objects: [{oid, size}]} which of a project's media the farm holds: {have: [oid]}
|
||||
# PUT /v1/blobs/OID?size=N one media file into the farm's cache, kept when it
|
||||
# hashes to OID (a box's project not in raea's LFS)
|
||||
# A job's folder may hold .raea-cloud-media.json: its media by Git LFS object id with URLs signed for it, fetched from
|
||||
# R2 through a cache on the volume keyed by hash instead of coming in the tar (docs/cloud-render.feature CR23).
|
||||
#
|
||||
@@ -22,6 +25,7 @@
|
||||
# - the clipping check (RAEA_CLIP_CHECK) is off on the GPUs: it is an agent's lint, and on a server's CPU it took more
|
||||
# of a render than its frames (bench/gpus.py)
|
||||
|
||||
import contextlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
@@ -62,6 +66,14 @@ image = (
|
||||
"| tar -xJ -C /opt && ln -s /opt/blender-$v-linux-x64/blender /usr/local/bin/blender && blender -b --version | head -1",
|
||||
)
|
||||
.pip_install("fastapi[standard]==0.121.2")
|
||||
# /v1/faces: OpenCV's YuNet face detector (232 KB, CPU), for the boxes' frames check (server/frames.ts): a box has
|
||||
# no vision backend of its own (raea-perceive isn't in raea's Linux build), so a face cut by a 9:16 crop went unseen
|
||||
.pip_install("opencv-python-headless==4.11.0.86", "numpy<2.3")
|
||||
.run_commands(
|
||||
"set -e; curl -fsSL -o /opt/yunet.onnx https://media.githubusercontent.com/media/opencv/opencv_zoo/main/models/"
|
||||
"face_detection_yunet/face_detection_yunet_2023mar.onnx "
|
||||
"&& echo '8f2383e4dd3cfbb4553ea8718107fc0423210dc964f9f4280604804ed2552fa4 /opt/yunet.onnx' | sha256sum -c"
|
||||
)
|
||||
.add_local_file(os.path.join(CLOUD, "image", "nvidia_icd.json"), "/usr/share/vulkan/icd.d/nvidia_icd.json", copy=True)
|
||||
.env({"WGPU_BACKEND": "vulkan", "NVIDIA_DRIVER_CAPABILITIES": "all", "RAEA_CLIP_CHECK": "0", "RAEA_AUDIO_MUTE": "1",
|
||||
"RAEA_MODELS": "/models/raea", "RAEA_FEED_MODELS": "/models/feed", "RAEA_LIBRARY_MODELS": "/models/library",
|
||||
@@ -81,6 +93,8 @@ models = modal.Volume.from_name("raea-models", create_if_missing=True, version=2
|
||||
logs = modal.Dict.from_name("raea-farm-logs", create_if_missing=True)
|
||||
# the farm's token (RAEA_CLOUD_TOKEN), its own: a CPU box names it as RAEA_CLOUD_GPU_TOKEN
|
||||
secret = modal.Secret.from_name(os.environ.get("RAEA_FARM_SECRET", "raea-farm"))
|
||||
# OPENROUTER_API_KEY for /v1/words: raea cloud's own key, the one its library index transcribes with
|
||||
words_secret = modal.Secret.from_name(os.environ.get("RAEA_FARM_WORDS_SECRET", "raea-farm-words"))
|
||||
# a CPU render (the coordinator's sound pass) on lavapipe, with EGL's vendors hidden (docs/cloud.feature CL13)
|
||||
CPU_ENV = {"VK_DRIVER_FILES": "/usr/share/vulkan/icd.d/lvp_icd.json", "__EGL_VENDOR_LIBRARY_DIRS": "/nonexistent"}
|
||||
|
||||
@@ -111,7 +125,10 @@ def snapshot(d):
|
||||
for base, _, files in os.walk(d):
|
||||
for f in files:
|
||||
p = os.path.join(base, f)
|
||||
s = os.stat(p)
|
||||
try:
|
||||
s = os.stat(p)
|
||||
except OSError: # a link that points nowhere here (a box's kits/ link to its cache): not a file of the job's
|
||||
continue
|
||||
out[os.path.relpath(p, d)] = f"{s.st_size}:{s.st_mtime_ns}"
|
||||
return out
|
||||
|
||||
@@ -158,7 +175,7 @@ def raea_run(id: str, args: list[str], frames: list[int] | None = None, first: i
|
||||
if probe:
|
||||
code, out, s = run(["raea", *args, "--frame", "0", "-o", "/tmp/probe.png", "--manifest", "/tmp/probe.json"], cwd=work)
|
||||
m = json.load(open("/tmp/probe.json")) if os.path.exists("/tmp/probe.json") else {}
|
||||
return {"code": code, "out": out[-3000:], "s": s, "length": m.get("length"), "fps": m.get("fps"), "w": m.get("width"), "h": m.get("height"), "kind": kind(), **life()}
|
||||
return {"code": code, "out": out[-3000:], "s": s, "length": m.get("length"), "fps": m.get("fps"), "w": m.get("width"), "h": m.get("height"), "kind": kind(), "manifest": m, **life()}
|
||||
if frames is None:
|
||||
code, out, s = run(["raea", *args], cwd=work)
|
||||
vol.commit()
|
||||
@@ -248,6 +265,9 @@ def coordinate(id: str, args: list[str], opts: dict):
|
||||
vol.commit()
|
||||
log.end(1)
|
||||
return
|
||||
# the media just linked (or fetched) into the job, committed before any GPU container reloads to render it: without
|
||||
# this a still on this container found the footage and every GPU run of a video didn't ("No such file", 11-25)
|
||||
vol.commit()
|
||||
before = snapshot(work)
|
||||
try:
|
||||
code = farm_plan.dispatch(args, {**opts, "id": id}, work, log, raea_run, blender_run, CPU_ENV, run, vol.reload)
|
||||
@@ -255,6 +275,19 @@ def coordinate(id: str, args: list[str], opts: dict):
|
||||
log(f"raea farm: {e!r}", err=True)
|
||||
code = 1
|
||||
vol.commit()
|
||||
# what the job's GPU containers committed (a whole render's stills, its folder output) is only seen here after a
|
||||
# reload: without it a render to a folder came back empty while a joined .mp4, written here, came back (11-20).
|
||||
# Another job's open files in this coordinator refuse a reload (ConflictError, 11-21: a 500 for the box): try again,
|
||||
# and if it still won't, go on with what this container sees rather than lose a finished render
|
||||
for pause in (0.5, 1, 2, 4, 0):
|
||||
try:
|
||||
vol.reload()
|
||||
break
|
||||
except Exception as e: # modal.exception.ConflictError
|
||||
if not pause:
|
||||
log(f"raea farm: the volume wouldn't reload ({e}); returning what this container sees", err=True)
|
||||
else:
|
||||
time.sleep(pause)
|
||||
after = snapshot(work)
|
||||
changed = [p for p, v in after.items() if before.get(p) != v]
|
||||
if opts.get("media"):
|
||||
@@ -271,7 +304,7 @@ def coordinate(id: str, args: list[str], opts: dict):
|
||||
log.end(code)
|
||||
|
||||
|
||||
@app.function(cpu=1, memory=4096, volumes={ROOT: vol}, secrets=[secret], timeout=3600)
|
||||
@app.function(cpu=1, memory=4096, volumes={ROOT: vol}, secrets=[secret, words_secret], timeout=3600)
|
||||
@modal.concurrent(max_inputs=32)
|
||||
@modal.asgi_app()
|
||||
def api():
|
||||
@@ -283,6 +316,59 @@ def api():
|
||||
web = FastAPI()
|
||||
token = os.environ["RAEA_CLOUD_TOKEN"]
|
||||
|
||||
# This container serves many requests at once, and a volume reload refuses while any of them has a file open
|
||||
# (ConflictError) and, when it goes ahead, takes /farm away from a request mid-write (PermissionError making a
|
||||
# job's folder). 11-25: StreetTalk's renders lost a finished job's results (GET out: 500) and failed to start
|
||||
# (POST jobs: 500) whenever two agents rendered together. So requests that touch the volume share it, and a
|
||||
# reload waits until none of them is in it.
|
||||
class Gate:
|
||||
def __init__(self):
|
||||
self.users = 0
|
||||
self.reloading = False
|
||||
self.cond = asyncio.Condition()
|
||||
|
||||
@contextlib.asynccontextmanager
|
||||
async def use(self):
|
||||
async with self.cond:
|
||||
await self.cond.wait_for(lambda: not self.reloading)
|
||||
self.users += 1
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
async with self.cond:
|
||||
self.users -= 1
|
||||
self.cond.notify_all()
|
||||
|
||||
async def reload(self, wait: bool = True) -> bool:
|
||||
"""the volume as other containers committed it; with wait=False skipped (False) while the volume is in use"""
|
||||
async with self.cond:
|
||||
if not wait and (self.users or self.reloading):
|
||||
return False
|
||||
await self.cond.wait_for(lambda: not self.users and not self.reloading)
|
||||
self.reloading = True
|
||||
try:
|
||||
for pause in (0.5, 1, 2, 4, 0):
|
||||
try:
|
||||
await vol.reload.aio()
|
||||
return True
|
||||
except Exception as e: # modal.exception.ConflictError: a file open elsewhere in this container
|
||||
if not pause:
|
||||
print(f"raea farm: the volume wouldn't reload: {e}")
|
||||
return False
|
||||
await asyncio.sleep(pause)
|
||||
return False
|
||||
finally:
|
||||
async with self.cond:
|
||||
self.reloading = False
|
||||
self.cond.notify_all()
|
||||
|
||||
gate = Gate()
|
||||
|
||||
async def reloaded():
|
||||
"""the coordinator's commits seen here, or a 503 the box tries again on (the job is still all here)"""
|
||||
if not await gate.reload():
|
||||
raise HTTPException(503, "the farm's volume is busy: try again")
|
||||
|
||||
def check(req: Request):
|
||||
got = req.headers.get("authorization", "").removeprefix("Bearer ") or req.query_params.get("token", "")
|
||||
if got != token:
|
||||
@@ -297,6 +383,88 @@ def api():
|
||||
check(req)
|
||||
return {"raea": RAEA, "blender": BLENDER, "device": {"renders": "gpu", "name": f"raea on {'/'.join(RAEA_GPUS)}, Blender on {'/'.join(BLENDER_GPUS)}, up to {GPUS} at once"}, "farm": True, "jobs": []}
|
||||
|
||||
# what's said in a piece of sound, word by word, for a box's `raea words` (server/words.ts): a box has no
|
||||
# transcriber of its own (raea's is parakeet-mlx, Mac only), so the same Whisper large-v3 on OpenRouter that raea
|
||||
# cloud's library index uses (apps/app host/library/words.ts) hears it here. The body is one MP3 piece (16 kHz mono,
|
||||
# at most 10 minutes; the box cuts the pieces), the answer its words in the piece's own seconds. 11-25, Shane: "give
|
||||
# it whatever we use for indexing and libraries and sync", so agents check the words their cuts say.
|
||||
def seams(g):
|
||||
"""a split screen's seams: rows (h) or columns (v) where the picture jumps across nearly all of the frame, as a
|
||||
cut between two pictures does and nothing filmed does (a caption's box spans part of it, a horizon is soft)"""
|
||||
import numpy as np
|
||||
|
||||
found = []
|
||||
for axis, d in (("h", np.abs(np.diff(g, axis=0))), ("v", np.abs(np.diff(g, axis=1)).T)):
|
||||
n = d.shape[0]
|
||||
share = (d > 24).mean(axis=1)
|
||||
for i in range(int(n * 0.08), int(n * 0.92)):
|
||||
if share[i] > 0.7 and share[i] >= share[max(i - 1, 0)] and share[i] >= share[min(i + 1, n - 1)]:
|
||||
found.append([axis, i + 1, round(float(share[i]), 2)])
|
||||
return found
|
||||
|
||||
@web.post("/v1/faces")
|
||||
async def faces(req: Request):
|
||||
"""the faces in a video's frames, for the boxes' frames check: the body is {"frames": [base64 JPEG, ...]} (at most
|
||||
400, any size), the answer each frame's size and its faces as [x, y, w, h, score] in that frame's pixels"""
|
||||
import base64
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
check(req)
|
||||
body = await req.json()
|
||||
frames = body.get("frames") if isinstance(body, dict) else None
|
||||
if not isinstance(frames, list) or not frames:
|
||||
raise HTTPException(400, 'the body is {"frames": [base64 JPEG, ...]}')
|
||||
if len(frames) > 400:
|
||||
raise HTTPException(413, "at most 400 frames a call")
|
||||
out, det, size = [], None, None
|
||||
for b64 in frames:
|
||||
im = cv2.imdecode(np.frombuffer(base64.b64decode(b64), np.uint8), cv2.IMREAD_COLOR)
|
||||
if im is None:
|
||||
out.append(None)
|
||||
continue
|
||||
h, w = im.shape[:2]
|
||||
if size != (w, h):
|
||||
det, size = cv2.FaceDetectorYN.create("/opt/yunet.onnx", "", (w, h), 0.6, 0.3, 5000), (w, h)
|
||||
_, found = det.detect(im)
|
||||
out.append({"w": w, "h": h, "faces": [[round(float(f[0]), 1), round(float(f[1]), 1), round(float(f[2]), 1), round(float(f[3]), 1), round(float(f[14]), 3)] for f in (found if found is not None else [])],
|
||||
"seams": seams(cv2.cvtColor(im, cv2.COLOR_BGR2GRAY).astype(np.int16))})
|
||||
return {"model": "yunet-2023mar", "frames": out}
|
||||
|
||||
@web.post("/v1/words")
|
||||
async def words(req: Request):
|
||||
import base64
|
||||
import json as _json
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
check(req)
|
||||
key = os.environ.get("OPENROUTER_API_KEY", "")
|
||||
if not key:
|
||||
raise HTTPException(503, "the farm has no OpenRouter key for words (Modal secret raea-farm-words)")
|
||||
mp3 = await req.body()
|
||||
if not mp3:
|
||||
raise HTTPException(400, "the body is the sound: an MP3, 16 kHz mono, at most 10 minutes")
|
||||
if len(mp3) > 24 << 20:
|
||||
raise HTTPException(413, "a piece is at most 24 MB: send 10-minute pieces at 32 kb/s")
|
||||
body = {"model": "openai/whisper-large-v3", "input_audio": {"data": base64.b64encode(mp3).decode(), "format": "mp3"}, "response_format": "verbose_json", "timestamp_granularities": ["word", "segment"]}
|
||||
if req.query_params.get("language"):
|
||||
body["language"] = req.query_params["language"]
|
||||
|
||||
def ask():
|
||||
r = urllib.request.Request("https://openrouter.ai/api/v1/audio/transcriptions", data=_json.dumps(body).encode(), headers={"authorization": f"Bearer {key}", "content-type": "application/json", "x-title": "raea cloud words"})
|
||||
try:
|
||||
with urllib.request.urlopen(r, timeout=300) as f:
|
||||
return 200, _json.load(f)
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, {"error": e.read()[:500].decode("utf8", "replace")}
|
||||
|
||||
code, got = await asyncio.to_thread(ask)
|
||||
if code != 200:
|
||||
raise HTTPException(502, f"OpenRouter's Whisper said {code}: {got.get('error', '')}")
|
||||
ws = [{"text": w.get("word", "").strip(), "start": float(w.get("start", 0)), "end": float(w.get("end", w.get("start", 0)))} for w in got.get("words") or [] if w.get("word", "").strip()]
|
||||
return {"model": "openai/whisper-large-v3", "duration": got.get("duration"), "text": got.get("text", ""), "words": ws}
|
||||
|
||||
@web.post("/v1/jobs")
|
||||
async def start(req: Request):
|
||||
check(req)
|
||||
@@ -307,22 +475,71 @@ def api():
|
||||
opts = {"gpus": min(int(q.get("gpus", GPUS)), GPUS), "gpu": q.get("gpu"), "max_usd": float(q["max_usd"]) if "max_usd" in q else None, "media": q.get("media") == "1"}
|
||||
id = str(uuid.uuid4())
|
||||
work = f"{JOBS}/{id}/work"
|
||||
os.makedirs(work)
|
||||
tar = f"{JOBS}/{id}/in.tar"
|
||||
with open(tar, "wb") as f:
|
||||
async for chunk in req.stream():
|
||||
f.write(chunk)
|
||||
# GNU tar reads the compression itself, refuses members with .. and strips a leading /
|
||||
x = subprocess.run(["tar", "-xf", tar, "-C", work, "--no-same-owner", "--no-same-permissions"], capture_output=True, text=True)
|
||||
os.remove(tar)
|
||||
if x.returncode:
|
||||
shutil.rmtree(f"{JOBS}/{id}", ignore_errors=True)
|
||||
raise HTTPException(400, f"the folder didn't unpack: {x.stderr.strip()}")
|
||||
await vol.commit.aio()
|
||||
async with gate.use():
|
||||
os.makedirs(work)
|
||||
tar = f"{JOBS}/{id}/in.tar"
|
||||
with open(tar, "wb") as f:
|
||||
async for chunk in req.stream():
|
||||
f.write(chunk)
|
||||
# GNU tar reads the compression itself, refuses members with .. and strips a leading /
|
||||
x = await asyncio.to_thread(subprocess.run, ["tar", "-xf", tar, "-C", work, "--no-same-owner", "--no-same-permissions"], capture_output=True, text=True)
|
||||
os.remove(tar)
|
||||
if x.returncode:
|
||||
shutil.rmtree(f"{JOBS}/{id}", ignore_errors=True)
|
||||
raise HTTPException(400, f"the folder didn't unpack: {x.stderr.strip()}")
|
||||
await vol.commit.aio()
|
||||
await logs.put.aio(id, [])
|
||||
await coordinate.spawn.aio(id, args, opts)
|
||||
return {"id": id}
|
||||
|
||||
# a project's footage by hash, sent once (11-25: StreetTalk's 1.9 GB of interviews went in every render's tar, even
|
||||
# one frame's, and three at once ran the box out of memory): the box asks which the farm has, PUTs the rest, and a
|
||||
# job's .raea-cloud-media.json names them with no href (farm_media.fetch uses them from the cache)
|
||||
@web.post("/v1/blobs/have")
|
||||
async def blobs_have(req: Request):
|
||||
check(req)
|
||||
objects = (await req.json()).get("objects") or []
|
||||
await gate.reload(wait=False) # the volume in use: what this container sees will do (a blob it lacks is sent again)
|
||||
have = []
|
||||
async with gate.use():
|
||||
for o in objects[:5000]:
|
||||
oid, size = str(o.get("oid", "")), int(o.get("size", -1))
|
||||
blob = f"{ROOT}/blobs/{oid}"
|
||||
if len(oid) == 64 and all(c in "0123456789abcdef" for c in oid) and os.path.exists(blob) and os.path.getsize(blob) == size:
|
||||
have.append(oid)
|
||||
return {"have": have}
|
||||
|
||||
@web.put("/v1/blobs/{oid}")
|
||||
async def blob_put(oid: str, req: Request):
|
||||
import hashlib
|
||||
|
||||
check(req)
|
||||
if len(oid) != 64 or any(c not in "0123456789abcdef" for c in oid):
|
||||
raise HTTPException(400, "not an object id: 64 hex characters")
|
||||
size = int(req.query_params.get("size", "-1"))
|
||||
async with gate.use():
|
||||
os.makedirs(f"{ROOT}/blobs", exist_ok=True)
|
||||
blob = f"{ROOT}/blobs/{oid}"
|
||||
if os.path.exists(blob) and os.path.getsize(blob) == size:
|
||||
return {"oid": oid, "bytes": size, "had": True}
|
||||
tmp = f"{blob}.up-{uuid.uuid4().hex[:8]}"
|
||||
h = hashlib.sha256()
|
||||
n = 0
|
||||
try:
|
||||
with open(tmp, "wb") as f:
|
||||
async for chunk in req.stream():
|
||||
h.update(chunk)
|
||||
f.write(chunk)
|
||||
n += len(chunk)
|
||||
if h.hexdigest() != oid or n != size:
|
||||
raise HTTPException(400, f"the file came as {h.hexdigest()[:12]}… ({n} bytes), not {oid[:12]}… ({size} bytes)")
|
||||
os.replace(tmp, blob)
|
||||
finally:
|
||||
if os.path.exists(tmp):
|
||||
os.remove(tmp)
|
||||
await vol.commit.aio()
|
||||
return {"oid": oid, "bytes": n}
|
||||
|
||||
@web.get("/v1/jobs/{id}")
|
||||
async def follow(id: str, req: Request):
|
||||
check(req)
|
||||
@@ -339,44 +556,47 @@ def api():
|
||||
await asyncio.sleep(0.5)
|
||||
|
||||
@web.get("/v1/jobs/{id}/media")
|
||||
def media_list(id: str, req: Request):
|
||||
async def media_list(id: str, req: Request):
|
||||
check(req)
|
||||
if logs.get(f"{id}:exit") is None:
|
||||
if await logs.get.aio(f"{id}:exit") is None:
|
||||
raise HTTPException(404, "no such finished job")
|
||||
vol.reload()
|
||||
p = f"{JOBS}/{id}/media.json"
|
||||
return {"objects": json.load(open(p)) if os.path.exists(p) else []}
|
||||
await reloaded()
|
||||
async with gate.use():
|
||||
p = f"{JOBS}/{id}/media.json"
|
||||
return {"objects": json.load(open(p)) if os.path.exists(p) else []}
|
||||
|
||||
@web.post("/v1/jobs/{id}/media")
|
||||
async def media_send(id: str, req: Request):
|
||||
import farm_media
|
||||
|
||||
check(req)
|
||||
if logs.get(f"{id}:exit") is None:
|
||||
if await logs.get.aio(f"{id}:exit") is None:
|
||||
raise HTTPException(404, "no such finished job")
|
||||
await vol.reload.aio()
|
||||
await reloaded()
|
||||
body = await req.json()
|
||||
objects = body.get("objects") if isinstance(body, dict) else None
|
||||
if not isinstance(objects, list):
|
||||
raise HTTPException(400, "objects: [{path, oid, href, header}]")
|
||||
# said in this container's log, not the job's (its log is done, and Log would start it again)
|
||||
try:
|
||||
return await asyncio.to_thread(farm_media.upload, f"{JOBS}/{id}/work", objects, print)
|
||||
async with gate.use():
|
||||
return await asyncio.to_thread(farm_media.upload, f"{JOBS}/{id}/work", objects, print)
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e))
|
||||
|
||||
@web.get("/v1/jobs/{id}/out")
|
||||
def out(id: str, req: Request):
|
||||
async def out(id: str, req: Request):
|
||||
check(req)
|
||||
if logs.get(f"{id}:exit") is None:
|
||||
if await logs.get.aio(f"{id}:exit") is None:
|
||||
raise HTTPException(404, "no such finished job")
|
||||
vol.reload()
|
||||
await reloaded()
|
||||
pack = {"zst": ["--zstd"], "gz": ["--gzip"], "tar": []}.get(req.query_params.get("as", "zst"), ["--zstd"])
|
||||
r = subprocess.run(["tar", *pack, "-cf", "-", "-C", f"{JOBS}/{id}/work", "--verbatim-files-from", "-T", f"{JOBS}/{id}/changed.txt"], capture_output=True)
|
||||
shutil.rmtree(f"{JOBS}/{id}", ignore_errors=True)
|
||||
vol.commit()
|
||||
async with gate.use():
|
||||
r = await asyncio.to_thread(subprocess.run, ["tar", *pack, "-cf", "-", "-C", f"{JOBS}/{id}/work", "--verbatim-files-from", "-T", f"{JOBS}/{id}/changed.txt"], capture_output=True)
|
||||
shutil.rmtree(f"{JOBS}/{id}", ignore_errors=True)
|
||||
await vol.commit.aio()
|
||||
for k in (id, f"{id}:exit"):
|
||||
logs.pop(k, None)
|
||||
await logs.pop.aio(k, None)
|
||||
if r.returncode:
|
||||
raise HTTPException(500, f"the results didn't pack: {r.stderr.decode().strip()}")
|
||||
return Response(r.stdout, media_type="application/octet-stream")
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
# a raea credential, only signed URLs that each reach one object.
|
||||
#
|
||||
# .raea-cloud-media.json in the job's folder, from the box: {"objects": [{"path", "oid", "size", "href", "header"}]}
|
||||
# An object with no href is one the box sent the farm itself (PUT /v1/blobs/OID, farm.py:
|
||||
# a project not in raea's LFS, 11-25): it is used from the cache, and only from there
|
||||
# fetch(work, cache, ...) each object into the cache (once), then into its path in the job's folder
|
||||
# outputs(work, changed) the job's media among what it made or changed: [{"path", "oid", "size"}]
|
||||
# upload(work, objects) PUTs each to its signed URL: [{"path", "oid", "href", "header"}]
|
||||
@@ -78,7 +80,12 @@ def fetch(work, cache, log=print, download=get, check=probe):
|
||||
if len(oid) != 64 or any(c not in "0123456789abcdef" for c in oid) or not inside(work, path):
|
||||
raise ValueError(f"media: {path!r} ({oid}) isn't a path in the job or an object id")
|
||||
blob = os.path.join(cache, oid)
|
||||
if os.path.exists(blob) and os.path.getsize(blob) == size:
|
||||
if not o.get("href"):
|
||||
# sent by the box over the farm's own token (PUT /v1/blobs), checked against its hash as it came
|
||||
if not (os.path.exists(blob) and os.path.getsize(blob) == size):
|
||||
raise ValueError(f"media: {path} ({oid[:12]}…) was never sent to the farm")
|
||||
cached += size
|
||||
elif os.path.exists(blob) and os.path.getsize(blob) == size:
|
||||
# a hash alone doesn't open the cache: the job's URL, signed for its account, has to answer
|
||||
check(o["href"], o.get("header"))
|
||||
cached += size
|
||||
@@ -95,7 +102,12 @@ def fetch(work, cache, log=print, download=get, check=probe):
|
||||
os.makedirs(os.path.dirname(dest), exist_ok=True)
|
||||
if os.path.lexists(dest):
|
||||
os.remove(dest)
|
||||
shutil.copyfile(blob, dest)
|
||||
# a link into the cache, not a copy: a project's footage is gigabytes, the same across every job (11-25); every
|
||||
# container of the job mounts the volume at the same place, so the link resolves on the GPUs too
|
||||
try:
|
||||
os.symlink(blob, dest)
|
||||
except OSError:
|
||||
shutil.copyfile(blob, dest)
|
||||
log(f"raea farm: {len(objects)} media files by hash, {fetched / 1e6:.1f} MB from R2, {cached / 1e6:.1f} MB already here")
|
||||
return {"objects": len(objects), "fetched": fetched, "cached": cached}
|
||||
|
||||
|
||||
@@ -28,6 +28,14 @@ def split_out(args):
|
||||
return args[:i] + args[i + 2 :], args[i + 1] if i + 1 < len(args) else None
|
||||
|
||||
|
||||
def drop_flag(args, flag):
|
||||
"""The arguments without FLAG VALUE, and VALUE (None when it isn't there)."""
|
||||
if flag not in args:
|
||||
return list(args), None
|
||||
i = args.index(flag)
|
||||
return args[:i] + args[i + 2 :], args[i + 1] if i + 1 < len(args) else None
|
||||
|
||||
|
||||
def splittable(args):
|
||||
"""A `raea render` of a composition to a video or a folder, every frame: the farm can split it."""
|
||||
if not args or args[0] != "render" or any(a in args for a in ("--frame", "--at", "--review", "--bundle", "--audio")):
|
||||
@@ -161,6 +169,10 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
|
||||
bill = bill or Bill()
|
||||
id = opts["id"]
|
||||
rest, out = split_out(args)
|
||||
# the render's own --manifest is written here once it's done (from frame 0's): left in, the probe's run had two and
|
||||
# wrote its own where the render's went, so it said no length and the job stopped unexplained (11-25: StreetTalk's
|
||||
# four cuts, each "exit 1" after frame 0); and every GPU run would have written one into the job's folder
|
||||
rest, manifest = drop_flag(rest, "--manifest")
|
||||
# the sound, on this CPU while the GPUs draw (a video's frames come back without it)
|
||||
sound = f"/tmp/{id}.wav"
|
||||
if out.endswith(VIDEO):
|
||||
@@ -169,6 +181,8 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
|
||||
p = bill.add(render.remote(id, rest, probe=True))
|
||||
if p["code"] or not p["length"]:
|
||||
log(p["out"], err=True)
|
||||
if not p["code"]:
|
||||
log("raea farm: frame 0 rendered but didn't say the piece's length, so its frames can't be shared out", err=True)
|
||||
return p["code"] or 1
|
||||
length, fps, kind = p["length"], p["fps"] or 30, p.get("kind") or opts.get("gpu") or "T4"
|
||||
log(f"raea farm: {length} frames at {p['w']}x{p['h']}, {fps} fps; frame 0 on a {kind} in {p['s']:.1f} s")
|
||||
@@ -194,11 +208,19 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
|
||||
code = spread(render, kind, [(id, rest, f, at, False, video) for f, at in runs(n0, length - 1, k * m, warm)], log, "frames", bill, k) if left else 0
|
||||
if code:
|
||||
return code
|
||||
# the sound's run finished first: its open files in the job's folder refuse the reload that brings the other
|
||||
# containers' frames (11-25: "the volume wouldn't reload ... cwd of raea render")
|
||||
if video:
|
||||
t.join()
|
||||
reload() # the other containers' frames
|
||||
frames = f"{os.path.dirname(work)}/frames"
|
||||
dest = os.path.join(work, out)
|
||||
if manifest and p.get("manifest"):
|
||||
path = os.path.join(work, manifest)
|
||||
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
|
||||
with open(path, "w") as f:
|
||||
json.dump(p["manifest"], f, indent=2)
|
||||
if video:
|
||||
t.join()
|
||||
os.makedirs(os.path.dirname(dest) or ".", exist_ok=True)
|
||||
c, o, s = join(frames, dest, sound, run)
|
||||
log(f"raea farm: joined {out} in {s:.1f} s" if not c else o, err=bool(c))
|
||||
|
||||
@@ -0,0 +1,386 @@
|
||||
# raea cloud's ingest on Modal (docs/cloud-ingest.feature): what a synced file needs that a Worker can't do itself.
|
||||
# The Worker (sync-run.ts) calls it with the file at an address it can fetch (a Composio download's s3url) and keeps
|
||||
# what comes back. From sdk/cloud:
|
||||
#
|
||||
# MODAL_PROFILE=raea modal deploy deploy/modal/ingest.py
|
||||
#
|
||||
# indexer (its own URL, raea--raea-ingest-indexer…): raea's library indexer (tools/library-index cloud-server.ts, the
|
||||
# desktop's indexFile in the cloud indexer's image: EmbeddingGemma 2 for pictures, shots, sound and words, TransNetV2
|
||||
# cuts, Whisper base): POST /v1/index {url, name, kind} -> {fragment, posters}; POST /v1/embed {texts} -> query
|
||||
# vectors. raea cloud writes the fragments to turbopuffer in raea-api's layout (IG8). Before deploying, bundle it:
|
||||
# tools/library-index/cloud-build.sh
|
||||
#
|
||||
# POST /v1/frame {url, at?} a video's frame as a JPEG 640 px on its long side; at is where, as a fraction of its
|
||||
# length (0.1 when left out: past a fade from black, before the end card). IG4
|
||||
# GET /healthz
|
||||
#
|
||||
# Every call but /healthz carries Authorization: Bearer RAEA_INGEST_TOKEN (Modal secret raea-ingest; the Worker's
|
||||
# secret of the same name). The secret's OPENROUTER_API_KEY, when set, has index jobs transcribe with Whisper large-v3
|
||||
# on OpenRouter. CPU only: a frame is ffmpeg seeking in the file, a second or two.
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
import modal
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
LIB = os.path.abspath(os.path.join(HERE, "..", "..", "..", "..", "tools", "library-index"))
|
||||
|
||||
app = modal.App("raea-ingest", image=modal.Image.debian_slim(python_version="3.12").apt_install("ffmpeg").pip_install("fastapi[standard]"))
|
||||
secret = modal.Secret.from_name("raea-ingest")
|
||||
|
||||
# the largest file fetched for a frame: a phone's minute of 4K is about 400 MB
|
||||
MAX_BYTES = 2 << 30
|
||||
LONG_SIDE = 640
|
||||
|
||||
|
||||
def probe_seconds(path: str) -> float:
|
||||
r = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", path], capture_output=True, text=True, timeout=60)
|
||||
try:
|
||||
return max(0.0, float(r.stdout.strip()))
|
||||
except ValueError:
|
||||
return 0.0
|
||||
|
||||
|
||||
def frame(path: str, at: float) -> bytes:
|
||||
secs = probe_seconds(path)
|
||||
t = secs * min(max(at, 0.0), 0.95) if secs else 0.0
|
||||
scale = f"scale='if(gt(iw,ih),{LONG_SIDE},-2)':'if(gt(iw,ih),-2,{LONG_SIDE})'"
|
||||
for seek in (t, 0.0):
|
||||
r = subprocess.run(["ffmpeg", "-v", "error", "-ss", f"{seek:.3f}", "-i", path, "-frames:v", "1", "-vf", scale, "-q:v", "4", "-f", "image2", "-c:v", "mjpeg", "pipe:1"], capture_output=True, timeout=120)
|
||||
if r.returncode == 0 and r.stdout:
|
||||
return r.stdout
|
||||
raise RuntimeError((r.stderr or b"no frame").decode(errors="replace")[-300:])
|
||||
|
||||
|
||||
@app.function(cpu=2, memory=4096, secrets=[secret], timeout=900, scaledown_window=120)
|
||||
@modal.concurrent(max_inputs=8)
|
||||
@modal.asgi_app()
|
||||
def api():
|
||||
import urllib.request
|
||||
|
||||
from fastapi import FastAPI, HTTPException, Request
|
||||
from fastapi.responses import PlainTextResponse, Response
|
||||
|
||||
web = FastAPI()
|
||||
token = os.environ["RAEA_INGEST_TOKEN"]
|
||||
|
||||
def check(req: Request):
|
||||
if req.headers.get("authorization", "").removeprefix("Bearer ") != token:
|
||||
raise HTTPException(401, "a raea ingest token is needed (Authorization: Bearer)")
|
||||
|
||||
@web.post("/v1/index-jobs")
|
||||
async def submit(req: Request):
|
||||
check(req)
|
||||
b = await req.json()
|
||||
if not isinstance(b.get("url"), str) or not b["url"].startswith("https://"):
|
||||
raise HTTPException(400, "url is the file's https address")
|
||||
if b.get("kind") not in ("video", "image", "audio", "doc"):
|
||||
raise HTTPException(400, "kind is one of video, image, audio, doc")
|
||||
call = await index_job.spawn.aio(b["url"], str(b.get("name") or "file"), b["kind"])
|
||||
return {"id": call.object_id}
|
||||
|
||||
@web.get("/v1/index-jobs/{job}")
|
||||
async def collect(job: str, req: Request):
|
||||
check(req)
|
||||
try:
|
||||
out = await modal.FunctionCall.from_id(job).get.aio(timeout=0)
|
||||
except modal.exception.FunctionTimeoutError:
|
||||
return {"state": "failed", "error": "the file took over an hour"}
|
||||
except (TimeoutError, modal.exception.TimeoutError):
|
||||
return {"state": "running"}
|
||||
except Exception as e:
|
||||
return {"state": "failed", "error": str(e)[:300]}
|
||||
if out.get("error"):
|
||||
return {"state": "failed", **out}
|
||||
return {"state": "done", **out}
|
||||
|
||||
# a fingerprint's model (fingerprint_fit below): trained as a job, its state collected like an index job's
|
||||
@web.post("/v1/fingerprints/fit")
|
||||
async def fp_fit(req: Request):
|
||||
check(req)
|
||||
b = await req.json()
|
||||
if not all(isinstance(b.get(k), str) and b[k] for k in ("workspace", "fingerprint")) or not isinstance(b.get("modalities"), dict):
|
||||
raise HTTPException(400, "workspace, fingerprint and modalities {v|a|t: {good, bad, background}}")
|
||||
call = await fingerprint_fit.spawn.aio(b["workspace"], b["fingerprint"], b["modalities"])
|
||||
return {"id": call.object_id}
|
||||
|
||||
@web.get("/v1/fingerprints/jobs/{job}")
|
||||
async def fp_job(job: str, req: Request):
|
||||
check(req)
|
||||
try:
|
||||
out = await modal.FunctionCall.from_id(job).get.aio(timeout=0)
|
||||
except (TimeoutError, modal.exception.TimeoutError):
|
||||
return {"state": "running"}
|
||||
except Exception as e:
|
||||
return {"state": "failed", "error": str(e)[:300]}
|
||||
return {"state": "failed", **out} if out.get("error") else {"state": "done", **out}
|
||||
|
||||
@web.post("/v1/fingerprints/score")
|
||||
async def fp_score(req: Request):
|
||||
check(req)
|
||||
b = await req.json()
|
||||
if not all(isinstance(b.get(k), str) and b[k] for k in ("workspace", "fingerprint")) or not isinstance(b.get("vectors"), dict):
|
||||
raise HTTPException(400, "workspace, fingerprint and vectors {v|a|t: [f16 base64]}")
|
||||
return await fingerprint_score.remote.aio(b["workspace"], b["fingerprint"], b["vectors"])
|
||||
|
||||
@web.get("/healthz")
|
||||
def healthz():
|
||||
return PlainTextResponse("ok")
|
||||
|
||||
@web.post("/v1/frame")
|
||||
async def make_frame(req: Request):
|
||||
check(req)
|
||||
body = await req.json()
|
||||
url, at = body.get("url"), float(body.get("at", 0.1))
|
||||
if not isinstance(url, str) or not url.startswith("https://"):
|
||||
raise HTTPException(400, "url is the file's https address")
|
||||
with tempfile.NamedTemporaryFile(suffix=".media") as f:
|
||||
got = 0
|
||||
try:
|
||||
with urllib.request.urlopen(urllib.request.Request(url, headers={"user-agent": "raea-ingest/1"}), timeout=120) as r:
|
||||
while chunk := r.read(1 << 20):
|
||||
got += len(chunk)
|
||||
if got > MAX_BYTES:
|
||||
raise HTTPException(413, "the file is over 2 GB")
|
||||
f.write(chunk)
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise HTTPException(502, f"couldn't fetch the file: {e}")
|
||||
f.flush()
|
||||
try:
|
||||
jpg = frame(f.name, at)
|
||||
except Exception as e:
|
||||
raise HTTPException(422, f"no frame in it: {e}")
|
||||
return Response(jpg, media_type="image/jpeg")
|
||||
|
||||
return web
|
||||
|
||||
|
||||
# the index jobs' GPU: an L4 by default (EmbeddingGemma 2 at fp16 on CUDA 13: loaded in 6 s, a batch in under one);
|
||||
# RAEA_INDEX_GPU= (empty) at deploy for the CPU at q8
|
||||
GPU = os.environ.get("RAEA_INDEX_GPU", "L4") or None
|
||||
|
||||
# the cloud indexer's own image (tools/library-index/Dockerfile: Node, ffmpeg, EmbeddingGemma 2's and Whisper's weights
|
||||
# baked in) on CUDA 13 with cuDNN 9 (onnxruntime-node 1.30's CUDA provider links CUDA 13, though its package says cuda12), its fp16 weights for the GPU beside the q8
|
||||
# ones, pdftotext for documents and the raea cloud server. EmbeddingGemma 2 (the fingerprints: pictures, shots, sound,
|
||||
# words) runs on the GPU; Whisper, TransNetV2's cuts and ffmpeg on the CPU beside it
|
||||
def indexer_image_for(gpu):
|
||||
return (
|
||||
# on a GPU, build/Dockerfile.gpu (cloud-build.sh: the CUDA 13 base and fp16 weights written in; Modal's builds
|
||||
# don't take a build argument in FROM, so BASE as an argument left a plain Ubuntu without CUDA)
|
||||
modal.Image.from_dockerfile(os.path.join(LIB, "build", "Dockerfile.gpu") if gpu else os.path.join(LIB, "Dockerfile"), context_dir=LIB, add_python="3.12")
|
||||
.apt_install("poppler-utils")
|
||||
.env({"RAEA_LIBRARY_DEVICE": "cuda", "RAEA_LIBRARY_DTYPE": "fp16"} if gpu else {})
|
||||
.add_local_file(os.path.join(LIB, "build", "cloud-server.mjs"), "/app/cloud-server.mjs")
|
||||
.add_local_file(os.path.join(LIB, "build", "cloud-cli.mjs"), "/app/cloud-cli.mjs")
|
||||
)
|
||||
|
||||
|
||||
# index jobs on the GPU when there is one; the search-words server on the CPU (a query is one short text, seconds on a
|
||||
# CPU, and a GPU held five minutes for it isn't worth it; q8 and fp16 vectors of the same model compare)
|
||||
indexer_image = indexer_image_for(GPU)
|
||||
server_image = indexer_image_for(None)
|
||||
|
||||
|
||||
# one file indexed as a job (tools/library-index cloud-cli.ts), for a file of any length: raea cloud submits it through
|
||||
# the API's POST /v1/index-jobs and collects it with GET /v1/index-jobs/ID on its next alarm (index-run.ts)
|
||||
@app.function(image=indexer_image, gpu=GPU, cpu=4, memory=16384, secrets=[secret], timeout=3600, max_containers=12, scaledown_window=120)
|
||||
def index_job(url: str, name: str, kind: str) -> dict:
|
||||
import json
|
||||
import subprocess as sp
|
||||
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
inp, out = os.path.join(d, "in.json"), os.path.join(d, "out.json")
|
||||
with open(inp, "w") as f:
|
||||
json.dump({"url": url, "name": name, "kind": kind}, f)
|
||||
# what's said: Whisper large-v3 on OpenRouter when the secret has its key (words.ts), else Whisper base here
|
||||
words = "openrouter" if os.environ.get("OPENROUTER_API_KEY") else "whisper"
|
||||
r = sp.run(["node", "/app/cloud-cli.mjs", inp, out], cwd="/app", capture_output=True, text=True, timeout=3500, env={**os.environ, "RAEA_LIBRARY_WORDS": words})
|
||||
if r.returncode != 0 or not os.path.exists(out):
|
||||
return {"error": f"the indexer stopped ({r.returncode}): {(r.stderr or '')[-300:]}"}
|
||||
with open(out) as f:
|
||||
return json.load(f)
|
||||
|
||||
|
||||
# a GPU only while there's work: five idle minutes and the container goes
|
||||
@app.function(image=server_image, cpu=4, memory=12288, secrets=[secret], timeout=3600, scaledown_window=300)
|
||||
@modal.concurrent(max_inputs=4)
|
||||
@modal.web_server(8080, startup_timeout=180)
|
||||
def indexer():
|
||||
import subprocess as sp
|
||||
|
||||
sp.Popen(["node", "/app/cloud-server.mjs"], cwd="/app", env={**os.environ, "PORT": "8080"})
|
||||
|
||||
|
||||
# the GPU checked: RAEA_INDEX_GPU=L4 MODAL_PROFILE=raea modal run deploy/modal/ingest.py::gpu_probe. EmbeddingGemma 2
|
||||
# loaded on the GPU at fp16 and two texts embedded, each step timed
|
||||
PROBE = """
|
||||
const t0 = Date.now(), log = (...a) => console.log(`[${((Date.now() - t0) / 1000).toFixed(1)}s]`, ...a)
|
||||
const tf = await import("@huggingface/transformers")
|
||||
tf.env.cacheDir = "/models"
|
||||
const id = "onnx-community/embeddinggemma-2-ONNX"
|
||||
const p = await tf.AutoProcessor.from_pretrained(id)
|
||||
log("model fp16 on", process.env.RAEA_LIBRARY_DEVICE)
|
||||
const m = await tf.AutoModel.from_pretrained(id, { dtype: "fp16", device: process.env.RAEA_LIBRARY_DEVICE || "cpu" })
|
||||
log("loaded")
|
||||
for (let k = 0; k < 2; k++) { const o = await m(await p(["a white rabbit in a forest", "a quarterly sales spreadsheet"])); log("two texts", o.sentence_embedding.dims, o.sentence_embedding.tolist()[0].slice(0, 3)) }
|
||||
process.exit(0)
|
||||
"""
|
||||
|
||||
|
||||
# ---- a fingerprint's model (raea cloud's fingerprint-model.ts; Shane 11-24: "our embedding models for fingerprints
|
||||
# stored and runnable from Modal GPU") ----
|
||||
# Per modality (v picture, a sound, t words), a linear head on EmbeddingGemma 2's 768-d vectors, trained on the GPU:
|
||||
# a fingerprint's good references against its bad ones, and, while it has few or no bad ones, against a sample of the
|
||||
# workspace's other files (what's distinctive in it, against the rest of the library). Its held-out separation (AUC,
|
||||
# k-fold) says how much it has learned. Kept on the volume raea-fingerprints at <workspace>/<fingerprint>.json, the
|
||||
# newest one per fingerprint; fingerprint_score loads it on the GPU and scores vectors (a file's segments) 0..1.
|
||||
# training.ts's SigLIP fine-tune replaces the head once a fingerprint has 200 judged examples.
|
||||
fp_volume = modal.Volume.from_name("raea-fingerprints", create_if_missing=True)
|
||||
fp_image = modal.Image.debian_slim(python_version="3.12").pip_install("torch==2.8.0", "numpy")
|
||||
|
||||
|
||||
def _fp_path(workspace: str, fingerprint: str) -> str:
|
||||
import re
|
||||
|
||||
safe = lambda x: re.sub(r"[^A-Za-z0-9._-]+", "-", x)[:80]
|
||||
return f"/fp/{safe(workspace)}/{safe(fingerprint)}.json"
|
||||
|
||||
|
||||
def _vectors(xs):
|
||||
import base64
|
||||
|
||||
import numpy as np
|
||||
|
||||
rows = [np.frombuffer(base64.b64decode(x), dtype="<f2").astype("float32") for x in xs or [] if isinstance(x, str)]
|
||||
rows = [r for r in rows if r.shape == (768,)]
|
||||
return np.stack(rows) if rows else np.zeros((0, 768), dtype="float32")
|
||||
|
||||
|
||||
def _auc(pos, neg) -> float:
|
||||
import numpy as np
|
||||
|
||||
if not len(pos) or not len(neg):
|
||||
return None
|
||||
allv = np.concatenate([pos, neg])
|
||||
ranks = allv.argsort().argsort() + 1.0
|
||||
return float((ranks[: len(pos)].sum() - len(pos) * (len(pos) + 1) / 2) / (len(pos) * len(neg)))
|
||||
|
||||
|
||||
def _r4(x):
|
||||
return None if x is None else round(x, 4)
|
||||
|
||||
|
||||
def _train(torch, good, neg, wneg, dev, steps=400):
|
||||
"""logistic regression on the GPU, classes balanced, started from the difference of their means"""
|
||||
X = torch.tensor(__import__("numpy").concatenate([good, neg]), device=dev)
|
||||
y = torch.cat([torch.ones(len(good), device=dev), torch.zeros(len(neg), device=dev)])
|
||||
wt = torch.cat([torch.full((len(good),), 0.5 / len(good), device=dev), torch.tensor(wneg, device=dev) * (0.5 / float(sum(wneg)))])
|
||||
init = X[: len(good)].mean(0) - X[len(good) :].mean(0)
|
||||
w = (init / (init.norm() + 1e-6) * 4).clone().requires_grad_(True)
|
||||
b = torch.zeros(1, device=dev, requires_grad=True)
|
||||
opt = torch.optim.Adam([w, b], lr=0.05)
|
||||
for _ in range(steps):
|
||||
opt.zero_grad()
|
||||
logit = X @ w + b
|
||||
loss = (torch.nn.functional.binary_cross_entropy_with_logits(logit, y, reduction="none") * wt).sum() + 1e-3 * (w * w).sum()
|
||||
loss.backward()
|
||||
opt.step()
|
||||
return w.detach(), b.detach()
|
||||
|
||||
|
||||
@app.function(image=fp_image, gpu=GPU, volumes={"/fp": fp_volume}, timeout=900)
|
||||
def fingerprint_fit(workspace: str, fingerprint: str, modalities: dict) -> dict:
|
||||
import json
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
dev = "cuda" if torch.cuda.is_available() else "cpu"
|
||||
out = {"workspace": workspace, "fingerprint": fingerprint, "model": "embeddinggemma-2@768", "version": int(time.time() * 1000), "device": torch.cuda.get_device_name(0) if dev == "cuda" else "cpu", "modalities": {}}
|
||||
for m, d in (modalities or {}).items():
|
||||
if m not in ("v", "a", "t"):
|
||||
continue
|
||||
good, bad, bg = _vectors(d.get("good")), _vectors(d.get("bad")), _vectors(d.get("background"))
|
||||
if len(good) < 3 or len(bad) + len(bg) < 3:
|
||||
continue
|
||||
neg = np.concatenate([bad, bg])
|
||||
# a bad reference says more than an unlabelled file: three times the weight
|
||||
wneg = [3.0] * len(bad) + [1.0] * len(bg)
|
||||
# held-out separation, k-fold on the good side and the negatives alike
|
||||
k = min(5, len(good), len(neg))
|
||||
rng = np.random.default_rng(0)
|
||||
gi, ni = rng.permutation(len(good)) % k, rng.permutation(len(neg)) % k
|
||||
hp, hn, hb = [], [], []
|
||||
for f in range(k):
|
||||
w, b = _train(torch, good[gi != f], neg[ni != f], [x for x, i in zip(wneg, ni) if i != f], dev, steps=250)
|
||||
hp += torch.sigmoid(torch.tensor(good[gi == f], device=dev) @ w + b).tolist()
|
||||
hn += torch.sigmoid(torch.tensor(neg[ni == f], device=dev) @ w + b).tolist()
|
||||
hb += [int(i) < len(bad) for i in np.where(ni == f)[0]]
|
||||
w, b = _train(torch, good, neg, wneg, dev)
|
||||
gs = torch.sigmoid(torch.tensor(good, device=dev) @ w + b).cpu().numpy()
|
||||
out["modalities"][m] = {
|
||||
"w": [round(float(x), 6) for x in w.cpu().numpy()],
|
||||
"b": float(b.cpu().numpy()[0]),
|
||||
"good": int(len(good)),
|
||||
"bad": int(len(bad)),
|
||||
"background": int(len(bg)),
|
||||
"auc": _r4(_auc(np.array(hp), np.array(hn))),
|
||||
# against its bad references alone, when it has any: the boundary people drew
|
||||
"auc_bad": _r4(_auc(np.array(hp), np.array([s for s, x in zip(hn, hb) if x]))),
|
||||
# a typical good example's score, to read a new one against
|
||||
"good_median": round(float(np.median(gs)), 4),
|
||||
}
|
||||
if not out["modalities"]:
|
||||
return {"error": "too few examples: a modality needs 3 good and 3 others"}
|
||||
path = _fp_path(workspace, fingerprint)
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
with open(path, "w") as f:
|
||||
json.dump(out, f)
|
||||
fp_volume.commit()
|
||||
return {k: v for k, v in out.items() if k != "modalities"} | {"modalities": {m: {k: v for k, v in x.items() if k != "w"} for m, x in out["modalities"].items()}, "path": path}
|
||||
|
||||
|
||||
@app.function(image=fp_image, gpu=GPU, volumes={"/fp": fp_volume}, timeout=300, scaledown_window=120)
|
||||
def fingerprint_score(workspace: str, fingerprint: str, vectors: dict) -> dict:
|
||||
import json
|
||||
|
||||
import torch
|
||||
|
||||
fp_volume.reload()
|
||||
path = _fp_path(workspace, fingerprint)
|
||||
if not os.path.exists(path):
|
||||
return {"error": "this fingerprint has no model yet"}
|
||||
model = json.load(open(path))
|
||||
dev = "cuda" if torch.cuda.is_available() else "cpu"
|
||||
scores = {}
|
||||
for m, xs in (vectors or {}).items():
|
||||
head = model["modalities"].get(m)
|
||||
X = _vectors(xs)
|
||||
if not head or not len(X):
|
||||
continue
|
||||
w = torch.tensor(head["w"], device=dev)
|
||||
scores[m] = [round(float(s), 4) for s in torch.sigmoid(torch.tensor(X, device=dev) @ w + head["b"]).tolist()]
|
||||
return {"version": model["version"], "device": torch.cuda.get_device_name(0) if dev == "cuda" else "cpu", "scores": scores, "good_median": {m: h["good_median"] for m, h in model["modalities"].items()}}
|
||||
|
||||
|
||||
@app.function(image=indexer_image, gpu=GPU, cpu=4, memory=16384, timeout=900)
|
||||
def gpu_probe() -> str:
|
||||
import subprocess as sp
|
||||
|
||||
def run(cmd: str, t: int = 600) -> str:
|
||||
r = sp.run(["bash", "-c", cmd], capture_output=True, text=True, timeout=t, cwd="/app")
|
||||
return (r.stdout + r.stderr)[-3000:]
|
||||
|
||||
out = run("nvidia-smi | grep -o 'CUDA Version: [0-9.]*'; nvidia-smi --query-gpu=name --format=csv,noheader")
|
||||
out += run("echo CUDA_VERSION=$CUDA_VERSION NV_CUDA=$NV_CUDA_LIB_VERSION LD=$LD_LIBRARY_PATH; ls -d /usr/local/cuda* 2>&1; find / -xdev \\( -name 'libcublas.so*' -o -name 'libcudart.so*' -o -name 'libcudnn.so*' \\) 2>/dev/null | head; cat /etc/os-release | head -2")
|
||||
out += run("ldd node_modules/onnxruntime-node/bin/napi-v*/linux/x64/libonnxruntime_providers_cuda.so | grep 'not found' || echo 'cuda provider: every library found'")
|
||||
with open("/app/probe.mjs", "w") as f:
|
||||
f.write(PROBE)
|
||||
out += run("node probe.mjs 2>&1 | cut -c1-300")
|
||||
print(out)
|
||||
return out
|
||||
@@ -8,21 +8,35 @@
|
||||
# box is set up by too), and its server started
|
||||
# deploy/sprites/box.sh status NAME its URL, raea, the server's health
|
||||
# deploy/sprites/box.sh token NAME its RAEA_CLOUD_TOKEN, for the TypeScript client
|
||||
# deploy/sprites/box.sh promote NAME the box into raea cloud's list of boxes, at the top: the one work runs on
|
||||
# (POST /v1/admin/boxes; its health must answer). A box below it takes over
|
||||
# by itself when it stops answering, so a box is never swapped by editing secrets
|
||||
# deploy/sprites/box.sh list raea cloud's boxes in order, each one's health and build
|
||||
# deploy/sprites/box.sh latest [VERSION] every box in raea cloud's list onto a release (the newest when none is
|
||||
# named), once its release run has attached the Linux archive: raea and
|
||||
# sdk/cloud's server both from that release's commit, each box after its running
|
||||
# agents finish. tools/agents/release-go.sh runs it after every release it publishes
|
||||
# deploy/sprites/box.sh key NAME a raea agent key (repos and storage scopes) from stdin, or the clipboard, onto
|
||||
# the box as RAEA_AGENT_KEY: its agents clone raea projects (raea-repo clone OWNER
|
||||
# PROJECT DIR, deploy/git/repo.sh), push, and send renders' media by hash (CR22, CR23)
|
||||
#
|
||||
# RAEA_VERSION (0.1.6) and AGENTS ("kimi-code claude-acp") pick what goes on, and RAEA_CLOUD_REF takes sdk/cloud from
|
||||
# RAEA_VERSION (the newest release when unset) and AGENTS ("kimi-code claude-acp") pick what goes on, and RAEA_CLOUD_REF takes sdk/cloud from
|
||||
# raea's public repo at that commit instead of this working tree; the farm comes from
|
||||
# ~/.config/raea-cloud/farm.env (RAEA_CLOUD_GPU_URL, RAEA_CLOUD_GPU_TOKEN). The Sprite's URL stays private to the org.
|
||||
# Game kits need ~/.config/raea-cloud/games/raea-games-linux-x86_64.tgz (raea-decompose and unity-rs built for Linux,
|
||||
# checked against its .sha256 beside it); without it the box can fetch builds but not take them apart.
|
||||
set -euo pipefail
|
||||
|
||||
# the org raea owns, never another business's (org.sh)
|
||||
. "$(dirname "$0")/org.sh"
|
||||
NAME=${2:-}
|
||||
[ -n "$NAME" ] || { echo "box: name the Sprite"; exit 2; }
|
||||
RAEA_VERSION=${RAEA_VERSION:-0.1.6}
|
||||
AGENTS=${AGENTS:-kimi-code claude-acp}
|
||||
[ -n "$NAME" ] || [ "${1:-}" = list ] || [ "${1:-}" = latest ] || { echo "box: name the Sprite"; exit 2; }
|
||||
REPO=shinyobjectz/raea
|
||||
# the newest published release (never an rc): what a box gets unless RAEA_VERSION names one
|
||||
newest() { gh release view -R "$REPO" --json tagName -q .tagName 2>/dev/null | sed 's/^v//'; }
|
||||
if [ -z "${RAEA_VERSION:-}" ] && [ "${1:-}" != latest ]; then RAEA_VERSION=$(newest); fi
|
||||
[ -n "${RAEA_VERSION:-}" ] || [ "${1:-}" = latest ] || { echo "box: couldn't read raea's newest release (gh signed in?); set RAEA_VERSION"; exit 2; }
|
||||
AGENTS=${AGENTS:-kimi-code claude-acp antigravity-acp}
|
||||
HERE=$(cd "$(dirname "$0")/../.." && pwd)
|
||||
FARM=${RAEA_FARM_ENV:-$HOME/.config/raea-cloud/farm.env}
|
||||
|
||||
@@ -38,13 +52,51 @@ up)
|
||||
sprite list -o "$ORG" | grep -qx "$NAME" || sprite create -o "$ORG" --skip-console --label raea --label raea-cloud "$NAME"
|
||||
# sdk/cloud's files from this working tree; with RAEA_CLOUD_REF set, setup.sh takes them from raea's public repo at
|
||||
# that commit instead, as a bot's box does
|
||||
if [ -z "${RAEA_CLOUD_REF:-}" ]; then
|
||||
# Every build is stamped (BUILD.json on the box, shown in its health): the commit, and from a working tree whether it
|
||||
# was dirty, which files, and an id from the packed files themselves; the tarball is kept under
|
||||
# ~/.config/raea-cloud/builds/ID.tgz, so a box can be made again from exactly what another one runs (RAEA_CLOUD_BUILD=ID)
|
||||
builds=$HOME/.config/raea-cloud/builds
|
||||
if [ -n "${RAEA_CLOUD_BUILD:-}" ]; then
|
||||
[ -s "$builds/$RAEA_CLOUD_BUILD.tgz" ] || { echo "box: no build $RAEA_CLOUD_BUILD in $builds"; exit 2; }
|
||||
put "$builds/$RAEA_CLOUD_BUILD.tgz" /tmp/raea-cloud.tgz
|
||||
put "$builds/$RAEA_CLOUD_BUILD.json" /tmp/raea-cloud-build.json
|
||||
elif [ -z "${RAEA_CLOUD_REF:-}" ]; then
|
||||
mkdir -p "$builds"
|
||||
pack=$(mktemp)
|
||||
COPYFILE_DISABLE=1 tar -czf "$pack" --no-mac-metadata -C "$HERE" server src image deploy/git package.json package-lock.json
|
||||
# the id: the packed files' own contents (names and bytes, not their times)
|
||||
id=$(cd "$HERE" && find server src image deploy/git package.json package-lock.json -type f -not -name '.DS_Store' -print0 | sort -z | xargs -0 shasum -a 256 | shasum -a 256 | cut -c1-12)
|
||||
commit=$(git -C "$HERE" rev-parse HEAD)
|
||||
dirty=$(git -C "$HERE" status --porcelain -- . | sed 's/^...//' | tr '\n' ' ')
|
||||
printf '{"build":"%s","commit":"%s","dirty":%s,"changed":"%s","from":"%s"}\n' "$id" "$commit" "$([ -n "$dirty" ] && echo true || echo false)" "${dirty% }" "$(hostname -s)" > "$builds/$id.json"
|
||||
cp "$pack" "$builds/$id.tgz"
|
||||
echo "box: build $id (commit ${commit:0:10}$([ -n "$dirty" ] && echo ", dirty: ${dirty% }"))"
|
||||
put "$pack" /tmp/raea-cloud.tgz
|
||||
put "$builds/$id.json" /tmp/raea-cloud-build.json
|
||||
rm -f "${pack:?}"
|
||||
fi
|
||||
put "$FARM" /tmp/farm.env
|
||||
games=${RAEA_GAMES_TGZ:-$HOME/.config/raea-cloud/games/raea-games-linux-x86_64.tgz}
|
||||
if [ -s "$games" ]; then
|
||||
if [ -s "$games.sha256" ] && ! shasum -a 256 -c --status "$games.sha256"; then echo "box: $games doesn't match its .sha256"; exit 1; fi
|
||||
put "$games" /tmp/raea-games.tgz
|
||||
fi
|
||||
# A box with agents running isn't rebuilt under them: setup.sh restarts the server, which cuts their runs off
|
||||
# (11-25: a StreetTalk project failed mid-run). Waits for none, a quarter of an hour at most; RAEA_BOX_FORCE=1
|
||||
# rebuilds anyway (raea cloud then resumes the cut-off runs, projects.ts resumeRequest).
|
||||
if [ "${RAEA_BOX_FORCE:-}" != 1 ]; then
|
||||
for i in $(seq 1 90); do
|
||||
n=$(x ". ~/.raea-cloud.env 2>/dev/null; curl -fsS -m 5 -H \"authorization: Bearer \$RAEA_CLOUD_TOKEN\" localhost:8080/v1/health 2>/dev/null" | python3 -c 'import json,sys
|
||||
try: print(json.load(sys.stdin).get("running", "unknown"))
|
||||
except Exception: print("down")')
|
||||
# down: nothing to cut off; unknown: a server too old to say, so it isn't rebuilt blind
|
||||
[ "$n" = 0 ] || [ "$n" = down ] && break
|
||||
[ "$n" = unknown ] && { echo "box: $NAME's server doesn't say whether agents are running: rebuild it when it's idle (RAEA_BOX_FORCE=1)"; exit 1; }
|
||||
[ "$i" = 90 ] && { echo "box: $NAME still has $n agents running: not rebuilt (RAEA_BOX_FORCE=1 to cut them off)"; exit 1; }
|
||||
[ "$i" = 1 ] && echo "box: $NAME has $n agents running: waiting for them to finish"
|
||||
sleep 10
|
||||
done
|
||||
fi
|
||||
# the box itself, set up by the one script a bot's box is set up by too
|
||||
if ! sprite exec -o "$ORG" -s "$NAME" -- bash -s -- "$NAME" "$RAEA_VERSION" "$AGENTS" "${RAEA_CLOUD_REF:-}" < "$(dirname "$0")/setup.sh" 2>&1 | quiet; then
|
||||
echo "box: setup.sh failed on $NAME"; exit 1
|
||||
@@ -56,6 +108,62 @@ status)
|
||||
x "/opt/raea/bin/raea --version; . ~/.raea-cloud.env; curl -fsS -H \"authorization: Bearer \$RAEA_CLOUD_TOKEN\" localhost:8080/v1/health | head -c 600; echo"
|
||||
;;
|
||||
token) x ". ~/.raea-cloud.env; echo \$RAEA_CLOUD_TOKEN" ;;
|
||||
latest)
|
||||
# Shane, 11-26: "make sure that release pipeline automatically updates boxes for raea cloud to the latest"
|
||||
version=${2:-$(newest)}
|
||||
[ -n "$version" ] || { echo "box: couldn't read raea's newest release (gh signed in?)"; exit 2; }
|
||||
tag=v$version
|
||||
linux=raea-$version-linux-x86_64.tar.gz
|
||||
attached() { gh release view "$tag" -R "$REPO" --json assets -q '.assets[].name' 2>/dev/null | grep -qx "$linux"; }
|
||||
# a box takes raea's Linux archive, which the tag's release.yml run attaches: that run is waited on to its end
|
||||
if ! attached; then
|
||||
# the run registers a few seconds after the tag is pushed (two minutes at most)
|
||||
id=""
|
||||
for _ in $(seq 1 24); do
|
||||
id=$(gh run list -R "$REPO" -w release.yml -b "$tag" --json databaseId -q '.[0].databaseId' 2>/dev/null)
|
||||
[ -n "$id" ] && break
|
||||
sleep 5
|
||||
done
|
||||
[ -n "$id" ] || { echo "box: no release.yml run for $tag: no box changed"; exit 1; }
|
||||
echo "box: waiting for $tag's release run ($id) to attach the Linux archive"
|
||||
gh run watch "$id" -R "$REPO" --exit-status > /dev/null 2>&1 || attached || { echo "box: $tag's release run failed before its Linux archive: no box changed"; exit 1; }
|
||||
attached || { echo "box: $tag's release run ended without $linux: no box changed"; exit 1; }
|
||||
fi
|
||||
# sdk/cloud's server from the release's own commit in the public repo, as a bot's box takes it
|
||||
ref=$(gh api "repos/$REPO/commits/$tag" -q .sha) || { echo "box: couldn't read $tag's commit"; exit 1; }
|
||||
names=$("$0" list | sed 's/^[* ] *//' | awk '{print $1}' | grep -v '^$') || { echo "box: couldn't list raea cloud's boxes"; exit 1; }
|
||||
[ -n "$names" ] || { echo "box: raea cloud lists no boxes"; exit 1; }
|
||||
failed=""
|
||||
for b in $names; do
|
||||
# a Sprite that's gone or whose disk died (raea-1, 11-25) is reported and passed over; the others still go
|
||||
echo "box: $b onto raea $version (${ref:0:10})"
|
||||
# RAEA_BOX_DRY=1: what it would do, and nothing done
|
||||
[ "${RAEA_BOX_DRY:-}" = 1 ] && continue
|
||||
RAEA_VERSION=$version RAEA_CLOUD_REF=$ref "$0" up "$b" || failed+=" $b"
|
||||
done
|
||||
"$0" list
|
||||
[ "${RAEA_BOX_DRY:-}" = 1 ] && { echo "box: dry run: no box changed"; exit 0; }
|
||||
[ -z "$failed" ] || { echo "box: not on $version:$failed"; exit 1; }
|
||||
echo "box: every box is on raea $version"
|
||||
;;
|
||||
promote | list)
|
||||
# raea cloud's staff key: RAEA_CLOUD_ADMIN_KEY, else the Mac's keychain (raea-cloud-prod-staff-key)
|
||||
api=${RAEA_CLOUD_API:-https://api.raea.cloud}
|
||||
key=${RAEA_CLOUD_ADMIN_KEY:-$(security find-generic-password -s raea-cloud-prod-staff-key -w 2> /dev/null || true)}
|
||||
[ -n "$key" ] || { echo "box: no staff key (RAEA_CLOUD_ADMIN_KEY, or raea-cloud-prod-staff-key in the keychain)"; exit 2; }
|
||||
if [ "$1" = promote ]; then
|
||||
url=$(sprite url -o "$ORG" -s "$NAME" 2>&1 | sed -n 's/^URL: *//p')
|
||||
tok=$(x ". ~/.raea-cloud.env; echo \$RAEA_CLOUD_TOKEN" | tail -1 | tr -d '[:space:]')
|
||||
[ -n "$url" ] && [ ${#tok} -ge 32 ] || { echo "box: couldn't read $NAME's address or token"; exit 1; }
|
||||
body=$(python3 -c 'import json,sys; print(json.dumps({"name": sys.argv[1], "url": sys.argv[2], "token": sys.argv[3], "first": True}))' "$NAME" "$url" "$tok")
|
||||
curl -fsS -X POST -H "authorization: Bearer $key" -H 'content-type: application/json' --data-binary @- "$api/v1/admin/boxes" <<< "$body" > /dev/null || { echo "box: raea cloud refused $NAME"; exit 1; }
|
||||
fi
|
||||
curl -fsS -H "authorization: Bearer $key" "$api/v1/admin/boxes" | python3 -c '
|
||||
import json, sys
|
||||
for b in json.load(sys.stdin)["data"]:
|
||||
bd = b.get("build") or {}
|
||||
print(("* " if b["runs_work"] else " ") + b["name"].ljust(10), b["note"].ljust(22), "build", bd.get("build", "?"), "commit", str(bd.get("commit", "?"))[:10], "dirty" if bd.get("dirty") else "", "raea", bd.get("raea", "?"))'
|
||||
;;
|
||||
key)
|
||||
# never echoed: from a pipe, or the clipboard when there's none
|
||||
if [ -t 0 ]; then k=$(pbpaste); else k=$(cat); fi
|
||||
|
||||
@@ -34,6 +34,15 @@ if [ "$(/opt/raea/bin/raea --version 2> /dev/null)" != "$VERSION" ]; then
|
||||
rm -f "/tmp/$f" "/tmp/$f.sha256"
|
||||
fi
|
||||
|
||||
# the Google sign-in's own browser (server/google-screen.ts): Chrome on a virtual display, shown over VNC
|
||||
sudo -E apt-get install -y -qq --no-install-recommends xvfb x11vnc xdotool fonts-noto-color-emoji > /dev/null
|
||||
command -v google-chrome > /dev/null || {
|
||||
say "google chrome"
|
||||
curl -fsSLo /tmp/chrome.deb https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
|
||||
sudo -E apt-get install -y -qq /tmp/chrome.deb > /dev/null
|
||||
rm -f /tmp/chrome.deb
|
||||
}
|
||||
|
||||
# sdk/cloud's server, client and wrapper, as the image has them (image/Dockerfile)
|
||||
if [ ! -s /tmp/raea-cloud.tgz ]; then
|
||||
[ -n "$REF" ] || { echo "box: no /tmp/raea-cloud.tgz and no REF to take sdk/cloud from"; exit 2; }
|
||||
@@ -68,7 +77,25 @@ if [ -s /tmp/farm.env ]; then
|
||||
fi
|
||||
grep -q '^RAEA_CLOUD_GPU_URL=' ~/.raea-cloud.env || { echo "box: no farm (write RAEA_CLOUD_GPU_URL and RAEA_CLOUD_GPU_TOKEN to /tmp/farm.env)"; exit 2; }
|
||||
umask 022
|
||||
for a in $AGENTS; do raea skills install --agent "$a" > /dev/null 2>&1 || say "raea skills for $a not installed"; done
|
||||
# raea's skills by raea's own agent names (the registry's ids aren't them: 11-25, every box had gone without), into the
|
||||
# box's home; each client's socket links them into its own config folders (server/main.ts linkSkills)
|
||||
for a in $AGENTS; do
|
||||
case "$a" in claude-acp) s=claude ;; antigravity-acp | gemini) s=gemini ;; kimi-code | kimi) s=kimi ;; codex-acp) s=codex ;; *) continue ;; esac
|
||||
/opt/raea/bin/raea skills install --agent "$s" > /dev/null 2>&1 || say "raea skills for $a ($s) not installed"
|
||||
done
|
||||
|
||||
# the build, as the caller stamped it (box.sh: /tmp/raea-cloud-build.json), with what this script put on: shown on
|
||||
# GET /v1/health and raea cloud's /v1/admin/boxes, so which code a box runs is never a guess
|
||||
python3 - "$NAME" "$VERSION" "$REF" << 'PY' > /opt/raea-cloud/BUILD.json
|
||||
import json, os, sys, datetime
|
||||
b = {}
|
||||
try: b = json.load(open("/tmp/raea-cloud-build.json"))
|
||||
except Exception: pass
|
||||
if sys.argv[3]: b.setdefault("commit", sys.argv[3]); b.setdefault("build", sys.argv[3][:12]); b.setdefault("dirty", False)
|
||||
b.update(box=sys.argv[1], raea=sys.argv[2], built_at=datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds"))
|
||||
print(json.dumps(b))
|
||||
PY
|
||||
rm -f /tmp/raea-cloud-build.json
|
||||
|
||||
# the server, as the Sprite's HTTP service on 8080: raea on lavapipe (docs/cloud.feature CL13), renders to the farm
|
||||
cat > /opt/raea-cloud/image/sprite-start.sh << 'EOF'
|
||||
|
||||
@@ -7,4 +7,11 @@ if [ -n "${RAEA_CLOUD_GPU_URL:-}" ] && [ -n "${1:-}" ]; then
|
||||
*" $1 "*) exec node /opt/raea-cloud/server/offload.ts "$@" ;;
|
||||
esac
|
||||
fi
|
||||
# what's said, by the farm's Whisper (server/words.ts): raea's own transcriber is Mac only. `raea transcribe` is the name
|
||||
# agents reach for, so it's the same
|
||||
case "${1:-}" in
|
||||
words|transcribe) exec node /opt/raea-cloud/server/words.ts "$@" ;;
|
||||
# faces cut by the frame or a seam, text too small (server/frames.ts, the farm's face detector)
|
||||
frames) exec node /opt/raea-cloud/server/frames.ts "$@" ;;
|
||||
esac
|
||||
exec /opt/raea/bin/raea "$@"
|
||||
@@ -124,8 +124,12 @@ export function spawnFor(id?: string): Spawn {
|
||||
const cmd = process.env.RAEA_AGENT_CMD
|
||||
if (cmd && (!want || want === "custom")) return { id: "custom", version: "", command: sh(), args: ["-c", cmd], env: {} }
|
||||
const all = installed()
|
||||
const s = want ? all.find((a) => a.id === want) : all[0]
|
||||
if (!s) throw new Error(want ? `${want} isn't installed in this image (installed: ${all.map((a) => a.id).join(", ") || "none"})` : "no agent is installed: build with AGENTS=..., or set RAEA_AGENT_CMD")
|
||||
// no default (11-24, Shane): an agent runs only when it's named, by the request (?agent=) or the box's RAEA_AGENT,
|
||||
// never whichever is installed first, so a run is never on a model nobody picked
|
||||
const ids = all.map((a) => a.id).join(", ") || "none"
|
||||
if (!want) throw new Error(`no agent named: pass ?agent=ID, or set RAEA_AGENT on the box (installed: ${ids})`)
|
||||
const s = all.find((a) => a.id === want)
|
||||
if (!s) throw new Error(`${want} isn't installed in this image (installed: ${ids})`)
|
||||
return s
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
// A Claude subscription's token, made by Claude Code's own sign-in (`claude setup-token`) on this box, so a person
|
||||
// signs in with nothing but a browser: raea cloud asks for a sign-in, shows them the claude.com link it prints, they
|
||||
// sign in there and paste back the code Anthropic shows, and Claude Code prints the token (a year long, for Claude
|
||||
// Code's use only). The token goes back to the caller once and is never kept here: each sign-in runs in a config
|
||||
// folder of its own that's removed when it ends, and one left waiting is stopped after 15 minutes.
|
||||
// POST /v1/claude-token {id, url}: a sign-in started, and the link to open
|
||||
// POST /v1/claude-token/ID {code} {token}: the code pasted in; or {error}
|
||||
// POST /v1/claude-token/check {token} {ok, said}: one short turn on a token
|
||||
import { type ChildProcess, spawn } from "node:child_process"
|
||||
import { randomBytes } from "node:crypto"
|
||||
import { mkdtempSync, rmSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import path from "node:path"
|
||||
|
||||
interface SignIn {
|
||||
child: ChildProcess
|
||||
dir: string
|
||||
out: string
|
||||
url?: string
|
||||
token?: string
|
||||
ended: boolean
|
||||
timer: NodeJS.Timeout
|
||||
}
|
||||
|
||||
const waiting = new Map<string, SignIn>()
|
||||
|
||||
/** a program on a terminal (200x60), its input from our stdin and its screen to our stdout. script(1) was here first,
|
||||
* but Claude Code never took Enter after a long code through it; written to the terminal directly, it does */
|
||||
const BRIDGE = `import os, pty, select, struct, fcntl, termios, sys
|
||||
pid, fd = pty.fork()
|
||||
if pid == 0:
|
||||
os.execvp(sys.argv[1], sys.argv[1:])
|
||||
fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", 60, 200, 0, 0))
|
||||
while True:
|
||||
r, _, _ = select.select([fd, 0], [], [])
|
||||
if fd in r:
|
||||
try:
|
||||
b = os.read(fd, 65536)
|
||||
except OSError:
|
||||
break
|
||||
if not b:
|
||||
break
|
||||
os.write(1, b)
|
||||
if 0 in r:
|
||||
b = os.read(0, 65536)
|
||||
if not b:
|
||||
break
|
||||
os.write(fd, b)
|
||||
os.kill(pid, 9) if os.waitpid(pid, os.WNOHANG) == (0, 0) else None
|
||||
`
|
||||
const CLAUDE = process.env.RAEA_CLAUDE_BIN ?? "claude"
|
||||
const TOKEN = /sk-ant-oat01-[A-Za-z0-9_-]{20,}/
|
||||
|
||||
/** the text a terminal shows, with its escapes gone; OSC 8 links keep their address */
|
||||
export const plain = (s: string) =>
|
||||
s
|
||||
.replace(/\x1b\]8;[^;]*;([^\x07\x1b]*)(?:\x07|\x1b\\)/g, " $1 ")
|
||||
.replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g, "")
|
||||
.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, "")
|
||||
|
||||
/** the sign-in link Claude Code printed */
|
||||
export const urlIn = (out: string) => /https:\/\/claude\.(?:com|ai)\/\S*oauth\/authorize\?\S+/.exec(plain(out))?.[0]
|
||||
/** the token it printed once the code was accepted (on one line: the terminal is 200 columns wide, room for it; 1000 broke Enter after a long code) */
|
||||
export const tokenIn = (out: string) => TOKEN.exec(plain(out))?.[0]
|
||||
|
||||
function end(id: string) {
|
||||
const s = waiting.get(id)
|
||||
if (!s) return
|
||||
waiting.delete(id)
|
||||
clearTimeout(s.timer)
|
||||
if (s.child.exitCode === null) s.child.kill("SIGTERM")
|
||||
rmSync(s.dir, { recursive: true, force: true })
|
||||
}
|
||||
|
||||
const until = async (s: SignIn, ok: () => boolean, ms: number) => {
|
||||
for (let t = 0; t < ms && !ok() && !s.ended; t += 200) await new Promise((r) => setTimeout(r, 200))
|
||||
}
|
||||
|
||||
export async function startClaudeSignIn(env: NodeJS.ProcessEnv): Promise<{ id: string; url: string }> {
|
||||
const dir = mkdtempSync(path.join(tmpdir(), "claude-sign-in-"))
|
||||
const id = randomBytes(12).toString("hex")
|
||||
const clean: NodeJS.ProcessEnv = { ...env, CLAUDE_CONFIG_DIR: dir, BROWSER: "true", TERM: "xterm-256color" }
|
||||
for (const k of ["ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN"]) delete clean[k]
|
||||
// Claude Code on a terminal of its own (BRIDGE), 200 columns: the token fits on one line (the link is read from its
|
||||
// OSC 8 address)
|
||||
const child = spawn("python3", ["-I", "-c", BRIDGE, CLAUDE, "setup-token"], { cwd: dir, env: clean, stdio: ["pipe", "pipe", "pipe"] })
|
||||
const s: SignIn = { child, dir, out: "", ended: false, timer: setTimeout(() => end(id), 15 * 60_000) }
|
||||
waiting.set(id, s)
|
||||
const read = (c: string) => {
|
||||
s.out += c
|
||||
s.url ??= urlIn(s.out)
|
||||
s.token ??= tokenIn(s.out)
|
||||
}
|
||||
child.stdout!.setEncoding("utf8").on("data", read)
|
||||
child.stderr!.setEncoding("utf8").on("data", read)
|
||||
child.on("exit", () => (s.ended = true))
|
||||
await until(s, () => !!s.url, 30_000)
|
||||
if (!s.url) {
|
||||
const why = plain(s.out).replace(/\s+/g, " ").trim().slice(-300)
|
||||
end(id)
|
||||
throw new Error(`Claude Code didn't print a sign-in link${why ? `: ${why}` : ""}`)
|
||||
}
|
||||
return { id, url: s.url }
|
||||
}
|
||||
|
||||
export async function finishClaudeSignIn(id: string, code: string): Promise<{ token: string }> {
|
||||
const s = waiting.get(id)
|
||||
if (!s) throw new Error("that sign-in has ended (they last 15 minutes): start again")
|
||||
const c = code.trim()
|
||||
if (!/^[A-Za-z0-9_#.~-]{10,600}$/.test(c)) throw new Error("that doesn't look like the code claude.com showed")
|
||||
const from = s.out.length
|
||||
// the code as one paste, then Enter on its own a second later (Enter in the same write is taken as part of the paste)
|
||||
s.child.stdin!.write(c)
|
||||
await new Promise((r) => setTimeout(r, 1000))
|
||||
s.child.stdin!.write("\r")
|
||||
// done at the token, or as soon as Claude Code says the code was wrong
|
||||
await until(s, () => !!s.token || /OAuth error|Invalid code|expired/i.test(plain(s.out.slice(from))), 60_000)
|
||||
const token = s.token
|
||||
const said = plain(s.out.slice(from)).replace(/\s+/g, " ").trim()
|
||||
// what Claude Code said after the code, any token masked: the service log shows why a sign-in didn't finish
|
||||
console.log(`raea-cloud: claude sign-in ${id.slice(0, 6)} ${token ? "got a token" : "no token"}: ${JSON.stringify(s.out.slice(from).replace(/sk-ant-[A-Za-z0-9_-]{8,}/g, "sk-ant-…")).slice(-1500)}`)
|
||||
end(id)
|
||||
if (!token) throw new Error(`Claude Code didn't accept the code${said ? `: ${said.slice(-300)}` : ""}`)
|
||||
return { token }
|
||||
}
|
||||
|
||||
/** whether a token (a subscription's, or an API key) gets an answer from Claude Code: one short turn, in a config folder
|
||||
* of its own that's removed after. {ok, said} */
|
||||
export async function checkClaude(env: NodeJS.ProcessEnv, token: string): Promise<{ ok: boolean; said: string }> {
|
||||
const t = token.trim()
|
||||
if (!/^sk-ant-(oat01|api03)-[A-Za-z0-9_-]{20,}$/.test(t)) throw new Error("that isn't a Claude token (sk-ant-oat01-…) or API key (sk-ant-api03-…)")
|
||||
const dir = mkdtempSync(path.join(tmpdir(), "claude-check-"))
|
||||
const clean: NodeJS.ProcessEnv = { ...env, CLAUDE_CONFIG_DIR: dir }
|
||||
delete clean.ANTHROPIC_API_KEY
|
||||
delete clean.CLAUDE_CODE_OAUTH_TOKEN
|
||||
clean[t.startsWith("sk-ant-oat01-") ? "CLAUDE_CODE_OAUTH_TOKEN" : "ANTHROPIC_API_KEY"] = t
|
||||
try {
|
||||
const child = spawn(CLAUDE, ["-p", "Reply with just the word: ready", "--max-turns", "1"], { cwd: dir, env: clean, stdio: ["ignore", "pipe", "pipe"] })
|
||||
let out = ""
|
||||
child.stdout.setEncoding("utf8").on("data", (c: string) => (out += c))
|
||||
child.stderr.setEncoding("utf8").on("data", (c: string) => (out += c))
|
||||
const code = await new Promise<number | null>((ok) => {
|
||||
const timer = setTimeout(() => child.kill("SIGTERM"), 90_000)
|
||||
child.on("exit", (c) => (clearTimeout(timer), ok(c)))
|
||||
})
|
||||
const said = plain(out).replace(/\s+/g, " ").trim().slice(0, 400)
|
||||
return { ok: code === 0 && /ready/i.test(said), said }
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
// `raea frames check` on a raea cloud box: what an export's pictures get wrong that a viewer sees at once, measured
|
||||
// (11-25, Shane: "it cuts out faces all the time and also does split frame shots when they make no sense", "it makes
|
||||
// text too small on some things, we should have a text/glyph readability check and measurement").
|
||||
//
|
||||
// raea frames check VIDEO [--manifest RENDER.json] [-o REPORT.json]
|
||||
// faces: VIDEO's frames, two a second, through the farm's face detector (POST /v1/faces, OpenCV's YuNet; a box has
|
||||
// no vision backend of its own). A face of a person in the shot (at least 6% of the frame's height) touching an
|
||||
// edge is cut by the frame: for a second or more it's an error, shorter a warning.
|
||||
// text: each text the render's manifest shows (raea render --manifest; a .tsx render through raea cloud writes
|
||||
// VIDEO.render.json by itself), its font size in pixels of a 1080-wide frame: under 40 px is an error (no one
|
||||
// reads it on a phone), under 48 px a warning (small for anything but a badge or small print).
|
||||
// Exit 1 on any error. A face at the edge that's meant (someone walking out of shot) is said, with its reason, in
|
||||
// VIDEO.despite.txt beside the video: its findings are then warnings.
|
||||
import { spawnSync } from "node:child_process"
|
||||
import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { pathToFileURL } from "node:url"
|
||||
|
||||
/** frames sampled a second, and the width they're read at (a face's place is in shares of the picture) */
|
||||
const RATE = 2
|
||||
const SIDE = 540
|
||||
/** a face this share of the frame's height or more is someone in the shot, not a passer-by far behind (a split
|
||||
* screen's half holds a face about this big) */
|
||||
export const FACE_MIN = 0.05
|
||||
/** least font sizes, in pixels of a frame 1080 wide (its shorter side): the Direct Response skill's table */
|
||||
export const TEXT_ERROR = 40
|
||||
export const TEXT_WARN = 48
|
||||
|
||||
export type Finding = { level: "error" | "warn"; kind: "face-cut" | "split" | "text-small"; at: number | null; until?: number; says: string }
|
||||
/** a line where the picture jumps across nearly the whole frame (the farm's): its axis (h, a row), where, and its share */
|
||||
export type Seam = [string, number, number]
|
||||
export type Faces = { w: number; h: number; faces: number[][]; seams?: Seam[] } | null
|
||||
type Split = { axis: "h" | "v"; at: number }
|
||||
|
||||
/** a frame's split-screen seams: lone lines in its middle 60% (a bar's two edges close together are a caption's box, a
|
||||
* badge or a letterbox, not a seam) */
|
||||
export function splitsOf(fr: NonNullable<Faces>): Split[] {
|
||||
const out: Split[] = []
|
||||
for (const axis of ["h", "v"] as const) {
|
||||
const dim = axis === "h" ? fr.h : fr.w
|
||||
const at = [...new Set((fr.seams ?? []).filter((x) => x[0] === axis).map((x) => x[1]))].sort((a, b) => a - b)
|
||||
const lines = at.filter((y, i) => i === 0 || y - at[i - 1] > 4)
|
||||
for (const y of lines) {
|
||||
const bar = lines.some((o) => o !== y && Math.abs(o - y) < dim * 0.15)
|
||||
if (!bar && y > dim * 0.2 && y < dim * 0.8) out.push({ axis, at: y })
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const near = (a: Split, b: Split) => a.axis === b.axis && Math.abs(a.at - b.at) <= 6
|
||||
const big = (fr: NonNullable<Faces>) => fr.faces.filter((f) => f[3] >= fr.h * FACE_MIN)
|
||||
|
||||
/** what cuts a face in a frame: an edge of the frame, or a split screen's seam */
|
||||
function cutBy(fr: NonNullable<Faces>, splits: Split[]): string | null {
|
||||
for (const [x, y, fw, fh] of big(fr)) {
|
||||
if (x <= 1) return "the left edge"
|
||||
if (x + fw >= fr.w - 1) return "the right edge"
|
||||
if (y <= 1) return "the top edge"
|
||||
if (y + fh >= fr.h - 1) return "the bottom edge"
|
||||
for (const sp of splits) {
|
||||
const [a, b] = sp.axis === "h" ? [y, y + fh] : [x, x + fw]
|
||||
if ((a < sp.at - 2 && b > sp.at + 2) || Math.abs(b - sp.at) <= 3 || Math.abs(a - sp.at) <= 3) return "the split screen's seam"
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** runs of the same thing in consecutive frames, as [from, to) in frames */
|
||||
function runs<T>(xs: (T | null)[], same: (a: T, b: T) => boolean = (a, b) => a === b): [number, number, T][] {
|
||||
const out: [number, number, T][] = []
|
||||
for (let i = 0; i < xs.length; ) {
|
||||
const x = xs[i]
|
||||
if (x === null) {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
let j = i + 1
|
||||
while (j < xs.length && xs[j] !== null && same(x, xs[j] as T)) j++
|
||||
out.push([i, j, x])
|
||||
i = j
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** faces cut by the frame's edges or a split screen's seam (a second or more an error, shorter a warning), and split
|
||||
* screens that hold one person (a split is for two things at once) */
|
||||
export function cutFaces(frames: Faces[], rate = RATE): Finding[] {
|
||||
const raw = frames.map((fr) => (fr ? splitsOf(fr) : []))
|
||||
// a seam held for a second or more: a split screen; a line for a frame is a cut or a flash
|
||||
const held = raw.map((ss, i) => ss.filter((s) => (raw[i - 1] ?? []).some((o) => near(s, o)) || (raw[i + 1] ?? []).some((o) => near(s, o))))
|
||||
const out: Finding[] = []
|
||||
const hits = frames.map((fr, i) => (fr ? cutBy(fr, held[i]) : null))
|
||||
for (const [i, j, by] of runs(hits)) {
|
||||
const from = i / rate
|
||||
const to = j / rate
|
||||
out.push({ level: to - from >= 1 ? "error" : "warn", kind: "face-cut", at: from, until: to, says: `a face is cut by ${by} from ${from.toFixed(1)} s to ${to.toFixed(1)} s: reframe on the person (both eyes, mouth and chin inside the picture)${by.includes("seam") ? ", or cut between two singles" : " or cut away"}` })
|
||||
}
|
||||
const split = held.map((ss) => ss[0] ?? null)
|
||||
for (const [i, j, sp] of runs(split, near)) {
|
||||
if (j - i < 2) continue
|
||||
// whose face is on each side of the seam, frame by frame
|
||||
let one = 0
|
||||
let any = 0
|
||||
for (let k = i; k < j; k++) {
|
||||
const fr = frames[k]
|
||||
if (!fr) continue
|
||||
const sides = new Set(big(fr).map(([x, y, fw, fh]) => ((sp.axis === "h" ? y + fh / 2 : x + fw / 2) < sp.at ? 0 : 1)))
|
||||
if (sides.size) any++
|
||||
if (sides.size === 1) one++
|
||||
}
|
||||
const from = i / rate
|
||||
const to = j / rate
|
||||
const where = sp.axis === "h" ? "top and bottom" : "side by side"
|
||||
if (any && one * 2 > any) out.push({ level: "warn", kind: "split", at: from, until: to, says: `a split screen (${where}) from ${from.toFixed(1)} s to ${to.toFixed(1)} s shows a face in only one half: split only for two things at once (two people reacting, a face and the product), else cut between singles` })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** texts under the size floor, from a render manifest: each text once, at its first frame */
|
||||
export function smallText(manifest: any): Finding[] {
|
||||
const w = Number(manifest?.width) || 1080
|
||||
const h = Number(manifest?.height) || 1920
|
||||
const fps = Number(manifest?.fps) || 30
|
||||
const scale = 1080 / Math.min(w, h)
|
||||
const seen = new Map<string, { at: number; px: number }>()
|
||||
for (const fr of (manifest?.frames ?? []) as any[]) {
|
||||
for (const t of (fr?.text ?? []) as any[]) {
|
||||
const text = String(t?.text ?? "").trim()
|
||||
if (!text || (t?.opacity ?? 1) <= 0.05) continue
|
||||
const px = Number(t?.size) * scale
|
||||
if (!Number.isFinite(px) || px <= 0) continue
|
||||
const was = seen.get(text)
|
||||
if (!was || px > was.px) seen.set(text, { at: was?.at ?? Number(fr?.frame ?? 0) / fps, px })
|
||||
}
|
||||
}
|
||||
const out: Finding[] = []
|
||||
for (const [text, { at, px }] of seen) {
|
||||
const q = text.length > 40 ? `"${text.slice(0, 40)}..."` : `"${text}"`
|
||||
if (px < TEXT_ERROR) out.push({ level: "error", kind: "text-small", at, says: `${q} is ${px.toFixed(0)} px (in a 1080-wide frame): under ${TEXT_ERROR} px no one reads it on a phone. Make it bigger, or cut words so it fits bigger` })
|
||||
else if (px < TEXT_WARN) out.push({ level: "warn", kind: "text-small", at, says: `${q} is ${px.toFixed(0)} px: small for anything but a badge or small print (captions 52 px, hooks 64 px)` })
|
||||
}
|
||||
return out.sort((a, b) => (a.at ?? 0) - (b.at ?? 0))
|
||||
}
|
||||
|
||||
function ffmpeg(args: string[]) {
|
||||
const r = spawnSync("ffmpeg", args, { encoding: "utf8" })
|
||||
if (r.status !== 0) throw new Error(`ffmpeg: ${(r.stderr ?? "").slice(-400)}`)
|
||||
}
|
||||
|
||||
/** VIDEO's faces, two frames a second, by the farm */
|
||||
export async function faces(file: string, f: typeof fetch = fetch): Promise<Faces[]> {
|
||||
const url = process.env.RAEA_CLOUD_GPU_URL
|
||||
const token = process.env.RAEA_CLOUD_GPU_TOKEN ?? ""
|
||||
if (!url) throw new Error("the faces check needs the farm (RAEA_CLOUD_GPU_URL); this box has none set")
|
||||
const dir = mkdtempSync(path.join(os.tmpdir(), "raea-frames-"))
|
||||
try {
|
||||
ffmpeg(["-v", "error", "-y", "-i", file, "-vf", `fps=${RATE},scale='if(gt(iw,ih),-2,${SIDE})':'if(gt(iw,ih),${SIDE},-2)'`, "-q:v", "4", path.join(dir, "f%05d.jpg")])
|
||||
const jpgs = readdirSync(dir).filter((n) => n.endsWith(".jpg")).sort()
|
||||
const out: Faces[] = []
|
||||
for (let i = 0; i < jpgs.length; i += 300) {
|
||||
const body = JSON.stringify({ frames: jpgs.slice(i, i + 300).map((n) => readFileSync(path.join(dir, n)).toString("base64")) })
|
||||
let r: Response | undefined
|
||||
let why = ""
|
||||
for (let k = 0; k < 4; k++) {
|
||||
r = await f(`${url.replace(/\/$/, "")}/v1/faces`, { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body, signal: AbortSignal.timeout(300_000) })
|
||||
if (r.ok) break
|
||||
why = `${r.status} ${(await r.text()).slice(0, 300)}`
|
||||
if (r.status < 500) break
|
||||
await new Promise((ok) => setTimeout(ok, 1000 * 2 ** k))
|
||||
}
|
||||
if (!r?.ok) throw new Error(`the farm couldn't look at ${path.basename(file)}: ${why}`)
|
||||
out.push(...((await r.json()) as { frames: Faces[] }).frames)
|
||||
}
|
||||
return out
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
function flag(args: string[], name: string): string | undefined {
|
||||
const i = args.indexOf(name)
|
||||
return i >= 0 ? args[i + 1] : undefined
|
||||
}
|
||||
|
||||
/** the manifest a render of VIDEO wrote: --manifest, or VIDEO.render.json beside it */
|
||||
export const manifestOf = (video: string) => `${video.slice(0, video.length - path.extname(video).length)}.render.json`
|
||||
|
||||
export async function main(args: string[]): Promise<number> {
|
||||
const a = args[0] === "check" ? args.slice(1) : args
|
||||
const video = a.find((x, i) => !x.startsWith("-") && !["--manifest", "-o"].includes(a[i - 1] ?? ""))
|
||||
if (!video || !existsSync(video)) {
|
||||
console.error("usage: raea frames check VIDEO [--manifest RENDER.json] [-o REPORT.json] (faces cut by the frame, and text too small to read)")
|
||||
return 2
|
||||
}
|
||||
const m = flag(a, "--manifest") ?? manifestOf(video)
|
||||
const found: Finding[] = []
|
||||
let looked = 0
|
||||
try {
|
||||
const fr = await faces(video)
|
||||
looked = fr.length
|
||||
found.push(...cutFaces(fr))
|
||||
} catch (e) {
|
||||
console.log(`WARN the faces check couldn't run: ${(e as Error).message}`)
|
||||
}
|
||||
const texts = existsSync(m) ? smallText(JSON.parse(readFileSync(m, "utf8"))) : null
|
||||
if (texts) found.push(...texts)
|
||||
const despite = `${video.slice(0, video.length - path.extname(video).length)}.despite.txt`
|
||||
const why = existsSync(despite) ? readFileSync(despite, "utf8").trim() : ""
|
||||
const out = found.map((x) => (why && x.kind === "face-cut" ? { ...x, level: "warn" as const, says: `${x.says} (despite: ${why.slice(0, 200)})` } : x)).sort((p, q) => (p.at ?? 0) - (q.at ?? 0))
|
||||
for (const x of out) console.log(`${x.level === "error" ? "ERROR" : "WARN "} ${x.at === null ? "" : `${x.at.toFixed(1)} s `}${x.says}`)
|
||||
const errors = out.filter((x) => x.level === "error").length
|
||||
const report = flag(a, "-o") ?? `${video.slice(0, video.length - path.extname(video).length)}.frames-check.json`
|
||||
writeFileSync(report, JSON.stringify({ video, looked_at: looked, text_checked: texts !== null, findings: out }, null, 1))
|
||||
console.log(`${errors ? "FAILED" : "PASSED"} ${path.basename(video)}: ${looked} frames looked at for faces, ${texts === null ? "no manifest for its text" : `${new Set(texts.map((t) => t.says)).size} small texts`}, ${errors} errors, ${out.length - errors} warnings; ${path.basename(report)}`)
|
||||
return errors ? 1 : 0
|
||||
}
|
||||
|
||||
if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
|
||||
const a = process.argv.slice(2)
|
||||
main(a[0] === "frames" ? a.slice(1) : a).then(
|
||||
(c) => process.exit(c),
|
||||
(e) => (console.error(`raea frames: ${(e as Error).message}`), process.exit(1)),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
// The Google sign-in's own browser (11-24, Shane: "I don't want people having to do it themselves"). Antigravity's
|
||||
// Google sign-in sends the browser back to 127.0.0.1 on the machine it runs on, so a browser on the person's computer
|
||||
// lands on a page that can't load. Here the sign-in runs in a Chrome on the box instead, on a virtual display of its
|
||||
// own, and the person sees and works it from the dashboard over VNC (RFB, carried on a WebSocket: main.ts
|
||||
// /v1/google-token/ID/screen). Google's last step then lands on Antigravity's listener on the box and the sign-in
|
||||
// finishes by itself, 2-step verification and all (checked 11-24 on Shane's account).
|
||||
//
|
||||
// Each sign-in gets its own display, Chrome profile (in the sign-in's folder, so the Google session it holds is removed
|
||||
// with it) and VNC port; all three stop when the sign-in ends. With no Chrome installed there's no screen, and the
|
||||
// sign-in falls back to the pasted address.
|
||||
import { type ChildProcess, spawn, spawnSync } from "node:child_process"
|
||||
import { existsSync, readFileSync, rmSync } from "node:fs"
|
||||
import { connect } from "node:net"
|
||||
import path from "node:path"
|
||||
|
||||
/** the screen's size: Google's sign-in fits it, and the dashboard's panel scales it */
|
||||
export const SCREEN = { width: 960, height: 760 }
|
||||
const CHROMES = ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser"]
|
||||
|
||||
export interface Screen {
|
||||
/** the VNC server's port on 127.0.0.1 */
|
||||
port: number
|
||||
/** whether it's still up */
|
||||
up(): boolean
|
||||
stop(): void
|
||||
}
|
||||
|
||||
const which = (bin: string) => spawnSync("sh", ["-c", `command -v ${bin}`], { encoding: "utf8" }).stdout.trim()
|
||||
const chrome = () => process.env.RAEA_CHROME || CHROMES.map(which).find(Boolean) || ""
|
||||
/** whether this box can show a sign-in: Chrome, a virtual display and a VNC server */
|
||||
export const canShow = () => !!chrome() && !!which("Xvfb") && !!which("x11vnc")
|
||||
|
||||
const until = async (ok: () => boolean, ms: number) => {
|
||||
for (let t = 0; t < ms && !ok(); t += 100) await new Promise((r) => setTimeout(r, 100))
|
||||
return ok()
|
||||
}
|
||||
const listening = (port: number) =>
|
||||
new Promise<boolean>((ok) => {
|
||||
const s = connect(port, "127.0.0.1")
|
||||
s.once("connect", () => (s.destroy(), ok(true)))
|
||||
s.once("error", () => ok(false))
|
||||
})
|
||||
|
||||
const alive = (pid: number) => {
|
||||
try {
|
||||
process.kill(pid, 0)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
/** the first display number from 100 that's free: no X server holds it (a socket and lock left by one that's gone,
|
||||
* as a restart of the service leaves them, are cleared) */
|
||||
function freeDisplay(): number {
|
||||
for (let n = 100; n < 400; n++) {
|
||||
const sock = `/tmp/.X11-unix/X${n}`, lock = `/tmp/.X${n}-lock`
|
||||
const pid = existsSync(lock) ? Number(readFileSync(lock, "utf8").trim()) : 0
|
||||
if (pid && alive(pid)) continue
|
||||
if (existsSync(sock) || existsSync(lock)) {
|
||||
try {
|
||||
rmSync(sock, { force: true })
|
||||
rmSync(lock, { force: true })
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
throw new Error("no free display for the sign-in's browser")
|
||||
}
|
||||
|
||||
/** whether Chrome has a window up on display n (xdotool; without it, assumed so) */
|
||||
const windowUp = (n: number) => {
|
||||
if (!which("xdotool")) return true
|
||||
const r = spawnSync("xdotool", ["search", "--onlyvisible", "--class", "chrome"], { env: { ...process.env, DISPLAY: `:${n}` }, encoding: "utf8" })
|
||||
return r.status === 0 && r.stdout.trim() !== ""
|
||||
}
|
||||
|
||||
/** a Chrome on a display of its own at url, served over VNC on 127.0.0.1; its profile is under dir */
|
||||
export async function openScreen(dir: string, url: string): Promise<Screen> {
|
||||
const bin = chrome()
|
||||
if (!bin) throw new Error("no Chrome on this box")
|
||||
const n = freeDisplay()
|
||||
const port = 5900 + n
|
||||
const kids: ChildProcess[] = []
|
||||
const stop = () => {
|
||||
for (const k of kids.reverse()) if (k.exitCode === null && k.signalCode === null) k.kill("SIGTERM")
|
||||
}
|
||||
try {
|
||||
const x = spawn("Xvfb", [`:${n}`, "-screen", "0", `${SCREEN.width}x${SCREEN.height}x24`, "-nolisten", "tcp"], { stdio: "ignore" })
|
||||
kids.push(x)
|
||||
if (!(await until(() => existsSync(`/tmp/.X11-unix/X${n}`) || x.exitCode !== null, 10_000)) || x.exitCode !== null) throw new Error("the virtual display didn't start")
|
||||
const env = { ...process.env, DISPLAY: `:${n}` }
|
||||
// no sandbox: the box's container has no user namespaces for it (test-type keeps Chrome from warning about that in
|
||||
// a bar across Google's page; pages can't see either flag); the window is an app window (no tabs or address
|
||||
// bar), the whole screen, and keeps its passwords in its profile (no keyring to ask about)
|
||||
kids.push(
|
||||
spawn(
|
||||
bin,
|
||||
[
|
||||
"--no-sandbox",
|
||||
"--test-type",
|
||||
"--disable-gpu",
|
||||
"--disable-dev-shm-usage",
|
||||
"--no-first-run",
|
||||
"--no-default-browser-check",
|
||||
"--password-store=basic",
|
||||
`--user-data-dir=${path.join(dir, "chrome")}`,
|
||||
"--window-position=0,0",
|
||||
`--window-size=${SCREEN.width},${SCREEN.height}`,
|
||||
`--app=${url}`,
|
||||
],
|
||||
{ env, stdio: "ignore" },
|
||||
),
|
||||
)
|
||||
kids.push(spawn("x11vnc", ["-display", `:${n}`, "-localhost", "-nopw", "-forever", "-shared", "-quiet", "-rfbport", String(port)], { env, stdio: "ignore" }))
|
||||
let ok = false
|
||||
for (let t = 0; t < 10_000 && !ok; t += 200) {
|
||||
ok = await listening(port)
|
||||
if (!ok) await new Promise((r) => setTimeout(r, 200))
|
||||
}
|
||||
if (!ok) throw new Error("the sign-in's screen didn't start")
|
||||
// the page, not a black screen: a fresh Chrome profile takes a while on the box's CPU (about 20 s seen 11-24)
|
||||
for (let t = 0; t < 45_000 && !windowUp(n); t += 300) await new Promise((r) => setTimeout(r, 300))
|
||||
} catch (e) {
|
||||
stop()
|
||||
throw e
|
||||
}
|
||||
return { port, up: () => kids.every((k) => k.exitCode === null && k.signalCode === null), stop }
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
// A Google AI subscription (Google One AI Pro or Ultra) for the box's Gemini agent, Google Antigravity (the ACP
|
||||
// registry's antigravity-acp). Since 2026-06-18 Gemini CLI refuses personal Google sign-ins, and Antigravity is where
|
||||
// Google sends them; it is also where Pro and Ultra get Gemini 4 Neon. Its "Log in with Google" (ACP method
|
||||
// oauth-personal) is an OAuth sign-in whose address sends the browser back to 127.0.0.1 on the machine it runs on.
|
||||
// Here that machine is the box, so the person signs in in their own browser, lands on a page that doesn't load (their
|
||||
// computer has nothing on that port), and pastes that page's address back; the box hands it to Antigravity's own
|
||||
// listener on 127.0.0.1, exactly as their browser would have.
|
||||
//
|
||||
// Off macOS Antigravity keeps its Google token as one JSON file under GEMINI_HOME. After a sign-in that file goes back
|
||||
// to the caller once, as one string (agy1:BASE64 of {path under GEMINI_HOME: text}), and is never kept here: each
|
||||
// sign-in runs in a folder of its own that's removed when it ends, and one left waiting is stopped after 15 minutes.
|
||||
// An agent socket that's given the string (x-raea-agent-env RAEA_GOOGLE_CREDENTIAL, main.ts) has it written into its
|
||||
// own GEMINI_HOME before Antigravity starts.
|
||||
// Where the box has a Chrome (google-screen.ts) the sign-in can run in a browser on the box instead, which the person
|
||||
// works from the dashboard: Google's last step then reaches Antigravity's listener on its own, and nothing is pasted.
|
||||
// POST /v1/google-token {screen?} {id, url, screen}: a sign-in started, the link to open, and whether it
|
||||
// runs in the box's own browser (WS /v1/google-token/ID/screen shows it)
|
||||
// POST /v1/google-token/ID {address?} {credential, email?}: with the address the browser landed on; with none,
|
||||
// once the box's browser has finished it ({pending: true} while it hasn't,
|
||||
// after waiting up to 25 s); or {error}
|
||||
// POST /v1/google-token/check {credential} {ok, said, models, current}: one short turn on a credential or a Gemini
|
||||
// API key (AIza…)
|
||||
import { type ChildProcess, spawn } from "node:child_process"
|
||||
import { randomBytes } from "node:crypto"
|
||||
import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import path from "node:path"
|
||||
import { spawnFor } from "./agents.ts"
|
||||
import { canShow, openScreen, type Screen } from "./google-screen.ts"
|
||||
|
||||
export const GOOGLE_AGENT = process.env.RAEA_GOOGLE_AGENT ?? "antigravity-acp"
|
||||
const PREFIX = "agy1:"
|
||||
const API_KEY = /^AIza[0-9A-Za-z_-]{30,}$/
|
||||
/** what never reaches Antigravity from the container: its own Google sign-ins and keys */
|
||||
const GOOGLE_ENV = ["GEMINI_API_KEY", "GOOGLE_API_KEY", "GOOGLE_APPLICATION_CREDENTIALS", "GOOGLE_CLOUD_PROJECT", "GOOGLE_GENAI_USE_VERTEXAI", "GEMINI_HOME"]
|
||||
|
||||
// ---- one Antigravity process, spoken to over ACP on its stdin and stdout ----
|
||||
interface Agy {
|
||||
child: ChildProcess
|
||||
/** everything it printed, both streams (its sign-in link goes to either) */
|
||||
out: string
|
||||
ended: boolean
|
||||
request<T = any>(method: string, params: Record<string, unknown>, ms?: number): Promise<T>
|
||||
onUpdate?: (u: any) => void
|
||||
}
|
||||
|
||||
function startAgy(env: NodeJS.ProcessEnv, home: string, cwd: string, own: Record<string, string> = {}): Agy {
|
||||
const a = spawnFor(GOOGLE_AGENT)
|
||||
const clean: NodeJS.ProcessEnv = { ...env, ...a.env }
|
||||
for (const k of GOOGLE_ENV) delete clean[k]
|
||||
Object.assign(clean, own, { GEMINI_HOME: home, AGY_ACP_FORCE_FILE_STORAGE: "1", BROWSER: "true", NO_BROWSER: "true" })
|
||||
const child = spawn(a.command, a.args, { cwd, env: clean, stdio: ["pipe", "pipe", "pipe"] })
|
||||
const pending = new Map<number, { ok: (v: any) => void; no: (e: Error) => void }>()
|
||||
let next = 1
|
||||
let buf = ""
|
||||
const agy: Agy = {
|
||||
child,
|
||||
out: "",
|
||||
ended: false,
|
||||
request(method, params, ms = 60_000) {
|
||||
if (agy.ended) return Promise.reject(new Error(`Antigravity has stopped: ${tail(agy.out)}`))
|
||||
const id = next++
|
||||
return new Promise((ok, no) => {
|
||||
const t = setTimeout(() => (pending.delete(id), no(new Error(`Antigravity didn't answer ${method} in ${ms / 1000} s`))), ms)
|
||||
pending.set(id, { ok: (v) => (clearTimeout(t), ok(v)), no: (e) => (clearTimeout(t), no(e)) })
|
||||
child.stdin!.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n")
|
||||
})
|
||||
},
|
||||
}
|
||||
child.stdout!.setEncoding("utf8").on("data", (c: string) => {
|
||||
agy.out += c
|
||||
buf += c
|
||||
for (let i; (i = buf.indexOf("\n")) >= 0; ) {
|
||||
const line = buf.slice(0, i).trim()
|
||||
buf = buf.slice(i + 1)
|
||||
if (!line.startsWith("{")) continue
|
||||
let m: any
|
||||
try {
|
||||
m = JSON.parse(line)
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
if (m.id !== undefined && m.method === undefined) {
|
||||
const p = pending.get(m.id)
|
||||
pending.delete(m.id)
|
||||
if (m.error) p?.no(new Error(m.error.message ?? JSON.stringify(m.error)))
|
||||
else p?.ok(m.result)
|
||||
} else if (m.method === "session/update") agy.onUpdate?.(m.params?.update)
|
||||
else if (m.id !== undefined) {
|
||||
// its requests to us: a permission is granted (a check asks for none), anything else refused
|
||||
const o = m.params?.options?.find((x: any) => x.kind === "allow_once") ?? m.params?.options?.[0]
|
||||
const reply = m.method === "session/request_permission" && o ? { result: { outcome: { outcome: "selected", optionId: o.optionId } } } : { error: { code: -32601, message: `no ${m.method} here` } }
|
||||
child.stdin!.write(JSON.stringify({ jsonrpc: "2.0", id: m.id, ...reply }) + "\n")
|
||||
}
|
||||
}
|
||||
})
|
||||
child.stderr!.setEncoding("utf8").on("data", (c: string) => (agy.out += c))
|
||||
child.on("exit", () => {
|
||||
agy.ended = true
|
||||
for (const p of pending.values()) p.no(new Error(`Antigravity stopped: ${tail(agy.out)}`))
|
||||
pending.clear()
|
||||
})
|
||||
return agy
|
||||
}
|
||||
|
||||
const initialize = (a: Agy) => a.request("initialize", { protocolVersion: 1, clientCapabilities: {}, clientInfo: { name: "raea-cloud", version: "1" } })
|
||||
/** its last words, without its Python warnings or log prefixes */
|
||||
const tail = (out: string) =>
|
||||
out
|
||||
.split("\n")
|
||||
.filter((l) => l.trim() && !/SyntaxWarning|^\s*[IW]\d{4} /.test(l))
|
||||
.slice(-3)
|
||||
.join(" ")
|
||||
.slice(-300)
|
||||
|
||||
/** the Google sign-in link Antigravity printed, and where it sends the browser back to */
|
||||
export function linkIn(out: string): { url: string; port: number; state: string } | undefined {
|
||||
const m = /https:\/\/accounts\.google\.com\/o\/oauth2\/[^\s"']+/.exec(out)
|
||||
if (!m) return undefined
|
||||
const u = new URL(m[0])
|
||||
const back = new URL(u.searchParams.get("redirect_uri") ?? "")
|
||||
if (!/^(127\.0\.0\.1|localhost|\[::1\])$/.test(back.hostname)) return undefined
|
||||
return { url: m[0], port: Number(back.port), state: u.searchParams.get("state") ?? "" }
|
||||
}
|
||||
|
||||
/** the address the person's browser landed on, checked against the sign-in it belongs to: the query to hand on */
|
||||
export function landedQuery(address: string, s: { port: number; state: string }): string {
|
||||
let u: URL
|
||||
try {
|
||||
u = new URL(address.trim())
|
||||
} catch {
|
||||
throw new Error("paste the whole address of the page Google sent you to (it starts http://127.0.0.1)")
|
||||
}
|
||||
if (!/^(127\.0\.0\.1|localhost|\[::1\])$/.test(u.hostname) || Number(u.port) !== s.port) throw new Error("that address isn't the page this sign-in sent you to: sign in from the newest link")
|
||||
if (u.searchParams.get("error")) throw new Error(`Google said ${u.searchParams.get("error")}`)
|
||||
if (!u.searchParams.get("code")) throw new Error("that address has no code in it: copy it from the browser's address bar after you approve")
|
||||
if (u.searchParams.get("state") !== s.state) throw new Error("that address is from another sign-in: sign in from the newest link")
|
||||
return `${u.pathname}${u.search}`
|
||||
}
|
||||
|
||||
// ---- the credential: the files under GEMINI_HOME that hold a refresh token, as one string ----
|
||||
export function packCredential(home: string): string | undefined {
|
||||
const files: Record<string, string> = {}
|
||||
const walk = (dir: string) => {
|
||||
for (const d of readdirSync(dir, { withFileTypes: true })) {
|
||||
const p = path.join(dir, d.name)
|
||||
if (d.isDirectory()) walk(p)
|
||||
else if (d.isFile() && d.name.endsWith(".json") && statSync(p).size < 64_000) {
|
||||
const text = readFileSync(p, "utf8")
|
||||
if (/"refresh_token"\s*:/.test(text)) files[path.relative(home, p)] = text
|
||||
}
|
||||
}
|
||||
}
|
||||
walk(home)
|
||||
return Object.keys(files).length ? PREFIX + Buffer.from(JSON.stringify(files)).toString("base64") : undefined
|
||||
}
|
||||
|
||||
/** writes a credential's files into an agent's GEMINI_HOME, 0600 under 0700 folders; each path stays inside it */
|
||||
export function unpackCredential(credential: string, home: string): void {
|
||||
if (!credential.startsWith(PREFIX)) throw new Error("that isn't a Google sign-in from raea cloud")
|
||||
let files: Record<string, unknown>
|
||||
try {
|
||||
files = JSON.parse(Buffer.from(credential.slice(PREFIX.length), "base64").toString("utf8"))
|
||||
} catch {
|
||||
throw new Error("that Google sign-in can't be read")
|
||||
}
|
||||
for (const [rel, text] of Object.entries(files)) {
|
||||
const p = path.resolve(home, rel)
|
||||
if (typeof text !== "string" || !p.startsWith(path.resolve(home) + path.sep)) throw new Error("that Google sign-in names a file outside its folder")
|
||||
mkdirSync(path.dirname(p), { recursive: true, mode: 0o700 })
|
||||
writeFileSync(p, text, { mode: 0o600 })
|
||||
}
|
||||
}
|
||||
|
||||
/** the account a credential is for, when its token file says */
|
||||
const emailIn = (credential: string): string | undefined => /"email"\s*:\s*"([^"]+@[^"]+)"/.exec(Buffer.from(credential.slice(PREFIX.length), "base64").toString("utf8"))?.[1]
|
||||
|
||||
// ---- signing in ----
|
||||
interface SignIn {
|
||||
agy: Agy
|
||||
dir: string
|
||||
home: string
|
||||
port: number
|
||||
state: string
|
||||
authed: boolean
|
||||
failed?: string
|
||||
timer: NodeJS.Timeout
|
||||
/** the box's own browser for it, when it runs there */
|
||||
screen?: Screen
|
||||
}
|
||||
const waiting = new Map<string, SignIn>()
|
||||
|
||||
function end(id: string) {
|
||||
const s = waiting.get(id)
|
||||
if (!s) return
|
||||
waiting.delete(id)
|
||||
clearTimeout(s.timer)
|
||||
s.screen?.stop()
|
||||
if (s.agy.child.exitCode === null) s.agy.child.kill("SIGTERM")
|
||||
rmSync(s.dir, { recursive: true, force: true })
|
||||
}
|
||||
|
||||
const until = async (ok: () => boolean, ms: number) => {
|
||||
for (let t = 0; t < ms && !ok(); t += 200) await new Promise((r) => setTimeout(r, 200))
|
||||
}
|
||||
|
||||
export async function startGoogleSignIn(env: NodeJS.ProcessEnv, o: { screen?: boolean } = {}): Promise<{ id: string; url: string; screen: boolean }> {
|
||||
const dir = mkdtempSync(path.join(tmpdir(), "google-sign-in-"))
|
||||
const home = path.join(dir, ".gemini")
|
||||
mkdirSync(home, { mode: 0o700 })
|
||||
const agy = startAgy(env, home, dir)
|
||||
const id = randomBytes(12).toString("hex")
|
||||
try {
|
||||
await initialize(agy)
|
||||
} catch (e) {
|
||||
agy.child.kill("SIGTERM")
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
throw new Error(`Antigravity didn't start: ${(e as Error).message}`)
|
||||
}
|
||||
const s: SignIn = { agy, dir, home, port: 0, state: "", authed: false, timer: setTimeout(() => end(id), 15 * 60_000) }
|
||||
waiting.set(id, s)
|
||||
// authenticate answers only once the browser has come back: it waits for the whole sign-in
|
||||
agy.request("authenticate", { methodId: "oauth-personal" }, 15 * 60_000).then(
|
||||
() => (s.authed = true),
|
||||
(e: Error) => (s.failed = e.message),
|
||||
)
|
||||
await until(() => !!linkIn(agy.out) || !!s.failed || agy.ended, 30_000)
|
||||
const link = linkIn(agy.out)
|
||||
if (!link) {
|
||||
const why = s.failed ?? tail(agy.out)
|
||||
end(id)
|
||||
throw new Error(`Antigravity didn't print a Google sign-in link${why ? `: ${why}` : ""}`)
|
||||
}
|
||||
s.port = link.port
|
||||
s.state = link.state
|
||||
// the box's own browser, when asked for and there is one; else the person signs in in theirs and pastes
|
||||
if (o.screen && canShow()) {
|
||||
try {
|
||||
s.screen = await openScreen(dir, link.url)
|
||||
} catch (e) {
|
||||
console.error(`raea-cloud: google sign-in ${id.slice(0, 6)}: no screen, the address is pasted instead:`, (e as Error).message)
|
||||
}
|
||||
}
|
||||
return { id, url: link.url, screen: !!s.screen }
|
||||
}
|
||||
|
||||
/** the VNC port of a sign-in's own browser, while it's up */
|
||||
export function screenPort(id: string): number | undefined {
|
||||
const s = waiting.get(id)
|
||||
return s?.screen?.up() ? s.screen.port : undefined
|
||||
}
|
||||
|
||||
export async function finishGoogleSignIn(id: string, address?: string): Promise<{ credential: string; email?: string } | { pending: true }> {
|
||||
const s = waiting.get(id)
|
||||
if (!s) throw new Error("that sign-in has ended (they last 15 minutes): start again")
|
||||
let r: { ok: boolean; status: number; statusText: string } = { ok: true, status: 200, statusText: "" }
|
||||
if (address) {
|
||||
const q = landedQuery(address, s)
|
||||
// the browser's visit to Antigravity's listener, made from the box
|
||||
r = await fetch(`http://127.0.0.1:${s.port}${q}`, { signal: AbortSignal.timeout(30_000) }).catch((e: Error) => ({ ok: false, status: 0, statusText: e.message }))
|
||||
await until(() => s.authed || !!s.failed || s.agy.ended, 60_000)
|
||||
} else {
|
||||
// the box's own browser finishes it: wait a while, and say it's still going if it hasn't (the caller asks again)
|
||||
await until(() => s.authed || !!s.failed || s.agy.ended, 25_000)
|
||||
if (!s.authed && !s.failed && !s.agy.ended) return { pending: true }
|
||||
}
|
||||
const credential = s.authed ? packCredential(s.home) : undefined
|
||||
const why = s.failed ?? (r.ok ? tail(s.agy.out) : `its sign-in page answered ${r.status || r.statusText}`)
|
||||
console.log(`raea-cloud: google sign-in ${id.slice(0, 6)} ${credential ? "got a credential" : `no credential: ${why}`}`)
|
||||
end(id)
|
||||
if (!credential) throw new Error(`Google's sign-in didn't finish${why ? `: ${why}` : ""}`)
|
||||
return { credential, email: emailIn(credential) }
|
||||
}
|
||||
|
||||
/** whether a credential (or a Gemini API key) gets an answer from Antigravity: one short turn in a folder of its own
|
||||
* that's removed after; the models it offers that account, and the one it picked */
|
||||
export async function checkGoogle(env: NodeJS.ProcessEnv, credential: string): Promise<{ ok: boolean; said: string; models: { id: string; name: string }[]; current?: string }> {
|
||||
const c = credential.trim()
|
||||
const key = API_KEY.test(c)
|
||||
if (!key && !c.startsWith(PREFIX)) throw new Error("that isn't a Google sign-in from raea cloud or a Gemini API key (AIza…)")
|
||||
const dir = mkdtempSync(path.join(tmpdir(), "google-check-"))
|
||||
const home = path.join(dir, ".gemini")
|
||||
mkdirSync(home, { mode: 0o700 })
|
||||
if (!key) unpackCredential(c, home)
|
||||
const agy = startAgy(env, home, dir, key ? { GEMINI_API_KEY: c } : {})
|
||||
let said = ""
|
||||
agy.onUpdate = (u) => {
|
||||
if (u?.sessionUpdate === "agent_message_chunk" && u.content?.type === "text") said += u.content.text ?? ""
|
||||
}
|
||||
const timer = setTimeout(() => agy.child.kill("SIGTERM"), 120_000)
|
||||
try {
|
||||
await initialize(agy)
|
||||
// with a good credential it signs in from the file; a link printed means Google wants a new sign-in
|
||||
const auth = agy.request("authenticate", { methodId: key ? "gemini-api-key" : "oauth-personal" }, 45_000)
|
||||
await Promise.race([auth, until(() => !!linkIn(agy.out), 45_000).then(() => linkIn(agy.out) && Promise.reject(new Error("Google wants this account signed in again")))])
|
||||
const s = await agy.request<{ sessionId: string; models?: { availableModels?: { modelId: string; name?: string }[]; currentModelId?: string } }>("session/new", { cwd: dir, mcpServers: [] })
|
||||
const models = (s.models?.availableModels ?? []).map((m) => ({ id: m.modelId, name: m.name ?? m.modelId }))
|
||||
await agy.request("session/prompt", { sessionId: s.sessionId, prompt: [{ type: "text", text: "Reply with just the word: ready" }] }, 90_000)
|
||||
said = said.replace(/\s+/g, " ").trim().slice(0, 400)
|
||||
return { ok: /ready/i.test(said), said, models, current: s.models?.currentModelId }
|
||||
} catch (e) {
|
||||
return { ok: false, said: (e as Error).message.slice(0, 400), models: [] }
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
if (agy.child.exitCode === null) agy.child.kill("SIGTERM")
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
+184
-5
@@ -11,8 +11,22 @@
|
||||
// (10 min unless given, 1 h at most) its process group is stopped and the last
|
||||
// line says {exit, timed_out: true}. For an agent's shell tool (raea cloud)
|
||||
// POST /v1/login?agent=ID an agent's terminal sign-in: {url, code, state, output}; GET says where it is
|
||||
// POST /v1/claude-token a Claude subscription sign-in in a browser: {id, url} (claude-token.ts)
|
||||
// POST /v1/claude-token/ID {code} the code claude.com showed, in: {token}, handed back once and never kept
|
||||
// POST /v1/claude-token/check {token} one short Claude Code turn on it: {ok, said}
|
||||
// POST /v1/google-token {screen?} a Google AI subscription sign-in (Antigravity): {id, url, screen} (google-token.ts)
|
||||
// POST /v1/google-token/ID {address?} the address Google's sign-in landed on, in (none when it ran in the box's own
|
||||
// browser): {credential, email?}, handed back once, or {pending: true}
|
||||
// WS /v1/google-token/ID/screen the box's own browser for that sign-in, over VNC (google-screen.ts)
|
||||
// POST /v1/google-token/check {credential} one short Antigravity turn on it (or a Gemini API key): {ok, said, models}
|
||||
// WS /v1/acp?agent=ID one agent process per socket: a text frame is one ACP message to its stdin,
|
||||
// each line it prints is one frame back
|
||||
// each line it prints is one frame back. A caller signing the agent in as one of
|
||||
// its own clients (raea cloud, per workspace) sends x-raea-agent-env: JSON of the
|
||||
// model keys below, and x-raea-agent-home: a short name. That socket's agent gets
|
||||
// only those keys (never the container's) and its own config folder under
|
||||
// ~/.agent-homes/NAME, so one client's sign-in never runs another's work. A
|
||||
// Google sign-in (RAEA_GOOGLE_CREDENTIAL) is the one thing written: its token
|
||||
// file, into that socket's own GEMINI_HOME, where Antigravity reads it.
|
||||
// POST /v1/jobs?args=JSON a render job: a folder in (tar.zst), `raea ARGS` on it, followed with
|
||||
// GET /v1/jobs/ID?from=N short requests, and the files it made back from /out (jobs.ts); how a CPU
|
||||
// GET /v1/jobs/ID/out box hands renders to a GPU worker (offload.ts)
|
||||
@@ -22,13 +36,17 @@
|
||||
|
||||
import { execFileSync, spawn } from "node:child_process"
|
||||
import { timingSafeEqual } from "node:crypto"
|
||||
import { mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, symlinkSync, writeFileSync } from "node:fs"
|
||||
import { createServer, type IncomingMessage, type ServerResponse } from "node:http"
|
||||
import path from "node:path"
|
||||
import { WebSocketServer } from "ws"
|
||||
import { installed, spawnFor } from "./agents.ts"
|
||||
import { guard } from "./memguard.ts"
|
||||
import { device } from "./gpu.ts"
|
||||
import * as jobs from "./jobs.ts"
|
||||
import { checkClaude, finishClaudeSignIn, startClaudeSignIn } from "./claude-token.ts"
|
||||
import { checkGoogle, finishGoogleSignIn, screenPort, startGoogleSignIn, unpackCredential } from "./google-token.ts"
|
||||
import { connect as tcp } from "node:net"
|
||||
import { login, loginState } from "./login.ts"
|
||||
import { Outside, resolve, WORK } from "./workspace.ts"
|
||||
|
||||
@@ -48,6 +66,83 @@ const childEnv = (): NodeJS.ProcessEnv => {
|
||||
}
|
||||
|
||||
let version: string | undefined
|
||||
|
||||
/** the model keys a caller may hand one agent process, and the config folder each agent keeps its state in */
|
||||
const AGENT_KEYS = ["ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN", "OPENAI_API_KEY", "CODEX_API_KEY", "GEMINI_API_KEY"] as const
|
||||
const AGENT_HOMES: Record<string, string> = { CLAUDE_CONFIG_DIR: "claude", CODEX_HOME: "codex", GEMINI_CLI_HOME: "gemini", GEMINI_HOME: "gemini/.gemini" }
|
||||
/** a Google sign-in's token file (google-token.ts), written into the socket's GEMINI_HOME rather than handed on */
|
||||
const GOOGLE_CREDENTIAL = "RAEA_GOOGLE_CREDENTIAL"
|
||||
|
||||
/** the agent processes running for open sockets now (GET /v1/health running) */
|
||||
const running = new Set<unknown>()
|
||||
|
||||
/** the box's build, as setup.sh wrote it (/opt/raea-cloud/BUILD.json); null on a box made before builds were stamped */
|
||||
function buildOf(): Record<string, unknown> | null {
|
||||
try {
|
||||
return JSON.parse(readFileSync(path.join(process.env.RAEA_CLOUD_ROOT ?? "/opt/raea-cloud", "BUILD.json"), "utf8"))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** raea's skills, installed once in the box's own home (setup.sh), linked into a socket's own config folders: each
|
||||
* client's agent gets its own home (AGENT_HOMES), which had left them without raea's skills (11-25) */
|
||||
const SKILL_DIRS: Record<string, string> = { CLAUDE_CONFIG_DIR: ".claude/skills", GEMINI_HOME: ".gemini/skills" }
|
||||
function linkSkills(env: Record<string, string>, home: string) {
|
||||
for (const [k, rel] of Object.entries(SKILL_DIRS)) {
|
||||
const from = path.join(home, rel)
|
||||
const to = path.join(env[k], "skills")
|
||||
try {
|
||||
if (existsSync(from) && !existsSync(to)) symlinkSync(from, to)
|
||||
} catch {
|
||||
// a folder of its own already there: left alone
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** a socket's own sign-in (its headers), or null to run on the container's environment */
|
||||
export function socketEnv(headers: Record<string, string | string[] | undefined>, home = process.env.HOME ?? "/root"): Record<string, string> | null {
|
||||
const raw = headers["x-raea-agent-env"]
|
||||
if (typeof raw !== "string" || !raw) return null
|
||||
let given: Record<string, unknown>
|
||||
try {
|
||||
given = JSON.parse(raw)
|
||||
} catch {
|
||||
throw new Error("x-raea-agent-env isn't JSON")
|
||||
}
|
||||
const env: Record<string, string> = {}
|
||||
for (const k of AGENT_KEYS) {
|
||||
const v = given[k]
|
||||
if (typeof v === "string" && v) env[k] = v
|
||||
}
|
||||
const google = typeof given[GOOGLE_CREDENTIAL] === "string" ? (given[GOOGLE_CREDENTIAL] as string) : ""
|
||||
if (!Object.keys(env).length && !google) throw new Error(`x-raea-agent-env names none of ${[...AGENT_KEYS, GOOGLE_CREDENTIAL].join(", ")}`)
|
||||
const name = String(headers["x-raea-agent-home"] ?? "")
|
||||
if (!/^[a-z0-9][a-z0-9_-]{0,62}$/.test(name)) throw new Error("x-raea-agent-home must be a short lowercase name")
|
||||
for (const [k, dir] of Object.entries(AGENT_HOMES)) {
|
||||
env[k] = path.join(home, ".agent-homes", name, dir)
|
||||
mkdirSync(env[k], { recursive: true, mode: 0o700 })
|
||||
}
|
||||
linkSkills(env, home)
|
||||
if (google) {
|
||||
unpackCredential(google, env.GEMINI_HOME)
|
||||
env.AGY_ACP_FORCE_FILE_STORAGE = "1"
|
||||
}
|
||||
return env
|
||||
}
|
||||
|
||||
/** what a socket signed in as one of raea cloud's clients runs with: its agent works one turn at a time for a caller
|
||||
* that ends the run when the turn ends, so Claude Code mustn't background a command and end its turn to wait for it
|
||||
* (11-21: a render backgrounded, the turn ended, the project stopped with nothing to show), and a render through
|
||||
* raea's MCP tools or in the shell gets half an hour */
|
||||
const RUN_DEFAULTS: Record<string, string> = { CLAUDE_CODE_DISABLE_BACKGROUND_TASKS: "1", BASH_DEFAULT_TIMEOUT_MS: "1800000", BASH_MAX_TIMEOUT_MS: "3600000", MCP_TOOL_TIMEOUT: "1800000" }
|
||||
|
||||
/** the container's environment less every model key: a socket with its own sign-in never falls back to the box's */
|
||||
const withoutKeys = (env: NodeJS.ProcessEnv) => {
|
||||
const out = { ...env }
|
||||
for (const k of [...AGENT_KEYS, "GOOGLE_API_KEY", "GOOGLE_APPLICATION_CREDENTIALS"]) delete out[k]
|
||||
return out
|
||||
}
|
||||
const raeaVersion = () => {
|
||||
try {
|
||||
version ??= execFileSync(RAEA, ["--version"], { encoding: "utf8", timeout: 20_000, env: childEnv() }).trim()
|
||||
@@ -150,12 +245,16 @@ const server = createServer(async (req, res) => {
|
||||
const gpu = process.env.RAEA_CLOUD_GPU_URL
|
||||
return json(res, {
|
||||
raea: raeaVersion(),
|
||||
// what deploy/sprites/box.sh put here: the build's id, the commit, whether the tree was dirty (BUILD.json)
|
||||
build: buildOf(),
|
||||
agent: def,
|
||||
agents: installed().map((a) => ({ id: a.id, version: a.version })),
|
||||
workspace: WORK,
|
||||
device: device(childEnv()),
|
||||
offload: gpu ? { url: gpu, commands: (process.env.RAEA_CLOUD_GPU_COMMANDS ?? "render").split(/\s+/).filter(Boolean) } : null,
|
||||
jobs: jobs.held(),
|
||||
// agents running now: deploy/sprites/box.sh up waits for none before it restarts this server
|
||||
running: running.size,
|
||||
})
|
||||
}
|
||||
if (url.pathname === "/v1/files" && (req.method === "GET" || req.method === "PUT")) return await files(req, res, url)
|
||||
@@ -181,6 +280,29 @@ const server = createServer(async (req, res) => {
|
||||
const f = await jobs.follow(job[1], Number(url.searchParams.get("from") ?? 0))
|
||||
return f ? json(res, f) : json(res, { error: "no job with that id" }, 404)
|
||||
}
|
||||
if (url.pathname === "/v1/claude-token" && req.method === "POST") return json(res, await startClaudeSignIn(childEnv()))
|
||||
if (url.pathname === "/v1/claude-token/check" && req.method === "POST") {
|
||||
const b = JSON.parse((await body(req)).toString("utf8") || "{}") as { token?: unknown }
|
||||
return json(res, await checkClaude(childEnv(), String(b.token ?? "")))
|
||||
}
|
||||
if (url.pathname === "/v1/google-token" && req.method === "POST") {
|
||||
const b = JSON.parse((await body(req)).toString("utf8") || "{}") as { screen?: unknown }
|
||||
return json(res, await startGoogleSignIn(childEnv(), { screen: b.screen === true }))
|
||||
}
|
||||
if (url.pathname === "/v1/google-token/check" && req.method === "POST") {
|
||||
const b = JSON.parse((await body(req)).toString("utf8") || "{}") as { credential?: unknown }
|
||||
return json(res, await checkGoogle(childEnv(), String(b.credential ?? "")))
|
||||
}
|
||||
const gt = /^\/v1\/google-token\/([0-9a-f]{24})$/.exec(url.pathname)
|
||||
if (gt && req.method === "POST") {
|
||||
const b = JSON.parse((await body(req)).toString("utf8") || "{}") as { address?: unknown }
|
||||
return json(res, await finishGoogleSignIn(gt[1], typeof b.address === "string" && b.address.trim() ? b.address : undefined))
|
||||
}
|
||||
const ct = /^\/v1\/claude-token\/([0-9a-f]{24})$/.exec(url.pathname)
|
||||
if (ct && req.method === "POST") {
|
||||
const b = JSON.parse((await body(req)).toString("utf8") || "{}") as { code?: unknown }
|
||||
return json(res, await finishClaudeSignIn(ct[1], String(b.code ?? "")))
|
||||
}
|
||||
if (url.pathname === "/v1/login") {
|
||||
const a = spawnFor(url.searchParams.get("agent") ?? undefined)
|
||||
return json(res, req.method === "POST" ? await login(a, childEnv()) : loginState(a.id))
|
||||
@@ -194,8 +316,23 @@ const server = createServer(async (req, res) => {
|
||||
|
||||
// the WebSocket upgrade checks the token before a socket opens
|
||||
const wss = new WebSocketServer({ noServer: true })
|
||||
const agentSockets = new Set<import("ws").WebSocket>()
|
||||
server.on("upgrade", (req, socket, head) => {
|
||||
const url = new URL(req.url ?? "/", "http://raea-cloud")
|
||||
// a Google sign-in's own browser (google-screen.ts): its VNC stream, both ways, as binary frames
|
||||
const gs = /^\/v1\/google-token\/([0-9a-f]{24})\/screen$/.exec(url.pathname)
|
||||
if (gs) {
|
||||
const port = authorized(req, url) ? screenPort(gs[1]) : undefined
|
||||
if (port === undefined) return socket.end(authorized(req, url) ? "HTTP/1.1 404 Not Found\r\n\r\n" : "HTTP/1.1 401 Unauthorized\r\n\r\n")
|
||||
return wss.handleUpgrade(req, socket, head, (ws) => {
|
||||
const vnc = tcp(port, "127.0.0.1")
|
||||
vnc.on("data", (d) => ws.readyState === ws.OPEN && ws.send(d))
|
||||
ws.on("message", (m) => vnc.write(m as Buffer))
|
||||
vnc.on("close", () => ws.close(1000, "the sign-in's screen closed"))
|
||||
vnc.on("error", () => ws.close(1011, "the sign-in's screen failed"))
|
||||
ws.on("close", () => vnc.destroy())
|
||||
})
|
||||
}
|
||||
if (url.pathname !== "/v1/acp" || !authorized(req, url)) return socket.end("HTTP/1.1 401 Unauthorized\r\n\r\n")
|
||||
let a
|
||||
try {
|
||||
@@ -204,8 +341,43 @@ server.on("upgrade", (req, socket, head) => {
|
||||
return socket.end(`HTTP/1.1 400 Bad Request\r\ncontent-type: text/plain\r\n\r\n${(e as Error).message}`)
|
||||
}
|
||||
const agent = a
|
||||
let own: Record<string, string> | null
|
||||
try {
|
||||
own = socketEnv(req.headers)
|
||||
} catch (e) {
|
||||
return socket.end(`HTTP/1.1 400 Bad Request\r\ncontent-type: text/plain\r\n\r\n${(e as Error).message}`)
|
||||
}
|
||||
const env = own ? { ...withoutKeys(childEnv()), ...agent.env, ...RUN_DEFAULTS, ...own } : { ...childEnv(), ...agent.env }
|
||||
wss.handleUpgrade(req, socket, head, (ws) => {
|
||||
const child = spawn(agent.command, agent.args, { cwd: WORK, env: { ...childEnv(), ...agent.env }, stdio: ["pipe", "pipe", "inherit"] })
|
||||
// its own process group, so what it started (a render left running in the background) stops with it: a killed
|
||||
// agent's renders went on as orphans, 4 GB of them on raea-2 (11-25)
|
||||
const child = spawn(agent.command, agent.args, { cwd: WORK, env, stdio: ["pipe", "pipe", "pipe"], detached: true })
|
||||
const stopAll = () => {
|
||||
if (!child.pid) return
|
||||
try {
|
||||
process.kill(-child.pid, "SIGTERM")
|
||||
} catch {}
|
||||
setTimeout(() => {
|
||||
try {
|
||||
process.kill(-child.pid!, "SIGKILL")
|
||||
} catch {}
|
||||
}, 5000).unref()
|
||||
}
|
||||
running.add(child)
|
||||
agentSockets.add(ws)
|
||||
// a message every 20 s, so the socket is never idle: between raea cloud and the box it's closed after about two
|
||||
// minutes without traffic, and an agent waiting on a long render sends nothing (11-25: five of StreetTalk's seven
|
||||
// "socket closed" ends came 114-125 s into a silence). raea cloud skips notifications it doesn't know; the agent
|
||||
// never sees it
|
||||
const beat = setInterval(() => ws.readyState === ws.OPEN && ws.send('{"jsonrpc":"2.0","method":"_raea/keepalive"}'), 20_000)
|
||||
ws.on("close", () => (agentSockets.delete(ws), clearInterval(beat)))
|
||||
child.on("exit", () => running.delete(child))
|
||||
// its stderr to the box's log as before, and along the socket as _raea/stderr notifications, so raea cloud keeps
|
||||
// it with the run's trace (runtrace.ts) instead of only on this box's disk (11-25: raea-1's logs died with it)
|
||||
child.stderr.setEncoding("utf8").on("data", (c: string) => {
|
||||
process.stderr.write(c)
|
||||
if (ws.readyState === ws.OPEN) ws.send(JSON.stringify({ jsonrpc: "2.0", method: "_raea/stderr", params: { text: c.slice(0, 16_000) } }))
|
||||
})
|
||||
let buf = ""
|
||||
// ACP messages are newline-delimited JSON: split on \n only
|
||||
child.stdout.setEncoding("utf8").on("data", (c: string) => {
|
||||
@@ -213,13 +385,20 @@ server.on("upgrade", (req, socket, head) => {
|
||||
for (let i; (i = buf.indexOf("\n")) >= 0; buf = buf.slice(i + 1)) if (i > 0) ws.send(buf.slice(0, i))
|
||||
})
|
||||
ws.on("message", (m) => child.stdin.write(m.toString() + "\n"))
|
||||
ws.on("close", () => child.exitCode === null && child.kill("SIGTERM"))
|
||||
ws.on("close", stopAll)
|
||||
child.on("error", (e) => ws.close(1011, `couldn't start ${agent.id}: ${e.message}`.slice(0, 120)))
|
||||
child.on("exit", (code) => ws.close(1011, `${agent.id} exited ${code}`))
|
||||
child.on("exit", (code) => (ws.close(1011, `${agent.id} exited ${code}`), stopAll()))
|
||||
})
|
||||
})
|
||||
|
||||
mkdirSync(WORK, { recursive: true })
|
||||
// the box kept from running out of memory (memguard.ts): what it stops is said in the box's log and in every agent's
|
||||
// trace (_raea/stderr), where a cut-off run's reason is read
|
||||
if (existsSync("/proc/meminfo") && process.env.RAEA_CLOUD_MEMGUARD !== "0")
|
||||
guard((line) => {
|
||||
process.stderr.write(line + "\n")
|
||||
for (const ws of agentSockets) if (ws.readyState === ws.OPEN) ws.send(JSON.stringify({ jsonrpc: "2.0", method: "_raea/stderr", params: { text: line + "\n" } }))
|
||||
})
|
||||
server.listen(PORT, () => {
|
||||
const d = device(childEnv())
|
||||
const gpu = process.env.RAEA_CLOUD_GPU_URL
|
||||
|
||||
+101
-1
@@ -10,8 +10,10 @@
|
||||
|
||||
import { createHash } from "node:crypto"
|
||||
import { spawnSync } from "node:child_process"
|
||||
import { createReadStream, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"
|
||||
import { createReadStream, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { Readable } from "node:stream"
|
||||
import type { Media } from "../src/index.ts"
|
||||
|
||||
const LFS = "application/vnd.git-lfs+json"
|
||||
@@ -132,5 +134,103 @@ export async function outputs(root: string, lfs: Lfs, made: Media[]): Promise<{
|
||||
return { send, done }
|
||||
}
|
||||
|
||||
// what goes by hash when the project isn't in raea's LFS (farmInputs): media by type, and anything large, as the farm's
|
||||
// farm_media.py MEDIA and LARGE judge it; a file under SMALL stays in the tar, where it costs less than a lookup
|
||||
const MEDIA = new Set(
|
||||
"mp4 mov m4v webm mkv avi mxf mp3 wav aiff aif flac m4a ogg opus caf png jpg jpeg heic heif webp gif tif tiff exr hdr psd blend glb gltf fbx obj usd usdz abc ply splat spz ktx2 ttf otf woff woff2 zip tar gz zst safetensors onnx bin npz npy pdf".split(" "),
|
||||
)
|
||||
const LARGE = 4 << 20
|
||||
const SMALL = 256 << 10
|
||||
|
||||
/** the farm's cache of media (farm.py POST /v1/blobs/have, PUT /v1/blobs/OID), over its own token */
|
||||
export interface FarmBlobs {
|
||||
/** which of these it holds; null when this farm has no cache (an older one): the media goes in the tar */
|
||||
have(objects: { oid: string; size: number }[]): Promise<Set<string> | null>
|
||||
put(file: string, oid: string, size: number): Promise<void>
|
||||
}
|
||||
|
||||
export function farmBlobs(url: string, token: string): FarmBlobs {
|
||||
const auth = { authorization: `Bearer ${token}` }
|
||||
return {
|
||||
async have(objects) {
|
||||
const r = await fetch(`${url}/v1/blobs/have`, { method: "POST", headers: { ...auth, "content-type": "application/json" }, body: JSON.stringify({ objects }) })
|
||||
if (r.status === 404) return null
|
||||
if (!r.ok) throw new Error(`the farm's media cache answered ${r.status}: ${(await r.text()).slice(0, 200)}`)
|
||||
return new Set(((await r.json()) as { have: string[] }).have)
|
||||
},
|
||||
async put(file, oid, size) {
|
||||
// streamed from the disk: a file is never held in memory (a project's interviews are gigabytes)
|
||||
const body = Readable.toWeb(createReadStream(file)) as unknown as ReadableStream
|
||||
const r = await fetch(`${url}/v1/blobs/${oid}?size=${size}`, { method: "PUT", headers: { ...auth, "content-type": "application/octet-stream", "content-length": String(size) }, body, duplex: "half" } as RequestInit)
|
||||
if (!r.ok) throw new Error(`the farm didn't keep ${path.basename(file)}: ${r.status} ${(await r.text()).slice(0, 200)}`)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** each file's hash, kept by the file itself (its device and inode) with its size and time, so a project's footage is
|
||||
* hashed once, not on every render, nor again in a new thread's folder that links the same files (11-25: StreetTalk's
|
||||
* restart hard-linked its 1.9 GB of interviews into a new folder, and they were hashed again) */
|
||||
function hashes(file: string) {
|
||||
let known: Record<string, { size: number; mtime: number; oid: string }> = {}
|
||||
try {
|
||||
known = JSON.parse(readFileSync(file, "utf8"))
|
||||
} catch {}
|
||||
let changed = false
|
||||
return {
|
||||
async of(p: string, id: string, size: number, mtime: number): Promise<string> {
|
||||
const k = known[id]
|
||||
if (k && k.size === size && k.mtime === mtime) return k.oid
|
||||
const oid = await sha256(p)
|
||||
known[id] = { size, mtime, oid }
|
||||
changed = true
|
||||
return oid
|
||||
},
|
||||
save() {
|
||||
if (!changed) return
|
||||
mkdirSync(path.dirname(file), { recursive: true })
|
||||
const tmp = `${file}.${process.pid}`
|
||||
writeFileSync(tmp, JSON.stringify(known))
|
||||
renameSync(tmp, file)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** A project's media when it isn't in raea's LFS (11-25): each media or large file by its hash, sent once into the
|
||||
* farm's cache and named in the job's manifest with no href, so a render's tar holds the code and not the footage
|
||||
* (StreetTalk's 1.9 GB of interviews went in every render's tar, even one frame's). null when the farm has no cache.
|
||||
* `skip`: the tar's excludes. Links are left to the tar, as before. */
|
||||
export async function farmInputs(root: string, farm: FarmBlobs, skip: (p: string) => boolean = () => false, said: (s: string) => void = () => {}, store = path.join(os.homedir(), ".cache", "raea-offload", "hashes.json")): Promise<{ media: Media[]; sent: number } | null> {
|
||||
const found: { path: string; abs: string; id: string; size: number; mtime: number }[] = []
|
||||
const walk = (dir: string) => {
|
||||
for (const e of readdirSync(dir, { withFileTypes: true })) {
|
||||
const abs = path.join(dir, e.name)
|
||||
const rel = path.relative(root, abs).split(path.sep).join("/")
|
||||
if (skip(rel)) continue
|
||||
if (e.isDirectory()) walk(abs)
|
||||
else if (e.isFile()) {
|
||||
const st = statSync(abs)
|
||||
const ext = e.name.includes(".") ? e.name.split(".").pop()!.toLowerCase() : ""
|
||||
if (st.size >= LARGE || (st.size >= SMALL && MEDIA.has(ext))) found.push({ path: rel, abs, id: `${st.dev}:${st.ino}`, size: st.size, mtime: st.mtimeMs })
|
||||
}
|
||||
}
|
||||
}
|
||||
walk(root)
|
||||
if (!found.length) return { media: [], sent: 0 }
|
||||
const h = hashes(store)
|
||||
const media: (Media & { abs: string })[] = []
|
||||
for (const f of found) media.push({ path: f.path, oid: await h.of(f.abs, f.id, f.size, f.mtime), size: f.size, abs: f.abs })
|
||||
h.save()
|
||||
const have = await farm.have(media.map(({ oid, size }) => ({ oid, size })))
|
||||
if (!have) return null
|
||||
let sent = 0
|
||||
const todo = media.filter((m, i) => !have.has(m.oid) && media.findIndex((x) => x.oid === m.oid) === i)
|
||||
if (todo.length) said(`sending ${todo.length} media files (${(todo.reduce((n, m) => n + m.size, 0) / 1e6).toFixed(1)} MB) to the farm's cache, once`)
|
||||
for (const m of todo) {
|
||||
await farm.put(m.abs, m.oid, m.size)
|
||||
sent += m.size
|
||||
}
|
||||
return { media: media.map(({ abs: _, ...m }) => m), sent }
|
||||
}
|
||||
|
||||
/** tar's exclude-from lines for paths that go by hash: each matched as written (glob characters escaped) */
|
||||
export const excludes = (media: Media[]) => media.map((m) => "./" + m.path.replace(/[\\*?[\]]/g, (c) => "\\" + c)).join("\n") + "\n"
|
||||
@@ -0,0 +1,89 @@
|
||||
// The box's memory, kept from running out (11-25): StreetTalk's agent, its renders failing on the farm, found raea's
|
||||
// own binary and rendered a cut of 4K interviews on the box's CPU; the 8 GB box ran out and stopped answering, every
|
||||
// agent's socket with it. A box is a VM whose processes share one cgroup that can't be split, so there's no kernel
|
||||
// cap to set: like earlyoom, this looks at the box's free memory every second and, when it runs low, kills the
|
||||
// largest thing the box's agents started (a render, an ffmpeg), never the server and never an agent itself (they're
|
||||
// a few hundred MB; only a process over MIN_RSS is a candidate). The command it was part of fails, said in its
|
||||
// output by the shell ("Killed"), and the agent carries on.
|
||||
import { readdirSync, readFileSync } from "node:fs"
|
||||
|
||||
/** below this much available memory (the larger of the two) the guard acts */
|
||||
export const FLOOR_MB = 700
|
||||
export const FLOOR_SHARE = 0.08
|
||||
/** a process smaller than this is never killed: the agents, the server, a shell */
|
||||
export const MIN_RSS_MB = 1024
|
||||
|
||||
export interface Proc {
|
||||
pid: number
|
||||
ppid: number
|
||||
rssMb: number
|
||||
name: string
|
||||
}
|
||||
|
||||
/** every process on the box (Linux /proc) */
|
||||
export function procs(root = "/proc"): Proc[] {
|
||||
const out: Proc[] = []
|
||||
for (const d of readdirSync(root)) {
|
||||
if (!/^\d+$/.test(d)) continue
|
||||
try {
|
||||
const stat = readFileSync(`${root}/${d}/stat`, "utf8")
|
||||
// the name is in parentheses and may hold spaces: the fields after its last ")" are fixed
|
||||
const close = stat.lastIndexOf(")")
|
||||
const name = stat.slice(stat.indexOf("(") + 1, close)
|
||||
const f = stat.slice(close + 2).split(" ")
|
||||
const status = readFileSync(`${root}/${d}/status`, "utf8")
|
||||
const rss = /VmRSS:\s+(\d+) kB/.exec(status)
|
||||
out.push({ pid: Number(d), ppid: Number(f[1]), rssMb: rss ? Number(rss[1]) / 1024 : 0, name })
|
||||
} catch {} // gone since the listing
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** the box's memory: total and available, in MB */
|
||||
export function memory(file = "/proc/meminfo"): { totalMb: number; availableMb: number } {
|
||||
const m = readFileSync(file, "utf8")
|
||||
const kb = (k: string) => Number(new RegExp(`${k}:\\s+(\\d+) kB`).exec(m)?.[1] ?? 0)
|
||||
return { totalMb: kb("MemTotal") / 1024, availableMb: kb("MemAvailable") / 1024 }
|
||||
}
|
||||
|
||||
/** the process to kill when memory is low: the largest of `root`'s descendants over MIN_RSS_MB, or none */
|
||||
export function victim(all: Proc[], root: number, keep: Set<number> = new Set()): Proc | null {
|
||||
const kids = new Map<number, Proc[]>()
|
||||
for (const p of all) kids.set(p.ppid, [...(kids.get(p.ppid) ?? []), p])
|
||||
const under: Proc[] = []
|
||||
const walk = (pid: number) => {
|
||||
for (const k of kids.get(pid) ?? []) {
|
||||
under.push(k)
|
||||
walk(k.pid)
|
||||
}
|
||||
}
|
||||
walk(root)
|
||||
const big = under.filter((p) => p.rssMb >= MIN_RSS_MB && !keep.has(p.pid)).sort((a, b) => b.rssMb - a.rssMb)
|
||||
return big[0] ?? null
|
||||
}
|
||||
|
||||
export interface Guard {
|
||||
stop(): void
|
||||
}
|
||||
|
||||
/** watch the box's memory and kill the largest runaway under `root` (this server) when it runs low; `said` hears why */
|
||||
export function guard(said: (line: string) => void, o: { root?: number; everyMs?: number; keep?: () => Set<number>; mem?: typeof memory; list?: typeof procs; kill?: (pid: number) => void } = {}): Guard {
|
||||
const root = o.root ?? process.pid
|
||||
const mem = o.mem ?? memory
|
||||
const list = o.list ?? procs
|
||||
const kill = o.kill ?? ((pid: number) => process.kill(pid, "SIGKILL"))
|
||||
const t = setInterval(() => {
|
||||
try {
|
||||
const m = mem()
|
||||
if (m.availableMb >= Math.max(FLOOR_MB, m.totalMb * FLOOR_SHARE)) return
|
||||
const v = victim(list(), root, o.keep?.())
|
||||
if (!v) return
|
||||
kill(v.pid)
|
||||
said(`raea cloud: the box was running out of memory (${Math.round(m.availableMb)} MB of ${Math.round(m.totalMb)} MB left), so ${v.name} (pid ${v.pid}, ${(v.rssMb / 1024).toFixed(1)} GB) was stopped. Render on the GPU with raea render, not on this box`)
|
||||
} catch (e) {
|
||||
said(`raea cloud: the memory guard: ${(e as Error).message}`)
|
||||
}
|
||||
}, o.everyMs ?? 1000)
|
||||
t.unref()
|
||||
return { stop: () => clearInterval(t) }
|
||||
}
|
||||
@@ -7,7 +7,7 @@
|
||||
// 2. `raea render` runs there with the same arguments, its paths made relative to that folder, and prints here as
|
||||
// it comes;
|
||||
// 3. the files it made or changed land back here: an output path outside the folder (-o /tmp/x.mp4) is written
|
||||
// there under .raea-cloud-out and moved to its place after.
|
||||
// there as .raea-cloud-out-N-NAME at its top and moved to its place after.
|
||||
// In a raea repo, with this box signed in, the project's media goes by hash instead (media.ts, CR23): the farm fetches
|
||||
// it from R2, and the media the render makes goes to R2 from the farm, here only as pointer files.
|
||||
//
|
||||
@@ -21,7 +21,7 @@ import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { pathToFileURL } from "node:url"
|
||||
import { RaeaCloud } from "../src/index.ts"
|
||||
import { excluded, excludes as mediaExcludes, inputs, lfsOf, outputs } from "./media.ts"
|
||||
import { excluded, excludes as mediaExcludes, farmBlobs, farmInputs, inputs, lfsOf, outputs } from "./media.ts"
|
||||
|
||||
const REAL = process.env.RAEA_REAL ?? "/opt/raea/bin/raea"
|
||||
// flags whose value is a path raea writes; the rest of a render's path arguments are read
|
||||
@@ -75,7 +75,9 @@ export function plan(args: string[], cwd: string, root?: string): Plan | string
|
||||
const abs = path.resolve(cwd, a)
|
||||
if (inside(r, abs)) out.push(path.relative(r, abs) || ".")
|
||||
else if (WRITES.has(flag)) {
|
||||
const rel = path.join(".raea-cloud-out", `${moves.length}-${path.basename(abs)}`)
|
||||
// a file at the top of the project, not in a folder: the folder isn't sent, and a still's writer (unlike a video's
|
||||
// encoder) doesn't make one, so a PNG made outside the project was never written (11-25, StreetTalk's storyboards)
|
||||
const rel = `.raea-cloud-out-${moves.length}-${path.basename(abs)}`
|
||||
moves.push({ from: rel, to: abs })
|
||||
out.push(rel)
|
||||
} else return `${a} is outside the project sent to the GPU (${r})`
|
||||
@@ -85,6 +87,14 @@ export function plan(args: string[], cwd: string, root?: string): Plan | string
|
||||
|
||||
async function main() {
|
||||
const args = process.argv.slice(2)
|
||||
// a video's render manifest (every text's size and place, frame by frame) beside it, for the frames check's text
|
||||
// sizes (frames.ts), unless the render already asks for one
|
||||
{
|
||||
const oi = args.indexOf("-o")
|
||||
const o = oi >= 0 ? (args[oi + 1] ?? "") : ""
|
||||
if (args[0] === "render" && /\.(mp4|mov|m4v|webm)$/i.test(o) && !args.includes("--manifest") && process.env.RAEA_CLOUD_FRAMES !== "0")
|
||||
args.push("--manifest", `${o.slice(0, o.length - path.extname(o).length)}.render.json`)
|
||||
}
|
||||
const url = process.env.RAEA_CLOUD_GPU_URL
|
||||
const token = process.env.RAEA_CLOUD_GPU_TOKEN ?? ""
|
||||
if (!url) local(args)
|
||||
@@ -93,13 +103,23 @@ async function main() {
|
||||
|
||||
const tmp = mkdtempSync(path.join(os.tmpdir(), "raea-offload-"))
|
||||
try {
|
||||
const excludes = (process.env.RAEA_CLOUD_GPU_EXCLUDE ?? "./.git ./out/* ./.raea-cloud-out").split(/\s+/).filter(Boolean)
|
||||
// kits/ (raea-game-kit) is a link into the box's shared cache, hundreds of MB, that the farm can't follow: a
|
||||
// composition uses copies of the kit files it needs in its own folder (11-21: the dangling link hung farm jobs)
|
||||
const excludes = (process.env.RAEA_CLOUD_GPU_EXCLUDE ?? "./.git ./out/* ./.raea-cloud-out ./.raea-cloud-out-* ./kits").split(/\s+/).filter(Boolean)
|
||||
// zstd with GNU tar (the image's); gzip with another tar (a Mac's), whose zstd needs a program of its own
|
||||
const gnu = spawnSync("tar", ["--version"], { encoding: "utf8" }).stdout?.includes("GNU")
|
||||
const sent = path.join(tmp, "in.tar")
|
||||
// the media that goes by hash: out of the tar, named in its manifest
|
||||
const lfs = lfsOf(p.root)
|
||||
const byHash = typeof lfs === "string" ? [] : await inputs(p.root, lfs, excluded(excludes))
|
||||
let byHash = typeof lfs === "string" ? [] : await inputs(p.root, lfs, excluded(excludes))
|
||||
// not in raea's LFS: the media goes into the farm's own cache by hash, once, instead of in every render's tar
|
||||
// (RAEA_CLOUD_GPU_BLOBS=0 puts it back in the tar). A farm without the cache, or one that can't be reached here,
|
||||
// leaves it in the tar, and the health check below says why the farm can't be reached
|
||||
let viaFarm: { media: typeof byHash; sent: number } | null = null
|
||||
if (typeof lfs === "string" && process.env.RAEA_CLOUD_GPU_BLOBS !== "0") {
|
||||
viaFarm = await farmInputs(p.root, farmBlobs(url, token), excluded(excludes), say).catch((e) => (say(`the farm's media cache: ${(e as Error).message}; the media goes in the tar`), null))
|
||||
if (viaFarm) byHash = viaFarm.media
|
||||
}
|
||||
const extra: string[] = []
|
||||
if (byHash.length) {
|
||||
writeFileSync(path.join(tmp, "media-excludes"), mediaExcludes(byHash))
|
||||
@@ -120,7 +140,8 @@ async function main() {
|
||||
throw new Error(`the GPU worker at ${url} didn't answer: ${(e as Error).message} (RAEA_CLOUD_GPU_FALLBACK=cpu renders here instead)`)
|
||||
}
|
||||
say(`rendering on ${new URL(url).host}, ${h.device.renders === "gpu" ? `GPU ${h.device.name}` : `its CPU (${h.device.name})`}: ${p.root} (${(folder.length / 1e6).toFixed(1)} MB) sent`)
|
||||
if (byHash.length) say(`${byHash.length} media files (${(byHash.reduce((n, m) => n + m.size, 0) / 1e6).toFixed(1)} MB) go by hash: the farm fetches them from R2`)
|
||||
if (viaFarm && byHash.length) say(`${byHash.length} media files (${(byHash.reduce((n, m) => n + m.size, 0) / 1e6).toFixed(1)} MB) go by hash from the farm's cache${viaFarm.sent ? `, ${(viaFarm.sent / 1e6).toFixed(1)} MB of it sent now` : ""}`)
|
||||
else if (byHash.length) say(`${byHash.length} media files (${(byHash.reduce((n, m) => n + m.size, 0) / 1e6).toFixed(1)} MB) go by hash: the farm fetches them from R2`)
|
||||
else if (typeof lfs === "string" && existsSync(path.join(p.root, ".lfsconfig"))) say(`media goes in the tar: ${lfs}`)
|
||||
// a render farm's choices (deploy/modal/farm.py): RAEA_CLOUD_GPUS, RAEA_CLOUD_GPU_KIND, RAEA_CLOUD_MAX_USD
|
||||
const n = (v?: string) => (v ? Number(v) : undefined)
|
||||
@@ -131,7 +152,9 @@ async function main() {
|
||||
finish = o.done
|
||||
return o.send
|
||||
}
|
||||
const { exit, files } = await cloud.job(p.args, folder, { as: gnu ? "zst" : "gz", farm, media, onOutput: (t, s) => (s === "out" ? process.stdout : process.stderr).write(t) })
|
||||
// what the job said, kept to spot a file it wanted that stayed here (out/ isn't sent: it's renders)
|
||||
let said = ""
|
||||
const { exit, files } = await cloud.job(p.args, folder, { as: gnu ? "zst" : "gz", farm, media, onOutput: (t, s) => ((said = (said + t).slice(-20000)), (s === "out" ? process.stdout : process.stderr).write(t)) })
|
||||
|
||||
const back = path.join(tmp, "out.tar")
|
||||
writeFileSync(back, files)
|
||||
@@ -149,12 +172,38 @@ async function main() {
|
||||
}
|
||||
}
|
||||
rmSync(path.join(p.root, ".raea-cloud-out"), { recursive: true, force: true })
|
||||
for (const m of p.moves) rmSync(path.join(p.root, m.from), { force: true })
|
||||
if (finish) {
|
||||
const bytes = await finish()
|
||||
say(`its media (${(bytes / 1e6).toFixed(1)} MB) went from the farm to R2; here it's pointers (git lfs pull PATH brings one here)`)
|
||||
}
|
||||
say(`done on the GPU worker in ${((performance.now() - t0) / 1000).toFixed(1)} s, exit ${exit}`)
|
||||
// 11-25: an agent kept its words in out/words/ and four renders failed on "No such file" with no reason given
|
||||
const missed = exit ? /(?:^|[\s/])(out\/[^\s:]+): No such file/m.exec(said) : null
|
||||
if (missed && excludes.includes("./out/*")) say(`${missed[1]} wasn't sent: out/ stays here, as it holds renders. Keep what a composition reads (words, data, stills it uses) in media/ or beside the composition`)
|
||||
process.exitCode = exit
|
||||
// a video's words, heard as soon as it's back (words.ts): the cut is held to OUT.lines.txt when it has one, so a
|
||||
// word clipped by a cut or faded under a crossfade is caught before anyone reviews it (11-25, Shane)
|
||||
// the -o asked for (an output outside the project came back there by its move)
|
||||
const oi = args.indexOf("-o")
|
||||
const made = oi >= 0 ? path.resolve(process.cwd(), args[oi + 1] ?? "") : ""
|
||||
if (!exit && /\.(mp4|mov|m4v|webm)$/i.test(made) && existsSync(made) && process.env.RAEA_CLOUD_WORDS !== "0") {
|
||||
const { afterRender } = await import("./words.ts")
|
||||
const code = await afterRender(made, say)
|
||||
if (code) process.exitCode = code
|
||||
}
|
||||
// what its pictures get wrong (frames.ts): faces cut by the frame or a split screen's seam, text too small to read
|
||||
// (11-25, Shane: "it cuts out faces all the time", "it makes text too small")
|
||||
if (!exit && /\.(mp4|mov|m4v|webm)$/i.test(made) && existsSync(made) && process.env.RAEA_CLOUD_FRAMES !== "0") {
|
||||
const { main: frames } = await import("./frames.ts")
|
||||
say(`the frames check: ${path.basename(made)}'s faces and text sizes`)
|
||||
const mi = args.indexOf("--manifest")
|
||||
const code = await frames(["check", made, ...(mi >= 0 ? ["--manifest", path.resolve(process.cwd(), args[mi + 1] ?? "")] : [])]).catch((e) => (say(`the frames check couldn't run: ${(e as Error).message}`), 0))
|
||||
if (code) {
|
||||
say(`${path.basename(made)} has a face cut or text too small: fix every ERROR above (reframe on the person, make the text bigger), then render again. A face at the edge that's meant goes in ${path.basename(made, path.extname(made))}.despite.txt with why`)
|
||||
process.exitCode = code
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
rmSync(tmp, { recursive: true, force: true })
|
||||
}
|
||||
|
||||
@@ -0,0 +1,294 @@
|
||||
// `raea words` on a raea cloud box: what a take or an export says, word by word, and whether an export says what its
|
||||
// cut meant it to. raea's own transcriber is parakeet-mlx (Mac only), so a box had none: agents guessed `raea
|
||||
// transcribe`, cut on guessed frames and shipped words clipped by a cut or faded under a crossfade (11-25, Shane: "cuts
|
||||
// where it applies crossfades on audio that make it so you can't hear it, and cuts where it will cut early over
|
||||
// someone speaking ... before exporting the audio requires a transcription pass to be sure it matches").
|
||||
//
|
||||
// raea words FILE [-o OUT.words.json] [--language en] [--fades]
|
||||
// FILE's sound heard by Whisper large-v3 (the farm's POST /v1/words, the model raea cloud's library index uses)
|
||||
// into FILE's words.json beside it ([{text, start_ms, end_ms}], what `raea cut`, captions and --words read)
|
||||
// raea words check VIDEO --expect LINES.txt [-o REPORT.json] [--language en]
|
||||
// VIDEO heard, then held to the lines its cut should say (plain text, in order): a word missing or cut short is
|
||||
// an error; a word heard differently, speech fading under a crossfade, or a word running into the first or last
|
||||
// frame is a warning. Exit 1 on any error. The VIDEO's words.json is kept for its captions.
|
||||
//
|
||||
// The sound goes as 16 kHz mono MP3 in 10-minute pieces (`raea media ffmpeg`), to RAEA_CLOUD_GPU_URL with its token.
|
||||
import { spawnSync } from "node:child_process"
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { pathToFileURL } from "node:url"
|
||||
|
||||
const REAL = process.env.RAEA_REAL ?? "/opt/raea/bin/raea"
|
||||
const PIECE_S = 600
|
||||
|
||||
export type Word = { text: string; start: number; end: number }
|
||||
export type Finding = { level: "error" | "warn" | "note"; kind: "missing" | "clipped" | "changed" | "faded" | "edge" | "extra"; at: number | null; says: string }
|
||||
|
||||
/** a word as it's compared: lower case, letters and digits only ("$1,000." and "1000" are the same word) */
|
||||
export const norm = (w: string) => w.toLowerCase().normalize("NFKD").replace(/[^\p{L}\p{N}]+/gu, "")
|
||||
|
||||
/** the lines' words and the heard words aligned (longest common subsequence), as pairs: [expected index | -1, heard index | -1] */
|
||||
export function align(want: string[], heard: string[]): [number, number][] {
|
||||
const n = want.length
|
||||
const m = heard.length
|
||||
const L = Array.from({ length: n + 1 }, () => new Uint16Array(m + 1))
|
||||
for (let i = n - 1; i >= 0; i--) for (let j = m - 1; j >= 0; j--) L[i][j] = want[i] === heard[j] ? L[i + 1][j + 1] + 1 : Math.max(L[i + 1][j], L[i][j + 1])
|
||||
const out: [number, number][] = []
|
||||
let i = 0
|
||||
let j = 0
|
||||
while (i < n && j < m) {
|
||||
if (want[i] === heard[j]) out.push([i++, j++])
|
||||
// a word for a word costs the alignment nothing: kept side by side, so a word heard cut short reads as one
|
||||
else if (L[i + 1][j + 1] === L[i][j]) out.push([i++, -1], [-1, j++])
|
||||
else if (L[i + 1][j] >= L[i][j + 1]) out.push([i++, -1])
|
||||
else out.push([-1, j++])
|
||||
}
|
||||
while (i < n) out.push([i++, -1])
|
||||
while (j < m) out.push([-1, j++])
|
||||
return out
|
||||
}
|
||||
|
||||
/** one heard word is the other cut short: "test" for "tests", "abl" for "able" (three letters at least) */
|
||||
const cutShort = (want: string, got: string) => got.length >= 2 && got.length < want.length && (want.startsWith(got) || want.endsWith(got))
|
||||
|
||||
/** the expected lines against what was heard */
|
||||
export function compare(lines: string, heard: Word[]): Finding[] {
|
||||
const wantRaw = lines.split(/\s+/).filter((w) => norm(w))
|
||||
const want = wantRaw.map(norm)
|
||||
const got = heard.map((w) => norm(w.text))
|
||||
const pairs = align(want, got)
|
||||
const out: Finding[] = []
|
||||
// a missing word next to an extra one is one word heard differently (or cut short): pair them up
|
||||
for (let k = 0; k < pairs.length; k++) {
|
||||
const [i, j] = pairs[k]
|
||||
if (i >= 0 && j >= 0) continue
|
||||
const next = pairs[k + 1]
|
||||
if (i >= 0 && next && next[0] < 0 && next[1] >= 0) {
|
||||
const h = heard[next[1]]
|
||||
out.push(cutShort(want[i], got[next[1]]) ? { level: "error", kind: "clipped", at: h.start, says: `"${wantRaw[i]}" is cut short: heard "${h.text}" at ${h.start.toFixed(2)} s. Move the cut into the gap after the word` } : { level: "warn", kind: "changed", at: h.start, says: `"${wantRaw[i]}" heard as "${h.text}" at ${h.start.toFixed(2)} s: listen there; if the word is clipped or muddied, fix the cut` })
|
||||
k++
|
||||
continue
|
||||
}
|
||||
if (i < 0 && next && next[0] >= 0 && next[1] < 0) {
|
||||
const h = heard[j]
|
||||
out.push(cutShort(want[next[0]], got[j]) ? { level: "error", kind: "clipped", at: h.start, says: `"${wantRaw[next[0]]}" is cut short: heard "${h.text}" at ${h.start.toFixed(2)} s. Move the cut into the gap after the word` } : { level: "warn", kind: "changed", at: h.start, says: `"${wantRaw[next[0]]}" heard as "${h.text}" at ${h.start.toFixed(2)} s: listen there; if the word is clipped or muddied, fix the cut` })
|
||||
k++
|
||||
continue
|
||||
}
|
||||
if (i >= 0) {
|
||||
// where it should have been: after the last word heard before it
|
||||
const before = pairs.slice(0, k).reverse().find((p) => p[1] >= 0)
|
||||
const at = before ? heard[before[1]].end : 0
|
||||
out.push({ level: "error", kind: "missing", at, says: `"${wantRaw[i]}" isn't heard (expected near ${at.toFixed(2)} s): a cut, a fade or the mix took it` })
|
||||
} else out.push({ level: "note", kind: "extra", at: heard[j].start, says: `"${heard[j].text}" at ${heard[j].start.toFixed(2)} s isn't in the lines` })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** the level every 10 ms, in dB, of 16 kHz mono 16-bit samples */
|
||||
export function levels(pcm: Int16Array): number[] {
|
||||
const hop = 160
|
||||
const out: number[] = []
|
||||
for (let s = 0; s + hop <= pcm.length; s += hop) {
|
||||
let e = 0
|
||||
for (let k = s; k < s + hop; k++) e += (pcm[k] / 32768) ** 2
|
||||
out.push(10 * Math.log10(e / hop + 1e-10))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** speech that fades under a crossfade: inside the heard words, a run of 120 ms or more at least 14 dB under the speech's
|
||||
* own median, that comes back up within the same word or the next (a fade out and in across a cut). And a word running
|
||||
* into the first or last 40 ms of the piece, which is speech cut by the piece's own edge */
|
||||
export function fades(db: number[], heard: Word[], seconds: number): Finding[] {
|
||||
const inside: number[] = []
|
||||
for (const w of heard) for (let f = Math.floor(w.start * 100); f < Math.min(db.length, Math.ceil(w.end * 100)); f++) inside.push(db[f])
|
||||
if (inside.length < 20) return []
|
||||
const median = [...inside].sort((a, b) => a - b)[Math.floor(inside.length / 2)]
|
||||
const out: Finding[] = []
|
||||
const quiet = (f: number) => db[f] < median - 14
|
||||
let lastAt = -9
|
||||
for (let n = 0; n < heard.length; n++) {
|
||||
const w = heard[n]
|
||||
const a = Math.floor(w.start * 100)
|
||||
const b = Math.min(db.length, Math.ceil(w.end * 100))
|
||||
// a dip that comes back up inside the word: a fade out and in across a join. One that runs on to the word's end is
|
||||
// the word trailing off (Whisper's spans take in the quiet after a word), not a fade
|
||||
let run = 0
|
||||
let deepest = 0
|
||||
for (let f = a; f < b; f++) {
|
||||
if (quiet(f)) {
|
||||
run++
|
||||
deepest = Math.max(deepest, median - db[f])
|
||||
continue
|
||||
}
|
||||
if (run >= 12 && db[f] > median - 8 && f / 100 - lastAt > 1) {
|
||||
lastAt = f / 100
|
||||
out.push({ level: "warn", kind: "faded", at: (f - run) / 100, says: `"${w.text}" at ${w.start.toFixed(2)} s dips ${deepest.toFixed(0)} dB under the speech for ${run * 10} ms and comes back: a crossfade or fade over speech? Dialogue joins are hard cuts in the gap between words, with fades of 20 ms at most` })
|
||||
}
|
||||
run = 0
|
||||
deepest = 0
|
||||
}
|
||||
}
|
||||
const first = heard[0]
|
||||
const last = heard[heard.length - 1]
|
||||
// Whisper puts a first word at 0 whether or not it's cut: only a sound already at speech level on the first (or last)
|
||||
// 30 ms is speech the edge cut into
|
||||
const loud = (fs: number[]) => fs.length > 0 && fs.every((f) => db[f] !== undefined && db[f] > median - 8)
|
||||
const n0 = db.length
|
||||
if (first && first.start < 0.04 && loud([0, 1, 2])) out.push({ level: "warn", kind: "edge", at: 0, says: `the first word "${first.text}" starts on the first frame: is its start cut off?` })
|
||||
if (last && seconds - last.end < 0.04 && loud([n0 - 3, n0 - 2, n0 - 1])) out.push({ level: "warn", kind: "edge", at: last.end, says: `the last word "${last.text}" runs to the last frame: is its end cut off?` })
|
||||
return out
|
||||
}
|
||||
|
||||
function ffmpeg(args: string[]) {
|
||||
const r = spawnSync(REAL, ["media", "ffmpeg", ...args], { encoding: "utf8" })
|
||||
if (r.status !== 0) {
|
||||
const r2 = spawnSync("ffmpeg", args, { encoding: "utf8" })
|
||||
if (r2.status !== 0) throw new Error(`ffmpeg ${args.join(" ")}: ${(r.stderr || r2.stderr || "").slice(-400)}`)
|
||||
}
|
||||
}
|
||||
|
||||
function seconds(file: string): number {
|
||||
const r = spawnSync(REAL, ["media", "ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", file], { encoding: "utf8" })
|
||||
const s = Number.parseFloat(r.stdout)
|
||||
if (Number.isFinite(s)) return s
|
||||
const r2 = spawnSync("ffprobe", ["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", file], { encoding: "utf8" })
|
||||
const s2 = Number.parseFloat(r2.stdout)
|
||||
if (!Number.isFinite(s2)) throw new Error(`${file}: no length (is it a video or sound file?)`)
|
||||
return s2
|
||||
}
|
||||
|
||||
/** what FILE says, by the farm's Whisper */
|
||||
export async function hear(file: string, language?: string, f: typeof fetch = fetch): Promise<Word[]> {
|
||||
const url = process.env.RAEA_CLOUD_GPU_URL
|
||||
const token = process.env.RAEA_CLOUD_GPU_TOKEN ?? ""
|
||||
if (!url) throw new Error("raea words needs the farm (RAEA_CLOUD_GPU_URL), which hears it with Whisper; this box has none set")
|
||||
const len = seconds(file)
|
||||
const dir = mkdtempSync(path.join(os.tmpdir(), "raea-words-"))
|
||||
try {
|
||||
const out: Word[] = []
|
||||
for (let at = 0; at < len; at += PIECE_S) {
|
||||
const mp3 = path.join(dir, `p${at}.mp3`)
|
||||
ffmpeg(["-v", "error", "-y", "-ss", String(at), "-t", String(PIECE_S), "-i", file, "-vn", "-ac", "1", "-ar", "16000", "-b:a", "32k", mp3])
|
||||
if (!existsSync(mp3)) throw new Error(`${file} has no sound to hear`)
|
||||
let r: Response | undefined
|
||||
let why = ""
|
||||
for (let k = 0; k < 4; k++) {
|
||||
r = await f(`${url.replace(/\/$/, "")}/v1/words${language ? `?language=${encodeURIComponent(language)}` : ""}`, { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "audio/mpeg" }, body: readFileSync(mp3), signal: AbortSignal.timeout(330_000) })
|
||||
if (r.ok) break
|
||||
why = `${r.status} ${(await r.text()).slice(0, 300)}`
|
||||
if (r.status < 500) break
|
||||
await new Promise((ok) => setTimeout(ok, 1000 * 2 ** k))
|
||||
}
|
||||
if (!r?.ok) throw new Error(`the farm couldn't hear ${path.basename(file)}: ${why}`)
|
||||
const b = (await r.json()) as { words: Word[] }
|
||||
out.push(...split(b.words).map((w) => ({ text: w.text, start: at + w.start, end: at + w.end })))
|
||||
}
|
||||
return out
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
/** Whisper sometimes hands back two words as one ("for $60"): one word each, sharing its time by their lengths */
|
||||
export function split(ws: Word[]): Word[] {
|
||||
return ws.flatMap((w) => {
|
||||
const parts = w.text.split(/\s+/).filter(Boolean)
|
||||
if (parts.length < 2) return [w]
|
||||
const total = parts.reduce((n, p) => n + p.length, 0)
|
||||
let t = w.start
|
||||
return parts.map((p) => {
|
||||
const d = ((w.end - w.start) * p.length) / total
|
||||
const x = { text: p, start: t, end: t + d }
|
||||
t += d
|
||||
return x
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
const wordsPath = (file: string) => `${file.slice(0, file.length - path.extname(file).length)}.words.json`
|
||||
const asRaea = (ws: Word[]) => ws.map((w) => ({ text: w.text, start_ms: Math.round(w.start * 1000), end_ms: Math.round(w.end * 1000) }))
|
||||
|
||||
function flag(args: string[], name: string): string | undefined {
|
||||
const i = args.indexOf(name)
|
||||
return i >= 0 ? args[i + 1] : undefined
|
||||
}
|
||||
|
||||
export async function main(args: string[]): Promise<number> {
|
||||
const language = flag(args, "--language")
|
||||
if (args[0] === "check") {
|
||||
const video = args[1]
|
||||
const expect = flag(args, "--expect")
|
||||
if (!video || !expect || !existsSync(video) || !existsSync(expect)) {
|
||||
console.error("usage: raea words check VIDEO --expect LINES.txt [-o REPORT.json] [--language en] (LINES.txt: the words the cut should say, in order)")
|
||||
return 2
|
||||
}
|
||||
const heard = await hear(video, language)
|
||||
writeFileSync(wordsPath(video), `${JSON.stringify(asRaea(heard))}\n`)
|
||||
const findings = [...compare(readFileSync(expect, "utf8"), heard), ...soundFindings(video, heard)].sort((a, b) => (a.at ?? 0) - (b.at ?? 0))
|
||||
const errors = findings.filter((x) => x.level === "error").length
|
||||
const warns = findings.filter((x) => x.level === "warn").length
|
||||
const report = { object: "words.check", video, expect, passed: errors === 0, errors, warnings: warns, heard: heard.map((w) => w.text).join(" "), findings }
|
||||
const o = flag(args, "-o") ?? `${video.slice(0, video.length - path.extname(video).length)}.words-check.json`
|
||||
writeFileSync(o, `${JSON.stringify(report, null, 2)}\n`)
|
||||
for (const x of findings.filter((x) => x.level !== "note")) console.log(`${x.level === "error" ? "ERROR" : "WARN "} ${x.at === null ? "" : `${x.at.toFixed(2)} s `}${x.says}`)
|
||||
const extra = findings.filter((x) => x.level === "note").length
|
||||
console.log(`${errors ? "FAILED" : "PASSED"} ${path.basename(video)}: ${heard.length} words heard, ${errors} errors, ${warns} warnings${extra ? `, ${extra} words not in the lines` : ""}; ${o}`)
|
||||
return errors ? 1 : 0
|
||||
}
|
||||
const file = args.find((a, i) => !a.startsWith("-") && args[i - 1] !== "-o" && args[i - 1] !== "--language")
|
||||
if (!file || !existsSync(file)) {
|
||||
console.error("usage: raea words FILE [-o OUT.words.json] [--language en] | raea words check VIDEO --expect LINES.txt [-o REPORT.json]")
|
||||
return 2
|
||||
}
|
||||
const heard = await hear(file, language)
|
||||
const o = flag(args, "-o") ?? wordsPath(file)
|
||||
writeFileSync(o, `${JSON.stringify(asRaea(heard))}\n`)
|
||||
console.log(`${o}: ${heard.length} words, ${heard.length ? heard[heard.length - 1].end.toFixed(1) : 0} s`)
|
||||
console.log(heard.map((w) => w.text).join(" "))
|
||||
if (args.includes("--fades")) for (const x of soundFindings(file, heard)) console.log(`WARN ${x.at === null ? "" : `${x.at.toFixed(2)} s `}${x.says}`)
|
||||
return 0
|
||||
}
|
||||
|
||||
/** fades and edge words in FILE's sound against what was heard */
|
||||
function soundFindings(file: string, heard: Word[]): Finding[] {
|
||||
const dir = mkdtempSync(path.join(os.tmpdir(), "raea-words-"))
|
||||
try {
|
||||
const raw = path.join(dir, "a.raw")
|
||||
ffmpeg(["-v", "error", "-y", "-i", file, "-vn", "-ac", "1", "-ar", "16000", "-c:a", "pcm_s16le", "-f", "s16le", raw])
|
||||
const b = readFileSync(raw)
|
||||
return fades(levels(new Int16Array(b.buffer, b.byteOffset, Math.floor(b.length / 2))), heard, seconds(file))
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
/** after a video render (offload.ts): its words heard and kept beside it, held to OUT.lines.txt when there is one. The
|
||||
* exit code is the check's when it ran (1 on an error), else 0; a farm that can't hear it never fails the render */
|
||||
export async function afterRender(out: string, say: (s: string) => void): Promise<number> {
|
||||
const lines = `${out.slice(0, out.length - path.extname(out).length)}.lines.txt`
|
||||
try {
|
||||
if (existsSync(lines)) {
|
||||
say(`the words check: ${path.basename(out)} held to ${path.basename(lines)}`)
|
||||
const code = await main(["check", out, "--expect", lines])
|
||||
if (code) say(`${path.basename(out)} doesn't say its lines: fix every ERROR above (move the cut into the gap between words, take the fade off the speech) and render again before any review`)
|
||||
return code
|
||||
}
|
||||
say(`the words heard in ${path.basename(out)} (no ${path.basename(lines)} beside it to hold them to: write the lines this cut should say there, and the next render checks them)`)
|
||||
await main([out, "--fades"])
|
||||
} catch (e) {
|
||||
say(`the words pass couldn't run: ${(e as Error).message}`)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
|
||||
// `raea transcribe` is the name agents reach for: the same thing
|
||||
const a = process.argv.slice(2)
|
||||
main(a[0] === "words" || a[0] === "transcribe" ? a.slice(1) : a).then(
|
||||
(c) => process.exit(c),
|
||||
(e) => (console.error(`raea words: ${(e as Error).message}`), process.exit(1)),
|
||||
)
|
||||
}
|
||||
+11
-3
@@ -5,7 +5,7 @@
|
||||
// await cloud.health() // {raea, agent, agents, workspace}
|
||||
// await cloud.write("card/edit.tsx", source) // into the workspace
|
||||
// await cloud.run(["render", "edit.tsx", "-o", "card.mp4"], { cwd: "card" })
|
||||
// const s = await cloud.session() // the default agent, over ACP
|
||||
// const s = await cloud.session() // the agent RAEA_AGENT names, over ACP
|
||||
// await s.prompt("Make card/edit.tsx a 3 s title card that says hello", (u) => console.log(u.sessionUpdate))
|
||||
// const mp4 = await cloud.read("card/card.mp4")
|
||||
// s.close()
|
||||
@@ -164,7 +164,15 @@ export class RaeaCloud {
|
||||
/** A finished job's files: the ones its run made or changed, as a tar (zstd unless `as` says gz or tar). The server
|
||||
* drops the job after. */
|
||||
async jobFiles(id: string, as: "zst" | "gz" | "tar" = "zst"): Promise<Uint8Array> {
|
||||
return new Uint8Array(await (await this.fetch(`/v1/jobs/${id}/out?as=${as}`)).arrayBuffer())
|
||||
// a farm whose volume is busy answers 503 and keeps the job (11-25: a 500 there lost a finished render): ask again
|
||||
for (let i = 0; ; i++) {
|
||||
try {
|
||||
return new Uint8Array(await (await this.fetch(`/v1/jobs/${id}/out?as=${as}`)).arrayBuffer())
|
||||
} catch (e) {
|
||||
if (i >= 4 || !/: 503 /.test((e as Error).message)) throw e
|
||||
await new Promise((r) => setTimeout(r, 1000 * 2 ** i))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A finished job's media outputs (a job started with farm.media), held on the farm until sendMedia. */
|
||||
@@ -220,7 +228,7 @@ export class RaeaCloud {
|
||||
return this.fetch(`/v1/login${agent ? `?agent=${encodeURIComponent(agent)}` : ""}`).then((r) => r.json())
|
||||
}
|
||||
|
||||
/** An ACP session with an agent in the workspace (the default agent unless one is named). */
|
||||
/** An ACP session with an agent in the workspace (the one named, else the one the box's RAEA_AGENT names; with neither, the box refuses). */
|
||||
async session(o: { agent?: string; cwd?: string; onPermission?: (p: Permission) => string | Promise<string> } = {}): Promise<Session> {
|
||||
const work = (this.ws ??= this.health().then((h) => h.workspace))
|
||||
const q = new URLSearchParams({ token: this.token, ...(o.agent ? { agent: o.agent } : {}) })
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
// A box's media by hash into the farm's own cache (server/media.ts farmInputs, 11-25), against a local stand-in for
|
||||
// the farm's POST /v1/blobs/have and PUT /v1/blobs/OID: node test/farm-blobs.ts from sdk/cloud.
|
||||
// Checked: a project's footage and large files go by hash and its code and small files stay in the tar; the first
|
||||
// render sends each once (streamed, checked against its hash), the next sends nothing and hashes nothing again; a
|
||||
// file changed since is sent again; out/ and links are left alone; a farm without the cache answers null.
|
||||
|
||||
import { createHash } from "node:crypto"
|
||||
import { linkSync, mkdirSync, mkdtempSync, readFileSync, symlinkSync, writeFileSync } from "node:fs"
|
||||
import { createServer } from "node:http"
|
||||
import type { AddressInfo } from "node:net"
|
||||
import { tmpdir } from "node:os"
|
||||
import path from "node:path"
|
||||
import { excluded, farmBlobs, farmInputs } from "../server/media.ts"
|
||||
|
||||
const ok = (m: string) => console.log(`ok ${m}`)
|
||||
const assert = (c: unknown, m: string) => {
|
||||
if (!c) throw new Error(`not ok: ${m}`)
|
||||
}
|
||||
|
||||
const held = new Map<string, number>()
|
||||
let puts = 0
|
||||
let cache = true
|
||||
const farm = createServer((req, res) => {
|
||||
const u = new URL(req.url!, "http://x")
|
||||
if (req.headers.authorization !== "Bearer farm-token") return void res.writeHead(401).end()
|
||||
if (!cache) return void res.writeHead(404).end()
|
||||
if (req.method === "POST" && u.pathname === "/v1/blobs/have") {
|
||||
let b = ""
|
||||
req.on("data", (c) => (b += c)).on("end", () => {
|
||||
const objects = (JSON.parse(b).objects ?? []) as { oid: string; size: number }[]
|
||||
res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ have: objects.filter((o) => held.get(o.oid) === o.size).map((o) => o.oid) }))
|
||||
})
|
||||
return
|
||||
}
|
||||
const m = /^\/v1\/blobs\/([0-9a-f]{64})$/.exec(u.pathname)
|
||||
if (req.method === "PUT" && m) {
|
||||
const h = createHash("sha256")
|
||||
let n = 0
|
||||
req.on("data", (c: Buffer) => (h.update(c), (n += c.length))).on("end", () => {
|
||||
if (h.digest("hex") !== m[1] || n !== Number(u.searchParams.get("size"))) return void res.writeHead(400).end("wrong hash")
|
||||
held.set(m[1], n)
|
||||
puts++
|
||||
res.writeHead(200).end("{}")
|
||||
})
|
||||
return
|
||||
}
|
||||
res.writeHead(404).end()
|
||||
})
|
||||
await new Promise<void>((r) => farm.listen(0, "127.0.0.1", r))
|
||||
const url = `http://127.0.0.1:${(farm.address() as AddressInfo).port}`
|
||||
|
||||
const root = mkdtempSync(path.join(tmpdir(), "farm-blobs-"))
|
||||
const store = path.join(root, "..", `${path.basename(root)}-hashes.json`)
|
||||
mkdirSync(path.join(root, "media"), { recursive: true })
|
||||
mkdirSync(path.join(root, "out"), { recursive: true })
|
||||
mkdirSync(path.join(root, "brand"), { recursive: true })
|
||||
writeFileSync(path.join(root, "media", "interview.MOV"), Buffer.alloc(5 << 20, 7))
|
||||
writeFileSync(path.join(root, "media", "copy.MOV"), Buffer.alloc(5 << 20, 7)) // the same bytes: one upload
|
||||
writeFileSync(path.join(root, "brand", "logo.png"), Buffer.alloc(300 << 10, 3))
|
||||
writeFileSync(path.join(root, "brand", "icon.png"), Buffer.alloc(2 << 10, 3)) // small: stays in the tar
|
||||
writeFileSync(path.join(root, "data.bin"), Buffer.alloc(6 << 20, 1)) // large, of no media type
|
||||
writeFileSync(path.join(root, "edit.tsx"), "export default () => null\n")
|
||||
writeFileSync(path.join(root, "out", "old.mp4"), Buffer.alloc(5 << 20, 9)) // an old render: the tar's excludes leave it
|
||||
symlinkSync(path.join(root, "media", "interview.MOV"), path.join(root, "media", "link.MOV"))
|
||||
|
||||
const skip = excluded(["./.git", "./out/*", "./.raea-cloud-out", "./kits"])
|
||||
const blobs = farmBlobs(url, "farm-token")
|
||||
const first = await farmInputs(root, blobs, skip, () => {}, store)
|
||||
assert(first, "a farm with the cache answers")
|
||||
const paths = first!.media.map((m) => m.path).sort()
|
||||
assert(JSON.stringify(paths) === JSON.stringify(["brand/logo.png", "data.bin", "media/copy.MOV", "media/interview.MOV"]), `what goes by hash: ${paths}`)
|
||||
assert(first!.media.every((m) => !m.href), "no href: the farm's own cache")
|
||||
assert(puts === 3 && first!.sent === (5 << 20) + (300 << 10) + (6 << 20), `sent once each, the same bytes once: ${puts} puts, ${first!.sent}`)
|
||||
ok("footage, large files and media over 256 KB go by hash, each sent once; code, small files, out/ and links stay in the tar")
|
||||
|
||||
const second = await farmInputs(root, blobs, skip, () => {}, store)
|
||||
assert(second!.sent === 0 && puts === 3, "the next render sends nothing")
|
||||
ok("the next render sends nothing: the farm has it all")
|
||||
|
||||
writeFileSync(path.join(root, "brand", "logo.png"), Buffer.alloc(300 << 10, 4))
|
||||
const third = await farmInputs(root, blobs, skip, () => {}, store)
|
||||
assert(third!.sent === 300 << 10 && puts === 4, `a changed file is sent again: ${third!.sent}`)
|
||||
ok("a file changed since is hashed and sent again")
|
||||
|
||||
// a new folder that hard-links the same footage (a thread started again) hashes nothing again
|
||||
const again = mkdtempSync(path.join(tmpdir(), "farm-blobs-linked-"))
|
||||
mkdirSync(path.join(again, "media"))
|
||||
linkSync(path.join(root, "media", "interview.MOV"), path.join(again, "media", "interview.MOV"))
|
||||
const linked = await farmInputs(again, blobs, skip, () => {}, store)
|
||||
assert(linked!.sent === 0 && linked!.media[0].oid === first!.media.find((m) => m.path === "media/interview.MOV")!.oid, "the linked file is known")
|
||||
const known = JSON.parse(readFileSync(store, "utf8")) as Record<string, unknown>
|
||||
assert(Object.keys(known).length === 4, `one entry a file (logo.png rewritten in place is the same file), not a path: ${Object.keys(known).length}`)
|
||||
ok("a new folder that links the same footage hashes and sends nothing again")
|
||||
|
||||
cache = false
|
||||
assert((await farmInputs(root, blobs, skip, () => {}, store)) === null, "an older farm")
|
||||
ok("a farm without the cache answers null: the media goes in the tar")
|
||||
farm.close()
|
||||
@@ -70,6 +70,23 @@ def job(objects):
|
||||
|
||||
|
||||
obj = {"path": "footage/take.mov", "oid": oid, "size": len(take), "href": f"{base}/{oid}", "header": {}}
|
||||
|
||||
# footage the box sent the farm itself (PUT /v1/blobs, no href): used from the cache as a link, never fetched
|
||||
sent = b"interview " * 5000
|
||||
soid = hashlib.sha256(sent).hexdigest()
|
||||
open(os.path.join(cache, soid), "wb").write(sent)
|
||||
ws = job([{"path": "media/int1.MOV", "oid": soid, "size": len(sent)}])
|
||||
gets = hits["GET"]
|
||||
ss = fm.fetch(ws, cache, log=lambda _: None)
|
||||
assert open(os.path.join(ws, "media/int1.MOV"), "rb").read() == sent and os.path.islink(os.path.join(ws, "media/int1.MOV"))
|
||||
assert ss == {"objects": 1, "fetched": 0, "cached": len(sent)} and hits["GET"] == gets, ss
|
||||
try:
|
||||
fm.fetch(job([{"path": "media/gone.MOV", "oid": "ab" * 32, "size": 10}]), cache, log=lambda _: None)
|
||||
raise AssertionError("footage never sent was used")
|
||||
except ValueError as e:
|
||||
assert "never sent" in str(e)
|
||||
ok("footage the box sent the farm itself comes from the cache as a link, and footage it never sent is refused")
|
||||
|
||||
w1 = job([obj])
|
||||
s1 = fm.fetch(w1, cache, log=lambda _: None)
|
||||
assert open(os.path.join(w1, "footage/take.mov"), "rb").read() == take
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
# The farm's planner (deploy/modal/farm_plan.py) with stand-in GPUs: python3 test/farm_plan.py from sdk/cloud. The
|
||||
# stand-ins write the frames they're asked for, so a split render is checked end to end, ffmpeg's encode included.
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
@@ -33,8 +34,12 @@ class FakeGpu:
|
||||
|
||||
def remote(self, id, args, frames=None, first=0, probe=False, video=False):
|
||||
self.calls.append(("probe" if probe else "run", frames, first))
|
||||
self.args = getattr(self, "args", []) + [list(args)]
|
||||
if probe:
|
||||
return {"code": 0, "out": "", "s": 12.5, "length": self.length, "fps": 30, "w": 1920, "h": 1080}
|
||||
# as raea does with two --manifest: the first wins, so the probe's own says nothing
|
||||
if args.count("--manifest") > 0:
|
||||
return {"code": 0, "out": "APPLIED 1 frames", "s": 12.5, "length": None, "fps": None, "w": None, "h": None, "manifest": {}}
|
||||
return {"code": 0, "out": "", "s": 12.5, "length": self.length, "fps": 30, "w": 1920, "h": 1080, "manifest": {"length": self.length, "fps": 30}}
|
||||
dest = os.path.join(self.root, "jobs", id, "frames")
|
||||
os.makedirs(dest, exist_ok=True)
|
||||
if video:
|
||||
@@ -90,6 +95,16 @@ frames = int(subprocess.run(["ffprobe", "-v", "error", "-count_frames", "-select
|
||||
assert frames == 60, frames
|
||||
ok("a 60-frame render: frame 0, a timed run of 8, the rest on one more GPU, the runs joined into 60 frames")
|
||||
|
||||
# the render's own --manifest (as an agent passes it): the GPUs never get it, and it's written from frame 0's at the end
|
||||
lines.clear()
|
||||
m = FakeGpu(root)
|
||||
os.makedirs(os.path.join(root, "jobs", "jm", "work"))
|
||||
code = fp.raea_render(["render", "a.tsx", "-o", "out/a.mp4", "--manifest", "out/a.render.json", "--quality", "high"], {"id": "jm", "gpu": "L4", "gpus": 10}, os.path.join(root, "jobs", "jm", "work"), log, m, {}, run)
|
||||
assert code == 0, lines
|
||||
assert all("--manifest" not in a and "--quality" in a for a in m.args), m.args
|
||||
assert json.load(open(os.path.join(root, "jobs", "jm", "work", "out", "a.render.json")))["length"] == 60
|
||||
ok("a render's own --manifest isn't passed to the GPUs (the probe would lose the length), and is written at the end")
|
||||
|
||||
lines.clear()
|
||||
long = FakeGpu(root, length=1000)
|
||||
os.makedirs(os.path.join(root, "jobs", "j2", "work"))
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
// The box's memory guard (server/memguard.ts): node test/memguard.ts from sdk/cloud. Offline, on a made-up process
|
||||
// table; and on Linux, against a real process that grows past the floor (set high for the test), which it kills.
|
||||
import { spawn } from "node:child_process"
|
||||
import { existsSync } from "node:fs"
|
||||
import { guard, MIN_RSS_MB, type Proc, victim } from "../server/memguard.ts"
|
||||
|
||||
const ok = (m: string) => console.log(`ok ${m}`)
|
||||
const assert = (c: unknown, m: string) => {
|
||||
if (!c) throw new Error(`not ok: ${m}`)
|
||||
}
|
||||
|
||||
// the server (1), an agent (2) and its helper (3), a shell (4) running a render (5) and an ffmpeg (6); another box
|
||||
// process (9) outside the server
|
||||
const table: Proc[] = [
|
||||
{ pid: 1, ppid: 0, rssMb: 120, name: "node" },
|
||||
{ pid: 2, ppid: 1, rssMb: 300, name: "agy_acp_server" },
|
||||
{ pid: 3, ppid: 2, rssMb: 180, name: "localharness" },
|
||||
{ pid: 4, ppid: 3, rssMb: 4, name: "bash" },
|
||||
{ pid: 5, ppid: 4, rssMb: 5200, name: "raea" },
|
||||
{ pid: 6, ppid: 4, rssMb: 1500, name: "ffmpeg" },
|
||||
{ pid: 9, ppid: 0, rssMb: 9000, name: "other" },
|
||||
]
|
||||
assert(victim(table, 1)?.pid === 5, "the largest runaway under the server")
|
||||
assert(victim(table, 1, new Set([5]))?.pid === 6, "a kept one is passed over")
|
||||
assert(victim(table.filter((p) => p.pid !== 5 && p.pid !== 6), 1) === null, `nothing under ${MIN_RSS_MB} MB is killed: not an agent, not the server`)
|
||||
ok("it picks the largest process an agent started, never the agent, the server or anything outside it")
|
||||
|
||||
// the loop: memory fine, nothing happens; memory low, the victim is killed and said
|
||||
let avail = 4000
|
||||
const killed: number[] = []
|
||||
const said: string[] = []
|
||||
const g = guard((l) => said.push(l), { root: 1, everyMs: 10, mem: () => ({ totalMb: 8192, availableMb: avail }), list: () => table, kill: (p) => killed.push(p) })
|
||||
await new Promise((r) => setTimeout(r, 60))
|
||||
assert(killed.length === 0, "memory fine: nothing killed")
|
||||
avail = 500
|
||||
await new Promise((r) => setTimeout(r, 30))
|
||||
g.stop()
|
||||
assert(killed[0] === 5 && /raea \(pid 5, 5\.1 GB\)/.test(said[0]), `low: the render is stopped and said: ${said[0]}`)
|
||||
ok("memory low: the render is stopped, and the guard says why")
|
||||
|
||||
if (existsSync("/proc/meminfo")) {
|
||||
// a real child that grows to 1.5 GB, under a floor set just below what's free now, so its growth trips it
|
||||
const { memory } = await import("../server/memguard.ts")
|
||||
const start = memory().availableMb
|
||||
const hog = spawn(process.execPath, ["-e", "const a=[]; for (let i=0;i<150;i++) a.push(Buffer.alloc(10<<20, 1)); setInterval(()=>{}, 1000)"], { stdio: "ignore" })
|
||||
const lines: string[] = []
|
||||
const real = guard((l) => lines.push(l), { everyMs: 200, mem: () => { const m = memory(); return { totalMb: m.totalMb, availableMb: m.availableMb + 700 - (start - 1200) } } })
|
||||
const code = await new Promise<number | null>((r) => {
|
||||
hog.on("exit", (c, sig) => r(sig === "SIGKILL" ? -9 : c))
|
||||
setTimeout(() => (hog.kill("SIGKILL"), r(null)), 30_000)
|
||||
})
|
||||
real.stop()
|
||||
assert(code === -9 && lines.length === 1, `the hog was killed by the guard: ${code} ${lines}`)
|
||||
ok(`on this box: a 1.5 GB runaway was stopped (${lines[0].slice(0, 90)}…)`)
|
||||
}
|
||||
Loaded 100 of 290 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user