Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

RR2: the camera changes per frame. <Camera3d is_active> (Bevy's Camera field) says which camera draws: each frame's first active camera in the tree is the piece's, the others are dropped from that frame with their depth of field and ambient, and the camera row's shot column steps where another camera takes over (raea-runtime-look active.rs). A frame where it steps is a cut (raea-sys-frame Shots), drawn as a shot rendered alone draws its first frame: motion blur's step before it draws the frame itself rather than the other camera's, with a plugin too, and Solari's and the path tracer's history reset. Play sends the shot on its live camera row (0 again when the first camera is back), and a live engine takes a changed shot as a cut (Moved). The step to f - 1 that motion blur needs never ran on any engine, because the Engine's reads count as a Bevy plugin; renders were right anyway (export draws f - 1 before f), and play blurred cuts from the other camera's frame. bench/rerender/rr2.sh on cams.tsx (cameras A, B, A with parts moving): without motion blur the piece equals its three shot compositions 120/120; with it the frames before the first cut and both cut frames are identical and the rest differ by the blur's grain alone (seeded by the frame number, SSIM >= 0.999439; one camera moved instead: 0.810 and 0.785 at the cuts); each shot of the piece rendered alone with --at is identical 120/120; play's 7 held seeks onto and across the cuts equal the render. The craft guide's rule 6 and limits.md say how to cut between cameras

shinyobjectz7d66dfc59cf5
diff --git a/bench/rerender/cams.tsx b/bench/rerender/cams.tsx
new file mode 100644
index 00000000..61cf49a0
--- /dev/null
+++ b/bench/rerender/cams.tsx
@@ -0,0 +1,82 @@
+// RR2: two cameras in one scene, cut between inside one render (<Camera3d is_active>): A, wide and dollying in, for
+// frames 0-39, B, low and close with a shallow depth of field, for 40-89, then A again for 90-119 (A's own nearly
+// sharp, f/16: the same effects either side, so a cut changes the camera alone, not the look, which would warm up
+// as RR1's cuts do). Parts move and the scene has motion blur, so a cut drawn with the frame before it (the other
+// camera's) would smear. The piece ("cut")
+// rendered once against the same frames rendered as one composition per shot ("a1", "b", "a2"), each starting at its
+// frame 0 as an agent's chunk does, with motion blur and without ("-still"): bench/rerender/rr2.sh.
+import { AbsoluteFill, Composition, interpolate, registerRoot, useCurrentFrame } from "raea";
+import { Canvas3D, DepthOfField, MotionBlur, ToneMapping, manifold } from "raea/3d";
+import { Camera3d } from "raea/camera";
+import { AmbientLight, DirectionalLight } from "raea/light";
+import { Mesh3d } from "raea/mesh";
+import { StandardMaterial } from "raea/pbr";
+import { Quat, Transform } from "raea/transform";
+
+const GROUND = manifold.box(60, 1, 60).move(0, -0.5, 0);
+const BOX = manifold.box(1.2, 1.2, 1.2);
+const POST = manifold.cylinder(3, 0.25, 0.25, 24);
+
+// the shots: which camera is the piece's from which frame
+const SHOTS = [
+ { id: "a1", cam: "A", from: 0, to: 40 },
+ { id: "b", cam: "B", from: 40, to: 90 },
+ { id: "a2", cam: "A", from: 90, to: 120 },
+] as const;
+
+// `jump`: one camera moved to B's place and back instead of two cameras, the control: its cut frames are drawn with
+// the frame before them, so motion blur smears them from the other shot
+function Scene({ t0, only, blur = true, jump = false }: { t0: number; only?: "A" | "B"; blur?: boolean; jump?: boolean }) {
+ const f = useCurrentFrame() + t0;
+ const on = SHOTS.find((s) => f >= s.from && f < s.to)?.cam ?? "A";
+ const a = Transform.fromXyz(interpolate(f, [0, 119], [9, 5]), 4, interpolate(f, [0, 119], [12, 7])).lookingAt([0, 0.8, 0], [0, 1, 0]);
+ const b = Transform.fromXyz(interpolate(f, [0, 119], [-3.5, -1.5]), 0.6, 2.4).lookingAt([0.5, 0.7, 0], [0, 1, 0]);
+ const lens = { Perspective: { fov: 0.8, near: 0.1, far: 120 } };
+ return (
+ <AbsoluteFill style={{ background: "#1c2128" }}>
+ <Canvas3D>
+ {jump ? (
+ <Camera3d transform={on === "A" ? a : b} projection={lens}><DepthOfField aperture_f_stops={on === "A" ? 16 : 1.4} /></Camera3d>
+ ) : null}
+ {!jump && only !== "B" ? (
+ <Camera3d transform={a} projection={lens} is_active={only === "A" || on === "A"}>
+ <DepthOfField aperture_f_stops={16} />
+ </Camera3d>
+ ) : null}
+ {!jump && only !== "A" ? (
+ <Camera3d transform={b} projection={lens} is_active={only === "B" || on === "B"}>
+ <DepthOfField aperture_f_stops={1.4} />
+ </Camera3d>
+ ) : null}
+ <DirectionalLight name="sun" transform={Transform.fromXyz(8, 14, 6).lookingAt([0, 0, 0], [0, 1, 0])} illuminance={15000} shadow_maps_enabled />
+ <AmbientLight brightness={180} />
+ <Mesh3d name="ground" shape={GROUND}><StandardMaterial base_color="#5d6b4a" perceptual_roughness={0.9} /></Mesh3d>
+ <Mesh3d name="slider" shape={BOX} transform={Transform.fromXyz(interpolate(f, [0, 119], [-3, 3]), 0.6, 0).withRotation(Quat.fromEuler("XYZ", 0, f * 0.08, 0))}>
+ <StandardMaterial base_color="#d04a2a" perceptual_roughness={0.4} />
+ </Mesh3d>
+ <Mesh3d name="spinner" shape={BOX} transform={Transform.fromXyz(0.5, 1.6 + Math.sin(f * 0.15) * 0.6, -2).withRotation(Quat.fromEuler("XYZ", f * 0.12, f * 0.2, 0))}>
+ <StandardMaterial base_color="#e8d27a" metallic={0.6} perceptual_roughness={0.3} />
+ </Mesh3d>
+ <Mesh3d name="post1" shape={POST} transform={Transform.fromXyz(-2.5, 1.5, -4)}><StandardMaterial base_color="#8c9aa8" /></Mesh3d>
+ <Mesh3d name="post2" shape={POST} transform={Transform.fromXyz(3, 1.5, -6)}><StandardMaterial base_color="#8c9aa8" /></Mesh3d>
+ <ToneMapping mode="agx" />
+ {blur ? <MotionBlur shutterAngle={1} samples={8} /> : null}
+ </Canvas3D>
+ </AbsoluteFill>
+ );
+}
+
+registerRoot(() => (
+ <>
+ {[true, false].map((blur) => {
+ const end = blur ? "" : "-still";
+ return [
+ <Composition key={`cut${end}`} id={`cut${end}`} component={() => <Scene t0={0} blur={blur} />} width={960} height={540} fps={30} durationInFrames={120} />,
+ ...SHOTS.map((s) => (
+ <Composition key={s.id + end} id={s.id + end} component={() => <Scene t0={s.from} only={s.cam} blur={blur} />} width={960} height={540} fps={30} durationInFrames={s.to - s.from} />
+ )),
+ ];
+ })}
+ <Composition id="jump" component={() => <Scene t0={0} jump />} width={960} height={540} fps={30} durationInFrames={120} />
+ </>
+));
diff --git a/bench/rerender/rr2.sh b/bench/rerender/rr2.sh
new file mode 100755
index 00000000..a3e5595b
--- /dev/null
+++ b/bench/rerender/rr2.sh
@@ -0,0 +1,141 @@
+#!/usr/bin/env bash
+# RR2 (docs/rerender.feature): the camera changes per frame. cams.tsx has two cameras, cut between with
+# <Camera3d is_active> (A 0-39, B 40-89 with its own depth of field, A 90-119) and parts moving. Four checks, each
+# writing OUT/<check>.json; frames are compared and deleted as they go:
+# still without motion blur, the piece ("cut-still") rendered once against its three shots rendered as compositions
+# of their own ("a1-still", "b-still", "a2-still"), each from its frame 0 as an agent's chunk: every frame
+# identical. Also how far each cut frame is from the frame before it (the cut is there) and the render times
+# blur the same with motion blur: the frames before the first cut and each cut frame (drawn as a shot alone draws
+# its first: no blur from the other camera's frame) identical. The other frames can't be: the blur's noise is
+# seeded by the frame number (raea-sys-post pin_frame_count), and a shot's own composition counts from 0; each
+# one's SSIM is said, and must be at least 0.999. The control: "jump", one camera moved to B's place and back,
+# its cut frames against the shots' first frames (smeared from the other shot: what a second camera saves)
+# range with motion blur, each shot of the piece rendered alone (--at its frames, the clock the piece's): identical
+# to the piece's frames, as RR3's re-rendered segments must be
+# play raea play seeking (offscreen) onto a cut, across each cut frame by frame and back onto a cut, against the
+# piece's render of those frames
+# bench/rerender/rr2.sh [OUT] [CHECKS]
+# RAEA_BIN the raea to run (target/release/raea)
+# CHECKS "still blur range play" by default
+# Exits 1 when a check fails.
+set -u
+cd "$(dirname "$0")/../.." || exit 2
+ROOT=$PWD
+BIN=${RAEA_BIN:-$ROOT/target/release/raea}
+OUT=${1:-${TMPDIR:-/tmp}/raea-rr2}
+CHECKS=${2:-still blur range play}
+SRC=$ROOT/bench/rerender/cams.tsx
+SHOTS=("a1 0 40" "b 40 90" "a2 90 120")
+export RAEA_SIGN=0 RAEA_MARK=0 RAEA_EXPORT_CACHE=0
+mkdir -p "$OUT"
+fail=0
+
+ssim() { ffmpeg -hide_banner -nostats -i "$1" -i "$2" -lavfi ssim -f null - 2>&1 | sed -n 's/.*All:\([0-9.]*\).*/\1/p'; }
+lower() { echo "$1 $2" | awk '{print ($2 < $1) ? $2 : $1}'; }
+now() { perl -MTime::HiRes=time -e 'printf "%.3f", time'; }
+png() { echo "$1/frame-$(printf %05d "$2").png"; }
+
+# render ID [--at LIST]: the composition into OUT/ID (OUT/ID-at with a list), printing its seconds
+render() {
+ local id=$1 dir=$OUT/$1 t0 t1
+ shift
+ [ $# -gt 0 ] && dir=$OUT/$id-at
+ rm -rf "${dir:?}"
+ t0=$(now)
+ "$BIN" render "$SRC" --composition "$id" "$@" -o "$dir" > "$dir.log" 2>&1 || { echo "$id failed: $(grep -E 'REFUSED|error' "$dir.log" | head -2)" >&2; return 1; }
+ t1=$(now)
+ echo "$t0 $t1" | awk '{printf "%.1f", $2 - $1}'
+}
+
+# the piece against its shots' own compositions (END: "" or "-still"): sets RES to "identical differ worst
+# must_be_identical_but_differ", CUTS and SECS, and writes the differing frames to OUT/CHECK-differ.txt
+against_shots() {
+ local check=$1 end=$2 same=0 diff=0 worst=1 need=0 s i id from to t ts=()
+ t=$(render "cut$end") || return 1; ts+=("\"cut$end\": $t")
+ : > "$OUT/$check-differ.txt"
+ for shot in "${SHOTS[@]}"; do
+ set -- $shot; id=$1$end from=$2 to=$3
+ t=$(render "$id") || return 1; ts+=("\"$id\": $t")
+ for i in $(seq "$from" $((to - 1))); do
+ if cmp -s "$(png "$OUT/cut$end" "$i")" "$(png "$OUT/$id" $((i - from)))"; then same=$((same + 1)); continue; fi
+ s=$(ssim "$(png "$OUT/cut$end" "$i")" "$(png "$OUT/$id" $((i - from)))")
+ diff=$((diff + 1)); echo "frame $i ($id $((i - from))) ssim $s" >> "$OUT/$check-differ.txt"
+ worst=$(lower "$worst" "$s")
+ # a frame before the first cut, or a cut frame, must be identical
+ if [ "$i" -lt 40 ] || [ "$i" = 40 ] || [ "$i" = 90 ]; then need=$((need + 1)); fi
+ done
+ rm -rf "${OUT:?}/$id"
+ done
+ CUTS="[$(ssim "$(png "$OUT/cut$end" 39)" "$(png "$OUT/cut$end" 40)"), $(ssim "$(png "$OUT/cut$end" 89)" "$(png "$OUT/cut$end" 90)")]"
+ rm -rf "${OUT:?}/cut$end"
+ SECS="{$(IFS=,; echo "${ts[*]}")}"
+ RES="$same $diff $worst $need"
+}
+
+still() {
+ against_shots still -still || return 1
+ set -- $RES
+ echo "{\"frames\": 120, \"identical\": $1, \"differ\": $2, \"worst_ssim\": $3, \"cut_vs_before_ssim\": $CUTS, \"seconds\": $SECS}" | tee "$OUT/still.json"
+ [ "$2" = 0 ]
+}
+
+blur() {
+ against_shots blur "" || return 1
+ set -- $RES
+ # the control: one camera moved instead of a second, its cut frames against the same shots' first frames
+ local b0 a0 jump
+ render b --at 0 > /dev/null && mv "$OUT/b-at/frame-00000.png" "$OUT/b0.png" && render a2 --at 0 > /dev/null && mv "$OUT/a2-at/frame-00000.png" "$OUT/a0.png" && render jump --at 40,90 > /dev/null || return 1
+ jump="[$(ssim "$OUT/jump-at/frame-00000.png" "$OUT/b0.png"), $(ssim "$OUT/jump-at/frame-00001.png" "$OUT/a0.png")]"
+ rm -rf "${OUT:?}"/b-at "${OUT:?}"/a2-at "${OUT:?}"/jump-at "$OUT/b0.png" "$OUT/a0.png"
+ echo "{\"frames\": 120, \"identical\": $1, \"differ\": $2, \"worst_ssim\": $3, \"must_be_identical_but_differ\": $4, \"cut_vs_before_ssim\": $CUTS, \"one_camera_moved_cut_frames_ssim\": $jump, \"seconds\": $SECS}" | tee "$OUT/blur.json"
+ [ "$4" = 0 ] && awk -v w="$3" 'BEGIN { exit !(w >= 0.999) }'
+}
+
+range() {
+ local same=0 diff=0 i from to at t ts=()
+ t=$(render cut) || return 1; ts+=("\"cut\": $t")
+ : > "$OUT/range-differ.txt"
+ for shot in "${SHOTS[@]}"; do
+ set -- $shot; from=$2 to=$3
+ at=$(seq "$from" $((to - 1)) | paste -sd, -)
+ t=$(render cut --at "$at") || return 1; ts+=("\"$1\": $t")
+ for i in $(seq "$from" $((to - 1))); do
+ if cmp -s "$(png "$OUT/cut" "$i")" "$(png "$OUT/cut-at" $((i - from)))"; then same=$((same + 1)); else diff=$((diff + 1)); echo "frame $i" >> "$OUT/range-differ.txt"; fi
+ done
+ rm -rf "${OUT:?}/cut-at"
+ done
+ rm -rf "${OUT:?}/cut"
+ echo "{\"frames\": 120, \"identical\": $same, \"differ\": $diff, \"seconds\": {$(IFS=,; echo "${ts[*]}")}}" | tee "$OUT/range.json"
+ [ "$diff" = 0 ]
+}
+
+play() {
+ # a jump onto a cut frame, then frames walked across each cut, then a seek back onto a cut. Held: the first seek and
+ # each seek to the frame after the one before. The others (a jump to 38 or 88, the seek back) are said, not held:
+ # with motion blur, a seek that isn't to the next frame has differed in play from the render since before RR2, cut
+ # or no cut (main's raea, one camera: frame 20 seeked back from 21, SSIM 0.999776), and the frame after it is exact
+ local d=$OUT/play seeks=(40 38 39 40 41 88 89 90 91 90) args=() at n f r v held=0 exact=0 worst=1 jump=""
+ rm -rf "${d:?}"; mkdir -p "$d/seek"
+ for n in "${!seeks[@]}"; do args+=(--seek "${seeks[$n]}" "$d/seek/$n.png"); done
+ at=$(printf '%s\n' "${seeks[@]}" | sort -n | uniq | paste -sd, -)
+ "$BIN" render "$SRC" --composition cut --at "$at" -o "$d/at" > "$OUT/play-at.log" 2>&1 || { echo "play: the render failed: $(tail -3 "$OUT/play-at.log")"; return 1; }
+ # play shows the file's first composition: the piece ("cut")
+ RAEA_AUDIO_MUTE=1 RAEA_LIVE3D_CHECK=1 "$BIN" play "$SRC" --offscreen --size 960x540 "${args[@]}" > "$OUT/play.log" 2>&1 || { echo "play: failed: $(tail -3 "$OUT/play.log")"; return 1; }
+ : > "$OUT/play-differ.txt"
+ for n in "${!seeks[@]}"; do
+ f=${seeks[$n]}
+ r=$(png "$d/at" "$(echo "$at" | tr , '\n' | grep -nx "$f" | cut -d: -f1 | awk '{print $1 - 1}')")
+ v=$(ssim "$d/seek/$n.png" "$r")
+ if [ "$n" != 0 ] && [ "${seeks[$((n - 1))]}" != $((f - 1)) ]; then jump="$jump\"${seeks[$((n - 1))]}->$f\": $v, "; continue; fi
+ held=$((held + 1)); worst=$(lower "$worst" "$v")
+ if [ "$v" = "1.000000" ]; then exact=$((exact + 1)); else echo "seek $n frame $f ssim $v" >> "$OUT/play-differ.txt"; fi
+ done
+ rm -rf "${d:?}"
+ echo "{\"seeks_held\": $held, \"ssim_1\": $exact, \"worst_ssim\": $worst, \"seeks_not_held\": {${jump%, }}}" | tee "$OUT/play.json"
+ [ "$exact" = "$held" ]
+}
+
+for c in $CHECKS; do
+ "$c" || { echo "rr2: $c FAILED"; fail=1; }
+done
+exit $fail
diff --git a/docs/manual/reference/sdk/camera.md b/docs/manual/reference/sdk/camera.md
index b3459fad..3f041b07 100644
--- a/docs/manual/reference/sdk/camera.md
+++ b/docs/manual/reference/sdk/camera.md
@@ -40,6 +40,7 @@ Bevy: `bevy_camera::components::Camera3d`, `bevy_camera::camera::Camera`, `bevy_
| `order` | `number` | Bevy's Camera order: a camera with a higher one draws after (over) those with lower; 0 by default |
| `clear_color` | `ClearColorConfig` | Bevy's ClearColorConfig: "Default" (the clear colour), "None" (drawn over what the cameras before it drew, as a second pass), or { Custom: colour } |
| `viewport` | `CameraViewport` | Bevy's Viewport: the camera draws into this region of the window only, `physical_position` from its top left and `physical_size` big (whole px, at a scale factor of 1) |
+| `is_active` | `boolean` | Bevy's Camera is_active: false and it draws nothing this frame, its lens and ambient with it. Several cameras in the scene, one active a frame, cut between them inside one render: the frame another camera becomes active (the first active one, in tree order, is the piece's) is a cut, drawn as a shot rendered alone draws its first frame (no motion blur from the frame before). True by default |
| `children` | `ReactNode` | components on the camera: post effects, tone mapping, a skybox |
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_volumes](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/3d/fog_volumes.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), and 60 more.
diff --git a/docs/rerender.feature b/docs/rerender.feature
index 52fe0f89..55403a01 100644
--- a/docs/rerender.feature
+++ b/docs/rerender.feature
@@ -110,10 +110,44 @@ Feature: Re-render, don't stitch: one render changes anything per frame, redraws
And a grade ramp over 60 frames equals 60 stills each rendered alone with that frame's grade
And a play of the film (raea play) shows the same look changes as its render (render = play)
+ @done
Scenario: RR2. The camera changes per frame
+ # Status 11-10: done. `<Camera3d is_active>` (Bevy's Camera field) says which camera draws: each frame's first
+ # active camera in the tree is the piece's, the others are dropped from that frame (their depth of field and
+ # ambient with them), and the camera row's `shot` column steps where another camera takes over (active.rs). A
+ # frame where it steps is a cut (Shots), drawn as a shot rendered alone draws its first frame: motion blur's
+ # step before it draws the frame itself, not the other camera's frame, and Solari's and the path tracer's
+ # history start again (`reset`). Play sends the shot on its live camera row, 0 again when the first camera is
+ # back, and its engine takes a changed shot as a cut (Moved). A teleport of one camera is no cut: it smears.
+ # Found on the way, and fixed for cuts only: the step to f - 1 that motion blur needs never runs on any engine,
+ # because the Engine's reads (react_share) count as a Bevy plugin. Renders are right anyway (export draws f - 1
+ # before every f for those reads); play blurs from the frame drawn last. Handed to the issues lane.
+ # RR0's film has no shot with two cameras, so bench/rerender/cams.tsx is the piece: camera A wide and dollying
+ # (frames 0-39), B low and close at f/1.4 (40-89), A again (90-119), parts moving, motion blur on. Each shot is
+ # also its own composition, as an agent's chunk is. Measured on this Mac with bench/rerender/rr2.sh:
+ # without motion blur, the piece against its three shot compositions: 120/120 frames identical (each cut
+ # frame is SSIM 0.707 and 0.688 from the frame before it: the cut is there)
+ # with motion blur, against the same compositions: the frames before the first cut and both cut frames
+ # identical; the other 78 differ by the blur's grain alone, SSIM >= 0.999439, because the grain is seeded by
+ # the frame number and a composition counts from 0 (raea-sys-post pin_frame_count). The control, one camera
+ # moved to B's place and back: its cut frames 0.810 and 0.785 against the shots' first frames
+ # with motion blur, each shot of the piece rendered alone (--at its frames): 120/120 identical, as RR3's
+ # re-rendered segments need
+ # raea play seeking onto a cut, across each cut frame by frame and back: 7/7 held seeks identical to the
+ # render. The seeks that jump (40 to 38, 41 to 88, 91 back to 90) are said, not held: with motion blur a jump
+ # differs from the render in play, cut or not, since before RR2
+ # Cost: the piece in 2.3-2.9 s, its three shots as compositions in 4.9-6.0 s together.
+ # Not covered: the three.js hosts (sdk/r3f, playables) still take the first camera node; a live game's cuts
+ # take the same path as play's but weren't run.
Given the plan
- | crate | file | lines | job |
- | raea-runtime-look | runtime/look/src/active.rs | 120 | which camera draws the output, per frame: `<Camera3d active>` keyed, or a cut list |
+ | crate | file | lines | job |
+ | raea-runtime-look | runtime/look/src/active.rs | 82 | which camera draws, per frame: the first active one (`<Camera3d is_active>`), the others dropped; its shot keyed where it steps |
+ | raea-sys-frame | systems/frame/src/shots.rs | 41 | the frames a shot starts at (Shots), and a live camera row's shot changed (Moved) |
+ | raea-render | engine/render/src/engine.rs | 490 | a cut drawn as a shot's first frame: the step before it draws the frame itself, with a plugin too; Solari reset (raytrace cut) |
+ | raea-runtime-scene | runtime/scene/src/live.rs | 432 | play's camera row says its shot, and 0 when the first camera is back |
+ | - | sdk/render/src/bevy3d/core.tsx | 332 | `is_active` on `<Camera3d>`; an inactive camera isn't the one the pointer picks through |
+ | - | bench/rerender/cams.tsx | 82 | two cameras cut A, B, A with parts moving, each shot its own composition too, and a one-camera control |
+ | - | bench/rerender/rr2.sh | 141 | the four checks above (still, blur, range, play), each writing its JSON, frames deleted as they're compared |
Then a film can cut between several cameras inside one render
And RR0's two-camera shot rendered once equals the same shot rendered as one render per camera, frame for frame
diff --git a/engine/render/raytrace/src/lib.rs b/engine/render/raytrace/src/lib.rs
index b06d5ff1..04cc3b12 100644
--- a/engine/render/raytrace/src/lib.rs
+++ b/engine/render/raytrace/src/lib.rs
@@ -23,3 +23,14 @@ pub fn add_denoiser(app: &mut App) {
#[cfg(not(target_os = "macos"))]
let _ = app;
}
+
+/// A cut to another camera (docs/rerender.feature RR2): Solari's and the path tracer's history start again, as on their
+/// first frame, so the last shot's light isn't carried into this one (Bevy's `reset`, for "sudden camera cuts").
+pub fn cut(world: &mut World) {
+ for mut s in world.query::<&mut bevy::solari::prelude::SolariLighting>().iter_mut(world) {
+ s.reset = true;
+ }
+ for mut p in world.query::<&mut bevy::solari::pathtracer::Pathtracer>().iter_mut(world) {
+ p.reset = true;
+ }
+}
diff --git a/engine/render/src/engine.rs b/engine/render/src/engine.rs
index b132cb73..c107bf50 100644
--- a/engine/render/src/engine.rs
+++ b/engine/render/src/engine.rs
@@ -257,14 +257,26 @@ impl Engine {
/// With MotionBlur, the frame before the clock's drawn first (its readback ignored): Bevy takes each mesh's,
/// skin's and the camera's previous pose from the update before, so this makes it frame f - 1's on every update of
/// frame f, in a render (which may update a frame several times), a seek and play alike. It costs a second draw.
+ /// A cut to another camera (a timeline's Shots, or a live camera row's shot Moved since the frame drawn last) has
+ /// no frame before it, as a shot rendered alone hasn't: the step draws the frame itself, and Solari's history starts
+ /// again (RR2). It's taken with a plugin too, unlike the step to f - 1: every engine has one (the Engine's reads,
+ /// react_share), so the cut drew its blur from the frame drawn last, the other camera's.
fn pre_step(&mut self) {
let f = self.app.world().resource::<Clock>().0;
- if !self.prestep || f <= 0 || plugins::active(self.app.world()) {
+ let moved = self.app.world_mut().remove_resource::<raea_sys_frame::shots::Moved>().is_some();
+ let cut = moved || self.app.world().get_resource::<raea_sys_frame::shots::Shots>().is_some_and(|s| s.starts(f));
+ #[cfg(feature = "raytracing")]
+ if cut {
+ raea_render_raytrace::cut(self.app.world_mut());
+ }
+ if !self.prestep || f <= 0 || (plugins::active(self.app.world()) && !cut) {
return;
}
let world = self.app.world_mut();
- world.resource_mut::<Clock>().0 = f - 1;
+ world.resource_mut::<Clock>().0 = if cut { f } else { f - 1 };
world.resource_mut::<PreStep>().0 = true;
+ // armed, or a plugin's Time would move by the last update's step again
+ plugins::arm(self.app.world_mut());
self.pipe.update(&mut self.app);
let world = self.app.world_mut();
world.resource_mut::<PreStep>().0 = false;
@@ -293,6 +305,10 @@ impl Engine {
if self.app.world_mut().resource_mut::<FrameRows>().parse_looks() {
self.warm_next = true;
}
+ // the camera row on another shot (its shot column sent only when it changes): the next frame drawn is a cut
+ if rows.iter().any(|t| t.kind == "camera" && t.vals.contains_key("shot")) {
+ self.app.world_mut().insert_resource(raea_sys_frame::shots::Moved);
+ }
// a glTF model, and a panorama a live frame showed first (#38), set up before the frame that shows it draws
if spawned { scene3d::await_models(&mut self.app)?; }
raea_sys_post::msaa_for_3d(self.app.world_mut(), has_3d(rows) || raea_sys_sprite::has_2d(rows));
diff --git a/engine/render/src/engine/load.rs b/engine/render/src/engine/load.rs
index 2f2a7825..471cabe1 100644
--- a/engine/render/src/engine/load.rs
+++ b/engine/render/src/engine/load.rs
@@ -127,6 +127,7 @@ impl Engine {
};
world.insert_resource(Edit { prog: prog.clone(), timeline, media });
world.insert_resource(raea_sys_frame::tables::Cuts::of(prog));
+ world.insert_resource(raea_sys_frame::shots::Shots::of(prog));
world.insert_resource(FrameRows::new(ix));
let Some(cam) = camera else { return Err("the edit needs a camera: INSERT INTO camera (id, ...) VALUES (...)".into()) };
let models = world.query::<&scene3d::Model3d>().iter(world).count();
diff --git a/runtime/look/src/active.rs b/runtime/look/src/active.rs
new file mode 100644
index 00000000..93e86202
--- /dev/null
+++ b/runtime/look/src/active.rs
@@ -0,0 +1,86 @@
+//! Which camera draws the output, frame by frame (docs/rerender.feature RR2). A scene may hold several cameras, each
+//! active on a frame or not (<Camera3d is_active>, Bevy's Camera is_active); the first active one in tree order is the
+//! piece's. The frame another becomes the piece's is a cut: the camera row's stepped `shot` marks it, and the engine
+//! draws that frame as a shot rendered alone draws its first (raea-sys-frame's Shots).
+use super::*;
+
+/// A frame's parts with its inactive cameras (`active: false`) taken out, and the first left stamped `shot` with its
+/// place among all the frame's cameras, when it isn't the first: the shot that frame belongs to. A frame with every
+/// camera inactive keeps none, and holds the nearest frame's camera as a frame without one does (filled).
+pub fn active_cameras(out: &mut Vec<Item>) {
+ let first = out.iter().filter(|i| i.kind == "camera").position(|i| !inactive(i));
+ if let Some(k) = first.filter(|k| *k > 0) {
+ if let Some(c) = out.iter_mut().filter(|i| i.kind == "camera").nth(k) {
+ std::sync::Arc::make_mut(&mut c.props).insert("shot".into(), Value::from(k));
+ }
+ }
+ out.retain(|i| !inactive(i));
+}
+
+/// A camera drawing nothing this frame (<Camera3d is_active={false}>).
+fn inactive(i: &Item) -> bool {
+ i.kind == "camera" && matches!(i.props.get("active"), Some(Value::Bool(false)))
+}
+
+/// The camera row's `shot` (`cams`: each frame's piece camera, filled), keyed by step where it changes, so a cut is a
+/// key: nothing while the first camera is the piece's throughout.
+pub fn shot_column(p: &mut Program, row: &mut BTreeMap<String, V>, id: &str, cams: &[Item]) {
+ let shots: Vec<f64> = cams.iter().map(|c| num(&c.props, "shot").unwrap_or(0.0)).collect();
+ if shots.iter().all(|s| *s == 0.0) {
+ return;
+ }
+ row.insert("shot".into(), V::N(shots[0]));
+ // a key at the first frame and at each cut: a step holds its value until the next key's frame
+ let keys = step_keys(&shots);
+ if keys.len() > 1 {
+ p.keys.insert((id.to_string(), "shot".to_string()), keys);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn cam(x: f64, active: Option<bool>) -> Item {
+ let mut props = Map::new();
+ props.insert("position".into(), serde_json::json!([x, 1.0, 5.0]));
+ if let Some(a) = active {
+ props.insert("active".into(), Value::Bool(a));
+ }
+ Item { kind: "camera", props: std::sync::Arc::new(props), shape: None, material: None, world: bevy::math::Mat4::IDENTITY }
+ }
+
+ #[test]
+ fn the_first_active_camera_draws_and_says_its_shot() {
+ let mut a = vec![cam(0.0, None), cam(1.0, Some(false))];
+ active_cameras(&mut a);
+ assert_eq!(a.len(), 1);
+ assert_eq!(a[0].props.get("shot"), None);
+ let mut b = vec![cam(0.0, Some(false)), cam(1.0, None)];
+ active_cameras(&mut b);
+ assert_eq!(b.len(), 1);
+ assert_eq!(b[0].props.get("position"), Some(&serde_json::json!([1.0, 1.0, 5.0])));
+ assert_eq!(b[0].props.get("shot"), Some(&Value::from(1)));
+ let mut none = vec![cam(0.0, Some(false)), cam(1.0, Some(false))];
+ active_cameras(&mut none);
+ assert!(none.is_empty());
+ }
+
+ #[test]
+ fn a_cut_is_a_step_key() {
+ let frames: Vec<Item> = [0, 0, 0, 1, 1, 0].iter().map(|k| {
+ let mut v = vec![cam(0.0, Some(*k == 0)), cam(1.0, Some(*k == 1))];
+ active_cameras(&mut v);
+ v.remove(0)
+ }).collect();
+ let (mut p, mut row) = (Program::default(), BTreeMap::new());
+ shot_column(&mut p, &mut row, "cam", &frames);
+ assert_eq!(row.get("shot"), Some(&V::N(0.0)));
+ let keys = &p.keys[&("cam".to_string(), "shot".to_string())];
+ assert_eq!(keys.iter().map(|k| (k.0, k.1)).collect::<Vec<_>>(), vec![(0, 0.0), (3, 1.0), (5, 0.0)]);
+ // one camera throughout: no column
+ let (mut p, mut row) = (Program::default(), BTreeMap::new());
+ shot_column(&mut p, &mut row, "cam", &frames[..3]);
+ assert!(row.get("shot").is_none() && p.keys.is_empty());
+ }
+}
diff --git a/runtime/look/src/camera.rs b/runtime/look/src/camera.rs
index 41463b46..550ce9f3 100644
--- a/runtime/look/src/camera.rs
+++ b/runtime/look/src/camera.rs
@@ -81,6 +81,10 @@ fn one(all: &[Vec<Item>], p: &mut Program, row: &mut BTreeMap<String, V>, k: usi
if all.iter().flatten().any(|i| i.kind == "dof") {
column(p, row, id, "focus", &its.iter().map(focus_of).collect::<Vec<_>>());
}
+ // which of the scene's cameras is the piece's, where that's not the first: a cut where it changes (active.rs)
+ if k == 0 {
+ shot_column(p, row, id, &its);
+ }
let first = &its[0].props;
if let Some(o) = num(first, "order") {
row.insert("order".into(), V::N(o));
diff --git a/runtime/look/src/lib.rs b/runtime/look/src/lib.rs
index 9a7b6c09..c57df7b3 100644
--- a/runtime/look/src/lib.rs
+++ b/runtime/look/src/lib.rs
@@ -15,6 +15,8 @@ pub use post::*;
mod parts;
pub use parts::*;
pub use instances::*;
+mod active;
+pub use active::*;
/// Bloom of intensity 1: Bevy's natural preset.
pub const BLOOM: f64 = 0.15;
diff --git a/runtime/look/src/parts.rs b/runtime/look/src/parts.rs
index d9f80589..211333de 100644
--- a/runtime/look/src/parts.rs
+++ b/runtime/look/src/parts.rs
@@ -117,6 +117,29 @@ pub fn srcs_of(its: &[Item]) -> Vec<String> {
}).collect()
}
+/// A screen's columns (<Screen>, <Model screens>): its spec (a panel's `screen`) or a model's `screens` and `hide`,
+/// JSON, from the first frame; the tube's power keyed when it changes.
+pub fn screen_columns(p: &mut Program, row: &mut BTreeMap<String, V>, id: &str, its: &[Item]) {
+ let first = &its[0].props;
+ for (k, col) in [("screen", "screen"), ("screens", "screens"), ("hide", "hide")] {
+ if let Some(v) = first.get(k).filter(|v| !v.is_null()) {
+ row.insert(col.into(), V::S(v.to_string()));
+ }
+ }
+ if its.iter().any(|i| i.props.contains_key("screenPower")) {
+ column(p, row, id, "screen_power", &its.iter().map(|i| n(&i.props, "screenPower", 1.0)).collect::<Vec<_>>());
+ }
+ // a flat screen's brightness over the frames (the spec holds the first; engine/screen.rs's sync_screens reads this)
+ if its.iter().any(|i| screen_bright(&i.props).is_some()) {
+ column(p, row, id, "screen_bright", &its.iter().map(|i| screen_bright(&i.props).unwrap_or(1.0)).collect::<Vec<_>>());
+ }
+}
+
+/// A flat screen's `brightness`, from its spec (Screen's prop)
+pub fn screen_bright(props: &Map<String, Value>) -> Option<f64> {
+ props.get("screen")?.get("brightness")?.as_f64()
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/runtime/scene/src/lib.rs b/runtime/scene/src/lib.rs
index a764c284..f6f52326 100644
--- a/runtime/scene/src/lib.rs
+++ b/runtime/scene/src/lib.rs
@@ -213,6 +213,8 @@ pub fn items_of(scene: &[Node3]) -> Vec<Item> {
for n in scene {
walk(n, Mat4::IDENTITY, &mut out);
}
+ // the cameras not drawing this frame (<Camera3d is_active={false}>) out, the piece's stamped with its shot (RR2)
+ active_cameras(&mut out);
// a camera's own AmbientLight (<Camera3d>'s <AmbientLight> child, Bevy 0.20's component) lights its view in place of
// the scene's others (GlobalAmbientLight)
let own = |i: &Item| i.kind == "ambient" && i.props.get("camera") == Some(&Value::Bool(true));
@@ -246,29 +248,6 @@ fn placement(p: &mut Program, row: &mut BTreeMap<String, V>, id: &str, its: &[It
}
}
-/// A screen's columns (<Screen>, <Model screens>): its spec (a panel's `screen`) or a model's `screens` and `hide`,
-/// JSON, from the first frame; the tube's power keyed when it changes.
-fn screen_columns(p: &mut Program, row: &mut BTreeMap<String, V>, id: &str, its: &[Item]) {
- let first = &its[0].props;
- for (k, col) in [("screen", "screen"), ("screens", "screens"), ("hide", "hide")] {
- if let Some(v) = first.get(k).filter(|v| !v.is_null()) {
- row.insert(col.into(), V::S(v.to_string()));
- }
- }
- if its.iter().any(|i| i.props.contains_key("screenPower")) {
- column(p, row, id, "screen_power", &its.iter().map(|i| n(&i.props, "screenPower", 1.0)).collect::<Vec<_>>());
- }
- // a flat screen's brightness over the frames (the spec holds the first; engine/screen.rs's sync_screens reads this)
- if its.iter().any(|i| screen_bright(&i.props).is_some()) {
- column(p, row, id, "screen_bright", &its.iter().map(|i| screen_bright(&i.props).unwrap_or(1.0)).collect::<Vec<_>>());
- }
-}
-
-/// A flat screen's `brightness`, from its spec (Screen's prop)
-fn screen_bright(props: &Map<String, Value>) -> Option<f64> {
- props.get("screen")?.get("brightness")?.as_f64()
-}
-
/// The lights, meshes, models and pictures in space, as rows, from each frame's parts.
pub fn rows(all: &[Vec<Item>], p: &mut Program) {
let before = p.spawns.len();
diff --git a/runtime/scene/src/live.rs b/runtime/scene/src/live.rs
index 6166ea52..e9b83230 100644
--- a/runtime/scene/src/live.rs
+++ b/runtime/scene/src/live.rs
@@ -122,10 +122,11 @@ impl LiveScene {
/// What the camera row changes, of the columns a render keys (cam_keyed): the camera's tuple, or None.
pub(crate) fn camera_diff(sent: &mut BTreeMap<String, V>, cam: &BTreeMap<String, V>) -> Option<raea_core_program::eval::Tup> {
let mut vals = BTreeMap::new();
- // and each frame's post-processing table and page background (RR1: render = play)
- let keyed = |k: &str| cam_keyed(k) || matches!(k, "frame_sets" | "frame_set_i" | "bg_r" | "bg_g" | "bg_b" | "bg_a");
- for k in cam.keys().map(String::as_str).filter(|k| keyed(k)).chain(["ambient"]) {
- let v = cam.get(k).cloned().or_else(|| (k == "ambient" && sent.contains_key("ambient")).then_some(V::N(0.0)));
+ // and each frame's post-processing table and page background (RR1: render = play), and its shot (RR2)
+ let keyed = |k: &str| cam_keyed(k) || matches!(k, "frame_sets" | "frame_set_i" | "bg_r" | "bg_g" | "bg_b" | "bg_a" | "shot");
+ // the ambient and the shot back to 0 when the row stops holding them (no light; the first camera's shot again)
+ for k in cam.keys().map(String::as_str).filter(|k| keyed(k)).chain(["ambient", "shot"]) {
+ let v = cam.get(k).cloned().or_else(|| (matches!(k, "ambient" | "shot") && sent.contains_key(k)).then_some(V::N(0.0)));
if let Some(v) = v {
if sent.get(k) != Some(&v) {
sent.insert(k.into(), v.clone());
@@ -413,4 +414,17 @@ mod tests {
let (set, _) = ls.frame(Shot { scene: &text(1.0), clear: None });
assert_eq!(set.iter().find(|t| t.kind == "glyph").and_then(|t| t.vals.get("opacity")), Some(&V::N(1.0)));
}
+
+ /// Two cameras cut between (<Camera3d is_active>): the camera row's shot is sent the frame it changes, and 0 when
+ /// the first camera is back, so a live engine draws both frames as cuts (RR2, Engine::set_rows).
+ #[test]
+ fn a_cut_back_sends_the_first_shot() {
+ let cams = |on: usize| -> Vec<Node3> { (0..2).map(|i| Node3 { kind: "PerspectiveCamera".into(), props: std::sync::Arc::new(json!({"position": [i, 1, 5], "active": i == on}).as_object().unwrap().clone()), shape: None, kids: Vec::new().into() }).collect() };
+ let shot = |set: &[raea_core_program::eval::Tup]| set.iter().find(|t| t.kind == "camera").and_then(|t| t.vals.get("shot").cloned());
+ let mut ls = LiveScene::default();
+ ls.open(Shot { scene: &cams(0), clear: None }, 64, 64, 30.0);
+ assert_eq!(shot(&ls.frame(Shot { scene: &cams(1), clear: None }).0), Some(V::N(1.0)));
+ assert_eq!(shot(&ls.frame(Shot { scene: &cams(1), clear: None }).0), None);
+ assert_eq!(shot(&ls.frame(Shot { scene: &cams(0), clear: None }).0), Some(V::N(0.0)));
+ }
}
diff --git a/sdk/guides/craft/bevy.md b/sdk/guides/craft/bevy.md
index c481d79a..50c646d2 100644
--- a/sdk/guides/craft/bevy.md
+++ b/sdk/guides/craft/bevy.md
@@ -62,10 +62,12 @@ the rest come from `raea`.
A Mesh that appears, disappears or swaps places with one of the same shape needs a `name`.
5. **A shape is fixed for the life of a part.** Animate position, rotation, scale, colour, opacity, glow,
roughness and metalness; don't change `args` or `shape` frame to frame (that's a new part each frame).
-6. **One camera; each frame's own effects.** The first camera in the tree is used. The effects (the sky, Bloom, Fog,
- Grade, ToneMapping, Shadows and the rest) and each light's colour, shadows and shafts take each frame's values, so
- shots with different looks are one composition and one render, not one render a shot joined after; the lens
- (Fisheye, LensDistortion) and MotionBlur animate per frame too.
+6. **One camera a frame; each frame's own effects.** The first active camera in the tree is the piece's: give each
+ shot its own `<Camera3d>` and switch them with `is_active={...}`, so a cut between cameras is one render, not one
+ render a camera joined after (the frame another camera becomes active is drawn as a shot rendered alone starts,
+ with no motion blur from the other camera's frame). The effects (the sky, Bloom, Fog, Grade, ToneMapping, Shadows
+ and the rest) and each light's colour, shadows and shafts take each frame's values, so shots with different looks
+ are one composition and one render too; the lens (Fisheye, LensDistortion) and MotionBlur animate per frame.
7. **Import what you use.** Every component in the scene comes from its module in the import line (`Camera3d`
from `raea/camera`, `Mesh3d` and `Cuboid` from `raea/mesh`, `StandardMaterial` from `raea/pbr`, the lights from
`raea/light`, `Transform` from `raea/transform`, `Canvas3D`, `Bloom` and the rest from `raea/3d`); a missing one
diff --git a/sdk/guides/craft/bevy/limits.md b/sdk/guides/craft/bevy/limits.md
index c435f387..0d60f9a3 100644
--- a/sdk/guides/craft/bevy/limits.md
+++ b/sdk/guides/craft/bevy/limits.md
@@ -33,10 +33,15 @@
The router's eight, plus:
- Parts are matched across frames by `name`, else kind and shape in tree order: name what comes and goes.
-- The first camera is the piece's. The effects and each light's colour, shadows and shafts are each frame's own. A
- frame that brings or takes a sky, ambient occlusion, anti-aliasing, a tonemapper, shadows or volumetric fog (a cut
- to a shot with a different look) warms up as a load does, about 0.3 s at that frame; a value that moves (a grade
- ramping) doesn't.
+- The first active camera is the piece's (`<Camera3d is_active={false}>` draws nothing that frame, its depth of
+ field and ambient with it). A frame where another camera becomes the piece's is a cut: it's drawn as a shot rendered
+ alone draws its first frame (no motion blur from the frame before, Solari's history started again), so one render of
+ shots on several cameras draws each shot as it's drawn alone: a shot re-rendered with `--at` its frames is identical
+ (as its own composition from frame 0, motion blur's grain, seeded by the frame number, differs after its first
+ frame). A teleport of one camera isn't a cut: motion blur smears it; use two cameras. The effects and each light's
+ colour, shadows and shafts are each frame's own. A frame that brings or takes a sky, ambient occlusion,
+ anti-aliasing, a tonemapper, shadows or volumetric fog (a cut to a shot with a different look) warms up as a load
+ does, about 0.3 s at that frame; a value that moves (a grade ramping) doesn't.
- Overlapping FogVolumes are composited in the order of their rows (the engine pins it), so a render of any frame
equals its play; give each a `name` so its row, and so the order, stays put when others come and go.
- A partly transparent page element over the 3D blends slightly differently in a render than in play; keep page
@@ -50,7 +55,8 @@ The router's eight, plus:
the 3D.
- `<Camera3d projection={{ Orthographic: { scaling_mode: { FixedVertical: { viewport_height } } } }}>`, `layers` on parts, lights and the camera, sprite sheets on ImagePlane (`grid`,
`frame`) are there, and `pick(pointer, camera, parts, size)` answers which part the pointer is over. A second camera
- or a viewport is an `<Entity>` with Bevy's `Camera3d` and `Camera` (see below), not a second `<Camera3d>`.
+ drawing at once (over the first, or into a viewport) is a second `<Camera3d order clear_color viewport>`, or an
+ `<Entity>` with Bevy's `Camera3d` and `Camera` (see below); a second camera to cut to is `<Camera3d is_active>`.
- Physics engines in a live game, particle systems: do motion in the game's step. (Fire is there: `<Fire>` in
`bevy/post`.)
- Bevy's own AnimationEvent (use `clipEvents(events, prev, now, duration)` from `raea/3d`).
diff --git a/sdk/raea/conformance/camera-active.test.tsx b/sdk/raea/conformance/camera-active.test.tsx
new file mode 100644
index 00000000..eadcd56c
--- /dev/null
+++ b/sdk/raea/conformance/camera-active.test.tsx
@@ -0,0 +1,31 @@
+// <Camera3d is_active> (Bevy's Camera is_active, docs/rerender.feature RR2): a camera not drawing this frame is the
+// camera alone, marked inactive, without its lens or ambient, so the scene knows which of its cameras is the piece's.
+import { expect, test } from "bun:test";
+import type { ReactElement } from "react";
+import { Camera3d } from "raea/camera";
+import { DepthOfField } from "raea/3d";
+import { AmbientLight } from "raea/light";
+import { Transform } from "raea/transform";
+
+type El = ReactElement<Record<string, unknown>>;
+const at = Transform.fromXyz(0, 1, 5);
+const kids = (e: El) => ([] as unknown[]).concat((e.props as { children?: unknown }).children).filter(Boolean) as El[];
+
+test("is_active={false}: the camera alone, marked, with no lens, ambient or children", () => {
+ const off = Camera3d({ transform: at, is_active: false, children: [<DepthOfField key="d" aperture_f_stops={2} />, <AmbientLight key="a" brightness={50} />] }) as El;
+ expect(off.props.active).toBe(false);
+ expect(off.props).toHaveProperty("lookAt");
+ expect(off.props.children).toBeUndefined();
+ const ortho = Camera3d({ transform: at, is_active: false, projection: { Orthographic: { scaling_mode: { FixedVertical: { viewport_height: 4 } } } } }) as El;
+ expect(ortho.props.active).toBe(false);
+});
+
+test("active (the default, or is_active={true}): no marker, and its lens and ambient as before", () => {
+ for (const is_active of [undefined, true]) {
+ const on = Camera3d({ transform: at, is_active, children: [<DepthOfField key="d" aperture_f_stops={2} />, <AmbientLight key="a" brightness={50} />] }) as El;
+ const parts = kids(on);
+ const cam = parts.find((k) => "lookAt" in (k.props as object)) as El;
+ expect(cam.props).not.toHaveProperty("active");
+ expect(parts.length).toBe(3);
+ }
+});
diff --git a/sdk/render/src/3d/lights.tsx b/sdk/render/src/3d/lights.tsx
index 4078ddc2..228adcc1 100644
--- a/sdk/render/src/3d/lights.tsx
+++ b/sdk/render/src/3d/lights.tsx
@@ -193,6 +193,9 @@ export interface PerspectiveCameraProps {
clear?: "none";
bg?: string;
viewport?: { physical_position: [number, number]; physical_size: [number, number] };
+ /** false: it draws nothing this frame (<Camera3d is_active>), and the first camera that does is the piece's; a frame
+ * where another camera becomes the piece's is a cut (docs/rerender.feature RR2) */
+ active?: boolean;
}
/** The viewpoint the scene is drawn from.
@@ -205,6 +208,6 @@ export function PerspectiveCamera({ fov = 50, children, ...rest }: PerspectiveCa
if (rest.up !== undefined) checkVec("PerspectiveCamera", "up", rest.up);
const v = rest.view;
if (v !== undefined && !(v && v.width > 0 && v.height > 0 && Number.isFinite(v.x) && Number.isFinite(v.y))) throw new TypeError(`PerspectiveCamera: view is { width, height, x, y } in frame pixels, got ${JSON.stringify(v)}`);
- useCamera3d({ position: rest.position, lookAt: rest.lookAt, fov, up: rest.up });
+ useCamera3d({ position: rest.position, lookAt: rest.lookAt, fov, up: rest.up }, rest.active !== false);
return node3d("PerspectiveCamera", { ...rest, fov }, children);
}
diff --git a/sdk/render/src/3d/model.tsx b/sdk/render/src/3d/model.tsx
index d12d94a3..183a2df5 100644
--- a/sdk/render/src/3d/model.tsx
+++ b/sdk/render/src/3d/model.tsx
@@ -30,7 +30,7 @@ export function OrthographicCamera({ height = 10, children, ...rest }: Orthograp
if (rest.lookAt !== undefined) checkVec("OrthographicCamera", "lookAt", rest.lookAt);
if (rest.up !== undefined) checkVec("OrthographicCamera", "up", rest.up);
if (!(height > 0 && Number.isFinite(height))) throw new RangeError(`OrthographicCamera: height is the view's height in metres, above 0, got ${height}`);
- useCamera3d({ position: rest.position, lookAt: rest.lookAt, height, up: rest.up });
+ useCamera3d({ position: rest.position, lookAt: rest.lookAt, height, up: rest.up }, rest.active !== false);
return node3d("PerspectiveCamera", { ...rest, ortho: height }, children);
}
diff --git a/sdk/render/src/bevy3d/core.tsx b/sdk/render/src/bevy3d/core.tsx
index 1a9a0062..cba9fd66 100644
--- a/sdk/render/src/bevy3d/core.tsx
+++ b/sdk/render/src/bevy3d/core.tsx
@@ -228,6 +228,11 @@ export interface Camera3dProps {
/** Bevy's Viewport: the camera draws into this region of the window only, `physical_position` from its top left and
* `physical_size` big (whole px, at a scale factor of 1) */
viewport?: CameraViewport;
+ /** Bevy's Camera is_active: false and it draws nothing this frame, its lens and ambient with it. Several cameras in
+ * the scene, one active a frame, cut between them inside one render: the frame another camera becomes active (the
+ * first active one, in tree order, is the piece's) is a cut, drawn as a shot rendered alone draws its first frame
+ * (no motion blur from the frame before). True by default */
+ is_active?: boolean;
/** components on the camera: post effects, tone mapping, a skybox */
children?: ReactNode;
}
@@ -247,7 +252,7 @@ export type ClearColorConfig = "Default" | "None" | { Custom: Srgba | LinearRgba
* @bevy bevy_camera::components::Camera3d
* @bevy bevy_camera::camera::Camera
* @bevy bevy_camera::projection::Projection */
-export function Camera3d({ transform, projection = { Perspective: {} }, layers, order, clear_color, viewport, children: kids }: Camera3dProps) {
+export function Camera3d({ transform, projection = { Perspective: {} }, layers, order, clear_color, viewport, is_active, children: kids }: Camera3dProps) {
if (order !== undefined && !Number.isInteger(order)) throw new TypeError(`Camera3d: order is a whole number, got ${order}`);
const clear = clearOf(clear_color);
if (viewport !== undefined) {
@@ -284,10 +289,13 @@ export function Camera3d({ transform, projection = { Perspective: {} }, layers,
// its rotation as its Transform holds it, which the engine places it by (rolled or not), exactly; the look-at point
// is for what reads a camera by where it looks (its lens's focus, picking, sound)
const look = { position: eye, lookAt, rotation: q, ...(layers ? { layers } : {}), ...(order ? { order } : {}), ...clear, ...(viewport ? { viewport } : {}) };
+ // not drawing this frame: the camera alone, marked, so the scene knows which of its cameras is (a cut, RR2)
+ const off = is_active === false;
if ("Orthographic" in projection) {
const o = projection.Orthographic;
const height = o.scaling_mode?.FixedVertical.viewport_height;
if (dof) throw new TypeError("Camera3d: DepthOfField needs a Perspective projection");
+ if (off) return <OrthographicCamera {...look} near={o.near} far={o.far} height={height} active={false} />;
return (
<>
<OrthographicCamera {...look} near={o.near} far={o.far} height={height}>{children}</OrthographicCamera>
@@ -296,6 +304,7 @@ export function Camera3d({ transform, projection = { Perspective: {} }, layers,
);
}
const p = projection.Perspective;
+ if (off) return <PerspectiveCamera {...look} fov={((p.fov ?? Math.PI / 4) * 180) / Math.PI} near={p.near} far={p.far} active={false} />;
return (
<>
<PerspectiveCamera {...look} fov={((p.fov ?? Math.PI / 4) * 180) / Math.PI} near={p.near} far={p.far} {...focus}>{children}</PerspectiveCamera>
diff --git a/sdk/render/src/events3d.tsx b/sdk/render/src/events3d.tsx
index e6bab951..5977e6a0 100644
--- a/sdk/render/src/events3d.tsx
+++ b/sdk/render/src/events3d.tsx
@@ -253,9 +253,10 @@ function begin(frame: number) {
}
/** The camera parts are picked through this frame (a PerspectiveCamera's or OrthographicCamera's props). */
-export function useCamera3d(camera: PickCamera) {
+export function useCamera3d(camera: PickCamera, active = true) {
begin(useCurrentFrame());
- scene.camera = camera;
+ // a camera not drawing this frame (<Camera3d is_active={false}>) isn't the one the pointer picks through
+ if (active) scene.camera = camera;
}
/** A part's handlers (its on* props) called for the frame's pointer events on it; `bounds` gives its shape's, in its
diff --git a/systems/frame/src/lib.rs b/systems/frame/src/lib.rs
index 9f04ea84..a8b00455 100644
--- a/systems/frame/src/lib.rs
+++ b/systems/frame/src/lib.rs
@@ -31,6 +31,8 @@ mod state;
pub use state::*;
/// a row's per-frame tables (a frame's look, the camera's post-processing), laid onto it frame by frame
pub mod tables;
+/// the frames where another camera becomes the piece's (a cut between cameras, RR2)
+pub mod shots;
/// A model row's entity (a glTF under it), whatever its loading stage.
#[derive(Component, Default)]
diff --git a/systems/frame/src/shots.rs b/systems/frame/src/shots.rs
new file mode 100644
index 00000000..64310512
--- /dev/null
+++ b/systems/frame/src/shots.rs
@@ -0,0 +1,41 @@
+//! Cuts between cameras (docs/rerender.feature RR2): the frames at which the camera row's `shot` steps, another of the
+//! scene's cameras becoming the piece's (<Camera3d is_active>, raea-runtime-look's active.rs).
+
+/// The frames that start a camera's shot, sorted, found once a load. Such a frame has no frame before it, as a shot
+/// rendered alone hasn't: motion blur's step before it draws the frame itself (Engine::pre_step), and a temporal
+/// effect's history (Solari's) starts again.
+#[derive(bevy::prelude::Resource, Default)]
+pub struct Shots(pub Vec<i64>);
+
+/// A live scene's camera row moved to another shot (Engine::set_rows: a game's or play's frames come as rows, with no
+/// timeline to find Shots in): the next frame drawn is a cut, whichever frame was drawn before it.
+#[derive(bevy::prelude::Resource)]
+pub struct Moved;
+
+impl Shots {
+ pub fn of(prog: &raea_core_program::ir::Program) -> Shots {
+ let keys = prog.keys.get(&("cam".to_string(), "shot".to_string()));
+ Shots(keys.map(|k| k.windows(2).filter(|w| w[0].1 != w[1].1).map(|w| w[1].0).collect()).unwrap_or_default())
+ }
+
+ /// Whether frame `f` starts a shot after another (the piece's first frame has none before it anyway).
+ pub fn starts(&self, f: i64) -> bool {
+ self.0.binary_search(&f).is_ok()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_cut_is_where_the_shot_steps() {
+ let mut p = raea_core_program::ir::Program::default();
+ assert!(!Shots::of(&p).starts(0));
+ let k = |f: i64, v: f64| (f, v, "step".to_string());
+ p.keys.insert(("cam".into(), "shot".into()), vec![k(0, 0.0), k(40, 1.0), k(90, 0.0)]);
+ let s = Shots::of(&p);
+ assert_eq!(s.0, vec![40, 90]);
+ assert!(s.starts(40) && s.starts(90) && !s.starts(41) && !s.starts(0));
+ }
+}