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.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
R3F23: a camera drawing into an image, in the engine (R3F23a). A PerspectiveCamera row whose target is "render:NAME:WxH" (":float" for an Rgba16Float image) is a rendercam: raea-runtime-look's rendercam.rs gives it a row of its own (into, on keyed by step, no tone curve, the ambient light of its own layers), the engine spawns it on that image (RenderTarget::Image, no multisampling or dither, Hdr for a float image) before the screen's camera, and a material's map naming the image reads what it drew. raea-sys-frame's render_image.rs parses and makes the image once for every source naming it; a three shader follows only the screen camera's tone mapping; the TSX PerspectiveCamera takes target and layers, and a camera with a target isn't the one the pointer picks through
shinyobjectz744c5a2a1f84
diff --git a/Cargo.lock b/Cargo.lockindex 8315bdf6..c94d73d4 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -16212,6 +16212,7 @@ dependencies = ["bevy","image","naga",+ "raea-sys-frame","raea-sys-material","raea-sys-sampler","raea-sys-shader",diff --git a/core/scene/src/lib.rs b/core/scene/src/lib.rsindex e103db56..bb663a5c 100644--- a/core/scene/src/lib.rs+++ b/core/scene/src/lib.rs@@ -52,6 +52,8 @@ pub fn base_ident(it: &Item) -> &str {"mesh" => it.shape.as_deref().unwrap_or_default(),"model" | "panel" | "plate" | "splat" | "meshseq" => it.props.get("src").and_then(Value::as_str).unwrap_or(""),"text" => it.props.get("text").and_then(Value::as_str).unwrap_or(""),+ // a camera drawing into an image (R3F23a): by the image, so two passes into one image a frame are #0 and #1+ "rendercam" => it.props.get("target").and_then(Value::as_str).unwrap_or(""),_ => "",}}diff --git a/engine/render/src/engine/load.rs b/engine/render/src/engine/load.rsindex 471cabe1..cde73d2d 100644--- a/engine/render/src/engine/load.rs+++ b/engine/render/src/engine/load.rs@@ -42,7 +42,7 @@ impl Engine {let has_3d = has_3d(inserted) || raea_sys_sprite::has_2d(inserted);// cameras first, so UI can target them; otherwise insertion orderlet mut order: Vec<(&Tup, Entity)> = inserted.iter().zip(ents.iter().copied()).collect();- order.sort_by_key(|(t, _)| t.kind != "camera");+ order.sort_by_key(|(t, _)| !matches!(t.kind.as_str(), "camera" | "rendercam"));for (t, e) in order {let vals = &t.vals;match t.kind.as_str() {@@ -50,6 +50,8 @@ impl Engine {spawn_camera(world, e, vals, inserted, &self.dir, (prog.width, prog.height), RenderTarget::Image(self.target.clone().into()), has_3d)?;camera.get_or_insert(e); // (the first camera: a second draws over it, two_passes)}+ // a camera into an image, a pass before the screen's (R3F23a)+ "rendercam" => render_camera(world, e, vals, inserted, &self.dir)?,k if is_3d_spawn(k) => {spawn_3d(world, e, t, inserted, &self.dir)?;}diff --git a/engine/render/src/engine/spawn.rs b/engine/render/src/engine/spawn.rsindex baa42612..ca78fd1a 100644--- a/engine/render/src/engine/spawn.rs+++ b/engine/render/src/engine/spawn.rs@@ -81,6 +81,17 @@ pub(crate) fn spawn_camera(world: &mut World, e: Entity, vals: &BTreeMap<String,Ok(())}+/// A camera row drawing into an image (a "rendercam", `into` "render:NAME:WxH[:float]": docs/r3f.feature R3F23a): the+/// camera spawn_camera makes, on that image (raea-sys-frame's into_image), which a material's map naming it reads.+pub(crate) fn render_camera(world: &mut World, e: Entity, vals: &BTreeMap<String, V>, inserted: &[Tup], dir: &Path) -> Result<(), String> {+ let Some(V::S(into)) = vals.get("into") else { return Err("a camera into an image needs `into` (\"render:NAME:WxH\")".into()) };+ let image = RenderImages::image(world, into, None)?;+ let size = RenderImages::name(into).and_then(|n| world.resource::<RenderImages>().0.get(n)).map_or((512, 512), |i| i.1);+ spawn_camera(world, e, vals, inserted, dir, size, RenderTarget::Image(image.into()), true)?;+ raea_sys_frame::camera::into_image(world, e, into);+ Ok(())+}+/// A live scene's rows applied to a World (Engine::set_rows, or a plain App's: docs/sdk.feature S6a): each row's values/// merged into its latest ones, a row not seen before spawned as a load spawns it, and the component and resource rows/// set through the registry. True when a glTF model was spawned, which the caller loads before the frame that shows it.@@ -118,6 +129,7 @@ pub fn apply_rows(world: &mut World, dir: &Path, rows: &[Tup]) -> Result<bool, Slet e = store::spawn(world, t);// a camera first seen here is a plain App's (SceneTarget); an Engine's comes with its loadmatch world.get_resource::<SceneTarget>().map(|s| (s.target.clone(), s.size)) {+ _ if t.kind == "rendercam" => render_camera(world, e, &t.vals, rows, dir)?,Some((target, size)) if t.kind == "camera" => spawn_camera(world, e, &t.vals, rows, dir, size, target, true)?,_ => spawn_3d(world, e, t, &media, dir)?,}diff --git a/runtime/look/src/camera.rs b/runtime/look/src/camera.rsindex 550ce9f3..f726d129 100644--- a/runtime/look/src/camera.rs+++ b/runtime/look/src/camera.rs@@ -50,77 +50,96 @@ fn one(all: &[Vec<Item>], p: &mut Program, row: &mut BTreeMap<String, V>, k: usilet cams: Vec<Option<Item>> = all.iter().map(|its| its.iter().filter(|i| i.kind == "camera").nth(k).cloned()).collect();if cams.iter().any(Option::is_some) {let its = filled(&cams);- let pos: Vec<[f64; 3]> = its.iter().map(|c| vec3(&c.props, "position", [0.0, 0.0, 5.0])).collect();- let look: Vec<[f64; 3]> = its.iter().map(|c| vec3(&c.props, "lookAt", [0.0, 0.0, 0.0])).collect();- for (k, name) in ["x", "y", "z"].iter().enumerate() {- column(p, row, id, name, &pos.iter().map(|v| v[k]).collect::<Vec<_>>());- }- for (k, name) in ["look_x", "look_y", "look_z"].iter().enumerate() {- column(p, row, id, name, &look.iter().map(|v| v[k]).collect::<Vec<_>>());- }- column(p, row, id, "fov", &its.iter().map(|c| n(&c.props, "fov", 50.0)).collect::<Vec<_>>());- // an orthographic camera (<OrthographicCamera height>): the view's height in metres, keyed; 0 is perspective- if its.iter().any(|c| c.props.contains_key("ortho")) {- column(p, row, id, "ortho", &its.iter().map(|c| n(&c.props, "ortho", 0.0)).collect::<Vec<_>>());- }- // which way is up (`up`; +Y by default): a camera that rolls, as a solved one does (raea-render's up_x/y/z, Matchmove)- keyed_vec(p, row, id, &its, "up", &["up_x", "up_y", "up_z"], &[0.0, 1.0, 0.0]);- // a Camera3d's Transform rotation (`rotation`, a quaternion on every frame), exact, which the engine places it by over- // its look-at point- if its.iter().all(|c| c.props.get("rotation").and_then(Value::as_array).is_some_and(|q| q.len() == 4)) {- quat_columns(p, row, id, "rot", &its.iter().map(Some).collect::<Vec<_>>());- }- // a window on a larger view (`view`: its full size and this frame's offset, in frame pixels): a crop of- // footage keeps its lens's centre (raea-render's camera view_*, Matchmove's 9:16 from 16:9)- if its.iter().any(|c| c.props.get("view").is_some_and(Value::is_object)) {- let view = |c: &Item, k: &str| c.props.get("view").and_then(|v| v.get(k)).and_then(Value::as_f64).unwrap_or(0.0);- for (k, col) in [("width", "view_w"), ("height", "view_h"), ("x", "view_x"), ("y", "view_y")] {- column(p, row, id, col, &its.iter().map(|c| view(c, k)).collect::<Vec<_>>());- }- }- 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));- }- if let Some(c) = first.get("clear").and_then(Value::as_str) {- row.insert("clear".into(), V::S(c.into()));- }- if let Some(b) = first.get("bg").and_then(Value::as_str) {- row.insert("bg".into(), V::S(b.into()));- }- // its viewport (Bevy's Viewport: physical px from the target's top left)- let vp = |k: &str, i: usize| first.get("viewport").and_then(|v| v.get(k)).and_then(|v| v.get(i)).and_then(Value::as_f64);- for (col, k, i) in [("vp_x", "physical_position", 0), ("vp_y", "physical_position", 1), ("vp_w", "physical_size", 0), ("vp_h", "physical_size", 1)] {- if let Some(x) = vp(k, i) {- row.insert(col.into(), V::N(x));- }- }- for (k, col) in [("near", "near"), ("far", "far")] {- if let Some(v) = num(first, k) {- row.insert(col.into(), V::N(v));- }- }- layers_column(row, first);- // Bevy's own components on the camera (<BevyComponent> inside it)- components(p, id, &its);+ placed(all, p, row, id, &its);} else {for (name, v) in [("x", 0.0), ("y", 0.0), ("z", 5.0), ("look_x", 0.0), ("look_y", 0.0), ("look_z", 0.0), ("fov", 50.0)] {row.insert(name.into(), V::N(v));}}+ lit(all, p, row, id);+}++/// A camera's place, lens and frame, from its items frame by frame (`its`, filled): where it is and looks, its field+/// of view or orthographic height, up, rotation, view window and focus, keyed; its order, clear, colour, viewport, near+/// and far, layers and Bevy components as its first frame has them. A screen camera's (one) and an image's (rendercam.rs).+pub fn placed(all: &[Vec<Item>], p: &mut Program, row: &mut BTreeMap<String, V>, id: &str, its: &[Item]) {+ let pos: Vec<[f64; 3]> = its.iter().map(|c| vec3(&c.props, "position", [0.0, 0.0, 5.0])).collect();+ let look: Vec<[f64; 3]> = its.iter().map(|c| vec3(&c.props, "lookAt", [0.0, 0.0, 0.0])).collect();+ for (k, name) in ["x", "y", "z"].iter().enumerate() {+ column(p, row, id, name, &pos.iter().map(|v| v[k]).collect::<Vec<_>>());+ }+ for (k, name) in ["look_x", "look_y", "look_z"].iter().enumerate() {+ column(p, row, id, name, &look.iter().map(|v| v[k]).collect::<Vec<_>>());+ }+ column(p, row, id, "fov", &its.iter().map(|c| n(&c.props, "fov", 50.0)).collect::<Vec<_>>());+ // an orthographic camera (<OrthographicCamera height>): the view's height in metres, keyed; 0 is perspective+ if its.iter().any(|c| c.props.contains_key("ortho")) {+ column(p, row, id, "ortho", &its.iter().map(|c| n(&c.props, "ortho", 0.0)).collect::<Vec<_>>());+ }+ // which way is up (`up`; +Y by default): a camera that rolls, as a solved one does (raea-render's up_x/y/z, Matchmove)+ keyed_vec(p, row, id, &its, "up", &["up_x", "up_y", "up_z"], &[0.0, 1.0, 0.0]);+ // a Camera3d's Transform rotation (`rotation`, a quaternion on every frame), exact, which the engine places it by over+ // its look-at point+ if its.iter().all(|c| c.props.get("rotation").and_then(Value::as_array).is_some_and(|q| q.len() == 4)) {+ quat_columns(p, row, id, "rot", &its.iter().map(Some).collect::<Vec<_>>());+ }+ // a window on a larger view (`view`: its full size and this frame's offset, in frame pixels): a crop of+ // footage keeps its lens's centre (raea-render's camera view_*, Matchmove's 9:16 from 16:9)+ if its.iter().any(|c| c.props.get("view").is_some_and(Value::is_object)) {+ let view = |c: &Item, k: &str| c.props.get("view").and_then(|v| v.get(k)).and_then(Value::as_f64).unwrap_or(0.0);+ for (k, col) in [("width", "view_w"), ("height", "view_h"), ("x", "view_x"), ("y", "view_y")] {+ column(p, row, id, col, &its.iter().map(|c| view(c, k)).collect::<Vec<_>>());+ }+ }+ if all.iter().flatten().any(|i| i.kind == "dof") {+ column(p, row, id, "focus", &its.iter().map(focus_of).collect::<Vec<_>>());+ }+ let first = &its[0].props;+ if let Some(o) = num(first, "order") {+ row.insert("order".into(), V::N(o));+ }+ if let Some(c) = first.get("clear").and_then(Value::as_str) {+ row.insert("clear".into(), V::S(c.into()));+ }+ if let Some(b) = first.get("bg").and_then(Value::as_str) {+ row.insert("bg".into(), V::S(b.into()));+ }+ // its viewport (Bevy's Viewport: physical px from the target's top left)+ let vp = |k: &str, i: usize| first.get("viewport").and_then(|v| v.get(k)).and_then(|v| v.get(i)).and_then(Value::as_f64);+ for (col, k, i) in [("vp_x", "physical_position", 0), ("vp_y", "physical_position", 1), ("vp_w", "physical_size", 0), ("vp_h", "physical_size", 1)] {+ if let Some(x) = vp(k, i) {+ row.insert(col.into(), V::N(x));+ }+ }+ for (k, col) in [("near", "near"), ("far", "far")] {+ if let Some(v) = num(first, k) {+ row.insert(col.into(), V::N(v));+ }+ }+ layers_column(row, first);+ // Bevy's own components on the camera (<BevyComponent> inside it)+ components(p, id, its);+}++/// The rest of a screen camera's row: the scene's ambient light, environment, sky, post-processing, composition+/// passes, lens and motion blur, frame by frame.+fn lit(all: &[Vec<Item>], p: &mut Program, row: &mut BTreeMap<String, V>, id: &str) {// ambient: every AmbientLight's intensity summed, per frame; its colour the first one's. Any AmbientLight sends the// column, so one of brightness 0 turns the ambient off as Bevy's does (with none, the camera keeps Bevy's default 80)- let amb: Vec<f64> = all.iter().map(|its| its.iter().filter(|i| i.kind == "ambient").map(|i| light_power("ambient", &i.props)).sum::<f64>()).collect();- if all.iter().flatten().any(|i| i.kind == "ambient") {+ // (those on the camera's layers: an image's pass lights its own scene with its own, rendercam.rs)+ let layers: Vec<u64> = match row.get("layers") {+ Some(V::S(l)) => l.split(',').filter_map(|x| x.trim().parse().ok()).collect(),+ _ => vec![0],+ };+ let amb: Vec<f64> = all.iter().map(|its| ambient_on(its, &layers)).collect();+ let lit_by = |i: &&Item| i.kind == "ambient" && sees(&layers, i);+ if all.iter().flatten().any(|i| lit_by(&i)) {column(p, row, id, "ambient", &amb);- if let Some(c) = all.iter().flatten().find(|i| i.kind == "ambient").and_then(|i| hex(i.props.get("color"))) {+ if let Some(c) = all.iter().flatten().find(lit_by).and_then(|i| hex(i.props.get("color"))) {if c != "#ffffff" {row.insert("ambient_color".into(), V::S(c));}diff --git a/runtime/look/src/lib.rs b/runtime/look/src/lib.rsindex c57df7b3..4e6f33c0 100644--- a/runtime/look/src/lib.rs+++ b/runtime/look/src/lib.rs@@ -14,6 +14,8 @@ mod post;pub use post::*;mod parts;pub use parts::*;+mod rendercam;+pub use rendercam::*;pub use instances::*;mod active;pub use active::*;diff --git a/runtime/look/src/rendercam.rs b/runtime/look/src/rendercam.rsnew file mode 100644index 00000000..808ba47d--- /dev/null+++ b/runtime/look/src/rendercam.rs@@ -0,0 +1,89 @@+//! A camera drawing into an image (<PerspectiveCamera target="render:NAME:WxH">: three's setRenderTarget then render,+//! docs/r3f.feature R3F23a) as a row of its own, "rcam0", "rcam1", ... by its track. It is placed and framed as a+//! screen camera is (camera.rs's placed); its image is `into` (not `target`, which a live row reads as the row a+//! component is on); `on` is keyed where it doesn't draw every frame (`active` false, or no such camera that frame);+//! it has no tone curve unless it names one (three writes a target linear), and the ambient light on its own layers.+//! The engine spawns it as a camera on that image (raea-render's render_camera), before the screen's by its `order`.++use super::*;++/// The scene's cameras into images as their rows (`tracks`: tracks_of's for "rendercam", each a camera by its image+/// and its place among that image's passes a frame), pushed as "rendercam" spawns.+pub fn render_cameras(all: &[Vec<Item>], tracks: &[(String, Vec<Option<Item>>)], p: &mut Program) {+ let mut rows = Vec::new();+ for (k, (_, track)) in tracks.iter().enumerate() {+ let id = format!("rcam{k}");+ let its = filled(track);+ let mut row = BTreeMap::new();+ row.insert("id".into(), V::S(id.clone()));+ placed(all, p, &mut row, &id, &its);+ let first = &its[0].props;+ row.insert("into".into(), V::S(first.get("target").and_then(Value::as_str).unwrap_or_default().to_string()));+ let on: Vec<f64> = track.iter().map(|t| t.as_ref().is_some_and(|i| i.props.get("active") != Some(&Value::Bool(false))) as u8 as f64).collect();+ if on.iter().any(|o| *o == 0.0) {+ row.insert("on".into(), V::N(on[0]));+ p.keys.insert((id.clone(), "on".into()), step_keys(&on));+ }+ row.insert("tonemap".into(), V::S(first.get("tonemap").and_then(Value::as_str).unwrap_or("none").to_string()));+ let layers = layers_of(first);+ let amb: Vec<f64> = all.iter().map(|f| ambient_on(f, &layers)).collect();+ if all.iter().flatten().any(|i| i.kind == "ambient" && sees(&layers, i)) {+ column(p, &mut row, &id, "ambient", &amb);+ }+ rows.push(row);+ }+ if !rows.is_empty() {+ p.spawns.push(("rendercam".into(), rows));+ }+}++/// A part's render layers (its `layers` prop), layer 0 when it names none, as Bevy's RenderLayers default.+pub fn layers_of(props: &Map<String, Value>) -> Vec<u64> {+ match props.get("layers").and_then(Value::as_array) {+ Some(l) => l.iter().filter_map(Value::as_u64).collect(),+ None => vec![0],+ }+}++/// Whether a camera on `layers` sees the part `i` (they share a layer).+pub fn sees(layers: &[u64], i: &Item) -> bool {+ layers_of(&i.props).iter().any(|l| layers.contains(l))+}++/// A frame's ambient light on `layers`: the brightness of every AmbientLight a camera on them sees, summed.+pub fn ambient_on(frame: &[Item], layers: &[u64]) -> f64 {+ frame.iter().filter(|i| i.kind == "ambient" && sees(layers, i)).map(|i| light_power("ambient", &i.props)).sum()+}++#[cfg(test)]+mod tests {+ use super::*;++ fn item(kind: &'static str, props: Value) -> Item {+ Item { kind, props: std::sync::Arc::new(props.as_object().cloned().unwrap_or_default()), shape: None, material: None, at: None, world: bevy::math::Mat4::IDENTITY }+ }++ #[test]+ fn a_camera_into_an_image_is_its_own_row_drawn_on_its_frames() {+ let cam = |active: bool| item("rendercam", serde_json::json!({"target": "render:fbo:64x64", "position": [0, 0, 3], "order": -10, "bg": "#000000ff", "layers": [5], "active": active}));+ let amb = |layers: Value| item("ambient", serde_json::json!({"intensity": 1, "layers": layers}));+ let frames = vec![vec![cam(true), amb(serde_json::json!([5])), amb(serde_json::json!([0]))], vec![cam(false), amb(serde_json::json!([5]))], vec![]];+ let tracks = tracks_of(&frames, &["rendercam"]);+ let mut p = Program::default();+ render_cameras(&frames, &tracks, &mut p);+ let (kind, rows) = &p.spawns[0];+ assert_eq!(kind, "rendercam");+ let r = &rows[0];+ assert_eq!(r["id"], V::S("rcam0".into()));+ assert_eq!(r["into"], V::S("render:fbo:64x64".into()));+ assert_eq!(r["order"], V::N(-10.0));+ assert_eq!(r["layers"], V::S("5".into()));+ assert_eq!(r["tonemap"], V::S("none".into()));+ // drawn on frame 0 only: inactive on 1, and missing on 2+ let on = &p.keys[&("rcam0".to_string(), "on".to_string())];+ assert_eq!(on.iter().map(|k| (k.0, k.1)).collect::<Vec<_>>(), vec![(0, 1.0), (1, 0.0)]);+ // its ambient is the one on layer 5 only+ let one = light_power("ambient", &amb(serde_json::json!([5])).props);+ assert_eq!(r["ambient"], V::N(one));+ }+}diff --git a/runtime/plugins/src/fields.rs b/runtime/plugins/src/fields.rsindex 2c47cf20..a41eca22 100644--- a/runtime/plugins/src/fields.rs+++ b/runtime/plugins/src/fields.rs@@ -192,34 +192,9 @@ impl Fields<'_> {// meet in it// ("render:NAME:WxH:depth" a depth image, Depth32Float with a comparison sampler, a camera's DepthCopy// copies its depth into and a Material samples as texture_depth_2d)+ // (":float" after the size an Rgba16Float image, a GPGPU pass's: raea-sys-frame's render_image.rs)Value::String(x) if asset == TypeId::of::<Image>() && x.starts_with("render:") => {- let rest = &x["render:".len()..];- let (rest, depth) = rest.strip_suffix(":depth").map_or((rest, false), |r| (r, true));- let (name, size) = match rest.rsplit_once(':') {- Some((n, sz)) if sz.contains('x') => (n, Some(sz)),- _ => (rest, None),- };- let (w, h) = match size {- Some(sz) => {- let (w, h) = sz.split_once('x').unwrap();- let p = |d: &str| d.parse::<u32>().ok().filter(|n| (1..=8192).contains(n));- p(w).zip(p(h)).ok_or_else(|| format!("{x:?}: a render image's size is WxH in pixels (1 to 8192)"))?- }- None => (512, 512),- };- if name.is_empty() {- return Err(format!("{x:?}: a render image needs a name (\"render:mirror\")"));- }- if let Some(hd) = self.world.get_resource::<RenderImages>().and_then(|r| r.0.get(name)) {- if size.is_some() && hd.1 != (w, h) {- return Err(format!("{x:?}: the render image {name:?} is already {}x{}", hd.1.0, hd.1.1));- }- return Ok(hd.0.clone().untyped());- }- let img = if depth { raea_sys_shader::own::depth_image(w, h) } else { Image::new_target_texture(w, h, bevy::render::render_resource::TextureFormat::Rgba8UnormSrgb, None) };- let hd = self.world.resource_mut::<Assets<Image>>().add(img);- self.world.get_resource_or_init::<RenderImages>().0.insert(name.to_string(), (hd.clone(), (w, h)));- Ok(hd.untyped())+ RenderImages::image(self.world, x, Some(raea_sys_shader::own::depth_image)).map(|h| h.untyped())}Value::String(x) => self.load_path(asset, name, x),Value::Object(_) => {diff --git a/runtime/scene/src/lib.rs b/runtime/scene/src/lib.rsindex 2c76e885..8beddf29 100644--- a/runtime/scene/src/lib.rs+++ b/runtime/scene/src/lib.rs@@ -141,6 +141,9 @@ fn walk(n: &Node3, parent: Mat4, out: &mut Vec<Item>) {"Plate" => out.push(item("plate", Mat4::IDENTITY, None)),"PerspectiveCamera" | "DirectionalLight" | "PointLight" | "SpotLight" | "RectAreaLight" => {let kind = match &*n.kind {+ // a camera drawing into an image (`target` "render:NAME:WxH", R3F23a) is a pass before the screen's,+ // outside the screen's cameras (their order, which is active, a cut): rendercam.rs+ "PerspectiveCamera" if n.props.get("target").is_some_and(Value::is_string) => "rendercam","PerspectiveCamera" => "camera","DirectionalLight" => "directional","PointLight" => "point",@@ -282,6 +285,7 @@ struct Tracks {meshseqs: Vec<Track>,entities: Vec<Track>,texts: Vec<Track>,+ rendercams: Vec<Track>,}impl Tracks {@@ -302,6 +306,7 @@ impl Tracks {meshseqs: tracks_of(all, &["meshseq"]),entities: tracks_of(all, &["entity"]),texts: tracks_of(all, &["text"]),+ rendercams: tracks_of(all, &["rendercam"]),}}}@@ -331,4 +336,6 @@ fn rows_into_of(all: &[Vec<Item>], tr: &Tracks, p: &mut Program) {raea_runtime_scene2d::shapes(&tr.shapes2d, p);// baked simulations (<MeshSequence>, <Goo>): meshseq.rsmeshseq::rows(&tr.meshseqs, p);+ // cameras drawing into images (R3F23a): raea-runtime-look's rendercam.rs+ render_cameras(all, &tr.rendercams, p);}diff --git a/runtime/scene3d/src/sync.rs b/runtime/scene3d/src/sync.rsindex c3978afc..f5de4c37 100644--- a/runtime/scene3d/src/sync.rs+++ b/runtime/scene3d/src/sync.rs@@ -205,8 +205,8 @@ pub fn sync_meshes(/// once, and a row that moves (or moves back) writes every frame it changes. An entity with no entry always writes,/// so a render seeking straight to frame N places its camera.#[allow(clippy::type_complexity)]-pub fn sync_camera(frame: Res<FrameRows>, edit: Option<Res<Edit>>, mut placed: Local<bevy::platform::collections::HashMap<Entity, (Vec3, Vec3, Option<Quat>)>>, mut q: Query<(Entity, &mut Transform, Option<&mut Projection>, Option<&mut AmbientLight>, Option<&mut bevy::post_process::dof::DepthOfField>, Option<&mut super::lens::Lens>, Option<&mut bevy::post_process::effect_stack::ChromaticAberration>, Option<&mut Camera>), (With<Camera3d>, Without<super::BareEntity>)>) {- for (e, mut t, proj, amb, dof, lens, ab, cam) in &mut q {+pub fn sync_camera(frame: Res<FrameRows>, edit: Option<Res<Edit>>, mut placed: Local<bevy::platform::collections::HashMap<Entity, (Vec3, Vec3, Option<Quat>)>>, mut shown: Local<bevy::platform::collections::HashMap<Entity, bool>>, mut q: Query<(Entity, &mut Transform, Option<&mut Projection>, Option<&mut AmbientLight>, Option<&mut bevy::post_process::dof::DepthOfField>, Option<&mut super::lens::Lens>, Option<&mut bevy::post_process::effect_stack::ChromaticAberration>, Option<&mut Camera>), (With<Camera3d>, Without<super::BareEntity>)>) {+ for (e, mut t, proj, amb, dof, lens, ab, mut cam) in &mut q {let Some(v) = frame.vals(e) else { continue };let v = &v;let pos = Vec3::new(num(v, "x", 0.0), num(v, "y", 2.0), num(v, "z", 9.0));@@ -286,6 +286,14 @@ pub fn sync_camera(frame: Res<FrameRows>, edit: Option<Res<Edit>>, mut placed: La.brightness = b.num() as f32;}}+ // a camera into an image drawn only on its frames (`on`, keyed: raea-runtime-look's rendercam.rs), written when+ // the row changes it, so a load's views::off (#48) keeps it off until views::on as it does the rest+ if let (Some(on), Some(c)) = (v.get("on").map(|o| o.num() > 0.5), cam.as_mut()) {+ let was = shown.insert(e, on);+ if was.map_or(!on, |w| w != on) && c.is_active != on {+ c.is_active = on;+ }+ }// a clear keyed frame by frame (bg_r..bg_a, sRGB: a holder's background that changes, runtime/export program.rs)if let (Some(r), Some(mut c)) = (v.get("bg_r"), cam) {let want = Color::srgba(r.num() as f32, num(v, "bg_g", 0.0), num(v, "bg_b", 0.0), num(v, "bg_a", 1.0));diff --git a/sdk/render/src/3d/lights.tsx b/sdk/render/src/3d/lights.tsxindex 228adcc1..8ca2590a 100644--- a/sdk/render/src/3d/lights.tsx+++ b/sdk/render/src/3d/lights.tsx@@ -196,6 +196,13 @@ export interface PerspectiveCameraProps {/** 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;+ /** draws into a named image instead of the frame ("render:NAME:WxH", ":float" after it for an Rgba16Float one): a+ * pass before the screen's, as three's setRenderTarget then render (docs/r3f.feature R3F23a). A material whose map+ * names the image reads what it drew. It has no tone curve and no multisampling, and it isn't the piece's camera;+ * give it an `order` below the screen's, a `bg` (or `clear` "none") and the `layers` its scene is on */+ target?: string;+ /** the render layers it draws (Bevy's RenderLayers: [0] by default), so a pass draws only its own scene */+ layers?: number[];}/** The viewpoint the scene is drawn from.@@ -208,6 +215,8 @@ export function PerspectiveCamera({ fov = 50, children, ...rest }: PerspectiveCaif (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 }, rest.active !== false);+ if (rest.target !== undefined && !/^render:[^:]+(:\d+x\d+)?(:float)?$/.test(rest.target)) throw new TypeError(`PerspectiveCamera: target is "render:NAME", "render:NAME:WxH" or "render:NAME:WxH:float", got ${JSON.stringify(rest.target)}`);+ // a camera into an image isn't the one the pointer picks through+ useCamera3d({ position: rest.position, lookAt: rest.lookAt, fov, up: rest.up }, rest.active !== false && rest.target === undefined);return node3d("PerspectiveCamera", { ...rest, fov }, children);}diff --git a/sdk/render/src/3d/model.tsx b/sdk/render/src/3d/model.tsxindex 183a2df5..a45320c1 100644--- a/sdk/render/src/3d/model.tsx+++ b/sdk/render/src/3d/model.tsx@@ -30,7 +30,8 @@ export function OrthographicCamera({ height = 10, children, ...rest }: Orthograpif (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 }, rest.active !== false);+ // a camera into an image (`target`, R3F23a) isn't the one the pointer picks through+ useCamera3d({ position: rest.position, lookAt: rest.lookAt, height, up: rest.up }, rest.active !== false && rest.target === undefined);return node3d("PerspectiveCamera", { ...rest, ortho: height }, children);}diff --git a/systems/frame/src/camera.rs b/systems/frame/src/camera.rsindex fd09e205..849fd11f 100644--- a/systems/frame/src/camera.rs+++ b/systems/frame/src/camera.rs@@ -44,3 +44,20 @@ pub struct Group {pub fn remove<B: Bundle>(world: &mut World, e: Entity) {world.entity_mut(e).remove::<B>();}++/// A camera drawing into a render image ("render:NAME:WxH", docs/r3f.feature R3F23a): a pass before the screen's, which+/// what follows the screen camera (a three shader's tone mapping) passes over.+#[derive(Component, Clone, Copy, Default)]+pub struct IntoImage;++/// A camera on a render image (`into`), as three draws into a render target: no multisampling (a target has none+/// unless it asks), no dither, and Hdr for a float image (":float") so its values stay as drawn, unclamped and signed.+/// Its tone curve is its row's (`tonemap` "none" unless it names one: raea-runtime-look's rendercam.rs).+pub fn into_image(world: &mut World, e: Entity, into: &str) {+ let float = matches!(RenderImages::spec(into), Ok((_, _, RenderKind::Float)));+ let mut c = world.entity_mut(e);+ c.insert((IntoImage, Msaa::Off, bevy::core_pipeline::tonemapping::DebandDither::Disabled));+ if float {+ c.insert(bevy::camera::Hdr);+ }+}diff --git a/systems/frame/src/lib.rs b/systems/frame/src/lib.rsindex a8b00455..887e4d0e 100644--- a/systems/frame/src/lib.rs+++ b/systems/frame/src/lib.rs@@ -29,6 +29,9 @@ pub mod store;// the frame loop's own state (Stages, the frame tag, the overlay and output resources)mod state;pub use state::*;+/// a named image a camera draws into ("render:NAME:WxH"), as every source naming it gets it (R3F23a)+pub mod render_image;+pub use render_image::RenderKind;/// a row's per-frame tables (a frame's look, the camera's post-processing), laid onto it frame by framepub mod tables;/// the frames where another camera becomes the piece's (a cut between cameras, RR2)diff --git a/systems/frame/src/render_image.rs b/systems/frame/src/render_image.rsnew file mode 100644index 00000000..fae3fdf6--- /dev/null+++ b/systems/frame/src/render_image.rs@@ -0,0 +1,102 @@+//! A named image a camera draws into, as a source names it: "render:NAME", "render:NAME:WxH", and after that ":float"+//! for an Rgba16Float image (a GPGPU pass's values, unclamped and signed) or ":depth" for a depth one. Every source that+//! names it gets the same image, so a camera's target, a material's map and a three shader's texture meet in it+//! (docs/r3f.feature R3F23a).++use super::*;+use bevy::render::render_resource::TextureFormat;++/// What a render image holds.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum RenderKind {+ /// colour as Rgba8UnormSrgb: a camera writes linear values and a material reads them back linear+ Colour,+ /// Rgba16Float: what a camera with Hdr and no tone curve wrote, as it wrote it+ Float,+ /// Depth32Float, sampled as texture_depth_2d (a camera's DepthCopy copies its depth into it)+ Depth,+}++impl RenderImages {+ /// A "render:..." source's name, its size when it gives one and its kind; Err for a source that isn't one.+ pub fn spec(src: &str) -> Result<(&str, Option<(u32, u32)>, RenderKind), String> {+ let rest = src.strip_prefix("render:").ok_or_else(|| format!("{src:?} isn't a render image (\"render:NAME\")"))?;+ let (rest, kind) = match rest.rsplit_once(':') {+ Some((r, "float")) => (r, RenderKind::Float),+ Some((r, "depth")) => (r, RenderKind::Depth),+ _ => (rest, RenderKind::Colour),+ };+ let (name, size) = match rest.rsplit_once(':') {+ Some((n, sz)) if sz.contains('x') => (n, Some(sz)),+ _ => (rest, None),+ };+ if name.is_empty() {+ return Err(format!("{src:?}: a render image needs a name (\"render:mirror\")"));+ }+ let size = match size {+ Some(sz) => {+ let (w, h) = sz.split_once('x').unwrap_or_default();+ let px = |d: &str| d.parse::<u32>().ok().filter(|n| (1..=8192).contains(n));+ Some(px(w).zip(px(h)).ok_or_else(|| format!("{src:?}: a render image's size is WxH in pixels (1 to 8192)"))?)+ }+ None => None,+ };+ Ok((name, size, kind))+ }++ /// A "render:..." source's name (`spec`'s), None for any other source.+ pub fn name(src: &str) -> Option<&str> {+ Self::spec(src).ok().map(|(n, _, _)| n)+ }++ /// The image a "render:..." source names, made the first time one names it (512 x 512 when it gives no size); a+ /// later source giving another size is refused. `depth` makes a depth image (raea-sys-shader's depth_image); None+ /// refuses one, where a depth image can't go (a camera's target, a material's map).+ pub fn image(world: &mut World, src: &str, depth: Option<fn(u32, u32) -> Image>) -> Result<Handle<Image>, String> {+ let (name, size, kind) = Self::spec(src)?;+ let (w, h) = size.unwrap_or((512, 512));+ if let Some(had) = world.get_resource::<RenderImages>().and_then(|r| r.0.get(name)) {+ if size.is_some() && had.1 != (w, h) {+ return Err(format!("{src:?}: the render image {name:?} is already {}x{}", had.1.0, had.1.1));+ }+ return Ok(had.0.clone());+ }+ let img = match kind {+ RenderKind::Depth => depth.ok_or_else(|| format!("{src:?}: a depth image can't be used here"))?(w, h),+ RenderKind::Float => Image::new_target_texture(w, h, TextureFormat::Rgba16Float, None),+ RenderKind::Colour => Image::new_target_texture(w, h, TextureFormat::Rgba8UnormSrgb, None),+ };+ let hd = world.resource_mut::<Assets<Image>>().add(img);+ world.get_resource_or_init::<RenderImages>().0.insert(name.to_string(), (hd.clone(), (w, h)));+ Ok(hd)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_render_source_says_its_name_size_and_kind() {+ assert_eq!(RenderImages::spec("render:mirror").unwrap(), ("mirror", None, RenderKind::Colour));+ assert_eq!(RenderImages::spec("render:a-b:256x128").unwrap(), ("a-b", Some((256, 128)), RenderKind::Colour));+ assert_eq!(RenderImages::spec("render:sim:64x64:float").unwrap(), ("sim", Some((64, 64)), RenderKind::Float));+ assert_eq!(RenderImages::spec("render:z:8x8:depth").unwrap(), ("z", Some((8, 8)), RenderKind::Depth));+ assert_eq!(RenderImages::name("render:z:8x8:depth"), Some("z"));+ assert!(RenderImages::spec("render::8x8").is_err());+ assert!(RenderImages::spec("render:x:0x8").is_err());+ assert!(RenderImages::spec("pic.png").is_err());+ }++ #[test]+ fn every_source_naming_an_image_gets_the_same_one() {+ let mut world = World::new();+ world.init_resource::<Assets<Image>>();+ let a = RenderImages::image(&mut world, "render:sim:64x32:float", None).unwrap();+ let b = RenderImages::image(&mut world, "render:sim", None).unwrap();+ assert_eq!(a, b);+ assert_eq!(world.resource::<Assets<Image>>().get(&a).unwrap().texture_descriptor.format, TextureFormat::Rgba16Float);+ assert!(RenderImages::image(&mut world, "render:sim:16x16", None).is_err());+ assert!(RenderImages::image(&mut world, "render:d:8x8:depth", None).is_err());+ }+}diff --git a/systems/frame/src/state.rs b/systems/frame/src/state.rsindex 2f3995b0..254e1030 100644--- a/systems/frame/src/state.rs+++ b/systems/frame/src/state.rs@@ -5,19 +5,11 @@ use super::*;#[cfg(feature = "native")]use crate::store::RowKey;-/// The images cameras draw into, by the name a Handle<Image> field gives them ("render:NAME"), and their sizes (made by-/// raea-runtime-plugins' fields::image; a sprite switches between them by name: raea-sys-sprite's sync_2d).+/// The images cameras draw into, by the name a source gives them ("render:NAME"), and their sizes (made by+/// render_image.rs's RenderImages::image; a sprite switches between them by name: raea-sys-sprite's sync_2d).#[derive(Resource, Default)]pub struct RenderImages(pub BTreeMap<String, (Handle<Image>, (u32, u32))>);-impl RenderImages {- /// A "render:NAME" or "render:NAME:WxH" source's name.- pub fn name(src: &str) -> Option<&str> {- let rest = src.strip_prefix("render:")?;- Some(rest.rsplit_once(':').filter(|(_, sz)| sz.contains('x')).map_or(rest, |(n, _)| n))- }-}-/// A string column that may change frame by frame (raea-runtime-look's keyed_strings) as this frame has it: from/// `{col}s` and `{col}_k` when it changes, `col` when it doesn't (`get` reads a column of the row).pub fn keyed(get: impl Fn(&str) -> Option<V>, col: &str) -> Option<String> {diff --git a/systems/material/src/maps.rs b/systems/material/src/maps.rsindex c737cd9f..23db6bb1 100644--- a/systems/material/src/maps.rs+++ b/systems/material/src/maps.rs@@ -201,17 +201,23 @@ pub fn material(world: &mut World, t: &Tup, inserted: &[Tup], dir: &Path) -> Res};let sam = |prop: &str| own.get(prop).or(all.as_ref());// a UiTexture's image (raea-screen:name@WxH) in any map: the screen image its UI is drawn into, as it is drawn- // (a panel that glows: its UI as the emissive map, so it shows under Solari, which draws no unlit surface)+ // (a panel that glows: its UI as the emissive map, so it shows under Solari, which draws no unlit surface); a+ // camera's image ("render:NAME:WxH", R3F23a) as that camera draws itlet named = world.get_resource::<NamedImages>().map(|n| n.0);- let screen = |world: &mut World, s: &str| named.and_then(|named| named(world, s));+ let screen = |world: &mut World, s: &str| -> Result<Option<Handle<Image>>, String> {+ if s.starts_with("render:") {+ return RenderImages::image(world, s, None).map(Some).map_err(|e| format!("mesh {}: {e}", t.id));+ }+ Ok(named.and_then(|named| named(world, s)))+ };if let Some(s) = src("map") {- m.base_color_texture = Some(match screen(world, &s) {+ m.base_color_texture = Some(match screen(world, &s)? {Some(h) => h,None => cached_map(world, s.clone(), MapKind::Colour, repeat, sam("map"), || map_picture(t, inserted, dir, "map", &s))?,});}if let Some(s) = src("normal_map") {- m.normal_map_texture = Some(match screen(world, &s) {+ m.normal_map_texture = Some(match screen(world, &s)? {Some(h) => h,None => cached_map(world, s.clone(), MapKind::Data, repeat, sam("normalMap"), || map_picture(t, inserted, dir, "normalMap", &s))?,});@@ -227,7 +233,7 @@ pub fn material(world: &mut World, t: &Tup, inserted: &[Tup], dir: &Path) -> Resreturn Err(format!("{}: clearcoat_normal_texture {s}: this raea is built without Bevy's clearcoat textures (raea-sys-material's multi-layer feature, off by default: docs/control.feature FC0a)", t.id));}if let Some(s) = src("mr_map") {- m.metallic_roughness_texture = Some(match screen(world, &s) {+ m.metallic_roughness_texture = Some(match screen(world, &s)? {Some(h) => h,None => cached_map(world, s.clone(), MapKind::Data, repeat, sam("metallicRoughnessMap"), || map_picture(t, inserted, dir, "metallicRoughnessMap", &s))?,});@@ -248,13 +254,13 @@ pub fn material(world: &mut World, t: &Tup, inserted: &[Tup], dir: &Path) -> Res})?);}if let Some(s) = src("ao_map") {- m.occlusion_texture = Some(match screen(world, &s) {+ m.occlusion_texture = Some(match screen(world, &s)? {Some(h) => h,None => cached_map(world, s.clone(), MapKind::Data, repeat, sam("aoMap"), || map_picture(t, inserted, dir, "aoMap", &s))?,});}if let Some(s) = src("emissive_map") {- m.emissive_texture = Some(match screen(world, &s) {+ m.emissive_texture = Some(match screen(world, &s)? {Some(h) => h,None => cached_map(world, s.clone(), MapKind::Colour, repeat, sam("emissiveMap"), || map_picture(t, inserted, dir, "emissiveMap", &s))?,});@@ -465,4 +471,18 @@ mod screen_map_tests {let t = Tup { kind: "mesh".into(), id: "panel".into(), vals };assert!(material(&mut world, &t, &[], Path::new(".")).is_err());}++ /// A camera's image ("render:NAME:WxH", docs/r3f.feature R3F23a) is the texture of a map that names it: the image+ /// that camera draws into, whichever of them names it first.+ #[test]+ fn a_render_image_is_the_texture_of_a_map() {+ let mut world = World::new();+ world.init_resource::<Assets<Image>>();+ let mut vals = BTreeMap::new();+ vals.insert("map".to_string(), V::S("render:fbo:64x32".into()));+ let t = Tup { kind: "mesh".into(), id: "plane".into(), vals };+ let m = material(&mut world, &t, &[], Path::new(".")).unwrap();+ let drawn = RenderImages::image(&mut world, "render:fbo:64x32", None).unwrap();+ assert_eq!(m.base_color_texture, Some(drawn));+ }}diff --git a/systems/three-shader/Cargo.toml b/systems/three-shader/Cargo.tomlindex b9383d27..9521f5c8 100644--- a/systems/three-shader/Cargo.toml+++ b/systems/three-shader/Cargo.toml@@ -10,6 +10,8 @@ description = "three.js's shaders drawn by Bevy (docs/r3f.feature R3F11): a Shadraea-sys-sampler = { path = "../sampler" }# a picture made in code (a data: URL), decoded as a material's map israea-sys-material = { path = "../material" }+# a camera drawing into an image (IntoImage) isn't the scene camera whose tone mapping the shaders follow+raea-sys-frame = { path = "../frame" }image = { version = "0.25", default-features = false }bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "3d_bevy_render"] }# wgsl-in too: naga 30.0.1's glsl-in calls the interpolator module only spv-in or wgsl-in compiles (natively Bevy turnsdiff --git a/systems/three-shader/src/lib.rs b/systems/three-shader/src/lib.rsindex ac4541d1..61311395 100644--- a/systems/three-shader/src/lib.rs+++ b/systems/three-shader/src/lib.rs@@ -369,8 +369,9 @@ pub fn fit_mesh(mesh: &mut Mesh, buffer: Option<&str>, own: &[String]) -> Result}/// Each three shader follows the scene camera's tone mapping, whichever it is this frame: a `display` one's colour is-/// taken back through it, a `linear` one's mapped by it where the camera maps in its materials' shaders.-fn follow_tonemapping(cams: Query<(&Camera, Option<&bevy::core_pipeline::tonemapping::Tonemapping>), With<Camera3d>>, luts: Option<Res<bevy::core_pipeline::tonemapping::TonemappingLuts>>, mut mats: ResMut<Assets<ThreeShader>>) {+/// taken back through it, a `linear` one's mapped by it where the camera maps in its materials' shaders. A camera+/// drawing into an image (R3F23a) isn't the scene camera, though it draws first.+fn follow_tonemapping(cams: Query<(&Camera, Option<&bevy::core_pipeline::tonemapping::Tonemapping>), (With<Camera3d>, Without<raea_sys_frame::camera::IntoImage>)>, luts: Option<Res<bevy::core_pipeline::tonemapping::TonemappingLuts>>, mut mats: ResMut<Assets<ThreeShader>>) {use bevy::core_pipeline::tonemapping::Tonemapping as T;let tm = cams.iter().filter(|(c, _)| c.is_active).min_by_key(|(c, _)| c.order).and_then(|(_, t)| t.copied()).unwrap_or(T::None);let (method, lut) = match tm {