Compare commits

..
8 Commits
Author SHA1 Message Date
shinyobjectz 609a22c9ec Drop the dependencies render-memory's splits left behind (cargo shear, CI's unused-dependencies gate): raea-render's eleven systems crates went with RaeaPlugins to raea-render-plugins, raea-runtime-calls's bevy with raea/ecs to raea-runtime-ecs, raea-sys-material's raea-core-shape with toon to raea-sys-toon. raea-render's cargo-shear ignore goes too: spawn.rs reads a mesh buffer through raea_core_shape::buffer_json now 2026-11-29 16:02:31 -08:00
shinyobjectz 4c25a4263d Engine::open_in: a live engine (re)opened in its slot, the one there let go first (RM2 in one place, docs/render-memory.feature). raea-runtime-export's five opens go through it, so a fed render stepped again in the page's box keeps its AOVs as its first engine did; aov_on takes the engine in place. raea-runtime-export is back under its planned 2000 (LT1 and LX6 hold the rest) 2026-11-29 16:02:31 -08:00
shinyobjectz 2835c1478a Split the five crates render-memory took past 2000 lines, each where it parts cleanly, so the next lane has room (the size and rask gates; the one-time allowance is gone):
- raea-core-tables (core/tables): a row's per-frame tables, from raea-sys-frame (re-exported there as tables)
- raea-runtime-ecs (runtime/ecs): raea/ecs on Bevy's ECS, from raea-runtime-calls (ecs.rs re-exports it)
- raea-sys-toon (systems/toon): toon surfaces and outlines, from raea-sys-material; its shaders keep the embedded path compositions name (raea_sys_material/toon.wesl)
- raea-render-plugins (engine/render/plugins): RaeaPlugins, from raea-render (engine.rs re-exports it as raea_plugins; the imports only it used are gone)
- raea-runtime-kinds (runtime/kinds): the rows of models, panels, decals, plates, fog, fire, splats, mesh sequences and grass, with placement and name_column, from raea-runtime-scene
maps.rs's inline and panel pictures move to maps/pictures.rs (re-exported, 422 lines left)
2026-11-29 16:02:31 -08:00
shinyobjectz ac9e2f9ba6 Fold render-memory's copies into what they copied (the dupes gate, 297/60 back to 293/57): one two-generation cache, raea_core_shape::Generations, for core/shape's meshes and runtime/calls' built Manifolds; swapped maps load their pictures with maps.rs's panel_picture; raea_io_home::write_whole for a file written whole or not at all (the BC7 maps first); spawn_sig(it, swapped) one function, its callers saying which; the store's spawn given its columns. Size allowances taken down to the folded sizes (solid.rs is back under 500) 2026-11-29 16:02:31 -08:00
shinyobjectz 3cd075ae08 Size: render-memory's eight over-limit crates and files allowed once at today's sizes (Shane 11-29, for 0.1.13): the folders hold other lanes' uncommitted GI/RT work, so they're split once that lands 2026-11-29 16:02:31 -08:00
shinyobjectz 0909761d60 raea-sys-memtally in tools/layers.toml: a system, as the layers gate asks 2026-11-29 16:02:31 -08:00
shinyobjectz b589826e7c RM1-RM10: halcyon r109's sequence from killed at 24-25 GB to a 7.8 GB peak (footprint 5.5 GB), the look within run-to-run noise
- RM1: materials' maps and Solari's traced meshes on the GPU only (RAEA_KEEP_CPU_ASSETS=1: the control)
- RM2: a sequence's first 3D engine let go before a second opens
- RM5: JS solids deduplicated by expression, their Manifolds in a two-generation cache (192 MB each); solid.free
- RM6: a map whose picture changes by frame is one part and one material, its picture swapped as frames show it
  (raea-sys-material swapped.rs): the pool's 96 water maps were 96 meshes and 186 textures
- RM7: Manifold shapes welded into indexed meshes (4.65 corners a vertex in halcyon; RAEA_NO_WELD=1: the control);
  a held frame settles to the same picture, boiling 0.30% against 0.38%
- the shape text kept out of the store and the Edit (the engine spawns from the program's rows)
- RM8: a BufferMesh of 64 KB or more kept on disk by its content (buffer:@NAME, raea's caches/buffers):
  shape text 274 MB -> 11.8 MB
- RM9: material maps as BC7 with their mips (intel_tex_2), cached by content in raea's caches/maps, any size
  resampled to whole blocks (RAEA_NO_BC=1: the control): GPU images 733 MB -> 282 MB
- RM10: raea-sys-contact's solids as bytes, a count and u16 surface points: 1.27 GB -> 0.37 GB mid-render
- memtally names the biggest GPU images; RAEA_MEM_MARKS prints the program's text by column and shape call
- tools/memprobe: memseq, heapwho/heapseq (malloc stack logging, holders.py), abenv/abseq/steadyab (A/B on one binary)

docs/render-memory.feature has each step's numbers and gates.
2026-11-29 16:02:31 -08:00
shinyobjectz 64c1e06ea9 RM0: each App's meshes and images, CPU and GPU bytes, after every RAEA_MEM_MARKS mark (raea-sys-memtally); docs/render-memory.feature RM0-RM4 2026-11-29 16:02:31 -08:00
91 changed files with 2539 additions and 2625 deletions

No files matched your search

Generated
+117 -22
View File
@@ -8490,6 +8490,15 @@ dependencies = [
"generic-array",
]
[[package]]
name = "intel_tex_2"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7980d359170e7da4bc2421aa74c49d338a3153313e006d732a3430f1af375a60"
dependencies = [
"ispc_rt",
]
[[package]]
name = "interpolate_name"
version = "0.2.4"
@@ -8573,6 +8582,16 @@ version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
[[package]]
name = "ispc_rt"
version = "2.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a396f76fd253fab9945bb4c6080f515d0c4036bc30219462d199b58886fd37b4"
dependencies = [
"libc",
"num_cpus",
]
[[package]]
name = "itertools"
version = "0.10.5"
@@ -14470,6 +14489,7 @@ version = "0.1.0"
name = "raea-core-shape"
version = "0.1.0"
dependencies = [
"blake3",
"manifold-rust",
"raea-core-fonts",
"raea-core-grow",
@@ -14488,6 +14508,15 @@ dependencies = [
"serde_json",
]
[[package]]
name = "raea-core-tables"
version = "0.1.0"
dependencies = [
"bevy",
"raea-core-program",
"serde_json",
]
[[package]]
name = "raea-core-wire"
version = "0.1.0"
@@ -15029,29 +15058,62 @@ dependencies = [
"raea-gpu-device",
"raea-io-media",
"raea-io-trace",
"raea-render-plugins",
"raea-render-raytrace",
"raea-runtime-gpuframe",
"raea-runtime-plugins",
"raea-runtime-scene3d",
"raea-runtime-view",
"raea-sys-compose",
"raea-sys-compute",
"raea-sys-engine-shaders",
"raea-sys-environment",
"raea-sys-fog",
"raea-sys-frame",
"raea-sys-grass",
"raea-sys-grid",
"raea-sys-hold",
"raea-sys-look",
"raea-sys-matchmove",
"raea-sys-material",
"raea-sys-memtally",
"raea-sys-meshseq",
"raea-sys-page",
"raea-sys-post",
"raea-sys-procmat",
"raea-sys-screen",
"raea-sys-shader",
"raea-sys-splat",
"raea-sys-sprite",
"raea-sys-text3d",
"raea-sys-three-shader",
"raea-sys-toon",
"raea-sys-viewbox",
"serde_json",
"wgpu",
]
[[package]]
name = "raea-render-plugins"
version = "0.1.0"
dependencies = [
"bevy",
"raea-core-program",
"raea-runtime-plugins",
"raea-runtime-scene3d",
"raea-sys-compose",
"raea-sys-compute",
"raea-sys-environment",
"raea-sys-fog",
"raea-sys-fog-half",
"raea-sys-frame",
"raea-sys-framepass",
"raea-sys-gi",
"raea-sys-grass",
"raea-sys-grid",
"raea-sys-hold",
"raea-sys-lod",
"raea-sys-look",
"raea-sys-matchmove",
"raea-sys-material",
"raea-sys-meshseq",
"raea-sys-page",
"raea-sys-parity",
"raea-sys-phase",
"raea-sys-post",
@@ -15065,10 +15127,8 @@ dependencies = [
"raea-sys-sprite",
"raea-sys-text3d",
"raea-sys-three-shader",
"raea-sys-viewbox",
"raea-sys-toon",
"raea-sys-volume",
"serde_json",
"wgpu",
]
[[package]]
@@ -15270,7 +15330,6 @@ name = "raea-runtime-calls"
version = "0.1.0"
dependencies = [
"base64 0.22.1",
"bevy",
"image",
"manifold-rust",
"parley",
@@ -15281,6 +15340,7 @@ dependencies = [
"raea-io-net",
"raea-io-trace",
"raea-native",
"raea-runtime-ecs",
"raea-runtime-plugins",
"raea-runtime-wear",
"raea-sys-fonts",
@@ -15355,6 +15415,14 @@ dependencies = [
"vello",
]
[[package]]
name = "raea-runtime-ecs"
version = "0.1.0"
dependencies = [
"bevy",
"serde_json",
]
[[package]]
name = "raea-runtime-edit"
version = "0.1.0"
@@ -15515,6 +15583,17 @@ dependencies = [
"rquickjs",
]
[[package]]
name = "raea-runtime-kinds"
version = "0.1.0"
dependencies = [
"bevy",
"raea-core-program",
"raea-core-scene",
"raea-runtime-look",
"serde_json",
]
[[package]]
name = "raea-runtime-live"
version = "0.1.0"
@@ -15638,6 +15717,7 @@ dependencies = [
"raea-core-alloc",
"raea-core-animate",
"raea-core-scene",
"raea-core-shape",
"raea-core-wire",
"raea-io-assets",
"raea-io-media",
@@ -15662,6 +15742,7 @@ dependencies = [
"raea-sys-light-meter",
"raea-sys-page",
"serde_json",
"xxhash-rust",
]
[[package]]
@@ -15672,6 +15753,7 @@ dependencies = [
"raea-core-program",
"raea-core-review",
"raea-core-scene",
"raea-runtime-kinds",
"raea-runtime-look",
"raea-runtime-scene2d",
"raea-sys-frame",
@@ -15710,6 +15792,7 @@ dependencies = [
"raea-sys-sampler",
"raea-sys-shader",
"raea-sys-share",
"raea-sys-toon",
"serde_json",
]
@@ -16186,6 +16269,7 @@ dependencies = [
"bevy",
"raea-core-program",
"raea-core-scene",
"raea-core-tables",
"raea-io-media",
"raea-sys-layers",
"raea-sys-shots",
@@ -16359,23 +16443,14 @@ dependencies = [
[[package]]
name = "raea-sys-lightbake"
version = "0.1.0"
dependencies = [
"gltf",
"image",
"parry3d",
"raea-sys-atlas",
"raea-sys-lighttrace",
"rayon",
"serde_json",
]
[[package]]
name = "raea-sys-lighttrace"
version = "0.1.0"
dependencies = [
"bytemuck",
"parry3d",
"pollster 0.4.0",
"raea-gpu-device",
"raea-sys-atlas",
"rayon",
"serde_json",
"wgpu",
]
@@ -16416,9 +16491,11 @@ version = "0.1.0"
dependencies = [
"base64 0.22.1",
"bevy",
"blake3",
"image",
"intel_tex_2",
"raea-core-program",
"raea-core-shape",
"raea-io-home",
"raea-io-net",
"raea-io-trace",
"raea-sys-frame",
@@ -16432,6 +16509,13 @@ dependencies = [
name = "raea-sys-measure"
version = "0.1.0"
[[package]]
name = "raea-sys-memtally"
version = "0.1.0"
dependencies = [
"bevy",
]
[[package]]
name = "raea-sys-mesh"
version = "0.1.0"
@@ -16790,6 +16874,17 @@ dependencies = [
"serde_json",
]
[[package]]
name = "raea-sys-toon"
version = "0.1.0"
dependencies = [
"bevy",
"raea-core-program",
"raea-core-shape",
"raea-sys-frame",
"serde_json",
]
[[package]]
name = "raea-sys-touch"
version = "0.1.0"
+6 -1
View File
@@ -12,6 +12,7 @@ members = [
"core/ease",
"core/fonts",
"core/program",
"core/tables",
"core/scene",
"core/shape",
"core/meshcheck",
@@ -30,6 +31,7 @@ members = [
"systems/phase",
"systems/shader/wgsl",
"systems/sampler",
"systems/memtally",
"systems/parity",
"systems/shader",
"systems/three-shader",
@@ -149,6 +151,7 @@ members = [
"systems/look",
"systems/compose",
"systems/material",
"systems/toon",
"systems/mesh",
"systems/post",
"systems/fog",
@@ -170,6 +173,7 @@ members = [
"tools/perceive",
"engine/render",
"engine/render/raytrace",
"engine/render/plugins",
"engine/render/denoise/bench",
"engine/seedling",
"engine/web",
@@ -189,6 +193,7 @@ members = [
"runtime/bundle/lib",
"engine/shape-web",
"runtime/calls",
"runtime/ecs",
"runtime/shots",
"runtime/wear",
"runtime/canvas",
@@ -203,12 +208,12 @@ members = [
"runtime/sound",
"runtime/look",
"runtime/scene",
"runtime/kinds",
"runtime/scene2d",
"runtime/shared",
"apps/ask",
"apps/lightbake",
"systems/lightbake",
"systems/lighttrace",
"systems/atlas",
"apps/double",
"apps/check",
-22
View File
@@ -1,22 +0,0 @@
Copyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al. All Rights Reserved.
Copyright (c) 2011-2022 Blender Foundation
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-6
View File
@@ -13,12 +13,6 @@ HyperFrames: https://github.com/heygen-com/hyperframes
font rules. The ported files carry a header saying so: sdk/ui/src/html.ts and sdk/ui/src/html/compile.ts, fonts.ts
and runtime.ts. raea renamed the format's runtime names (window.__raea, data-raea-* attributes, the "html" profile).
Cycles: https://github.com/blender/cycles
Copyright 2009-2010 Sony Pictures Imageworks Inc., et al., and 2011-2022 Blender Foundation. BSD-3-Clause
(LICENSES/cycles-BSD-3-Clause.txt). systems/lighttrace's glossy layers (src/glossy.rs and src/wgsl/glossy.wgsl) are
written from its microfacet, Fresnel and sampling code (src/kernel/closure/bsdf_microfacet.h and bsdf_util.h,
src/kernel/sample/mapping.h), in part adapted from Open Shading Language.
muxide: vendor/muxide, MIT OR Apache-2.0 (its LICENSE-MIT and LICENSE-APACHE).
animato (MIT OR Apache-2.0), usvg and resvg (Apache-2.0 OR MIT), mediabunny (MPL-2.0, used unmodified), manifold-rust
+1 -1
View File
@@ -110,7 +110,7 @@ fn shape(expr: &str, out: &Path, meshes: &mut BTreeMap<String, String>) -> R<Val
// a mesh given by its own vertices (a <BufferMesh>, a three.js geometry through raea/r3f): written as it
// is, with its normals and texture coordinates, since it needn't be a closed solid
Some(b) => {
let (t, uv) = raea_core_shape::buffer_tris(b)?;
let (t, uv) = raea_core_shape::buffer_tris(&raea_core_shape::buffer_json(b)?)?;
raea_core_shape::export_tris(&t, uv.as_deref(), &glb, "glb")?;
raea_core_shape::export_tris(&t, uv.as_deref(), &obj, "obj")?;
}
+29 -7
View File
@@ -109,10 +109,26 @@ fn hash_props(m: &Map<String, Value>, h: &mut impl Hasher, take: impl Fn(&str) -
}
}
/// A standard material's maps whose picture a render swaps frame by frame (raea-sys-material's SwappedMaps,
/// docs/render-memory.feature RM6): a change of picture keys the map's column instead of cutting the part's track.
/// The packed roughness and metalness maps are one texture made from two pictures, so they still cut.
pub const SWAPPED_MAPS: [(&str, &str); 5] = [("map", "map"), ("normalMap", "normal_map"), ("metallicRoughnessMap", "mr_map"), ("aoMap", "ao_map"), ("emissiveMap", "emissive_map")];
/// Whether a part's standard material takes its pictures frame by frame in a render (SWAPPED_MAPS): a plain
/// standard or physical surface, none of the surfaces built over it (a grid, paint, wear, a procedural pattern, a
/// shader), whose maps are made into their own material once.
pub fn swaps_maps(it: &Item) -> bool {
let Some(m) = &it.material else { return false };
matches!(&*m.kind, "MeshStandardMaterial" | "MeshPhysicalMaterial")
&& !["grid", "paint", "wear", "procedural", "shader", "toon"].iter().any(|k| m.props.contains_key(*k))
&& !["shader", "three", "surface"].iter().any(|k| it.props.contains_key(*k))
}
/// A part's kept inputs as one number: what its row takes from the frame it's spawned in (its shape, its material's
/// maps and modes, its words and their glyphs, a model's file). Two frames of a part with the same number make the
/// same kept columns.
pub fn spawn_sig(it: &Item) -> u64 {
/// same kept columns. With `swapped`, a swapped map's picture is left out (whether it has one still counts), as a
/// render keys it (SWAPPED_MAPS) rather than cutting the part's track for it; without, every picture counts.
pub fn spawn_sig(it: &Item, swapped: bool) -> u64 {
let mut h = std::collections::hash_map::DefaultHasher::new();
it.kind.hash(&mut h);
match it.kind {
@@ -120,9 +136,14 @@ pub fn spawn_sig(it: &Item) -> u64 {
it.shape.hash(&mut h);
if let Some(m) = &it.material {
m.kind.hash(&mut h);
let swap = swapped && swaps_maps(it);
let picture = |k: &str| swap && SWAPPED_MAPS.iter().any(|(p, _)| *p == k) && m.props.get(k).and_then(Value::as_str).is_some_and(|s| !s.starts_with("render:"));
// a three.js shader's spec is its uniforms and its source, the one keyed and the other its identity
if &*m.kind != "ThreeShaderMaterial" {
hash_props(&m.props, &mut h, |k| !MAT_LIVE.contains(&k));
hash_props(&m.props, &mut h, |k| !MAT_LIVE.contains(&k) && !picture(k));
}
for (p, _) in SWAPPED_MAPS.iter().filter(|(p, _)| picture(p)) {
p.hash(&mut h);
}
}
hash_props(&it.props, &mut h, |k| MESH_KEPT.contains(&k));
@@ -147,7 +168,7 @@ pub fn spawn_sig(it: &Item) -> u64 {
h.finish()
}
/// Tracks cut where a part's kept inputs change: each run of frames with the same spawn_sig is a track of its own
/// Tracks cut where a part's kept inputs change: each run of frames with the same spawn_sig (swapped maps left out) is a track of its own
/// (`ID~1`, `ID~2` after the first), so a render's row never holds one frame's shape or words over another frame's.
pub fn split_kept(tracks: Vec<(String, Vec<Option<Item>>)>) -> Vec<(String, Vec<Option<Item>>)> {
let mut out = Vec::with_capacity(tracks.len());
@@ -161,7 +182,8 @@ pub fn split_kept(tracks: Vec<(String, Vec<Option<Item>>)>) -> Vec<(String, Vec<
let mut runs: Vec<(u64, Vec<Option<Item>>)> = Vec::new();
for (i, slot) in track.into_iter().enumerate() {
let Some(it) = slot else { continue };
let s = spawn_sig(&it);
// a render keys a swapped map's picture (SWAPPED_MAPS) rather than cutting for it
let s = spawn_sig(&it, true);
if runs.last().is_none_or(|(r, _)| *r != s) {
runs.push((s, vec![None; n]));
}
@@ -197,7 +219,7 @@ pub struct KeptInputs {
impl KeptInputs {
pub fn of(it: &Item) -> KeptInputs {
KeptInputs { sig: spawn_sig(it), props: it.props.clone(), mat: it.material.as_ref().map(|m| m.props.clone()), shape: it.shape.clone() }
KeptInputs { sig: spawn_sig(it, false), props: it.props.clone(), mat: it.material.as_ref().map(|m| m.props.clone()), shape: it.shape.clone() }
}
/// Whether `it` has the kept inputs these were taken from; when it has, its props are held from now on.
@@ -210,7 +232,7 @@ impl KeptInputs {
if Arc::ptr_eq(&self.props, &it.props) && held(&self.mat, it.material.as_ref().map(|m| &m.props)) && self.shape == it.shape {
return true;
}
if spawn_sig(it) != self.sig {
if spawn_sig(it, false) != self.sig {
return false;
}
*self = KeptInputs::of(it);
+2
View File
@@ -13,6 +13,8 @@ manifold-rust = "0.16.0"
skrifa = "0.44"
raea-core-fonts = { path = "../fonts" }
serde_json = "1"
# content names for kept BufferMesh text (buffer.rs kept_buffer)
blake3 = "1.8"
# blended distance fields and generators (trees, lofts, terrain, rosettes), meshed then closed into solids
raea-core-sdf = { path = "../sdf" }
raea-core-grow = { path = "../grow" }
+48
View File
@@ -128,6 +128,42 @@ pub fn export_tris(t: &Tris, uvs: Option<&[[f32; 2]]>, path: &str, format: &str)
Ok(bytes.len())
}
/// A <BufferMesh>'s text from this long on is kept on disk and named by its content (kept_buffer).
pub const KEEP_BUFFER_AT: usize = 1 << 16;
/// A long BufferMesh shape (`buffer:{json}`) as `buffer:@NAME`: its JSON written once to raea's caches
/// (buffers/NAME.json, NAME its content's BLAKE3), so what holds the shape holds 40 characters
/// (docs/render-memory.feature RM8). halcyon's palms were 263 MB of vertex arrays as text, held by the React scene,
/// every frame's program row, the store and the evaluator: two of them 51 MB each. None for a short one, one already
/// kept, or when the caches folder can't be written (the text then goes as it is).
pub fn kept_buffer(expr: &str) -> Option<String> {
let json = expr.strip_prefix("buffer:")?;
if json.len() < KEEP_BUFFER_AT || json.starts_with('@') {
return None;
}
let hex = blake3::hash(json.as_bytes()).to_hex();
let name = &hex.as_str()[..32];
let dir = crate::kept::caches()?.join("buffers");
let p = dir.join(format!("{name}.json"));
if !p.exists() {
let part = dir.join(format!(".{name}.{}.part", std::process::id()));
std::fs::create_dir_all(&dir).ok()?;
std::fs::write(&part, json).ok()?;
std::fs::rename(&part, &p).ok()?;
}
Some(format!("buffer:@{name}"))
}
/// A buffer shape's JSON (what follows `buffer:`): its own text, or the kept file `@NAME` names (kept_buffer).
pub fn buffer_json(b: &str) -> Result<std::borrow::Cow<'_, str>, String> {
let Some(name) = b.strip_prefix('@') else { return Ok(std::borrow::Cow::Borrowed(b)) };
if name.len() != 32 || !name.bytes().all(|c| c.is_ascii_hexdigit()) {
return Err(format!("buffer:@{name}: not a kept buffer's name"));
}
let p = crate::kept::caches().ok_or("no caches folder for a kept buffer")?.join("buffers").join(format!("{name}.json"));
std::fs::read_to_string(&p).map(std::borrow::Cow::Owned).map_err(|e| format!("buffer:@{name}: {}: {e}", p.display()))
}
#[cfg(test)]
mod tests {
use super::*;
@@ -160,4 +196,16 @@ mod tests {
assert_eq!((v.len(), i.len()), (18, 6));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_long_buffer_is_kept_by_its_content_and_read_back() {
let pos: Vec<String> = (0..36000).map(|i| format!("{}", i % 7)).collect();
let expr = format!("buffer:{{\"positions\": [{}]}}", pos.join(", "));
assert!(expr.len() > KEEP_BUFFER_AT);
let Some(k) = kept_buffer(&expr) else { return }; // no caches folder here: nothing to check
assert!(k.starts_with("buffer:@") && k.len() == 8 + 32, "{k}");
assert_eq!(kept_buffer(&expr).as_deref(), Some(k.as_str()), "the same text, the same name");
assert_eq!(buffer_json(&k[7..]).unwrap(), &expr[7..]);
assert!(kept_buffer("buffer:{\"positions\": [0, 0, 0]}").is_none(), "a short one stays as it is");
}
}
+60
View File
@@ -0,0 +1,60 @@
//! A cache by key in two generations of at most `cap` bytes each, for what's costly to make and too big to keep all
//! of: core/shape's meshes (`cached`) and runtime/calls' built Manifolds (docs/render-memory.feature). One asked for
//! again moves to the newest generation and stays; one made and never asked for again goes a generation later, so two
//! generations at most are held. An entry's weight is its holder's to say; its key counts too.
use std::collections::HashMap;
pub struct Generations<V> {
now: HashMap<String, (V, usize)>,
old: HashMap<String, (V, usize)>,
/// the newest generation's bytes
bytes: usize,
cap: usize,
}
impl<V: Clone> Generations<V> {
pub fn new(cap: usize) -> Self {
Generations { now: HashMap::new(), old: HashMap::new(), bytes: 0, cap }
}
/// What's held for `key`, in either generation: one from the older is held again in the newest.
pub fn get(&mut self, key: &str) -> Option<V> {
if let Some((v, _)) = self.now.get(key) {
return Some(v.clone());
}
let (v, weight) = self.old.remove(key)?;
self.hold(key, v.clone(), weight);
Some(v)
}
/// `v`, weighing `weight` bytes, held for `key` in the newest generation, which becomes the older one when it
/// would pass the cap.
pub fn hold(&mut self, key: &str, v: V, weight: usize) {
let bytes = weight + key.len();
if self.bytes + bytes > self.cap && !self.now.is_empty() {
self.old = std::mem::take(&mut self.now);
self.bytes = 0;
}
self.bytes += bytes;
self.now.insert(key.to_string(), (v, weight));
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn held_entries_go_a_generation_at_a_time_and_what_is_asked_again_stays() {
// entries of a quarter of a generation each
let mut g = Generations::new(4000);
g.hold("kept", 1u8, 996);
for i in 0..12 {
g.hold(&format!("bar {i:02}"), 1u8, 994);
assert!(g.get("kept").is_some(), "asked each time, it stays (after bar {i})");
}
assert!(g.get("bar 00").is_none(), "made once and never asked again, it went");
assert!(g.now.len() + g.old.len() <= 8, "two generations at most: {} + {}", g.now.len(), g.old.len());
}
}
+1 -1
View File
@@ -10,7 +10,7 @@ use std::path::PathBuf;
/// raea's caches folder, as raea-io-home names it (this crate is below it): ~/Library/Caches/raea on macOS,
/// %LOCALAPPDATA%\raea\cache on Windows, $XDG_CACHE_HOME/raea or ~/.cache/raea elsewhere.
fn caches() -> Option<PathBuf> {
pub(crate) fn caches() -> Option<PathBuf> {
let base = PathBuf::from(std::env::var_os(if cfg!(windows) { "LOCALAPPDATA" } else { "HOME" })?);
if base.as_os_str().is_empty() {
return None;
+12 -48
View File
@@ -34,9 +34,12 @@ mod kept;
mod mesh;
mod parse;
mod sphere;
pub mod generations;
pub use generations::Generations;
pub use sphere::{SphereOf, cuboid_of, cylinder_of, plane_of, sphere_of};
pub use buffer::{buffer_tris, export_tris};
pub use buffer::{buffer_json, buffer_tris, export_tris, kept_buffer, KEEP_BUFFER_AT};
pub use mesh::{export, from_mesh, read_glb, read_obj, to_mesh};
use std::collections::HashMap;
@@ -211,47 +214,22 @@ const KEEP_MS: f64 = 2.0;
/// and the end checks once more.
const GEN_BYTES: usize = 16 << 20;
/// The shapes held, the newest generation and the one before, and the newest's bytes.
#[derive(Default)]
struct Held {
now: HashMap<String, std::sync::Arc<Tris>>,
old: HashMap<String, std::sync::Arc<Tris>>,
bytes: usize,
}
impl Held {
fn get(&mut self, expr: &str) -> Option<std::sync::Arc<Tris>> {
if let Some(t) = self.now.get(expr) {
return Some(t.clone());
}
let t = self.old.remove(expr)?;
self.hold(expr, &t);
Some(t)
}
/// `t` held for `expr` in the newest generation, which becomes the one before when it would pass GEN_BYTES.
fn hold(&mut self, expr: &str, t: &std::sync::Arc<Tris>) {
let bytes = (t.positions.len() + t.normals.len()) * 12 + expr.len();
if self.bytes + bytes > GEN_BYTES && !self.now.is_empty() {
self.old = std::mem::take(&mut self.now);
self.bytes = 0;
}
self.bytes += bytes;
self.now.insert(expr.to_string(), t.clone());
}
/// What a mesh weighs as it's held: its positions and normals.
fn tris_bytes(t: &Tris) -> usize {
(t.positions.len() + t.normals.len()) * 12
}
/// The mesh for an expression, built once per expression (a re-cut or a key that doesn't change the shape costs nothing).
pub fn cached(expr: &str) -> Result<std::sync::Arc<Tris>, String> {
static CACHE: OnceLock<Mutex<Held>> = OnceLock::new();
let cache = CACHE.get_or_init(Default::default);
static CACHE: OnceLock<Mutex<Generations<std::sync::Arc<Tris>>>> = OnceLock::new();
let cache = CACHE.get_or_init(|| Mutex::new(Generations::new(GEN_BYTES)));
if let Some(t) = cache.lock().unwrap().get(expr) {
return Ok(t);
}
// a buffer mesh's own triangles (buffer.rs): data already, so nothing is kept on disk for it
if let Some(b) = expr.strip_prefix("buffer:") {
let t = std::sync::Arc::new(buffer_tris(b)?.0);
cache.lock().unwrap().hold(expr, &t);
let t = std::sync::Arc::new(buffer_tris(&buffer_json(b)?)?.0);
cache.lock().unwrap().hold(expr, t.clone(), tris_bytes(&t));
return Ok(t);
}
// made by this build before, on disk (kept.rs): read back as it was written
@@ -267,7 +245,7 @@ pub fn cached(expr: &str) -> Result<std::sync::Arc<Tris>, String> {
t
}
};
cache.lock().unwrap().hold(expr, &t);
cache.lock().unwrap().hold(expr, t.clone(), tris_bytes(&t));
Ok(t)
}
@@ -275,20 +253,6 @@ pub fn cached(expr: &str) -> Result<std::sync::Arc<Tris>, String> {
mod tests {
use super::*;
#[test]
fn held_shapes_go_a_generation_at_a_time_and_what_is_asked_again_stays() {
let mut h = Held::default();
// a shape of a quarter of a generation
let t = std::sync::Arc::new(Tris { positions: vec![[0.0; 3]; GEN_BYTES / 96], normals: vec![[0.0; 3]; GEN_BYTES / 96] });
h.hold("kept", &t);
for i in 0..12 {
h.hold(&format!("bar {i}"), &t);
assert!(h.get("kept").is_some(), "asked each time, it stays (after bar {i})");
}
assert!(h.get("bar 0").is_none(), "made once and never asked again, it went");
assert!(h.now.len() + h.old.len() <= 8, "two generations at most: {} + {}", h.now.len(), h.old.len());
}
#[test]
fn a_kept_mesh_reads_back_as_it_was_written() {
let dir = std::env::temp_dir().join(format!("raea-shape-kept-{}", std::process::id()));
+12
View File
@@ -0,0 +1,12 @@
[package]
name = "raea-core-tables"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "A row's per-frame tables: the column sets that change from frame to frame (a frame's look, the camera's post-processing, a light's), laid onto the row frame by frame"
[dependencies]
raea-core-program = { path = "../program" }
bevy = { version = "=0.20.0", default-features = false, features = ["std"] }
serde_json = "1"
File renamed without changes.
+10 -149
View File
@@ -22,9 +22,9 @@ Feature: Light baked by raea: bounce light into lightmaps on raea's own ray trac
2. What is baked is the light that bounces: the sky, emissive surfaces and the lights marked baked, through every
bounce, plus the sun's bounce. The sun's direct light stays live (as lightbake.py subtracts it), so anything
that moves still casts its shadow and is lit as before.
3. It runs on wgpu ray queries (Metal on Apple silicon's ray hardware, Vulkan, DX12), over a BLAS and TLAS the bake
builds from the meshes raea draws, not systems/rt's (BK3 says why). Every OS raea ships on; never Mac-only. A
device without ray queries is told so, with the reason, and the composition renders unbaked.
3. It runs on systems/rt: the same BLAS and TLAS the traced shadows and raea GI read, through wgpu ray queries
(Metal on Apple silicon's ray hardware, Vulkan, DX12). Every OS raea ships on; never Mac-only. A device without
ray queries is told so, with the reason, and the composition renders unbaked.
4. Shading is Cycles', from tools/cycles-port (each function held to Cycles' own output), so the bake and the
reference agree by construction, and LT5's path tracer (docs/realism.feature) reuses the same kernel.
5. It lights raea's own meshes (Mesh3d, solids, raea/room) directly, as well as a <Model>'s, with no export.
@@ -32,7 +32,6 @@ Feature: Light baked by raea: bounce light into lightmaps on raea's own ray trac
Background:
Given systems/rt (raea-sys-rt): BLAS per mesh from Bevy's own buffers, a TLAS of visible opaque instances,
glass left out so sky and sun reach through windows; its traced AO, raea GI's world probes and cache (LT2, LT3)
And raea-sys-lighttrace, the kernel of BK3, split from the bake so systems/rt and LT5's path tracer can build on it
And tools/cycles-port/cycles_bsdf.wgsl: GGX/Beckmann D, G2, Fresnel, F82 conductors, VNDF sampling, passing against
Cycles on an M5 Pro; diffuse and energy-conserving Oren-Nayar next
And <Lightmap> (sdk/render/src/bevy3d/lightmap.tsx, systems/material lightmap.rs): Bevy's lightmap on a <Model>'s
@@ -148,8 +147,7 @@ Feature: Light baked by raea: bounce light into lightmaps on raea's own ray trac
And built 11-23: `raea_sys_lightbake::texels::texels(glb, request)` lays the model out (BK1's layout, raea_sys_atlas::laid; the
light-only request is `request(texels, max_side)`, a worn model passes its wear bake's), takes
the model's world triangles as the parry3d BVH the atlas was laid out over, moves each point
off its surface by 1e-6 of the model's size or farthest coordinate (at least a micron; 1e-5 and 10 until BK3 found
what it costs), and casts 16
off its surface by 1e-5 of the model's size or farthest coordinate (at least 10 microns), and casts 16
cosine-weighted rays from each: a texel is inside when at least half its rays meet a back face and more meet
back faces than front ones (a floor that is one plane is met from below one way and not at all the other).
CPU and rayon for now, as weathering's own rays; BK3's GPU pass may take the test over
@@ -180,15 +178,10 @@ Feature: Light baked by raea: bounce light into lightmaps on raea's own ray trac
Scenario: BK3. The light that bounces, traced on raea's ray tracer
Given the plan
| crate | file | lines | job |
| raea-sys-lightbake | systems/lightbake/src/trace_tests.rs | 240 | a white furnace, a wall's form factor, a glowing box, a red wall's bleed, the sun at a texel and at a hit, a panorama's direction, a ray straight up, a textured floor, the same bytes twice; the measured run |
| raea-sys-lightbake | systems/lightbake/src/own.rs | 185 | a model read on its own second UVs (a map a mesh, as lightbake.py lays them): its world triangles, base colour and textures, and each map's texels |
| raea-sys-lightbake | systems/lightbake/src/own/tests.rs | 150 | its texels on a known quad; the ignored run against a Cycles bake of the same .glb |
| raea-sys-lighttrace | systems/lighttrace/src/wgsl/diffuse.wgsl | 40 | the diffuse BSDF and the paths' random numbers, a module systems/rt and LT5's path tracer can include as it is |
| raea-sys-lighttrace | systems/lighttrace/src/glossy.rs | 130 | GGX on the CPU (Cycles'), and the table of a rough lobe's albedo the kernel reads |
| raea-sys-lighttrace | systems/lighttrace/src/wgsl/glossy.wgsl | 130 | a metal's and a dielectric's layers over Lambert: weights, evaluation, sampling |
| raea-sys-lighttrace | systems/lighttrace/src/tests.rs | 130 | white surfaces keep all their light; the sun and a panel off a floor against a CPU sum |
| raea-sys-lighttrace | systems/lighttrace/src/lib.rs | 265 | the passes: dispatch per atlas, samples accumulated over passes, progress, cancel |
| raea-sys-lighttrace | systems/lighttrace/src/wgsl/trace.wgsl | 250 | per texel: cosine-weighted paths against the bake's own TLAS; the sky from the composition's <Environment>, emissives, baked lights; Russian roulette; Cycles' BSDFs from cycles-port at each bounce |
| raea-sys-lightbake | systems/lightbake/src/trace/tests.rs | 160 | a white furnace, a wall's form factor, a glowing box, a red wall's bleed, the same bytes twice; the measured run |
| raea-sys-lightbake | systems/lightbake/src/wgsl/diffuse.wgsl | 60 | the diffuse BSDF and the paths' random numbers, a module systems/rt and LT5's path tracer can include as it is |
| raea-sys-lightbake | systems/lightbake/src/trace.rs | 260 | the passes: dispatch per atlas, samples accumulated over passes, progress, cancel |
| raea-sys-lightbake | systems/lightbake/src/wgsl/trace.wgsl | 320 | per texel: cosine-weighted paths against the bake's own TLAS; the sky from the composition's <Environment>, emissives, baked lights; Russian roulette; Cycles' BSDFs from cycles-port at each bounce |
Then each texel integrates the incoming diffuse light over its hemisphere along paths of up to `bounces`
(default 4) through a BLAS and TLAS the bake builds itself from the meshes raea draws, by the wgpu ray queries
systems/rt uses. (Not rt's own: a bake runs offline, before any frame, with no Bevy render world to hold them,
@@ -199,126 +192,6 @@ Feature: Light baked by raea: bounce light into lightmaps on raea's own ray trac
the cause maps (sdk/wear), so a grimy brick wall bounces grimy brick. The kernel evaluates them from one WGSL
module shared with the raster, not a copy (Shane, 11-23); Blender's export drops these materials, so this is
a bake Cycles' round trip can't make
And what a module must take as arguments to be shared, read from the three sources 11-23 (nothing built): a
compute kernel has no screen derivatives, no implicit-level texture reads and no eye
| what the raster uses | where | what the kernel gives |
| fwidth of the normal over the position's (edges) | procmat.wesl, worn.ts | the turn of the triangle's vertex normals over its edges |
| fwidth of the plane, fading fine threads | procmat.wesl (fabric, brushed) | the hit's texel size |
| a pixel's size (cracks no thinner than one) | sdk/wear index.ts, wear_geo's px | the hit's texel size |
| textureSample of the four cause maps | sdk/wear causes.ts | textureSampleLevel, level 0 |
| the eye, for the parallax behind lost render | sdk/wear causes.ts, wear_geo | the normal (no parallax: a bounce has no one eye) |
| metallic, which the marks also change | worn.ts; iron, zinc, copper, brass | the bounce is base colour x (1 - metallic) |
| u_NAME(), tex_NAME, samp_NAME, from the hook | systems/shader's module() | the same names over the kernel's own bindings |
And systems/procmat's module is written as systems/procmat/src/drawn.wesl, not compiled or used yet; procmat.wesl
takes it, its own copy deleted, in the commit that builds it, with a frame before and after held to the same
bytes (fabric and brushed to one step of 8 bits: their scale moves outside the derivative). WearExtension and raea/wear are text made in TypeScript (worn.ts, sdk/wear), so the kernel gets theirs
from the composition's material, not from a file
And the atelier's static set is traced and held to the Cycles bake its own agent made of it (lightbake.py; the
eighth bake read 11-23: 202 meshes of one primitive, 699 902 triangles, 198 maps of 128-1024 a side), as soon as
the trace can: each mesh's map against Cycles' by map_stops, with its time and memory. Its light is a panorama (strength
0.366, rotation 2.449 in the blend its bake used), one sun and no lamps
And measured 11-23 on the M5 Pro, in progress: own.rs reads the .glb on its own second UVs, the .glb's positions
and second UVs being equal in every bake compared. Cycles 512 samples, 56 texels a metre, smooth 2; the trace
1024 samples, 4 bounces, with no fitted gain; 2 358 922 texels of 198 meshes, the same in every row. "biased" is
meshes whose mean signed error is over 1/3 stop; light is total over total. Rows 1-4 and 6 bake the scene with
every material plain diffuse (base colour x (1 - metallic)), unclamped, in a scratch copy, so the trace and
Cycles differ only in the tracing
| compared | mean stops | bias | light | over 1/3 | biased |
| noise: Cycles / Cycles, another seed | 0.161 | -0.001 | 1.000 | 54 | 2 |
| Cycles' clamp 3 / no clamp | 0.017 | -0.017 | 0.963 | 5 | 5 |
| materials: Cycles diffuse-only / real, no clamp | 0.284 | -0.272 | 0.863 | 132 | 128 |
| trace / Cycles, diffuse-only, no clamp | 0.218 | -0.064 | 0.994 | 94 | 46 |
| trace / Cycles, real materials, no clamp | 0.389 | -0.336 | 0.857 | 157 | 140 |
| trace / the atelier's own bake (clamp 3) | 0.384 | -0.319 | 0.889 | 155 | 135 |
And what they say: on matched materials the trace's total light is within 0.6% of Cycles' and the floor, deck,
walls and door are within 0.02 stops at the median. 14% of the light is the metals' and speculars' bounces, so
GGX and F82 were needed (built, below). The 46 "biased" meshes are not an
error of the trace's, except 5 of them (4 the footprint's, bench_strips the offset's): that count is by mean log error on smoothed maps and it drops texels
where one side is 0. By each mesh's total light, zeros counted and no smoothing, 8 of 198 are over 1/3 stop (Cycles
against itself, smoothed: 1, and 95% of meshes within 0.05). Time: the trace 17-25 s, 10 s at 256 samples and
119 s at 4096, peak 1.2 GB, setup 70-200 s in a debug build; Cycles' diffuse-only bake 5m33s, 2.7 GB, the
atelier's own 5m36s, 3.4 GB for its whole script
And the 8, by the trace's light over Cycles': 4 are the footprint. The trace starts every ray at the texel's
centre, and Cycles jitters its samples over the texel; on 30 mm texels a sheet's 6 mm ledge is all or nothing.
Traced 8x8 points a texel and averaged, over the same texels: bench_stock 0.333 -> 0.960, bench_mat 1.333 ->
1.006, dt_ledge 1.291 -> 0.997, dt_rule 0.765 -> 1.068; bench_strips only 0.616 -> 0.679 (the offset, below). Built after it:
a texel starts from the open ones of 16 points over its footprint (on its triangle, clear of its edges, not
inside other geometry, as BK2's rays judge them), so a partly buried texel is lit by what can be seen of it. A texel
under a sheet's edge, three quarters of it covered, reads 0.2495 for 0.249 where its centre alone reads 0; one
three quarters inside a block reads 0.52 from its open quarter
And 3 are the reference's (mug_coffee, books_5 and tower_base): Cycles' adaptive sampling (on by default, threshold 0.01; lightbake.py doesn't turn
it off) stops a dark pocket's pixel before it has seen the light, so a cup or a shelf's back bakes too dark. With
it off (1024 samples, the same meshes, raw floats): mug_coffee 1.94 -> 1.012, books_5 1.279 -> 1.021, meet_tea
1.216 -> 1.030, tower_base 1.183 -> 1.040, books_0 1.199 -> 1.072. Neither the sun's subtraction nor the PNGs'
16-bit clipping (0.92-1.05 of the raw floats) nor the sheets' gaps (a fixture of sheets 0.05-5 mm apart: both
black at 0.2 mm) explain it. BK0's own references were baked the same way
And against the honest reference, measured 11-23 with jittered starts, a release build: Cycles' diffuse-only atelier
with adaptive sampling off, unsmoothed, unclamped, 512 samples, raw floats (12m49s against 3m55s with it on, the
same scene), by each mesh's total light, zeros counted; the trace 1024 samples, 4 bounces. (Cycles' own second
seed, smoothed, is over 1/3 stop on 1 of 198.) The atelier's own bakes were made with adaptive sampling on
| a texel's samples start from | over 1/3 stop | over 1/10 | total light |
| the open part of it (what the bake does) | 3 of 198 | 21 | 0.997 |
| all of it, buried points too (as Cycles averages) | 1 of 198 | 10 | 0.993 |
| the open part, at the offset below | 1 of 198 | 15 | 1.000 |
| all of it, at the offset below | 0 of 198 | 5 | 0.995 |
They differ where a texel is partly buried: Cycles' average counts the dark inside, so it bakes such a texel darker
than what can be seen of it; the bake keeps the open part. Left, over the whole footprint: bench_stock 1.188,
site_base, site_contours, house_base and house_roof about 1.10, bench_strips 1.068; not explained
And the offset was bench_strips: rays started 1e-5 of the model's size off a surface, 0.15 mm in the atelier, whose
strips are stacked 0.2 mm apart, so a ray had 0.05 mm of each gap and the sun's first half millimetre in it was
lost. By offset (bench_strips, lamp_shade_in, dt_tape; whole footprint, over Cycles'): 0.15 mm 0.558, 1.376,
0.865; 50 microns 0.638, 1.117, 0.954; 20 1.007, 1.049, 0.980; 10 1.063, 1.022, 0.989; 2 1.059, 1.002, 0.997. It is
1e-6 now. No ray off a tilted plane meets it, from the texel or from a bounce, down to 3e-7 of its distance from
the origin (1 m to 5 km); the first do at 1e-7, on Metal. Vulkan and DX12 haven't run it. A fixed 0.1 mm under a
40 km floor does meet it (0.8% of the light lost)
And the times: setup in release, the atelier's own .glb 12.8 s to read and lay out, 2 992 000 texels on
its own UVs, and 16.7 s to trace 1024 samples, peak 1.5 GB. On the atlas bake of BK2 (64 texels a metre): the table
set 0.85 s with its texels, 0.84 s to trace 512 samples (1.5 M texels), and the atelier 19.9 s and 8.5 s (4.3 M texels).
Other sessions were rendering. The bar is 60 s on the table set, all in: not yet timed with reading,
cleaning (BK4) and writing in it. The 16-ray probe on the CPU is fast enough there, and 20 of the atelier's 28 s
And each bounce goes on by the surface's glossy layers over Lambert, as Cycles' Principled does: a metal (GGX, F82
with a white tint) and a dielectric of IOR 1.5 at Specular 0.5, what a rough lobe loses given back from a table
glossy.rs makes. GGX, its sampling and the Fresnels are Cycles' formulas (bsdf_microfacet.h, bsdf_util.h,
mapping.h at 6ea3d9bcd81a: BSD-3-Clause, in NOTICE, not Apache-2.0), written in systems/lighttrace until
tools/cycles-port is on main and then swapped for its functions; three cases of its oracle are copied into the
tests (D, G, lambda, the visible-normal sample). Filter glossy is Cycles' default 1: after a texel's diffuse turn a
lobe's alpha is at least 0.41. Held to a CPU sum: the sun off five surfaces within 0.03%, a panel found by the
paths' own turns within 0.6%, white surfaces keep 0.997-0.9998 of their light
And against Cycles' real materials, adaptive sampling off (unclamped, unsmoothed, 512 samples, 15m02s, peak 2.7 GB;
all 202 materials MULTI_GGX, IOR 1.5, Specular 0.5), the trace 1024 samples, 4 bounces, by each mesh's total light
| the trace | over 1/3 stop | over 1/10 | total light | time |
| Lambert only, the whole of a texel | 108 of 198 | 190 | 0.858 | 20.3 s |
| glossy layers, the whole of a texel | 0 of 198 | 5 | 0.997 | 22.1 s |
| glossy layers, its open part (what the bake does) | 1 of 198 | 16 | 1.002 | 18.1 s |
Off most over the whole: bench_stock 1.166 and the dim house, site and roof models 1.08-1.10, not explained; over
the open part: meet_sheet_0 1.325. (Other sessions' renders ran beside these.)
And where the energy table is read is ours: at the blurred alpha, so a blurred lobe keeps its light; Cycles reads it at
the material's own alpha, before the blur. Measured, the trace's light over Cycles' for ours, then Cycles' way:
all meshes 0.9972, 0.9952; the 36 with any metal 1.0021, 1.0002; the 17 of metallic 0.5 and over 0.9997, 0.9974.
Cycles' way is darker by at most 3.4% on one mesh (mug_coffee); the mean error a mesh is 0.0177 and 0.0175 stops
And trace() refuses a texel without the samples asked for, or light that isn't finite
And a picture a material reads that isn't there is refused by lightbake.py and look.py before they write (Cycles draws
it magenta and bounces it: a first reference made from a copy without its textures was 6 times too bright and is
discarded). They also have --no-adaptive, not the default. Both files are another lane's, not on main
And the trace's own indirect clamp is gone: at 3 it kept 0.869 of Cycles' light at the same clamp where unclamped
it keeps 0.994 (Cycles' own clamp keeps 0.963), so it was not Cycles' clamp. A bake is unclamped
And a ray straight up gave a non-finite value on Metal (a panorama's longitude, atan2(0, 0)), one texel of the
atelier at 1024 samples; a test casts 134 million of them
And that comparison is read knowing what the reference is: Cycles' own materials as the .glb has them, not raea's
drawn ones (the export drops uv_transform, _arm maps and tints; 39 materials are metal, which Cycles reflects
and Lambert here doesn't); clamped at 3, smoothed twice, its maps' light only where Cycles has some. Cycles'
map times its scale is the mean incoming light, as the trace's is, so the two are compared with no fitted gain
And a <ShaderExtension> a user wrote can't run in the kernel in general (its hook reads Bevy's PbrInput, the view
and its own textures): it bounces its base colour, and `raea bake light` names each material it did that for
And raea/wear's caused wear (touch, edges, cavity, run-off's stains and deposits, sun fade, soot, crumbling, age and
neglect) comes from the baked cause maps and the scene's settings, the same every frame, and bounces as any other
albedo does. Only its per-frame layer over that (wx: wet, snow, storm, ice; season: damp, dust, leaves, melt) is
not the surface's own, and the bake bounces it at the values the composition gives; with no weather given it
bakes dry (decided 11-23; BK5's key)
# Considered and not taken 11-23: drawing each material into the atlas in texture space, which would give a user's
# shader too but needs a Bevy render in the bake.
And the bounce matches the frame: the season's values are those wearShader draws, so "dry" is wx all 0 with the
season as drawn (with no weather given that is day 172, whose dust is 0.595, kept in the bake; decided 11-23)
And the sky is the composition's <Environment> panorama at its intensity and rotation; emissive surfaces light
the set; the sun's direct light is left out at the first hit and kept at every later bounce (so a sunlit floor
lights the ceiling), and a light marked `bake` is carried whole
@@ -334,10 +207,8 @@ Feature: Light baked by raea: bounce light into lightmaps on raea's own ray trac
reads 2.004 for 2; breaking the cosine, the offset, the roulette, its weight, the emission or their order each
fails one of them. Only Metal has run it. At 512 samples and 4 bounces, every surface 0.7 grey under a white
sky, the trace alone takes 0.8 s on the table set, 0.3 s on the Cornell box and 0.9 s on the window room
(M5 Pro; linear in samples, 5.6 s at 4096). Built since: the panorama
with its strength and rotation, the sun at later hits by shadow rays and out at the first, base colour textures.
Not built: baked lights, and the albedo raea draws under procmat, wear and sdk/wear; a metallic-roughness texture
(a material's factors only) and smooth normals at a hit (the triangle's own)
(M5 Pro; linear in samples, 5.6 s at 4096). Not built: the <Environment> panorama, baked lights, the sun left
out at the first hit, textures, and the albedo raea draws under procmat, wear and sdk/wear
@needs:BK3
Scenario: BK4. A clean map: denoised, dilated, no seams
@@ -363,18 +234,8 @@ Feature: Light baked by raea: bounce light into lightmaps on raea's own ray trac
| @raea/render | sdk/render/src/bevy3d/lightbake.tsx | 120 | <LightBake samples bounces texels> around the static parts it bakes; re-exported from raea/3d |
Then `<LightBake>` around a composition's static parts bakes them on the first frame a render, a play or a
`render --at` needs it, and every later frame and run reads the kept bake
And the BLAS come from the composition's own mesh data (Mesh3d, solids and room parts with their transforms, a
<Model>'s meshes), never from a re-export
And it lights raea's own Mesh3d, solids and raea/room parts in place, as well as a <Model>'s meshes, so the
parts stay parts: `raea scene lint`, `raea render --review` and `raea make` see each one, not one baked model
And the key holds each worn material's wear settings (age: years, soot, upkeep), its cause maps and its weather
and season values (wx, season), so each combination bakes once, when it's first used, and is kept; with no
weather given it bakes dry (wx 0, the season as wearShader draws it)
And a weather or season animated over the shot bakes once, at its values on the composition's first frame with the
<LightBake> in it, whichever frame is rendered first (so `render --at` and a full render read one bake and a
frame has one look); it isn't refused and isn't baked each frame, and the bake's report and `raea bake light`
name the values used and say the weather moves over the shot (decided 11-23)
# Not built, a later scenario: two bakes, at the start and the end of a weather change, mixed by its uniform.
And a change to a static part, a material, the sky or a setting changes the key and bakes again; a change to
anything outside <LightBake> (the camera, a moving part, the sun's direct light) doesn't
And `raea bake light EDIT.tsx` bakes ahead of a render and says what it baked (meshes, texels, samples, time)
+169
View File
@@ -0,0 +1,169 @@
@spec
Feature: Render memory: a realistic set renders well under 16 GB
Shane, 2026-11-26, as memguard's 24 GB cap killed the halcyon reel's shots one after another: "why are those renders
so big... how do we keep them down?". Shots of a realistic set ran at 20.5-22.7 GB all morning, with no single
regression: any small addition tipped one over the cap.
Why: raea's brand is local work on consumer hardware, a 16 GB Mac first. A render that needs 24 GB can't run there at
all, and on a 64 GB machine it leaves no room for a second job.
The model this file sets:
1. Memory is cut at the cause: a copy nobody reads after it was made is not made, or is let go once read. Nothing
here changes what a frame looks like: every step is checked frame for frame against the binary before it.
2. Every step is measured on the same probe, the halcyon reel's shot r109 (a walkway, a door, a bicycle; no pool
water), as a still (frame 106) and as a sequence, with tools/memprobe (macOS `footprint` by category) and raea's
own marks (RAEA_MEM_MARKS), on a binary built from the same tree with and without the step.
3. The measures stay: RAEA_MEM_MARKS prints each world's meshes and images with the bytes they hold on the CPU and
on the GPU, so a copy that comes back shows up as a number, not as a killed render.
Background:
Given the halcyon motel project (~/Documents/raea/raea/projects/halcyon-motel, compositions/reel.tsx, shot-r109)
And tools/memprobe/memprobe.sh (a still) and memseq.sh (a sequence), run under antsy with --mem 20G
And the numbers of 11-26 on the 11-25 binary: the still peaks at 14.9 GB (malloc large 6.4, malloc small 4.3,
graphics 3.9); the sequence opens its 3D at 10.3 GB of graphics and is killed at 24-25 GB before frame 0
Rule: the bar
The r109 sequence peaks under 16 GB of footprint and the still under 9 GB, with the same frames as before.
@done
Scenario: RM0. Each world's assets after every mark
Given the plan
| crate | file | lines | job |
| raea-sys-memtally | systems/memtally/src/lib.rs | 140 | after each mark (raea-render's `mem_mark`) one `mem_assets` line per App: its main world's meshes, images and storage buffers with their CPU bytes, its render world's meshes and images with their GPU bytes |
When a render runs with RAEA_MEM_MARKS=1
Then each mark is followed, at each App's next update, by "mem_assets app N main: meshes M (K on the CPU) X MB,
images ... MB, buffers ... MB" and "mem_assets app N render: meshes M X MB, images M Y MB"
And the Apps are numbered in the order they opened, so a sequence that holds two 3D worlds shows two
@needs:RM0 @done
Scenario: RM1. Meshes and maps on the GPU only, once nothing on the CPU reads them
Then a mesh raea builds (systems/mesh, its indexed buffers, meshseq) and a material's maps (systems/material maps.rs)
keep no main-world copy after they are uploaded, where nothing in the main world reads them after: their bounds
are taken at spawn, and picking, the end checks' clipping, raea-sys-contact, LOD and Solari's traced copy are
each checked to read what they need first
And Solari's traced copy of a mesh is made from the CPU copy before that copy is let go, or the mesh is built in
Solari's layout from the start so one mesh serves both (engine/render/raytrace/src/solari.rs traceable)
And the mem_assets lines show the main world's image bytes near zero once the scene has settled (r109: 19.5 MB,
9 of 87 images, all of them pictures raea-sys-sampler and the page read back)
And a mesh raea builds keeps its main-world copy, because main-world systems read meshes after their first frame:
picking (runtime/input pick.rs), a render's layers (systems/frame layer.rs), toon hulls (systems/material
toon.rs), the screen's UVs, sprite3d, and the GI lane's emitters and cells (systems/rt). What it keeps is welded
(RM7): r109's 618 meshes on the CPU hold 198 MB, where the 11-25 build's held 1.38 GB. Solari's traced copy
(traceable's Copy) is on the GPU only
@needs:RM0 @done
Scenario: RM2. One 3D world at a time in a sequence
Then a render never holds two 3D engines at once: where a camera in a page element makes the 3D's rows be stepped
again (runtime/export render.rs, fed.rs), the first engine is let go before the second opens
And the mem_assets lines of a sequence show one 3D App's render world at a time (r109's sequence: app 0 alone)
@needs:RM0
Scenario: RM3. The growth while a frame settles
Then the CPU heap's growth while a held frame settles (about 350 MB/s, still and sequence alike) is found and cut
And the still's footprint after its frame is written is within 10% of its footprint after warm-up
@needs:RM0
Scenario: RM4. A texture whose path changes each frame is let go
Then a texture a frame names (halcyon's pool: water/n-NN.png, g-NN.jpg, 96 of each) is let go, CPU and GPU, once
no part shows it, so a sequence holds the frames in view and not every frame it passed
And a pool shot's sequence (its caustics) holds as many textures at its last frame as at its first
# 11-26, later: Shane widened the goal ("reduce rendering memory footprint as much as possible ... no boiling and
# amazing rendering realism ... the fastest, best looking, most efficient rendering engine for gametime performance
# and film rendering performance"), the halcyon motel as the benchmark. The scenarios below RM4 carry it on; each is
# measured on the same probes, and none may move the look or add boiling (raea light steady under 1.5%).
Rule: the measured state, 11-26 (r109, 1080x1920)
| build | still peak | sequence peak | main-world maps | main-world meshes |
| 11-25 frozen | 14.9 GB | killed at 24-25 GB before frame 0 | 2.4 GB | 1.38 GB |
| RM1 | 14.6 GB | 16.1 GB, all 107 frames written | 0.02 GB | 0.56 GB |
| RM1+RM5+RM6 | | 11.4 GB; 93 images (was 277), GPU 3.7 GB (was 5.5) | 0.02 GB | |
| + RM7 weld, shape text out of the store | | 10.2 GB (footprint 7.1 GB), 0 errors | 0.02 GB | 0.20 GB (618 of 1226 meshes) |
| + RM8 kept buffers | | 8.8 GB (footprint 6.7 GB), 0 errors; shape text 11.8 MB (was 274) | 0.02 GB | 0.20 GB |
| + RM9 BC7 maps | | 8.4 GB (footprint 5.7 GB), 0 errors; GPU images 282 MB (was 733) | 0.02 GB | 0.20 GB |
| + RM10 contact solids | | 7.8 GB (footprint 5.5 GB), 0 errors, the same findings | 0.02 GB | 0.20 GB |
The pool's caustics shot (196 frames), from before RM6 to the weld build: peak 18.8 GB to 9.9 GB, every 8th frame
within run-to-run noise (pixels off by more than 2 levels 0.2-1.5%, by more than 16 at most 0.03%; this tree's
noise between two runs of one binary is about 1%).
The weld against RAEA_NO_WELD=1 on one binary (r109 f106): a frame held 96 frames (`raea light steady`) settles to
the same picture either way (pixels off by more than 16 levels 0.008%), boiling 0.30% welded against 0.38%
(worst tile 1.53% against 2.98%), and two runs of the welded build differ in 0.11% of pixels against 1.2%. In the
shot's own render, one small emitter's wash (the room sconce's light on the wall, above and below its can) has
built up less by f106 when welded: a difference in how fast it settles, not in where it settles.
RM9 against RAEA_NO_BC=1 on one binary (r109 f106, caustics f60, the facade's 8776-wide wear maps and the pool's
96 water normal maps among them): pixels off by more than 16 levels 0.057% and 0.097%, all of it the bicycle's
sub-pixel spokes' glints and a chair's shadow edge on the deck; nothing on the facade or the water (two runs of
either build: about 0.03%).
Still held after the weld (before RM8): shape text 274 MB in 2,526 rows, 263 MB of it 88 BufferMesh shapes (the palms' vertex
arrays as JSON, two of them 51 MB each), half of it the same text in another row (RM8).
@needs:RM1 @done
Scenario: RM5. The CPU heap, named by who holds it
Then a still's live heap after warm-up is attributed by call tree (macOS malloc stack logging, malloc_history
-callTree; tools/memprobe/heapwho.sh) to the crate that allocated it, and each holder over 250 MB is either cut,
let go once read, or written here with why it stays
And the shape cache (raea-core-shape `cached`, `solid`), the React world, wgpu's staging and the end checks' solids
are each given a number
And after RM5 to RM10 (tools/memprobe/heapseq.sh, r109's sequence mid-render; holders.py) what is over 250 MB stays
for a reason: MetalFX's denoising scaler 317 MB (Apple's framework, made once a view, the denoiser's own
working memory); JavaScriptCore's heap 300 MB in a still, up to 870 MB mid-sequence (the composition's live
objects; collecting after every frame, RAEA_JSC_EDEN=1, frees the small heap later but not the peak); the
contact check's solids 366 MB (RM10, every part in view the whole shot); wgpu's Metal command encoding
250-360 MB in the first frames (inside wgpu-hal). Gone from the list: Manifold's solids (2.4 GB, RM5's cache),
the shape text (977 MB of clones, RM8 and the store), the names cache (297 MB, RM8)
@needs:RM4
Scenario: RM6. A picture sequence is one texture, streamed
Then a map whose picture changes each frame (a water normal map, a caustic) is one GPU texture written each frame
from the frame's file (decoded ahead on a thread), not one texture per picture made at load
And a pool shot's sequence holds one texture per such map, its GPU bytes flat from its first frame to its last
@needs:RM1 @done
Scenario: RM7. A mesh as few vertices as its corners need
Then a Manifold shape's mesh is indexed (U32) and welded where corners share a place and a normal exactly
(systems/mesh welded): halcyon's shapes had 4.65 corners to each vertex, so the raster mesh, its main-world copy
and Solari's traced copy are each about a third of what they were (r109's main-world meshes 0.56 GB to 0.20 GB)
And a shape with its own UVs or colours a corner (a <BufferMesh>) is left as it is; RAEA_NO_WELD=1 is the control
And a frame held 96 frames settles to the same picture welded or not, with no more boiling (numbers above)
And it is not built in Solari's layout to spare the traced copy: the main-world copy stays (RM1's readers), so
the layout's tangents and colours would make every vertex 64 bytes on the CPU and the GPU, where today it is 32
on the CPU and 32 + 64 on the GPU: bytes moved from the GPU to the CPU, not saved
@needs:RM7 @done
Scenario: RM8. A long BufferMesh is held as a name, its text kept on disk by its content
Given a <BufferMesh> whose shape text is 64 KB or longer (raea-core-shape KEEP_BUFFER_AT)
Then the React read (runtime/react read.rs names3d) writes its JSON once to raea's caches (buffers/NAME.json, NAME
its BLAKE3) and passes `buffer:@NAME` on, so the scene, every frame's row, the store and the evaluator hold 40
characters, not the vertex arrays
And the part is known again each frame by the text's length and xxh3 without naming it again
And every reader of a buffer shape (raea-sys-mesh shape_mesh, the three shader's fit, interchange's export) reads
the kept file through raea_core_shape::buffer_json, so what is drawn and exported is the same
@needs:RM1 @done
Scenario: RM9. A material's maps are block-compressed on the GPU
Given a device that samples BC textures (wgpu TEXTURE_COMPRESSION_BC: Apple silicon and Intel Macs, and desktop
GPUs on Windows and Linux)
Then every map raea-sys-material makes (map_image: colour as BC7 sRGB, normal, metallic-roughness, occlusion and
emissive as BC7 linear) is BC7 with its whole mip chain, 16 bytes for each 4x4 texels, a quarter of RGBA8's
And the blocks are encoded once (intel_tex_2's ISPC kernels, on every core) and kept in raea's caches by the
picture's content (maps/NAME.bc7), so a later run reads them and makes no mips
And a map whose side isn't a multiple of 4, a device without BC, or RAEA_NO_BC=1 is RGBA8 as before
And BC7 keeps all four channels, so Bevy's and Solari's shaders read every map as they did
@done
Scenario: RM10. The contact check's solids hold what it reads
Given a sequence's parts are checked for clipping as its frames come (raea-sys-contact), every part in view held
as a solid until the end checks let them go: in r109, 603 MB of depth grids, 368 MB of inside-cell lists and 301
MB of surface points (the heap's biggest holder mid-render, by malloc stack logging)
Then a cell's depth is a byte (at most half a grid's side; held at 255 past it), the inside cells are a count
(the check reads only how many), and the surface points are three u16s across the part's box with no spare
capacity: about 366 MB where there were 1,272, the findings the same (the crate's 18 tests)
Still open (11-26): a transient 1 GB of heap inside the first frame (after "resources prepared", gone within 10 s)
sets the warm sequence's footprint peak (6.5 GB at about 49 s); JavaScriptCore collecting after every frame
(RAEA_JSC_EDEN=1, RAEA_JSC_RELEASE_S=1) flattens the small heap later (990 to 330 MB) but not that peak. The GPU's
2.6 GB: 282 MB of images, 455 MB of meshes, the rest Solari's and the views' own buffers and MetalFX.
Rule: speed and quality are measured beside memory
Each step reports, on the r109 still and sequence: peak footprint, seconds per frame once warm, and `raea light
steady` boiling at a held frame. A step that cuts memory and costs time or adds boiling is not done.
+4 -16
View File
@@ -17,8 +17,6 @@ raea-sys-hold = { path = "../../systems/hold" }
# the passes, each a crate of its own (systems/)
raea-sys-splat = { path = "../../systems/splat" }
raea-sys-sprite = { path = "../../systems/sprite" }
raea-sys-rt = { path = "../../systems/rt" }
raea-sys-gi = { path = "../../systems/gi" }
# soft shadows (experimental_pbr_pcss) are under the native feature with raea-runtime-scene3d/pcss: WebGPU refuses their sampling
bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "multi_threaded", "3d_bevy_render", "ui_bevy_render", "png", "tonemapping_luts", "ktx2", "zstd_rust"] }
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "hdr"] }
@@ -38,27 +36,22 @@ raea-sys-matchmove = { path = "../../systems/matchmove" }
raea-sys-grid = { path = "../../systems/grid" }
# the view a camera on the Engine's target draws: the frame above its tag row, or a page's box (#130)
raea-sys-viewbox = { path = "../../systems/viewbox" }
raea-sys-rendermap = { path = "../../systems/rendermap" }
raea-sys-meshseq = { path = "../../systems/meshseq" }
raea-sys-environment = { path = "../../systems/environment" }
raea-sys-look = { path = "../../systems/look" }
raea-sys-compose = { path = "../../systems/compose" }
raea-sys-material = { path = "../../systems/material" }
raea-sys-framepass = { path = "../../systems/framepass" }
raea-sys-compute = { path = "../../systems/compute" }
raea-sys-phase = { path = "../../systems/phase" }
raea-sys-sampler = { path = "../../systems/sampler" }
raea-sys-parity = { path = "../../systems/parity" }
raea-sys-toon = { path = "../../systems/toon" }
# raea's modules as Bevy plugins (RaeaPlugins), a crate of their own
raea-render-plugins = { path = "plugins" }
raea-sys-memtally = { path = "../../systems/memtally" }
raea-sys-shader = { path = "../../systems/shader" }
# three.js's shaders: a ShaderMaterial's GLSL and a node material's WGSL (docs/r3f.feature R3F11)
raea-sys-three-shader = { path = "../../systems/three-shader" }
raea-sys-post = { path = "../../systems/post" }
raea-sys-fog = { path = "../../systems/fog" }
raea-sys-fog-half = { path = "../../systems/fog-half" }
raea-sys-volume = { path = "../../systems/volume" }
# a field of grass made in tiles by distance (<Grass>)
raea-sys-grass = { path = "../../systems/grass" }
raea-sys-lod = { path = "../../systems/lod" }
serde_json = { version = "1", features = ["float_roundtrip"] }
# the direct render's views, the 2D rows, clips' masks and the paint device (runtime/view)
raea-runtime-view = { path = "../../runtime/view", optional = true }
@@ -104,8 +97,3 @@ network = ["native"]
bevy-all = ["bevy/bevy_gilrs", "bevy/gamepad", "bevy/area_light_luts", "bevy/experimental_pbr_pcss", "bevy/dfg_lut", "bevy/smaa_luts", "bevy/tonemapping_luts", "bevy/bluenoise_texture", "bevy/bevy_gizmos", "bevy/bevy_gizmos_render", "bevy/bevy_dev_tools", "bevy/debug", "bevy/bevy_ui_debug", "bevy/file_watcher", "bevy/embedded_watcher", "bevy/asset_processor", "bevy/png", "bevy/jpeg", "bevy/ktx2", "bevy/zstd_rust", "bevy/basis-universal", "bevy/exr", "bevy/hdr", "bevy/webp", "bevy/dds", "bevy/tga", "bevy/bmp", "bevy/gif", "bevy/ico", "bevy/qoi", "bevy/pnm", "bevy/tiff", "bevy/picking", "bevy/bevy_picking", "bevy/mesh_picking", "bevy/sprite_picking", "bevy/ui_picking", "bevy/meshlet", "bevy/meshlet_processor", "bevy/bevy_solari", "bevy/bevy_animation", "bevy/gltf_animation", "bevy/morph", "bevy/morph_animation", "bevy/bevy_gltf", "bevy/bevy_sprite", "bevy/bevy_sprite_render", "bevy/2d_bevy_render", "bevy/3d_bevy_render", "bevy/ui_bevy_render", "bevy/bevy_ui_widgets", "bevy/bevy_feathers", "bevy/custom_cursor", "bevy/bevy_input_focus", "bevy/bevy_camera_controller", "bevy/free_camera", "bevy/pan_camera", "bevy/bevy_text", "bevy/system_font_discovery", "bevy/scene", "bevy/bevy_state", "bevy/serialize", "bevy/reflect_functions", "bevy/reflect_documentation", "bevy/sysinfo_plugin", "bevy/bevy_clipboard", "bevy/system_clipboard", "bevy/clipboard_image", "bevy/ghost_nodes", "bevy/bevy_settings", "bevy/shader_format_spirv", "bevy/bevy_debug_stepping", "bevy/bevy_world_serialization", "bevy/bevy_audio", "bevy/mp3", "bevy/flac", "bevy/vorbis", "bevy/wav", "bevy/aac", "bevy/mp4", "bevy/http", "bevy/https", "bevy/web_asset_cache", "bevy/bevy_curve", "bevy/complex_script_segmentation", "bevy/compressed_image_saver_universal", "bevy/pan_orbit_camera", "bevy/pan_orbit_gizmo", "bevy/render_dev_tools"]
# per-system spans as a chrome trace (RUST_LOG=info, trace-*.json in the working directory)
trace = ["bevy/trace", "bevy/trace_chrome"]
[package.metadata.cargo-shear]
# raea-core-shape is unused since a mesh row's shape went to raea_sys_material::mesh::shape_mesh. Its line sits beside
# an unlanded branch's (scene-loop: raea-sys-procmat), so it goes, with this table, once that branch lands
ignored = ["raea-core-shape"]
+42
View File
@@ -0,0 +1,42 @@
[package]
name = "raea-render-plugins"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "raea's Engine as Bevy plugins (docs/sdk.feature S6a): RaeaPlugins, each module's install as a Plugin in Engine::new's order, so any Bevy App can draw raea's looks"
[dependencies]
raea-core-program = { path = "../../../core/program" }
raea-runtime-plugins = { path = "../../../runtime/plugins" }
raea-runtime-scene3d = { path = "../../../runtime/scene3d" }
raea-sys-compose = { path = "../../../systems/compose" }
raea-sys-environment = { path = "../../../systems/environment" }
raea-sys-fog = { path = "../../../systems/fog" }
raea-sys-fog-half = { path = "../../../systems/fog-half" }
raea-sys-frame = { path = "../../../systems/frame" }
raea-sys-grid = { path = "../../../systems/grid" }
raea-sys-look = { path = "../../../systems/look" }
raea-sys-material = { path = "../../../systems/material" }
raea-sys-meshseq = { path = "../../../systems/meshseq" }
raea-sys-post = { path = "../../../systems/post" }
raea-sys-screen = { path = "../../../systems/screen" }
raea-sys-shader = { path = "../../../systems/shader" }
raea-sys-splat = { path = "../../../systems/splat" }
raea-sys-sprite = { path = "../../../systems/sprite" }
raea-sys-text3d = { path = "../../../systems/text3d" }
raea-sys-toon = { path = "../../../systems/toon" }
raea-sys-volume = { path = "../../../systems/volume" }
raea-sys-procmat = { path = "../../../systems/procmat" }
raea-sys-rt = { path = "../../../systems/rt" }
raea-sys-gi = { path = "../../../systems/gi" }
raea-sys-grass = { path = "../../../systems/grass" }
raea-sys-lod = { path = "../../../systems/lod" }
raea-sys-three-shader = { path = "../../../systems/three-shader" }
raea-sys-framepass = { path = "../../../systems/framepass" }
raea-sys-compute = { path = "../../../systems/compute" }
raea-sys-phase = { path = "../../../systems/phase" }
raea-sys-parity = { path = "../../../systems/parity" }
raea-sys-rendermap = { path = "../../../systems/rendermap" }
raea-sys-sampler = { path = "../../../systems/sampler" }
bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "3d_bevy_render"] }
@@ -14,6 +14,27 @@ use bevy::prelude::*;
// the frame's system sets, raea-sys-frame's: a plugin orders its systems by them
pub use raea_sys_frame::{FrameSystems, Scene3dSystems};
// raea's modules, by the names Engine::new installs them under (raea-render's engine.rs)
use raea_runtime_plugins as plugins;
use raea_runtime_scene3d as scene3d;
use raea_sys_compose::{compose, passes};
use raea_sys_environment as environment;
use raea_sys_fog::{fire, froxel, froxel_glass};
use raea_sys_fog_half as fog_half;
use raea_sys_frame::bevy_api;
use raea_sys_grid as grid;
use raea_sys_look::{look, paint};
use raea_sys_material::{decal, shadow_catch, shadow_only};
use raea_sys_meshseq as meshseq;
use raea_sys_post::{cut, dof, effect_stack, lens, motion_blur, outline};
use raea_sys_screen as screen;
use raea_sys_shader as shader_ext;
use raea_sys_splat as splat;
use raea_sys_sprite as sprite2d;
use raea_sys_text3d as text3d;
use raea_sys_toon as toon;
use raea_sys_volume as volume;
macro_rules! raea_plugin {
($($name:ident: $install:path, $doc:literal;)*) => {
$(
@@ -37,46 +58,46 @@ macro_rules! raea_plugin {
}
raea_plugin! {
VolumetricFogPlugin: super::scene3d::install_fog_shader, "Volumetric fog's shader, its dither seeded from the film frame (scene3d.rs).";
DepthOfFieldPlugin: super::dof::install, "Bevy's depth of field, keeping the frame's alpha (dof.rs).";
EffectStackPlugin: super::effect_stack::install, "The effect stack (a <Grade>'s aberration and vignette), keeping alpha (effect_stack.rs).";
Bevy019DefaultsPlugin: super::bevy_api::install_0_19_defaults, "Bevy 0.19's tone curve \"none\" and screen-space transmission, which 0.20 changed (bevy_api.rs).";
HalfFogPlugin: super::fog_half::install, "Volumetric fog at a fraction of the frame's resolution, upsampled by depth (fog_half.rs).";
EnvironmentPlugin: super::environment::install, "Each panorama's light filtered once (environment.rs).";
FroxelFogPlugin: super::froxel::install, "Fog as one medium in a grid along the view (froxel.rs).";
FroxelGlassPlugin: super::froxel_glass::install, "Glass seen through froxel fog (froxel_glass.rs).";
LookPlugin: super::look::install, "Models drawn as pixel art or the site's grain (look.rs).";
OutlinePlugin: super::outline::install, "Ink outlines (outline.rs).";
VolumetricFogPlugin: crate::scene3d::install_fog_shader, "Volumetric fog's shader, its dither seeded from the film frame (scene3d.rs).";
DepthOfFieldPlugin: crate::dof::install, "Bevy's depth of field, keeping the frame's alpha (dof.rs).";
EffectStackPlugin: crate::effect_stack::install, "The effect stack (a <Grade>'s aberration and vignette), keeping alpha (effect_stack.rs).";
Bevy019DefaultsPlugin: crate::bevy_api::install_0_19_defaults, "Bevy 0.19's tone curve \"none\" and screen-space transmission, which 0.20 changed (bevy_api.rs).";
HalfFogPlugin: crate::fog_half::install, "Volumetric fog at a fraction of the frame's resolution, upsampled by depth (fog_half.rs).";
EnvironmentPlugin: crate::environment::install, "Each panorama's light filtered once (environment.rs).";
FroxelFogPlugin: crate::froxel::install, "Fog as one medium in a grid along the view (froxel.rs).";
FroxelGlassPlugin: crate::froxel_glass::install, "Glass seen through froxel fog (froxel_glass.rs).";
LookPlugin: crate::look::install, "Models drawn as pixel art or the site's grain (look.rs).";
OutlinePlugin: crate::outline::install, "Ink outlines (outline.rs).";
SteadyPlugin: raea_sys_post::steady::install, "raea's temporal filter: each frame jittered and blended with those before it (raea-sys-post steady.rs, docs/realism.feature LT12).";
ComposePlugin: super::compose::install, "Composition passes: each object's pass mask, read by Look, Outline, Bloom and Grade (compose.rs).";
Text3dPlugin: super::text3d::install, "Text in the 3D world: bevy_rich_text3d and its faces (raea-sys-text3d).";
FirePlugin: super::fire::install, "Flames drawn as volumes (fire.rs).";
SplatPlugin: super::splat::install, "Gaussian splats, sorted per frame for the scene camera (raea-sys-splat).";
MeshSequencePlugin: super::meshseq::install, "Mesh sequences by the frame, glitches on parts (meshseq.rs).";
ComposePlugin: crate::compose::install, "Composition passes: each object's pass mask, read by Look, Outline, Bloom and Grade (compose.rs).";
Text3dPlugin: crate::text3d::install, "Text in the 3D world: bevy_rich_text3d and its faces (raea-sys-text3d).";
FirePlugin: crate::fire::install, "Flames drawn as volumes (fire.rs).";
SplatPlugin: crate::splat::install, "Gaussian splats, sorted per frame for the scene camera (raea-sys-splat).";
MeshSequencePlugin: crate::meshseq::install, "Mesh sequences by the frame, glitches on parts (meshseq.rs).";
Draws2dPlugin: raea_sys_sprite::install, "Plugins' 2D drawing brings up the scene's 2D camera (raea-sys-sprite's Draws2d).";
ScreenPlugin: super::screen::install, "Live pictures on surfaces, drawn as CRTs (screen.rs).";
GridPlugin: super::grid::install, "Greybox surfaces: graph paper and outlines (grid.rs).";
ScreenPlugin: crate::screen::install, "Live pictures on surfaces, drawn as CRTs (screen.rs).";
GridPlugin: crate::grid::install, "Greybox surfaces: graph paper and outlines (grid.rs).";
ProcMatPlugin: raea_sys_procmat::install, "Procedural surfaces: wood, stone, brick, tiles and the rest, with dust and dirt (systems/procmat).";
PaintPlugin: super::paint::install, "The paint and cartoon looks' surfaces (paint.rs).";
PassesPlugin: super::passes::install, "Render passes per view (passes.rs).";
PaintPlugin: crate::paint::install, "The paint and cartoon looks' surfaces (paint.rs).";
PassesPlugin: crate::passes::install, "Render passes per view (passes.rs).";
TracedAoPlugin: raea_sys_rt::passes, "Traced passes: ambient occlusion, raealism's world probes and the sun's far shadow map (raea-sys-rt).";
GiScreenPlugin: raea_sys_gi::install, "raealism's light on screen: each pixel's indirect diffuse from the world cache, read by the main pass (raea-sys-gi, RAEA_GI=1).";
VolumePlugin: super::volume::install, "Simulated smoke, clouds and contrails, raymarched (volume.rs).";
VolumePlugin: crate::volume::install, "Simulated smoke, clouds and contrails, raymarched (volume.rs).";
GrassPlugin: raea_sys_grass::install, "Fields of grass, made in tiles as detailed as the camera's distance asks (systems/grass).";
DetailPlugin: raea_sys_lod::install, "Where each part is drawn: levels by distance or size on screen, cross-faded, draw distance and shadows left to a coarser level (raea-sys-lod, docs/realism.feature LT21).";
ShadowOnlyPlugin: super::shadow_only::install, "Meshes in the shadow maps only (shadow_only.rs).";
ShadowCatchPlugin: super::shadow_catch::install, "Surfaces that show only the shadows falling on them (shadow_catch.rs).";
ShadowOnlyPlugin: crate::shadow_only::install, "Meshes in the shadow maps only (shadow_only.rs).";
ShadowCatchPlugin: crate::shadow_catch::install, "Surfaces that show only the shadows falling on them (shadow_catch.rs).";
TintPlugin: raea_sys_material::tint::install, "A colour a copy over an <Instances>' surface, three's instanceColor (tint.rs).";
ToonPlugin: super::toon::install, "The toon surface and its ink outline's materials (toon.rs).";
ShaderExtPlugin: super::shader_ext::install, "Shaders written in TypeScript over the lit standard surface (raea-sys-shader).";
ToonPlugin: crate::toon::install, "The toon surface and its ink outline's materials (toon.rs).";
ShaderExtPlugin: crate::shader_ext::install, "Shaders written in TypeScript over the lit standard surface (raea-sys-shader).";
ThreeShaderPlugin: raea_sys_three_shader::install, "three.js's shaders: a ShaderMaterial's GLSL (naga) and a node material's WGSL, with three's built-ins (raea-sys-three-shader).";
FramePassPlugin: raea_sys_framepass::install, "Full-screen passes written in TypeScript (raea-sys-framepass).";
ComputePlugin: raea_sys_compute::install, "Compute shaders written in TypeScript, run before the cameras draw (raea-sys-compute).";
PhaseItemPlugin: raea_sys_phase::install, "Your own draws in a camera's opaque phase, as Bevy's custom_phase_item queues one (raea-sys-phase).";
LensPlugin: super::lens::install, "The camera's lens (Fisheye, LensDistortion), after tone mapping (lens.rs).";
LensPlugin: crate::lens::install, "The camera's lens (Fisheye, LensDistortion), after tone mapping (lens.rs).";
ParityPlugin: raea_sys_parity::install, "The parity probe: a frame's cost and World, written when RAEA_PARITY is set (raea-sys-parity, docs/control.feature FC0a).";
CameraCutPlugin: super::cut::install, "A camera that jumps is a cut: its history starts again and its motion blur waits (cut.rs, RT31).";
MotionBlurPlugin: super::motion_blur::install, "Motion blur's frame counter pinned to the frame (motion_blur.rs).";
CameraCutPlugin: crate::cut::install, "A camera that jumps is a cut: its history starts again and its motion blur waits (cut.rs, RT31).";
MotionBlurPlugin: crate::motion_blur::install, "Motion blur's frame counter pinned to the frame (motion_blur.rs).";
}
/// The frame's state that raea's plugins' systems read (the clock, the frame's rows, the loaded edit, the error), empty
@@ -86,11 +107,11 @@ pub struct FramePlugin;
impl Plugin for FramePlugin {
fn build(&self, app: &mut App) {
app.init_resource::<super::Clock>().init_resource::<super::Error>().init_resource::<super::FrameRows>();
if !app.world().contains_resource::<super::Edit>() {
app.init_resource::<raea_sys_frame::Clock>().init_resource::<raea_sys_frame::Error>().init_resource::<raea_sys_frame::FrameRows>();
if !app.world().contains_resource::<raea_sys_frame::Edit>() {
let prog = raea_core_program::ir::Program::default();
let timeline = raea_core_program::timeline::Timeline::new(&prog, &[]).expect("an empty timeline");
app.insert_resource(super::Edit { prog, timeline: std::sync::Arc::new(timeline), media: Vec::new() });
app.insert_resource(raea_sys_frame::Edit { prog, timeline: std::sync::Arc::new(timeline), media: Vec::new() });
}
}
}
@@ -102,7 +123,7 @@ pub struct RegisteredPlugins {
impl Plugin for RegisteredPlugins {
fn build(&self, app: &mut App) {
super::plugins::install(app, self.fps);
crate::plugins::install(app, self.fps);
}
}
@@ -111,14 +132,14 @@ impl Plugin for RegisteredPlugins {
pub fn scene3d_systems() -> ScheduleConfigs<ScheduleSystem> {
(
// 2D over the 3D: its camera once there's a part, then each part's place, cell and colour (raea-sys-sprite)
(super::sprite2d::camera_2d, super::sprite2d::sync_2d).chain(),
super::scene3d::model_setup,
super::scene3d::instance_models,
super::scene3d::model_shadow_markers,
super::scene3d::toon_models,
((super::scene3d::sync_meshes, super::scene3d::sync_instances, super::scene3d::sync_pictures, raea_sys_rendermap::sync_render_maps, super::shader_ext::sync_shaded, raea_sys_sampler::arrays::sync_arrays, raea_sys_sampler::sync_samplers).chain(), super::toon::sync_toon, (super::scene3d::sync_camera, super::scene3d::sync_post).chain(), super::motion_blur::sync_motion_blur, (super::environment::sync_environment, super::environment::sync_prefiltered, super::environment::sync_suns).chain(), (super::scene3d::sync_light_sets, super::scene3d::sync_lights).chain(), super::scene3d::sync_fog_volumes, super::scene3d::sync_fog_dither, super::scene3d::sync_models, super::scene3d::sync_morphs, super::scene3d::sync_attach, super::grid::grid_models, super::scene3d::sync_bones, super::look::sync_frame_look, super::look::sync_looks, super::compose::sync_passes, super::look::sync_flat, super::paint::sync_paint, super::decal::sync_decals, super::text3d::sync_texts).chain(),
(crate::sprite2d::camera_2d, crate::sprite2d::sync_2d).chain(),
crate::scene3d::model_setup,
crate::scene3d::instance_models,
crate::scene3d::model_shadow_markers,
crate::scene3d::toon_models,
((crate::scene3d::sync_meshes, crate::scene3d::sync_instances, crate::scene3d::sync_pictures, raea_sys_rendermap::sync_render_maps, raea_sys_material::swapped::sync_swapped_maps, crate::shader_ext::sync_shaded, raea_sys_sampler::arrays::sync_arrays, raea_sys_sampler::sync_samplers).chain(), crate::toon::sync_toon, (crate::scene3d::sync_camera, crate::scene3d::sync_post).chain(), crate::motion_blur::sync_motion_blur, (crate::environment::sync_environment, crate::environment::sync_prefiltered, crate::environment::sync_suns).chain(), (crate::scene3d::sync_light_sets, crate::scene3d::sync_lights).chain(), crate::scene3d::sync_fog_volumes, crate::scene3d::sync_fog_dither, crate::scene3d::sync_models, crate::scene3d::sync_morphs, crate::scene3d::sync_attach, crate::grid::grid_models, crate::scene3d::sync_bones, crate::look::sync_frame_look, crate::look::sync_looks, crate::compose::sync_passes, crate::look::sync_flat, crate::paint::sync_paint, crate::decal::sync_decals, crate::text3d::sync_texts).chain(),
// --clay and --review's clay half: every standard surface grey, after the rows set their colours
super::scene3d::clay::clay_materials,
crate::scene3d::clay::clay_materials,
)
.chain()
}
@@ -149,8 +170,8 @@ mod tests {
let mut app = App::new();
app.add_plugins(FramePlugin);
let w = app.world();
assert!(w.contains_resource::<super::super::Clock>() && w.contains_resource::<super::super::Error>());
assert!(w.contains_resource::<super::super::FrameRows>() && w.contains_resource::<super::super::Edit>());
assert!(w.contains_resource::<raea_sys_frame::Clock>() && w.contains_resource::<raea_sys_frame::Error>());
assert!(w.contains_resource::<raea_sys_frame::FrameRows>() && w.contains_resource::<raea_sys_frame::Edit>());
assert!(RaeaPlugins.build().enabled::<FramePlugin>());
}
+6 -1
View File
@@ -347,7 +347,12 @@ fn traceable(src: &Mesh, mapped: bool) -> Option<Traceable> {
let n = pos.len();
let normal = src.attribute(Mesh::ATTRIBUTE_NORMAL)?.clone();
let uv = src.attribute(Mesh::ATTRIBUTE_UV_0).cloned().unwrap_or(VertexAttributeValues::Float32x2(vec![[0.0, 0.0]; n]));
let mut out = Mesh::new(PrimitiveTopology::TriangleList, bevy::asset::RenderAssetUsages::default());
// RM1 (docs/render-memory.feature): the GPU's copy alone. Solari builds its BLAS from the render world's mesh
// (blas.rs: RenderMesh, MeshAllocator) and nothing on the CPU reads this copy once it's made (its tangents are
// made below, before it's added); kept in the main world too, every traced part was held twice there
// (RAEA_KEEP_CPU_ASSETS=1 keeps it in the main world too: the A/B control)
let usage = if std::env::var_os("RAEA_KEEP_CPU_ASSETS").is_some() { bevy::asset::RenderAssetUsages::default() } else { bevy::asset::RenderAssetUsages::RENDER_WORLD };
let mut out = Mesh::new(PrimitiveTopology::TriangleList, usage);
out.insert_attribute(Mesh::ATTRIBUTE_POSITION, pos);
out.insert_attribute(Mesh::ATTRIBUTE_NORMAL, normal);
out.insert_attribute(Mesh::ATTRIBUTE_UV_0, uv);
+13 -20
View File
@@ -47,16 +47,9 @@ pub use aov::Aov;
// a frame's rows, the edit, the clock and the row helpers every pass reads (raea-sys-frame)
use raea_sys_frame::*;
use raea_sys_frame::bevy_api;
use raea_sys_environment as environment;
use raea_runtime_scene3d as scene3d;
use raea_sys_look::look;
use raea_sys_post::outline;
// composition passes: which pass drew each pixel, and the frame-wide effects held back from some
use raea_sys_compose::compose;
use raea_sys_fog_half as fog_half;
use raea_sys_fog::froxel;
use raea_sys_fog::froxel_glass;
use raea_sys_fog::fire;
// text in the 3D world, a glyph an entity (raea-sys-text3d)
use raea_sys_text3d as text3d;
@@ -67,34 +60,25 @@ use raea_sys_sprite as sprite2d;
use raea_sys_grid as grid;
// footage behind the 3D and a camera's window on a larger view (<Matchmove>)
use raea_sys_matchmove as matchmove;
use raea_sys_look::paint;
use raea_sys_material::decal;
use raea_sys_compose::passes;
use raea_sys_screen as screen;
// the Engine's screens
#[cfg(feature = "native")]
mod screens;
use raea_sys_volume as volume;
// meshes that cast shadows without being drawn (<Mesh shadow="only">)
use raea_sys_material::shadow_only;
use raea_sys_material::shadow_catch;
// baked simulations played back by the frame (<MeshSequence>, <Goo>) and glitches on any part (physics.tsx)
use raea_sys_meshseq as meshseq;
// toon (cel) surfaces and their ink outlines (<MeshToonMaterial>)
use raea_sys_material::toon;
use raea_sys_toon as toon;
use raea_sys_shader as shader_ext;
// the camera's lens: Fisheye and LensDistortion, a pass after tone mapping
use raea_sys_post::lens;
// the camera's motion blur (<MotionBlur>), a function of the frame
use raea_sys_post::motion_blur;
use raea_sys_post::cut;
// Bevy's depth of field, patched to keep the frame's alpha (the paint look's sky)
use raea_sys_post::dof;
use raea_sys_post::effect_stack;
// Bevy plugins compiled in by a crate that registers them, driven by generic rows and stepped by the frame index
use raea_runtime_plugins as plugins;
/// raea's modules as Bevy plugins, gathered in RaeaPlugins (docs/sdk.feature S6a)
pub mod raea_plugins;
/// raea's modules as Bevy plugins, gathered in RaeaPlugins (raea-render-plugins, docs/sdk.feature S6a)
pub use raea_render_plugins as raea_plugins;
pub struct Engine {
app: App,
@@ -142,7 +126,8 @@ impl Drop for Engine {
#[cfg(feature = "native")] pub(crate) use raea_io_trace::stat; #[cfg(not(feature = "native"))] pub(crate) fn stat(_: &str) -> bool { false } // a stat channel (io/trace stats.rs, nobuild NB2a); the web's build has none
/// RAEA_MEM_MARKS: one line on stderr per start-up phase, "mem_mark <ms since the first mark> <phys_footprint MB>
/// <phase>", to line up with a memory timeline (the footprint is the process's, as the OS counts it).
/// <phase>", to line up with a memory timeline (the footprint is the process's, as the OS counts it). Each App's
/// assets follow it, as raea-sys-memtally tallies them (RM0).
pub fn mem_mark(what: &str) {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
static T0: std::sync::OnceLock<bevy::platform::time::Instant> = std::sync::OnceLock::new();
@@ -152,6 +137,7 @@ pub fn mem_mark(what: &str) {
let t = T0.get_or_init(bevy::platform::time::Instant::now).elapsed().as_secs_f64() * 1e3;
let mb = phys_footprint().map(|b| format!("{:.1}", b as f64 / 1048576.0)).unwrap_or_else(|| "?".into());
eprintln!("mem_mark {t:.1} {mb} {what}");
raea_sys_memtally::marked();
}
/// The edit has 3D rows (a light or a mesh): its camera draws through the 3D pipeline, and the Apple encoder runs
@@ -227,6 +213,13 @@ impl Engine {
Engine::build(prog, inserted, dir, None, true)
}
/// The live engine in `slot` (re)opened for `prog`, with its own inserted rows: the one there is let go first, so
/// two 3D worlds are never held at once (docs/render-memory.feature RM2).
pub fn open_in<'a>(slot: &'a mut Option<Engine>, prog: &Program, dir: &Path) -> Result<&'a mut Engine, String> {
*slot = None;
Ok(slot.insert(Engine::new_live(prog, &crate::inserted_of(prog), dir)?))
}
/// The frame `draw` drew last, if any.
pub fn drawn(&self) -> Option<i64> { self.drawn }
+56 -2
View File
@@ -40,7 +40,58 @@ impl Engine {
store::clear(world);
world.insert_resource(raea_sys_frame::RenderImages::default()); // its render images: this load's are made as its rows spawn
world.despawn_all::<With<Mirror>>();
let ents = store::load(world, inserted);
// RM9: maps made BC7 where this device samples BC (raea-sys-material maps.rs bc7_chain)
if let Some(d) = world.get_resource::<bevy::render::renderer::RenderDevice>() {
raea_sys_material::maps::set_block_compression(d.features().contains(bevy::render::render_resource::WgpuFeatures::TEXTURE_COMPRESSION_BC));
}
let ents = store::load_for_engine(world, inserted);
// RAEA_MEM_MARKS (docs/render-memory.feature RM5): the rows' text by kind and column, the biggest first. Each
// string is held by the program, the store and the evaluator's gathered columns, so its bytes count three times
if std::env::var_os("RAEA_MEM_MARKS").is_some() {
let mut by: std::collections::HashMap<(&str, &str), (usize, usize)> = std::collections::HashMap::new();
for t in inserted {
for (c, v) in &t.vals {
if let raea_core_program::ir::V::S(s) = v {
let e = by.entry((t.kind.as_str(), c.as_str())).or_default();
e.0 += s.len();
e.1 += 1;
}
}
}
let mut by: Vec<_> = by.into_iter().collect();
by.sort_by(|a, b| b.1 .0.cmp(&a.1 .0));
let all: usize = by.iter().map(|(_, (n, _))| n).sum();
eprintln!("mem_text all {:.1} MB in {} rows", all as f64 / 1e6, inserted.len());
for ((k, c), (n, rows)) in by.iter().take(10) {
eprintln!("mem_text {k}.{c} {:.1} MB over {rows} rows", *n as f64 / 1e6);
}
// the shapes by their outermost call, and how many are the same text as another's
let mut heads: std::collections::HashMap<&str, (usize, usize)> = std::collections::HashMap::new();
let mut seen: std::collections::HashSet<&str> = std::collections::HashSet::new();
let (mut dup, mut moved_inner) = (0usize, std::collections::HashSet::<&str>::new());
for t in inserted.iter().filter(|t| t.kind == "mesh") {
let Some(raea_core_program::ir::V::S(sh)) = t.vals.get("shape") else { continue };
let head = sh.split(|c: char| c == '(' || c == ':').next().unwrap_or("");
let e = heads.entry(head).or_default();
e.0 += sh.len();
e.1 += 1;
if !seen.insert(sh.as_str()) {
dup += sh.len();
}
// a moved, turned or scaled shape: its inside, which copies placed apart share
if matches!(head, "move" | "rotate" | "scale" | "transform") {
if let (Some(a), Some(b)) = (sh.find('('), sh.rfind(',')) {
moved_inner.insert(&sh[a + 1..b.max(a + 1)]);
}
}
}
let mut heads: Vec<_> = heads.into_iter().collect();
heads.sort_by(|a, b| b.1 .0.cmp(&a.1 .0));
eprintln!("mem_text shapes: {:.1} MB the same text as another row's; by outermost call: {}", dup as f64 / 1e6, heads.iter().take(8).map(|(h, (n, c))| format!("{h} {:.1} MB/{c}", *n as f64 / 1e6)).collect::<Vec<_>>().join(", "));
let mut longest: Vec<usize> = inserted.iter().filter_map(|t| match t.vals.get("shape") { Some(raea_core_program::ir::V::S(s)) => Some(s.len()), _ => None }).collect();
longest.sort_unstable_by(|a, b| b.cmp(a));
eprintln!("mem_text shapes: longest {:?} chars", &longest[..longest.len().min(6)]);
}
#[cfg(feature = "native")]
let mut rows2d: Vec<(String, serde_json::Value, Entity)> = Vec::new();
let mut camera = None;
@@ -133,7 +184,10 @@ impl Engine {
Some(t) => t,
None => std::sync::Arc::new(raea_core_program::timeline::Timeline::from_cols(prog, base)?),
};
world.insert_resource(Edit { prog: prog.clone(), timeline, media });
// the edit's header only (its size, rate and length: all anything reads of it); a whole copy held every row's
// text a fourth time, halcyon's shapes 274 MB (docs/render-memory.feature RM5)
let head = Program { fps: prog.fps, width: prog.width, height: prog.height, frames: prog.frames, ..Default::default() };
world.insert_resource(Edit { prog: head, 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));
+3
View File
@@ -191,6 +191,9 @@ impl Engine {
app.insert_non_send(Media { backend, decoders: HashMap::new(), dir: dir.to_path_buf() });
}
raea_sys_hold::install(&mut app, live); // a part held by a hand, and wireframe (docs/scene-feed.feature SF4c, SF3e)
if super::stat("RAEA_MEM_MARKS") {
raea_sys_memtally::install(&mut app); // RM0: each world's assets after a mark
}
mem_mark("engine: plugins built (DefaultPlugins, the render device)");
Ok(Opening { app, prog: prog.clone(), inserted: inserted.to_vec(), dir: dir.to_path_buf(), timeline, live })
}
+6 -1
View File
@@ -280,7 +280,8 @@ pub(crate) fn spawn_3d(world: &mut World, e: Entity, t: &Tup, inserted: &[Tup],
};
let mesh = match &three {
Some((_, own)) => {
let m = raea_sys_three_shader::fitted(world.resource::<Assets<Mesh>>().get(&mesh), &t.id, expr.strip_prefix("buffer:"), own)?;
let buffer = expr.strip_prefix("buffer:").map(raea_core_shape::buffer_json).transpose().map_err(|e| format!("mesh {}: {e}", t.id))?;
let m = raea_sys_three_shader::fitted(world.resource::<Assets<Mesh>>().get(&mesh), &t.id, buffer.as_deref(), own)?;
scene3d::shared_mesh(world, &format!("{expr}\0{uvs}\0{tangents}\0three:{}", own.join(",")), || Ok(m))?
}
None => mesh,
@@ -314,6 +315,10 @@ pub(crate) fn spawn_3d(world: &mut World, e: Entity, t: &Tup, inserted: &[Tup],
if shared {
world.entity_mut(e).insert(scene3d::SharedMaterial);
}
// a map whose picture a render keys frame by frame (RM6): swapped on this part's material
if let Some(sw) = raea_sys_material::swapped::of(t, dir)? {
world.entity_mut(e).insert(sw);
}
} else {
grid::put(world, e, mesh, mat, vals);
// a shader over the lit surface (shader_ext.rs): put on once the rows are applied (scene3d's shade_rows)
+12
View File
@@ -112,6 +112,18 @@ pub fn logs() -> Option<std::path::PathBuf> {
/// A new temp file named `raea-NAME-PID-N`, open to read and write, gone when raea is: unlinked once open on unix,
/// delete-on-close on Windows, so a render that dies leaves nothing behind (an encoder's samples, a render's parts).
/// `bytes` written to `path` whole or not at all: into a part file beside it (named for this process, so two
/// writers never share one), then renamed over it, so a reader never sees half a file. Its folder is made first.
pub fn write_whole(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
if let Some(d) = path.parent() {
std::fs::create_dir_all(d)?;
}
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let part = path.with_file_name(format!(".{name}.{}.part", std::process::id()));
std::fs::write(&part, bytes)?;
std::fs::rename(&part, path)
}
pub fn scratch_file(name: &str) -> Result<std::fs::File, String> {
static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let p = std::env::temp_dir().join(format!("raea-{name}-{}-{}", std::process::id(), N.fetch_add(1, std::sync::atomic::Ordering::Relaxed)));
+2 -1
View File
@@ -17,6 +17,8 @@ raea-runtime-wear = { path = "../wear" }
raea-native = { path = "../../engine/native", default-features = false }
raea-io-trace = { path = "../../io/trace" }
raea-core-shape = { path = "../../core/shape" }
# ECS worlds on Bevy's own ECS (ecs.*), a crate of their own
raea-runtime-ecs = { path = "../ecs" }
raea-core-place = { path = "../../core/place" }
raea-core-scene = { path = "../../core/scene" }
raea-io-media = { path = "../../io/media", default-features = false, features = ["soft-audio", "apple"] }
@@ -26,7 +28,6 @@ raea-sys-grab = { path = "../../systems/grab" }
raea-sys-fonts = { path = "../../systems/fonts" }
raea-sys-ml = { path = "../../systems/ml", optional = true }
raea-sys-speech = { path = "../../systems/speech", optional = true }
bevy = { version = "=0.20.0", default-features = false, features = ["std"] }
manifold-rust = "0.16.0"
base64 = "0.22"
image = { version = "0.25", default-features = false, features = ["png", "hdr"] }
+2 -470
View File
@@ -1,470 +1,2 @@
//! raea/ecs on Bevy's own ECS: each world is a `bevy::ecs::world::World`. A component is a real Bevy component
//! registered by name at run time (its value a JSON object, in Bevy's archetype tables); an entity holds any number of
//! them; queries are Bevy's (QueryBuilder with/without by component id) with column conditions on top; parent and child
//! are Bevy's `ChildOf` relationship (despawning a parent takes its children); resources and per-frame events sit beside
//! the world. Entities carry stable ids of ours, so a world copies (for `at(frame)`) and comes back the same.
//!
//! The first version's calls (one kind per entity: spawn {kind, cols}, query {kind, where}, column, count, rows) are
//! kept: a kind is a component named after it.
use std::cell::RefCell;
use std::collections::{BTreeMap, HashMap};
use bevy::ecs::component::{ComponentCloneBehavior, ComponentDescriptor, ComponentId, StorageType};
use bevy::ecs::entity::Entity;
use bevy::ecs::hierarchy::{ChildOf, Children};
use bevy::ecs::query::QueryBuilder;
use bevy::ecs::world::World;
use bevy::ptr::OwningPtr;
use serde_json::{Map, Value, json};
type R<T> = Result<T, String>;
/// One world: Bevy's, plus our ids, the component names, resources and this frame's events.
struct BWorld {
w: World,
comps: BTreeMap<String, ComponentId>,
ids: BTreeMap<u64, Entity>,
back: HashMap<Entity, u64>,
/// the kind an entity was spawned with (the first version's single component)
kind: HashMap<u64, String>,
next: u64,
resources: BTreeMap<String, Value>,
events: BTreeMap<String, Vec<Value>>,
}
unsafe fn drop_value(p: OwningPtr<'_>) {
// SAFETY: every dynamic component's value is a serde_json::Value (its descriptor's layout)
unsafe { p.drop_as::<Value>() }
}
impl BWorld {
fn new() -> BWorld {
BWorld { w: World::new(), comps: BTreeMap::new(), ids: BTreeMap::new(), back: HashMap::new(), kind: HashMap::new(), next: 0, resources: BTreeMap::new(), events: BTreeMap::new() }
}
/// The component registered for `name` (made on first use).
fn comp(&mut self, name: &str) -> ComponentId {
if let Some(c) = self.comps.get(name) {
return *c;
}
// SAFETY: the layout and drop are serde_json::Value's, which is Send + Sync; no relationship
let d = unsafe { ComponentDescriptor::new_with_layout(name.to_string(), StorageType::Table, std::alloc::Layout::new::<Value>(), Some(drop_value), true, false, ComponentCloneBehavior::Ignore, None) };
let id = self.w.register_component_with_descriptor(d);
self.comps.insert(name.to_string(), id);
id
}
fn entity(&self, id: u64) -> R<Entity> {
self.ids.get(&id).copied().ok_or_else(|| format!("no entity {id}"))
}
fn insert(&mut self, e: Entity, name: &str, value: Value) {
let c = self.comp(name);
OwningPtr::make(value, |ptr| {
// SAFETY: `c` was registered with Value's layout and `ptr` holds a Value
unsafe {
self.w.entity_mut(e).insert_by_id(c, ptr);
}
});
}
fn get(&self, e: Entity, name: &str) -> Option<&Value> {
let c = *self.comps.get(name)?;
// SAFETY: as insert
self.w.get_by_id(e, c).map(|p| unsafe { p.deref::<Value>() })
}
fn spawn(&mut self, comps: &Map<String, Value>) -> u64 {
let e = self.w.spawn_empty().id();
self.next += 1;
let id = self.next;
self.ids.insert(id, e);
self.back.insert(e, id);
for (k, v) in comps {
self.insert(e, k, v.clone());
}
id
}
/// The names of the components an entity has, sorted.
fn names(&self, e: Entity) -> Vec<String> {
self.comps.iter().filter(|(_, c)| self.w.get_by_id(e, **c).is_some()).map(|(n, _)| n.clone()).collect()
}
fn despawn(&mut self, id: u64) -> R<()> {
let e = self.entity(id)?;
// Bevy despawns the children with it (ChildOf links them): their ids go too
let mut gone = vec![e];
let mut i = 0;
while i < gone.len() {
if let Some(ch) = self.w.get::<Children>(gone[i]) {
gone.extend(ch.iter());
}
i += 1;
}
self.w.despawn(e);
for g in gone {
if let Some(gid) = self.back.remove(&g) {
self.ids.remove(&gid);
self.kind.remove(&gid);
}
}
Ok(())
}
/// Entities with every `with` component and none of `without`, by Bevy's query; ours in id order.
fn find(&mut self, with: &[String], without: &[String]) -> Vec<u64> {
let with_ids: Vec<ComponentId> = with.iter().map(|n| self.comp(n)).collect();
let without_ids: Vec<ComponentId> = without.iter().map(|n| self.comp(n)).collect();
let mut qb = QueryBuilder::<Entity>::new(&mut self.w);
for c in &with_ids {
qb.with_id(*c);
}
for c in &without_ids {
qb.without_id(*c);
}
let mut q = qb.build();
let mut out: Vec<u64> = q.iter(&self.w).filter_map(|e| self.back.get(&e).copied()).collect();
out.sort_unstable();
out
}
/// A column condition: "Comp.field" (or "field" of the first `with` component) compared with a value.
fn passes(&self, e: Entity, default: Option<&str>, cond: &Value) -> bool {
let Some(a) = cond.as_array() else { return false };
let (col, op, val) = (a.first().and_then(Value::as_str).unwrap_or(""), a.get(1).and_then(Value::as_str).unwrap_or("=="), a.get(2).cloned().unwrap_or(Value::Null));
let (comp, field) = match col.split_once('.') {
Some((c, f)) => (c, f),
None => (default.unwrap_or(""), col),
};
let x = self.get(e, comp).and_then(|v| v.get(field)).cloned().unwrap_or(Value::Null);
let num = |v: &Value| match v {
Value::Bool(b) => Some(if *b { 1.0 } else { 0.0 }),
Value::Number(n) => n.as_f64(),
_ => None,
};
match op {
"==" => x == val || (num(&x).is_some() && num(&x) == num(&val)),
"!=" => !(x == val || (num(&x).is_some() && num(&x) == num(&val))),
_ => match (num(&x), num(&val)) {
(Some(y), Some(w)) => match op {
"<" => y < w,
"<=" => y <= w,
">" => y > w,
">=" => y >= w,
_ => false,
},
_ => false,
},
}
}
/// Everything, to copy the world: each entity's id, kind, components and parent, plus resources and events.
fn dump(&self) -> Value {
let ents: Vec<Value> = self
.ids
.iter()
.map(|(id, e)| {
let comps: Map<String, Value> = self.names(*e).into_iter().filter_map(|n| self.get(*e, &n).cloned().map(|v| (n, v))).collect();
let parent = self.w.get::<ChildOf>(*e).and_then(|c| self.back.get(&c.parent()).copied());
json!({"id": id, "kind": self.kind.get(id), "components": comps, "parent": parent})
})
.collect();
json!({"entities": ents, "next": self.next, "resources": self.resources, "events": self.events})
}
fn load(d: &Value) -> BWorld {
let mut w = BWorld::new();
let ents = d["entities"].as_array().cloned().unwrap_or_default();
for en in &ents {
let id = en["id"].as_u64().unwrap_or(0);
let e = w.w.spawn_empty().id();
w.ids.insert(id, e);
w.back.insert(e, id);
if let Some(k) = en["kind"].as_str() {
w.kind.insert(id, k.to_string());
}
for (k, v) in en["components"].as_object().into_iter().flatten() {
w.insert(e, k, v.clone());
}
}
for en in &ents {
if let (Some(id), Some(p)) = (en["id"].as_u64(), en["parent"].as_u64()) {
let (c, p) = (w.ids[&id], w.ids[&p]);
w.w.entity_mut(c).insert(ChildOf(p));
}
}
w.next = d["next"].as_u64().unwrap_or(0);
w.resources = d["resources"].as_object().map(|m| m.iter().map(|(k, v)| (k.clone(), v.clone())).collect()).unwrap_or_default();
w.events = d["events"].as_object().map(|m| m.iter().map(|(k, v)| (k.clone(), v.as_array().cloned().unwrap_or_default())).collect()).unwrap_or_default();
w
}
/// The first version's row: {id, kind, ...the kind component's columns}.
fn row(&self, id: u64) -> R<Value> {
let e = self.entity(id)?;
let kind = self.kind.get(&id).cloned().unwrap_or_default();
let mut m = self.get(e, &kind).and_then(Value::as_object).cloned().unwrap_or_default();
m.insert("id".into(), json!(id));
m.insert("kind".into(), json!(kind));
Ok(Value::Object(m))
}
}
thread_local! {
static WORLDS: RefCell<(u64, HashMap<u64, BWorld>)> = RefCell::new((0, HashMap::new()));
}
fn u(v: &Value, k: &str) -> R<u64> {
v.get(k).and_then(Value::as_u64).ok_or_else(|| format!("{k}: a number"))
}
fn s<'a>(v: &'a Value, k: &str) -> R<&'a str> {
v.get(k).and_then(Value::as_str).ok_or_else(|| format!("{k}: a string"))
}
fn strings(v: &Value, k: &str) -> Vec<String> {
v.get(k).and_then(Value::as_array).map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or_default()
}
fn with_world<T>(v: &Value, f: impl FnOnce(&mut BWorld) -> R<T>) -> R<T> {
let id = u(v, "world")?;
WORLDS.with(|ws| {
let mut ws = ws.borrow_mut();
let w = ws.1.get_mut(&id).ok_or_else(|| format!("no world {id}"))?;
f(w)
})
}
fn put(w: BWorld) -> Value {
WORLDS.with(|ws| {
let mut ws = ws.borrow_mut();
ws.0 += 1;
let id = ws.0;
ws.1.insert(id, w);
json!({"world": id})
})
}
/// The ecs.* calls.
pub fn call(name: &str, v: &Value) -> R<Value> {
match name {
"ecs.new" => Ok(put(BWorld::new())),
"ecs.clone" => {
let d = with_world(v, |w| Ok(w.dump()))?;
Ok(put(BWorld::load(&d)))
}
"ecs.free" => {
let id = u(v, "world")?;
WORLDS.with(|ws| ws.borrow_mut().1.remove(&id));
Ok(Value::Null)
}
"ecs.spawn" => with_world(v, |w| {
let mut comps = v.get("components").and_then(Value::as_object).cloned().unwrap_or_default();
let kind = v.get("kind").and_then(Value::as_str).map(str::to_string);
if let Some(k) = &kind {
comps.insert(k.clone(), Value::Object(v.get("cols").and_then(Value::as_object).cloned().unwrap_or_default()));
}
let id = w.spawn(&comps);
if let Some(k) = kind {
w.kind.insert(id, k);
}
if let Some(p) = v.get("parent").and_then(Value::as_u64) {
let (c, p) = (w.entity(id)?, w.entity(p)?);
w.w.entity_mut(c).insert(ChildOf(p));
}
Ok(json!({"id": id}))
}),
"ecs.set" => with_world(v, |w| {
let id = u(v, "id")?;
let e = w.entity(id)?;
let kind = w.kind.get(&id).cloned().ok_or_else(|| format!("entity {id} has no kind (use ecs.insert)"))?;
let mut cur = w.get(e, &kind).and_then(Value::as_object).cloned().unwrap_or_default();
for (k, x) in v.get("cols").and_then(Value::as_object).into_iter().flatten() {
cur.insert(k.clone(), x.clone());
}
w.insert(e, &kind, Value::Object(cur));
Ok(Value::Null)
}),
"ecs.get" => with_world(v, |w| w.row(u(v, "id")?)),
"ecs.despawn" => with_world(v, |w| w.despawn(u(v, "id")?).map(|_| Value::Null)),
"ecs.insert" => with_world(v, |w| {
let e = w.entity(u(v, "id")?)?;
for (k, x) in v.get("components").and_then(Value::as_object).into_iter().flatten() {
w.insert(e, k, x.clone());
}
Ok(Value::Null)
}),
"ecs.remove" => with_world(v, |w| {
let e = w.entity(u(v, "id")?)?;
for n in strings(v, "names") {
if let Some(c) = w.comps.get(&n).copied() {
w.w.entity_mut(e).remove_by_id(c);
}
}
Ok(Value::Null)
}),
"ecs.components" => with_world(v, |w| {
let e = w.entity(u(v, "id")?)?;
let m: Map<String, Value> = w.names(e).into_iter().filter_map(|n| w.get(e, &n).cloned().map(|x| (n, x))).collect();
Ok(Value::Object(m))
}),
"ecs.find" => with_world(v, |w| {
let with = strings(v, "with");
let without = strings(v, "without");
let conds: Vec<Value> = v.get("where").and_then(Value::as_array).cloned().unwrap_or_default();
let ids = w.find(&with, &without);
let default = with.first().cloned();
let ids: Vec<u64> = ids.into_iter().filter(|id| conds.iter().all(|c| w.passes(w.ids[id], default.as_deref(), c))).collect();
if v.get("rows").and_then(Value::as_bool).unwrap_or(false) {
let rows: Vec<Value> = ids
.iter()
.map(|id| {
let e = w.ids[id];
let comps: Map<String, Value> = w.names(e).into_iter().filter_map(|n| w.get(e, &n).cloned().map(|x| (n, x))).collect();
json!({"id": id, "components": comps})
})
.collect();
return Ok(json!({"ids": ids, "rows": rows}));
}
Ok(json!({"ids": ids}))
}),
// the first version's query: a kind's entities by its columns
"ecs.query" => with_world(v, |w| {
let kind = s(v, "kind")?.to_string();
let conds: Vec<Value> = v.get("where").and_then(Value::as_array).cloned().unwrap_or_default();
let ids: Vec<u64> = w.find(std::slice::from_ref(&kind), &[]).into_iter().filter(|id| w.kind.get(id) == Some(&kind)).filter(|id| conds.iter().all(|c| w.passes(w.ids[id], Some(&kind), c))).collect();
Ok(json!({"ids": ids}))
}),
"ecs.column" => with_world(v, |w| {
let kind = s(v, "kind")?.to_string();
let col = s(v, "col")?;
let ids: Vec<u64> = w.find(std::slice::from_ref(&kind), &[]).into_iter().filter(|id| w.kind.get(id) == Some(&kind)).collect();
Ok(json!(ids.iter().map(|id| w.get(w.ids[id], &kind).and_then(|c| c.get(col)).and_then(Value::as_f64).map(|x| json!(x)).unwrap_or(Value::Null)).collect::<Vec<_>>()))
}),
"ecs.count" => with_world(v, |w| {
let kind = s(v, "kind")?.to_string();
Ok(json!(w.find(std::slice::from_ref(&kind), &[]).into_iter().filter(|id| w.kind.get(id) == Some(&kind)).count()))
}),
"ecs.rows" => with_world(v, |w| {
let mut ids: Vec<(String, u64)> = w.kind.iter().map(|(id, k)| (k.clone(), *id)).collect();
ids.sort();
Ok(Value::Array(ids.into_iter().filter_map(|(_, id)| w.row(id).ok()).collect()))
}),
"ecs.parent" => with_world(v, |w| {
let c = w.entity(u(v, "id")?)?;
match v.get("parent").and_then(Value::as_u64) {
Some(p) => {
let p = w.entity(p)?;
w.w.entity_mut(c).insert(ChildOf(p));
}
None if v.get("parent").is_some_and(Value::is_null) => {
w.w.entity_mut(c).remove::<ChildOf>();
}
None => {}
}
Ok(json!(w.w.get::<ChildOf>(c).and_then(|p| w.back.get(&p.parent()).copied())))
}),
"ecs.children" => with_world(v, |w| {
let e = w.entity(u(v, "id")?)?;
let mut out: Vec<u64> = w.w.get::<Children>(e).map(|c| c.iter().filter_map(|x| w.back.get(&x).copied()).collect()).unwrap_or_default();
out.sort_unstable();
Ok(json!(out))
}),
"ecs.resource" => with_world(v, |w| {
let name = s(v, "name")?.to_string();
if let Some(x) = v.get("value") {
w.resources.insert(name.clone(), x.clone());
}
Ok(w.resources.get(&name).cloned().unwrap_or(Value::Null))
}),
"ecs.send" => with_world(v, |w| {
w.events.entry(s(v, "name")?.to_string()).or_default().push(v.get("value").cloned().unwrap_or(Value::Null));
Ok(Value::Null)
}),
"ecs.events" => with_world(v, |w| Ok(json!(w.events.get(s(v, "name")?).cloned().unwrap_or_default()))),
"ecs.clear_events" => with_world(v, |w| {
w.events.clear();
Ok(Value::Null)
}),
// what renders, straight from the world: entities with a Mesh and a Transform as 3D nodes (world space,
// parents' transforms composed), and lights; the bridge draws these without a React element per entity
"ecs.scene" => with_world(v, |w| {
let mut out = Vec::new();
for id in w.find(&["Mesh".into()], &[]) {
let e = w.ids[&id];
let mesh = w.get(e, "Mesh").cloned().unwrap_or(Value::Null);
let mut t = transform_of(w.get(e, "Transform"));
let mut p = w.w.get::<ChildOf>(e).map(|c| c.parent());
while let Some(pe) = p {
let pt = transform_of(w.get(pe, "Transform"));
t = compose(&pt, &t);
p = w.w.get::<ChildOf>(pe).map(|c| c.parent());
}
out.push(json!({"id": id, "kind": "Mesh", "mesh": mesh, "position": [t[0], t[1], t[2]], "rotation": [t[3], t[4], t[5]], "scale": t[6]}));
}
for id in w.find(&["Light".into()], &[]) {
out.push(json!({"id": id, "kind": "Light", "light": w.get(w.ids[&id], "Light").cloned().unwrap_or(Value::Null)}));
}
Ok(Value::Array(out))
}),
o => Err(format!("no native call {o}")),
}
}
/// [x, y, z, rx, ry, rz, scale] from a Transform component ({x, y, z, rx, ry, rz, scale}, all optional).
fn transform_of(t: Option<&Value>) -> [f64; 7] {
let g = |k: &str, d: f64| t.and_then(|t| t.get(k)).and_then(Value::as_f64).unwrap_or(d);
[g("x", 0.0), g("y", 0.0), g("z", 0.0), g("rx", 0.0), g("ry", 0.0), g("rz", 0.0), g("scale", 1.0)]
}
/// A child's transform in its parent's space, made world space (rotation by z, then y, then x; uniform scale).
fn compose(parent: &[f64; 7], child: &[f64; 7]) -> [f64; 7] {
let (sx, cx) = parent[3].sin_cos();
let (sy, cy) = parent[4].sin_cos();
let (sz, cz) = parent[5].sin_cos();
let (mut x, mut y, mut z) = (child[0] * parent[6], child[1] * parent[6], child[2] * parent[6]);
// z
let (x1, y1) = (x * cz - y * sz, x * sz + y * cz);
x = x1;
y = y1;
// y
let (x2, z2) = (x * cy + z * sy, -x * sy + z * cy);
x = x2;
z = z2;
// x
let (y3, z3) = (y * cx - z * sx, y * sx + z * cx);
y = y3;
z = z3;
[parent[0] + x, parent[1] + y, parent[2] + z, parent[3] + child[3], parent[4] + child[4], parent[5] + child[5], parent[6] * child[6]]
}
/// The ecs.* names with their TypeScript types, for the registry.
pub const CALLS: &[(&str, &str, &str, &str)] = &[
("ecs.new", "{}", "{ world: number }", "a new world (Bevy's)"),
("ecs.clone", "{ world: number }", "{ world: number }", "a copy of a world"),
("ecs.free", "{ world: number }", "null", "drop a world"),
("ecs.spawn", "{ world: number; kind?: string; cols?: Record<string, number | string | boolean>; components?: Record<string, unknown>; parent?: number }", "{ id: number }", "a new entity: a kind with columns, and/or any components"),
("ecs.set", "{ world: number; id: number; cols: Record<string, number | string | boolean> }", "null", "columns merged into an entity's kind"),
("ecs.get", "{ world: number; id: number }", "{ id: number; kind: string } & Record<string, number | string | boolean>", "an entity's row (its kind's columns)"),
("ecs.despawn", "{ world: number; id: number }", "null", "remove an entity and its children"),
("ecs.insert", "{ world: number; id: number; components: Record<string, unknown> }", "null", "components added to (or replaced on) an entity"),
("ecs.remove", "{ world: number; id: number; names: string[] }", "null", "components taken off an entity"),
("ecs.components", "{ world: number; id: number }", "Record<string, unknown>", "an entity's components by name"),
("ecs.find", "{ world: number; with?: string[]; without?: string[]; where?: [string, \"==\" | \"!=\" | \"<\" | \"<=\" | \">\" | \">=\", number | string | boolean][]; rows?: boolean }", "{ ids: number[]; rows?: { id: number; components: Record<string, unknown> }[] }", "entities with every `with` component and no `without` one (Bevy's query), passing every condition (\"Comp.field\")"),
("ecs.query", "{ world: number; kind: string; where: [string, \"==\" | \"!=\" | \"<\" | \"<=\" | \">\" | \">=\", number | string | boolean][] }", "{ ids: number[] }", "ids of kind's entities passing every condition"),
("ecs.column", "{ world: number; kind: string; col: string }", "(number | null)[]", "one numeric column of a kind, in id order"),
("ecs.count", "{ world: number; kind: string }", "number", "how many entities of a kind"),
("ecs.rows", "{ world: number }", "({ id: number; kind: string } & Record<string, number | string | boolean>)[]", "every kind's rows, by kind then id"),
("ecs.parent", "{ world: number; id: number; parent?: number | null }", "number | null", "an entity's parent (set it with parent; null clears it)"),
("ecs.children", "{ world: number; id: number }", "number[]", "an entity's children"),
("ecs.resource", "{ world: number; name: string; value?: unknown }", "unknown", "a resource (set it with value)"),
("ecs.send", "{ world: number; name: string; value?: unknown }", "null", "an event for this frame"),
("ecs.events", "{ world: number; name: string }", "unknown[]", "this frame's events of a name"),
("ecs.clear_events", "{ world: number }", "null", "the frame's events cleared (each step starts with none)"),
("ecs.scene", "{ world: number }", "{ id: number; kind: \"Mesh\" | \"Light\"; mesh?: unknown; light?: unknown; position?: [number, number, number]; rotation?: [number, number, number]; scale?: number }[]", "the world's Mesh+Transform entities (world space) and lights, to draw"),
];
/// How many worlds are alive (media.live's leak check).
pub fn live() -> usize {
WORLDS.with(|ws| ws.borrow().1.len())
}
//! raea/ecs on Bevy's own ECS: raea-runtime-ecs, its own crate since 11-29 (the crate limit).
pub use raea_runtime_ecs::*;
+2
View File
@@ -104,6 +104,8 @@ struct Picture {
#[derive(Default)]
struct State {
solids: HashMap<u64, solid::Solid>,
/// each expression's one solid (solid.rs put_later)
solid_ids: HashMap<String, u64>,
pictures: HashMap<u64, Picture>,
#[cfg(target_vendor = "apple")]
vdecs: HashMap<u64, raea_io_media::apple::packets::PacketDecoder>,
+64 -21
View File
@@ -5,21 +5,48 @@ use serde_json::{Value, json};
use super::{R, State, args, f, s, u};
/// A solid by its expression, and its Manifold once something needs it. A boolean or a move only writes the
/// expression: the renderer builds the mesh from that (raea-core-shape, which keeps it on disk), so a set made of cuts
/// isn't cut a second time here on every open (a third of a launch-film set's script pass, 11-10). A query, a mesh,
/// an export or an operation that works on the solid itself builds it then.
/// A solid by its expression. A boolean or a move only writes the expression: the renderer builds the mesh from that
/// (raea-core-shape, which keeps it on disk), so a set made of cuts isn't cut a second time here on every open (a third
/// of a launch-film set's script pass, 11-10). A query, a mesh, an export or an operation that works on the solid
/// itself builds its Manifold then, into BUILT.
///
/// docs/render-memory.feature RM5: a solid was once its expression and its Manifold for as long as the script ran. No
/// component frees its solids (TypeScript has no finalizer to), and each render of a component makes them again, so
/// halcyon's script held 2.4 GB of Manifolds (their colliders 1 GB) by the end of warm-up, a third of the render's
/// heap. Now the same expression is one solid, counted (solid.free lets one holder go), and a built Manifold lives in
/// BUILT, a bounded cache by expression: one let go is built again from its expression if it's asked for again.
pub(crate) struct Solid {
m: std::cell::OnceCell<Manifold>,
expr: String,
refs: u32,
}
/// Built Manifolds by expression, two generations of at most GEN_BYTES each (raea-core-shape's Generations).
const GEN_BYTES: usize = 192 << 20;
/// A Manifold's heap, roughly: its halfedges, vertices, normals and properties, and the collider a boolean builds on
/// it (measured 11-26 on halcyon's solids: about 250 bytes a triangle in all).
fn manifold_bytes(m: &Manifold) -> usize {
m.num_tri() * 250 + 4096
}
/// `m` kept in BUILT for `expr`, weighed by its heap.
fn keep_built(expr: &str, m: std::rc::Rc<Manifold>) {
let weight = manifold_bytes(&m);
BUILT.with(|b| b.borrow_mut().hold(expr, m, weight));
}
thread_local! {
static BUILT: std::cell::RefCell<raea_core_shape::Generations<std::rc::Rc<Manifold>>> = std::cell::RefCell::new(raea_core_shape::Generations::new(GEN_BYTES));
}
impl Solid {
fn m(&self) -> R<&Manifold> {
if self.m.get().is_none() {
let _ = self.m.set(raea_core_shape::solid_or_empty(&self.expr)?);
fn m(&self) -> R<std::rc::Rc<Manifold>> {
if let Some(m) = BUILT.with(|b| b.borrow_mut().get(&self.expr)) {
return Ok(m);
}
Ok(self.m.get().expect("just set"))
let m = std::rc::Rc::new(raea_core_shape::solid_or_empty(&self.expr)?);
keep_built(&self.expr, m.clone());
Ok(m)
}
}
@@ -32,18 +59,24 @@ fn arg_text(a: &Value) -> String {
}
impl State {
/// A solid already built: its Manifold kept in BUILT for what asks for it next.
fn put(&mut self, m: Manifold, expr: String) -> Value {
self.next += 1;
let id = self.next;
self.solids.insert(id, Solid { m: std::cell::OnceCell::from(m), expr: expr.clone() });
json!({"id": id, "expr": expr})
keep_built(&expr, std::rc::Rc::new(m));
self.put_later(expr)
}
/// A solid that is only its expression so far.
/// A solid that is only its expression so far: the one solid of that expression, counted once more.
fn put_later(&mut self, expr: String) -> Value {
if let Some(&id) = self.solid_ids.get(&expr) {
if let Some(sd) = self.solids.get_mut(&id) {
sd.refs += 1;
return json!({"id": id, "expr": expr});
}
}
self.next += 1;
let id = self.next;
self.solids.insert(id, Solid { m: std::cell::OnceCell::new(), expr: expr.clone() });
self.solid_ids.insert(expr.clone(), id);
self.solids.insert(id, Solid { expr: expr.clone(), refs: 1 });
json!({"id": id, "expr": expr})
}
@@ -51,6 +84,16 @@ impl State {
self.solids.get(&id).ok_or_else(|| format!("solid {id} is gone (freed?)"))
}
/// One holder of solid `id` lets it go; the last one's going frees it.
fn free_solid(&mut self, id: u64) {
let Some(sd) = self.solids.get_mut(&id) else { return };
sd.refs = sd.refs.saturating_sub(1);
if sd.refs == 0 {
if let Some(sd) = self.solids.remove(&id) {
self.solid_ids.remove(&sd.expr);
}
}
}
}
/// A solid no expression describes (made from a mesh, a level set, a warp), written as OBJ under its content's hash; its
@@ -176,7 +219,7 @@ pub(super) fn call(st: &mut State, name: &str, v: &Value) -> R<Value> {
"genus" => Ok(json!(sd.m()?.genus())),
"min_gap" => {
let o = st.solid(u(v, "other")?)?;
Ok(json!(sd.m()?.min_gap(o.m()?, f(v, "z")?)))
Ok(json!(sd.m()?.min_gap(&*o.m()?, f(v, "z")?)))
}
"ray" => {
let a: Vec<f64> = args(v).iter().filter_map(Value::as_f64).collect();
@@ -225,7 +268,7 @@ pub(super) fn call(st: &mut State, name: &str, v: &Value) -> R<Value> {
}
"minkowski" | "minkowski_diff" => {
let o = other.ok_or_else(|| format!("{fun} takes another solid"))?;
let m = if fun == "minkowski" { base.m()?.minkowski_sum(o.m()?) } else { base.m()?.minkowski_difference(o.m()?) };
let m = if fun == "minkowski" { base.m()?.minkowski_sum(&*o.m()?) } else { base.m()?.minkowski_difference(&*o.m()?) };
(m, format!("{fun}({}, {})", base.expr, o.expr))
}
"simplify" | "refine_length" | "refine_tolerance" => {
@@ -252,7 +295,7 @@ pub(super) fn call(st: &mut State, name: &str, v: &Value) -> R<Value> {
}
"solid.mesh" => {
let sd = st.solid(u(v, "id")?)?;
let (verts, tris) = raea_core_shape::to_mesh(sd.m()?);
let (verts, tris) = raea_core_shape::to_mesh(&*sd.m()?);
Ok(json!({"verts": verts, "tris": tris}))
}
"solid.from_mesh" => {
@@ -297,7 +340,7 @@ pub(super) fn call(st: &mut State, name: &str, v: &Value) -> R<Value> {
let sd = st.solid(u(v, "id")?)?;
let path = s(v, "path")?;
let format = v.get("format").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| if path.ends_with(".glb") { "glb".into() } else { "obj".into() });
Ok(json!({"bytes": raea_core_shape::export(sd.m()?, path, &format)?}))
Ok(json!({"bytes": raea_core_shape::export(&*sd.m()?, path, &format)?}))
}
"solid.import" => {
let path = s(v, "path")?;
@@ -330,7 +373,7 @@ pub(super) fn call(st: &mut State, name: &str, v: &Value) -> R<Value> {
}
let parts: Vec<&Solid> = ids.iter().map(|i| st.solid(*i)).collect::<R<_>>()?;
let expr = if parts.len() == 1 { parts[0].expr.clone() } else { format!("union({})", parts.iter().map(|p| p.expr.as_str()).collect::<Vec<_>>().join(", ")) };
let m = Manifold::compose(&parts.iter().map(|p| p.m().cloned()).collect::<R<Vec<_>>>()?);
let m = Manifold::compose(&parts.iter().map(|p| p.m().map(|m| (*m).clone())).collect::<R<Vec<_>>>()?);
Ok(st.put(m, expr))
}
// the convex hull of points
@@ -428,7 +471,7 @@ pub(super) fn call(st: &mut State, name: &str, v: &Value) -> R<Value> {
Ok(section_json(&cs))
}
"solid.free" => {
st.solids.remove(&u(v, "id")?);
st.free_solid(u(v, "id")?);
Ok(Value::Null)
}
o => Err(format!("no native call {o}")),
+11
View File
@@ -0,0 +1,11 @@
[package]
name = "raea-runtime-ecs"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "raea/ecs on Bevy's own ECS: worlds of real Bevy components registered by name at run time, a composition's native ecs.* calls"
[dependencies]
bevy = { version = "=0.20.0", default-features = false, features = ["std"] }
serde_json = "1"
+470
View File
@@ -0,0 +1,470 @@
//! raea/ecs on Bevy's own ECS: each world is a `bevy::ecs::world::World`. A component is a real Bevy component
//! registered by name at run time (its value a JSON object, in Bevy's archetype tables); an entity holds any number of
//! them; queries are Bevy's (QueryBuilder with/without by component id) with column conditions on top; parent and child
//! are Bevy's `ChildOf` relationship (despawning a parent takes its children); resources and per-frame events sit beside
//! the world. Entities carry stable ids of ours, so a world copies (for `at(frame)`) and comes back the same.
//!
//! The first version's calls (one kind per entity: spawn {kind, cols}, query {kind, where}, column, count, rows) are
//! kept: a kind is a component named after it.
use std::cell::RefCell;
use std::collections::{BTreeMap, HashMap};
use bevy::ecs::component::{ComponentCloneBehavior, ComponentDescriptor, ComponentId, StorageType};
use bevy::ecs::entity::Entity;
use bevy::ecs::hierarchy::{ChildOf, Children};
use bevy::ecs::query::QueryBuilder;
use bevy::ecs::world::World;
use bevy::ptr::OwningPtr;
use serde_json::{Map, Value, json};
type R<T> = Result<T, String>;
/// One world: Bevy's, plus our ids, the component names, resources and this frame's events.
struct BWorld {
w: World,
comps: BTreeMap<String, ComponentId>,
ids: BTreeMap<u64, Entity>,
back: HashMap<Entity, u64>,
/// the kind an entity was spawned with (the first version's single component)
kind: HashMap<u64, String>,
next: u64,
resources: BTreeMap<String, Value>,
events: BTreeMap<String, Vec<Value>>,
}
unsafe fn drop_value(p: OwningPtr<'_>) {
// SAFETY: every dynamic component's value is a serde_json::Value (its descriptor's layout)
unsafe { p.drop_as::<Value>() }
}
impl BWorld {
fn new() -> BWorld {
BWorld { w: World::new(), comps: BTreeMap::new(), ids: BTreeMap::new(), back: HashMap::new(), kind: HashMap::new(), next: 0, resources: BTreeMap::new(), events: BTreeMap::new() }
}
/// The component registered for `name` (made on first use).
fn comp(&mut self, name: &str) -> ComponentId {
if let Some(c) = self.comps.get(name) {
return *c;
}
// SAFETY: the layout and drop are serde_json::Value's, which is Send + Sync; no relationship
let d = unsafe { ComponentDescriptor::new_with_layout(name.to_string(), StorageType::Table, std::alloc::Layout::new::<Value>(), Some(drop_value), true, false, ComponentCloneBehavior::Ignore, None) };
let id = self.w.register_component_with_descriptor(d);
self.comps.insert(name.to_string(), id);
id
}
fn entity(&self, id: u64) -> R<Entity> {
self.ids.get(&id).copied().ok_or_else(|| format!("no entity {id}"))
}
fn insert(&mut self, e: Entity, name: &str, value: Value) {
let c = self.comp(name);
OwningPtr::make(value, |ptr| {
// SAFETY: `c` was registered with Value's layout and `ptr` holds a Value
unsafe {
self.w.entity_mut(e).insert_by_id(c, ptr);
}
});
}
fn get(&self, e: Entity, name: &str) -> Option<&Value> {
let c = *self.comps.get(name)?;
// SAFETY: as insert
self.w.get_by_id(e, c).map(|p| unsafe { p.deref::<Value>() })
}
fn spawn(&mut self, comps: &Map<String, Value>) -> u64 {
let e = self.w.spawn_empty().id();
self.next += 1;
let id = self.next;
self.ids.insert(id, e);
self.back.insert(e, id);
for (k, v) in comps {
self.insert(e, k, v.clone());
}
id
}
/// The names of the components an entity has, sorted.
fn names(&self, e: Entity) -> Vec<String> {
self.comps.iter().filter(|(_, c)| self.w.get_by_id(e, **c).is_some()).map(|(n, _)| n.clone()).collect()
}
fn despawn(&mut self, id: u64) -> R<()> {
let e = self.entity(id)?;
// Bevy despawns the children with it (ChildOf links them): their ids go too
let mut gone = vec![e];
let mut i = 0;
while i < gone.len() {
if let Some(ch) = self.w.get::<Children>(gone[i]) {
gone.extend(ch.iter());
}
i += 1;
}
self.w.despawn(e);
for g in gone {
if let Some(gid) = self.back.remove(&g) {
self.ids.remove(&gid);
self.kind.remove(&gid);
}
}
Ok(())
}
/// Entities with every `with` component and none of `without`, by Bevy's query; ours in id order.
fn find(&mut self, with: &[String], without: &[String]) -> Vec<u64> {
let with_ids: Vec<ComponentId> = with.iter().map(|n| self.comp(n)).collect();
let without_ids: Vec<ComponentId> = without.iter().map(|n| self.comp(n)).collect();
let mut qb = QueryBuilder::<Entity>::new(&mut self.w);
for c in &with_ids {
qb.with_id(*c);
}
for c in &without_ids {
qb.without_id(*c);
}
let mut q = qb.build();
let mut out: Vec<u64> = q.iter(&self.w).filter_map(|e| self.back.get(&e).copied()).collect();
out.sort_unstable();
out
}
/// A column condition: "Comp.field" (or "field" of the first `with` component) compared with a value.
fn passes(&self, e: Entity, default: Option<&str>, cond: &Value) -> bool {
let Some(a) = cond.as_array() else { return false };
let (col, op, val) = (a.first().and_then(Value::as_str).unwrap_or(""), a.get(1).and_then(Value::as_str).unwrap_or("=="), a.get(2).cloned().unwrap_or(Value::Null));
let (comp, field) = match col.split_once('.') {
Some((c, f)) => (c, f),
None => (default.unwrap_or(""), col),
};
let x = self.get(e, comp).and_then(|v| v.get(field)).cloned().unwrap_or(Value::Null);
let num = |v: &Value| match v {
Value::Bool(b) => Some(if *b { 1.0 } else { 0.0 }),
Value::Number(n) => n.as_f64(),
_ => None,
};
match op {
"==" => x == val || (num(&x).is_some() && num(&x) == num(&val)),
"!=" => !(x == val || (num(&x).is_some() && num(&x) == num(&val))),
_ => match (num(&x), num(&val)) {
(Some(y), Some(w)) => match op {
"<" => y < w,
"<=" => y <= w,
">" => y > w,
">=" => y >= w,
_ => false,
},
_ => false,
},
}
}
/// Everything, to copy the world: each entity's id, kind, components and parent, plus resources and events.
fn dump(&self) -> Value {
let ents: Vec<Value> = self
.ids
.iter()
.map(|(id, e)| {
let comps: Map<String, Value> = self.names(*e).into_iter().filter_map(|n| self.get(*e, &n).cloned().map(|v| (n, v))).collect();
let parent = self.w.get::<ChildOf>(*e).and_then(|c| self.back.get(&c.parent()).copied());
json!({"id": id, "kind": self.kind.get(id), "components": comps, "parent": parent})
})
.collect();
json!({"entities": ents, "next": self.next, "resources": self.resources, "events": self.events})
}
fn load(d: &Value) -> BWorld {
let mut w = BWorld::new();
let ents = d["entities"].as_array().cloned().unwrap_or_default();
for en in &ents {
let id = en["id"].as_u64().unwrap_or(0);
let e = w.w.spawn_empty().id();
w.ids.insert(id, e);
w.back.insert(e, id);
if let Some(k) = en["kind"].as_str() {
w.kind.insert(id, k.to_string());
}
for (k, v) in en["components"].as_object().into_iter().flatten() {
w.insert(e, k, v.clone());
}
}
for en in &ents {
if let (Some(id), Some(p)) = (en["id"].as_u64(), en["parent"].as_u64()) {
let (c, p) = (w.ids[&id], w.ids[&p]);
w.w.entity_mut(c).insert(ChildOf(p));
}
}
w.next = d["next"].as_u64().unwrap_or(0);
w.resources = d["resources"].as_object().map(|m| m.iter().map(|(k, v)| (k.clone(), v.clone())).collect()).unwrap_or_default();
w.events = d["events"].as_object().map(|m| m.iter().map(|(k, v)| (k.clone(), v.as_array().cloned().unwrap_or_default())).collect()).unwrap_or_default();
w
}
/// The first version's row: {id, kind, ...the kind component's columns}.
fn row(&self, id: u64) -> R<Value> {
let e = self.entity(id)?;
let kind = self.kind.get(&id).cloned().unwrap_or_default();
let mut m = self.get(e, &kind).and_then(Value::as_object).cloned().unwrap_or_default();
m.insert("id".into(), json!(id));
m.insert("kind".into(), json!(kind));
Ok(Value::Object(m))
}
}
thread_local! {
static WORLDS: RefCell<(u64, HashMap<u64, BWorld>)> = RefCell::new((0, HashMap::new()));
}
fn u(v: &Value, k: &str) -> R<u64> {
v.get(k).and_then(Value::as_u64).ok_or_else(|| format!("{k}: a number"))
}
fn s<'a>(v: &'a Value, k: &str) -> R<&'a str> {
v.get(k).and_then(Value::as_str).ok_or_else(|| format!("{k}: a string"))
}
fn strings(v: &Value, k: &str) -> Vec<String> {
v.get(k).and_then(Value::as_array).map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or_default()
}
fn with_world<T>(v: &Value, f: impl FnOnce(&mut BWorld) -> R<T>) -> R<T> {
let id = u(v, "world")?;
WORLDS.with(|ws| {
let mut ws = ws.borrow_mut();
let w = ws.1.get_mut(&id).ok_or_else(|| format!("no world {id}"))?;
f(w)
})
}
fn put(w: BWorld) -> Value {
WORLDS.with(|ws| {
let mut ws = ws.borrow_mut();
ws.0 += 1;
let id = ws.0;
ws.1.insert(id, w);
json!({"world": id})
})
}
/// The ecs.* calls.
pub fn call(name: &str, v: &Value) -> R<Value> {
match name {
"ecs.new" => Ok(put(BWorld::new())),
"ecs.clone" => {
let d = with_world(v, |w| Ok(w.dump()))?;
Ok(put(BWorld::load(&d)))
}
"ecs.free" => {
let id = u(v, "world")?;
WORLDS.with(|ws| ws.borrow_mut().1.remove(&id));
Ok(Value::Null)
}
"ecs.spawn" => with_world(v, |w| {
let mut comps = v.get("components").and_then(Value::as_object).cloned().unwrap_or_default();
let kind = v.get("kind").and_then(Value::as_str).map(str::to_string);
if let Some(k) = &kind {
comps.insert(k.clone(), Value::Object(v.get("cols").and_then(Value::as_object).cloned().unwrap_or_default()));
}
let id = w.spawn(&comps);
if let Some(k) = kind {
w.kind.insert(id, k);
}
if let Some(p) = v.get("parent").and_then(Value::as_u64) {
let (c, p) = (w.entity(id)?, w.entity(p)?);
w.w.entity_mut(c).insert(ChildOf(p));
}
Ok(json!({"id": id}))
}),
"ecs.set" => with_world(v, |w| {
let id = u(v, "id")?;
let e = w.entity(id)?;
let kind = w.kind.get(&id).cloned().ok_or_else(|| format!("entity {id} has no kind (use ecs.insert)"))?;
let mut cur = w.get(e, &kind).and_then(Value::as_object).cloned().unwrap_or_default();
for (k, x) in v.get("cols").and_then(Value::as_object).into_iter().flatten() {
cur.insert(k.clone(), x.clone());
}
w.insert(e, &kind, Value::Object(cur));
Ok(Value::Null)
}),
"ecs.get" => with_world(v, |w| w.row(u(v, "id")?)),
"ecs.despawn" => with_world(v, |w| w.despawn(u(v, "id")?).map(|_| Value::Null)),
"ecs.insert" => with_world(v, |w| {
let e = w.entity(u(v, "id")?)?;
for (k, x) in v.get("components").and_then(Value::as_object).into_iter().flatten() {
w.insert(e, k, x.clone());
}
Ok(Value::Null)
}),
"ecs.remove" => with_world(v, |w| {
let e = w.entity(u(v, "id")?)?;
for n in strings(v, "names") {
if let Some(c) = w.comps.get(&n).copied() {
w.w.entity_mut(e).remove_by_id(c);
}
}
Ok(Value::Null)
}),
"ecs.components" => with_world(v, |w| {
let e = w.entity(u(v, "id")?)?;
let m: Map<String, Value> = w.names(e).into_iter().filter_map(|n| w.get(e, &n).cloned().map(|x| (n, x))).collect();
Ok(Value::Object(m))
}),
"ecs.find" => with_world(v, |w| {
let with = strings(v, "with");
let without = strings(v, "without");
let conds: Vec<Value> = v.get("where").and_then(Value::as_array).cloned().unwrap_or_default();
let ids = w.find(&with, &without);
let default = with.first().cloned();
let ids: Vec<u64> = ids.into_iter().filter(|id| conds.iter().all(|c| w.passes(w.ids[id], default.as_deref(), c))).collect();
if v.get("rows").and_then(Value::as_bool).unwrap_or(false) {
let rows: Vec<Value> = ids
.iter()
.map(|id| {
let e = w.ids[id];
let comps: Map<String, Value> = w.names(e).into_iter().filter_map(|n| w.get(e, &n).cloned().map(|x| (n, x))).collect();
json!({"id": id, "components": comps})
})
.collect();
return Ok(json!({"ids": ids, "rows": rows}));
}
Ok(json!({"ids": ids}))
}),
// the first version's query: a kind's entities by its columns
"ecs.query" => with_world(v, |w| {
let kind = s(v, "kind")?.to_string();
let conds: Vec<Value> = v.get("where").and_then(Value::as_array).cloned().unwrap_or_default();
let ids: Vec<u64> = w.find(std::slice::from_ref(&kind), &[]).into_iter().filter(|id| w.kind.get(id) == Some(&kind)).filter(|id| conds.iter().all(|c| w.passes(w.ids[id], Some(&kind), c))).collect();
Ok(json!({"ids": ids}))
}),
"ecs.column" => with_world(v, |w| {
let kind = s(v, "kind")?.to_string();
let col = s(v, "col")?;
let ids: Vec<u64> = w.find(std::slice::from_ref(&kind), &[]).into_iter().filter(|id| w.kind.get(id) == Some(&kind)).collect();
Ok(json!(ids.iter().map(|id| w.get(w.ids[id], &kind).and_then(|c| c.get(col)).and_then(Value::as_f64).map(|x| json!(x)).unwrap_or(Value::Null)).collect::<Vec<_>>()))
}),
"ecs.count" => with_world(v, |w| {
let kind = s(v, "kind")?.to_string();
Ok(json!(w.find(std::slice::from_ref(&kind), &[]).into_iter().filter(|id| w.kind.get(id) == Some(&kind)).count()))
}),
"ecs.rows" => with_world(v, |w| {
let mut ids: Vec<(String, u64)> = w.kind.iter().map(|(id, k)| (k.clone(), *id)).collect();
ids.sort();
Ok(Value::Array(ids.into_iter().filter_map(|(_, id)| w.row(id).ok()).collect()))
}),
"ecs.parent" => with_world(v, |w| {
let c = w.entity(u(v, "id")?)?;
match v.get("parent").and_then(Value::as_u64) {
Some(p) => {
let p = w.entity(p)?;
w.w.entity_mut(c).insert(ChildOf(p));
}
None if v.get("parent").is_some_and(Value::is_null) => {
w.w.entity_mut(c).remove::<ChildOf>();
}
None => {}
}
Ok(json!(w.w.get::<ChildOf>(c).and_then(|p| w.back.get(&p.parent()).copied())))
}),
"ecs.children" => with_world(v, |w| {
let e = w.entity(u(v, "id")?)?;
let mut out: Vec<u64> = w.w.get::<Children>(e).map(|c| c.iter().filter_map(|x| w.back.get(&x).copied()).collect()).unwrap_or_default();
out.sort_unstable();
Ok(json!(out))
}),
"ecs.resource" => with_world(v, |w| {
let name = s(v, "name")?.to_string();
if let Some(x) = v.get("value") {
w.resources.insert(name.clone(), x.clone());
}
Ok(w.resources.get(&name).cloned().unwrap_or(Value::Null))
}),
"ecs.send" => with_world(v, |w| {
w.events.entry(s(v, "name")?.to_string()).or_default().push(v.get("value").cloned().unwrap_or(Value::Null));
Ok(Value::Null)
}),
"ecs.events" => with_world(v, |w| Ok(json!(w.events.get(s(v, "name")?).cloned().unwrap_or_default()))),
"ecs.clear_events" => with_world(v, |w| {
w.events.clear();
Ok(Value::Null)
}),
// what renders, straight from the world: entities with a Mesh and a Transform as 3D nodes (world space,
// parents' transforms composed), and lights; the bridge draws these without a React element per entity
"ecs.scene" => with_world(v, |w| {
let mut out = Vec::new();
for id in w.find(&["Mesh".into()], &[]) {
let e = w.ids[&id];
let mesh = w.get(e, "Mesh").cloned().unwrap_or(Value::Null);
let mut t = transform_of(w.get(e, "Transform"));
let mut p = w.w.get::<ChildOf>(e).map(|c| c.parent());
while let Some(pe) = p {
let pt = transform_of(w.get(pe, "Transform"));
t = compose(&pt, &t);
p = w.w.get::<ChildOf>(pe).map(|c| c.parent());
}
out.push(json!({"id": id, "kind": "Mesh", "mesh": mesh, "position": [t[0], t[1], t[2]], "rotation": [t[3], t[4], t[5]], "scale": t[6]}));
}
for id in w.find(&["Light".into()], &[]) {
out.push(json!({"id": id, "kind": "Light", "light": w.get(w.ids[&id], "Light").cloned().unwrap_or(Value::Null)}));
}
Ok(Value::Array(out))
}),
o => Err(format!("no native call {o}")),
}
}
/// [x, y, z, rx, ry, rz, scale] from a Transform component ({x, y, z, rx, ry, rz, scale}, all optional).
fn transform_of(t: Option<&Value>) -> [f64; 7] {
let g = |k: &str, d: f64| t.and_then(|t| t.get(k)).and_then(Value::as_f64).unwrap_or(d);
[g("x", 0.0), g("y", 0.0), g("z", 0.0), g("rx", 0.0), g("ry", 0.0), g("rz", 0.0), g("scale", 1.0)]
}
/// A child's transform in its parent's space, made world space (rotation by z, then y, then x; uniform scale).
fn compose(parent: &[f64; 7], child: &[f64; 7]) -> [f64; 7] {
let (sx, cx) = parent[3].sin_cos();
let (sy, cy) = parent[4].sin_cos();
let (sz, cz) = parent[5].sin_cos();
let (mut x, mut y, mut z) = (child[0] * parent[6], child[1] * parent[6], child[2] * parent[6]);
// z
let (x1, y1) = (x * cz - y * sz, x * sz + y * cz);
x = x1;
y = y1;
// y
let (x2, z2) = (x * cy + z * sy, -x * sy + z * cy);
x = x2;
z = z2;
// x
let (y3, z3) = (y * cx - z * sx, y * sx + z * cx);
y = y3;
z = z3;
[parent[0] + x, parent[1] + y, parent[2] + z, parent[3] + child[3], parent[4] + child[4], parent[5] + child[5], parent[6] * child[6]]
}
/// The ecs.* names with their TypeScript types, for the registry.
pub const CALLS: &[(&str, &str, &str, &str)] = &[
("ecs.new", "{}", "{ world: number }", "a new world (Bevy's)"),
("ecs.clone", "{ world: number }", "{ world: number }", "a copy of a world"),
("ecs.free", "{ world: number }", "null", "drop a world"),
("ecs.spawn", "{ world: number; kind?: string; cols?: Record<string, number | string | boolean>; components?: Record<string, unknown>; parent?: number }", "{ id: number }", "a new entity: a kind with columns, and/or any components"),
("ecs.set", "{ world: number; id: number; cols: Record<string, number | string | boolean> }", "null", "columns merged into an entity's kind"),
("ecs.get", "{ world: number; id: number }", "{ id: number; kind: string } & Record<string, number | string | boolean>", "an entity's row (its kind's columns)"),
("ecs.despawn", "{ world: number; id: number }", "null", "remove an entity and its children"),
("ecs.insert", "{ world: number; id: number; components: Record<string, unknown> }", "null", "components added to (or replaced on) an entity"),
("ecs.remove", "{ world: number; id: number; names: string[] }", "null", "components taken off an entity"),
("ecs.components", "{ world: number; id: number }", "Record<string, unknown>", "an entity's components by name"),
("ecs.find", "{ world: number; with?: string[]; without?: string[]; where?: [string, \"==\" | \"!=\" | \"<\" | \"<=\" | \">\" | \">=\", number | string | boolean][]; rows?: boolean }", "{ ids: number[]; rows?: { id: number; components: Record<string, unknown> }[] }", "entities with every `with` component and no `without` one (Bevy's query), passing every condition (\"Comp.field\")"),
("ecs.query", "{ world: number; kind: string; where: [string, \"==\" | \"!=\" | \"<\" | \"<=\" | \">\" | \">=\", number | string | boolean][] }", "{ ids: number[] }", "ids of kind's entities passing every condition"),
("ecs.column", "{ world: number; kind: string; col: string }", "(number | null)[]", "one numeric column of a kind, in id order"),
("ecs.count", "{ world: number; kind: string }", "number", "how many entities of a kind"),
("ecs.rows", "{ world: number }", "({ id: number; kind: string } & Record<string, number | string | boolean>)[]", "every kind's rows, by kind then id"),
("ecs.parent", "{ world: number; id: number; parent?: number | null }", "number | null", "an entity's parent (set it with parent; null clears it)"),
("ecs.children", "{ world: number; id: number }", "number[]", "an entity's children"),
("ecs.resource", "{ world: number; name: string; value?: unknown }", "unknown", "a resource (set it with value)"),
("ecs.send", "{ world: number; name: string; value?: unknown }", "null", "an event for this frame"),
("ecs.events", "{ world: number; name: string }", "unknown[]", "this frame's events of a name"),
("ecs.clear_events", "{ world: number }", "null", "the frame's events cleared (each step starts with none)"),
("ecs.scene", "{ world: number }", "{ id: number; kind: \"Mesh\" | \"Light\"; mesh?: unknown; light?: unknown; position?: [number, number, number]; rotation?: [number, number, number]; scale?: number }[]", "the world's Mesh+Transform entities (world space) and lights, to draw"),
];
/// How many worlds are alive (media.live's leak check).
pub fn live() -> usize {
WORLDS.with(|ws| ws.borrow().1.len())
}
+3 -3
View File
@@ -167,9 +167,9 @@ pub fn live_scene(world: &mut World, ls: &mut LiveScene, engine: &mut Option<rae
None => {
let clear = scene_clear(world);
let p = ls.open(Shot { scene: &scene, clear: clear.as_deref() }, size.0, size.1, fps);
let mut e = aov_on(raea_render::engine::Engine::new_live(&p, &raea_render::inserted_of(&p), dir).map_err(|e| format!("the 3D didn't open: {e}"))?);
let e = raea_render::engine::Engine::open_in(engine, &p, dir).map_err(|e| format!("the 3D didn't open: {e}"))?;
aov_on(e);
e.set_rows(&[])?;
*engine = Some(e);
}
Some(e) => {
// the frame's own clear, keyed as a render keys a background that changes (RR1)
@@ -268,7 +268,7 @@ pub(crate) fn render_fed(app: &mut App, js: &Path, w: u32, h: u32, fps: f64, tot
if programmed && !restepped && raea_runtime_page::VIEW_BOX.lock().unwrap().is_some() {
restepped = true;
if let Some(p) = scene_program_checked(js, &dir, total, Some(wanted))? {
cx.scene3d = Some(raea_render::engine::Engine::new_live(&p, &raea_render::inserted_of(&p), &dir)?);
aov_on(raea_render::engine::Engine::open_in(&mut cx.scene3d, &p, &dir)?);
if let Some(m) = cx.manifest.as_mut() {
m.pop();
}
+4 -5
View File
@@ -299,7 +299,7 @@ pub(crate) fn render_bundle_with(js: &Path, dir: &Path, out: &Path, wanted: Opti
let mut cx = Ctx { dir, work: &work, sounds: Vec::new(), scene: Vec::new(), clear: None, marker: None, mix: None, audible: HashMap::new(), brand: page_css(dir, w, js), manifest: MANIFEST.lock().unwrap().as_ref().map(|_| Vec::new()), now: 0, said: Default::default(), made: HashMap::new(), scene3d: None, live3d: None };
if fed {
if let Some(p) = scene {
cx.scene3d = Some(aov_on(raea_render::engine::Engine::new_live(&p, &raea_render::inserted_of(&p), dir)?));
aov_on(raea_render::engine::Engine::open_in(&mut cx.scene3d, &p, dir)?);
raea_runtime_react::startup_mark("the 3D's engine open");
}
if live3d {
@@ -312,7 +312,7 @@ pub(crate) fn render_bundle_with(js: &Path, dir: &Path, out: &Path, wanted: Opti
let programmed = scene.is_some();
match scene {
Some(p) => {
cx.scene3d = Some(aov_on(raea_render::engine::Engine::new_live(&p, &raea_render::inserted_of(&p), dir)?));
aov_on(raea_render::engine::Engine::open_in(&mut cx.scene3d, &p, dir)?);
raea_runtime_react::startup_mark("the 3D's engine open");
}
None => cx.live3d = Some(LiveScene::default()),
@@ -337,7 +337,7 @@ pub(crate) fn render_bundle_with(js: &Path, dir: &Path, out: &Path, wanted: Opti
if i == 0 && programmed && raea_runtime_page::VIEW_BOX.lock().unwrap().is_some() {
let upto = wanted.iter().max().map_or(0, |m| m + 1);
if let Some(p) = scene_program_checked(js, dir, upto, Some(&wanted))? {
cx.scene3d = Some(aov_on(raea_render::engine::Engine::new_live(&p, &raea_render::inserted_of(&p), dir)?));
aov_on(raea_render::engine::Engine::open_in(&mut cx.scene3d, &p, dir)?);
px = bevy_over_3d(app.world_mut(), pg, &mut cx, fps)?;
}
}
@@ -442,11 +442,10 @@ pub(crate) fn render_bundle_with(js: &Path, dir: &Path, out: &Path, wanted: Opti
}
/// An engine for the scene path, drawing the guide data when `--aov` asked for it.
pub(crate) fn aov_on(mut e: raea_render::engine::Engine) -> raea_render::engine::Engine {
pub(crate) fn aov_on(e: &mut raea_render::engine::Engine) {
if AOV.load(std::sync::atomic::Ordering::Relaxed) {
e.want_aov();
}
e
}
/// Frame i's guide data (RT1) as mlxdlss run-sequence reads it: DIR/motion/frame-NNNNN.f32 (H x W x 2 float32) and
+14
View File
@@ -0,0 +1,14 @@
[package]
name = "raea-runtime-kinds"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "A 3D scene's rows for the kinds placed as a whole: glTF models, panels, decals, plates, fog volumes, fires, Gaussian splats, mesh sequences and fields of grass"
[dependencies]
raea-core-scene = { path = "../../core/scene" }
raea-core-program = { path = "../../core/program" }
raea-runtime-look = { path = "../look" }
bevy = { version = "=0.20.0", default-features = false, features = ["std"] }
serde_json = "1"
@@ -4,7 +4,7 @@
use super::*;
pub(super) fn rows(tracks: &[Track], p: &mut Program) {
pub fn rows(tracks: &[Track], p: &mut Program) {
for (k, (_, track)) in tracks.iter().enumerate() {
let its = filled(track);
let first = &its[0].props;
+51
View File
@@ -0,0 +1,51 @@
//! A 3D scene's rows for the kinds placed as a whole: glTF models, panels, decals, plates, fog volumes, fires, Gaussian
//! splats, mesh sequences and fields of grass. raea-runtime-scene walks the scene into each kind's tracks and builds the
//! rest (meshes, lights, text, the camera); a part's placement and name columns are shared by both.
use std::collections::BTreeMap;
use raea_core_program::ir::{Program, V};
use raea_core_scene::*;
use raea_runtime_look::*;
use serde_json::{Map, Value};
/// One part's frames, by its key: the part as each frame has it, or none where it isn't there.
pub type Track = (String, Vec<Option<Item>>);
mod models;
pub use models::*;
/// Gaussian splats' rows (<Splat>).
pub mod splat;
/// Baked simulations' and glitches' rows (<MeshSequence>, <Goo>, glitch props).
pub mod meshseq;
/// Fields of grass' rows (<Grass>).
pub mod grass;
/// A part's SDK name as its row's `name` column: what a Bevy Entity field (a ChildOf's parent) names it by.
pub fn name_column(row: &mut BTreeMap<String, V>, props: &Map<String, Value>) {
if let Some(Value::String(n)) = props.get("name") {
row.insert("name".into(), V::S(n.clone()));
}
}
/// World position, rotation (Bevy's quaternion, q_x q_y q_z q_w: no Euler round trip, docs/control.feature FC1d) and
/// scale of each frame; each frame's quaternion takes the sign nearer the frame before's, so keys turn the short way.
pub fn placement(p: &mut Program, row: &mut BTreeMap<String, V>, id: &str, its: &[Item]) {
let mut prev = bevy::math::Quat::IDENTITY;
let per: Vec<[f64; 10]> = its.iter().map(|it| {
let (s, q, t) = it.world.to_scale_rotation_translation();
// a zero scale has no rotation (it comes out NaN, keyed on every frame since NaN never equals itself): the one before
let q = if q.is_finite() { q } else { prev };
prev = if q.dot(prev) < 0.0 { -q } else { q };
[t.x as f64, t.y as f64, t.z as f64, prev.x as f64, prev.y as f64, prev.z as f64, prev.w as f64, s.x as f64, s.y as f64, s.z as f64]
}).collect();
for (k, name) in ["x", "y", "z", "q_x", "q_y", "q_z", "q_w"].iter().enumerate() {
exact(p, row, id, name, &per.iter().map(|t| t[k]).collect::<Vec<_>>());
}
let sc: Vec<[f64; 3]> = per.iter().map(|t| [t[7], t[8], t[9]]).collect();
if sc.iter().any(|s| s.iter().any(|v| (v - 1.0).abs() > 1e-9)) {
for (k, name) in ["scale_x", "scale_y", "scale_z"].iter().enumerate() {
exact(p, row, id, name, &sc.iter().map(|s| s[k]).collect::<Vec<_>>());
}
}
}
@@ -33,7 +33,7 @@ pub(super) fn cloth_columns(p: &mut Program, row: &mut BTreeMap<String, V>, id:
/// Numeric props of a sequence and the columns they key (the default when a frame leaves one out).
const KEYED: &[(&str, &str, f64)] = &[("frame", "frame", 0.0), ("roughness", "rough", 0.3), ("metalness", "metal", 0.0)];
pub(super) fn rows(tracks: &[Track], p: &mut Program) {
pub fn rows(tracks: &[Track], p: &mut Program) {
for (k, (_, track)) in tracks.iter().enumerate() {
let its = filled(track);
let id = format!("meshseq{k}");
@@ -1,8 +1,8 @@
use super::*;
/// glTF models: the file, its clip and the clip's time (keyed: the component works it out from the frame)
pub(crate) fn models_rows(tr: &Tracks, names: &[String], p: &mut Program) {
for (k, (_, track)) in tr.models.iter().enumerate() {
pub fn models_rows(tracks: &[Track], names: &[String], p: &mut Program) {
for (k, (_, track)) in tracks.iter().enumerate() {
let its = filled(&track);
let id = format!("model{k}");
let mut row = BTreeMap::new();
@@ -64,7 +64,7 @@ pub(crate) fn models_rows(tr: &Tracks, names: &[String], p: &mut Program) {
// attached to another model's bone: that model's row by its name
if let Some(a) = first.get("attach") {
let to = a.get("to").and_then(Value::as_str).unwrap_or("");
if let Some(j) = tr.models.iter().position(|(_, t)| t.iter().flatten().next().and_then(|i| i.props.get("name")).and_then(Value::as_str) == Some(to)) {
if let Some(j) = tracks.iter().position(|(_, t)| t.iter().flatten().next().and_then(|i| i.props.get("name")).and_then(Value::as_str) == Some(to)) {
row.insert("attach_to".into(), V::S(format!("model{j}")));
row.insert("attach_bone".into(), V::S(a.get("bone").and_then(Value::as_str).unwrap_or("").into()));
} else {
@@ -76,7 +76,7 @@ pub(crate) fn models_rows(tr: &Tracks, names: &[String], p: &mut Program) {
let (mut joints, mut rows) = (Vec::new(), Vec::new());
for (joint, to) in b {
let to = to.as_str().unwrap_or("");
match tr.models.iter().position(|(_, t)| t.iter().flatten().next().and_then(|i| i.props.get("name")).and_then(Value::as_str) == Some(to)) {
match tracks.iter().position(|(_, t)| t.iter().flatten().next().and_then(|i| i.props.get("name")).and_then(Value::as_str) == Some(to)) {
Some(j) => {
joints.push(joint.clone());
rows.push(format!("model{j}"));
@@ -140,8 +140,8 @@ pub(crate) fn models_rows(tr: &Tracks, names: &[String], p: &mut Program) {
}
/// pictures in space (raea-render's panel: unlit, painted once, moved by the GPU)
pub(crate) fn panels_rows(tr: &Tracks, names: &[String], p: &mut Program) {
for (k, (_, track)) in tr.panels.iter().enumerate() {
pub fn panels_rows(tracks: &[Track], names: &[String], p: &mut Program) {
for (k, (_, track)) in tracks.iter().enumerate() {
let its = filled(&track);
let id = format!("plane{k}");
let mut row = BTreeMap::new();
@@ -177,8 +177,8 @@ pub(crate) fn panels_rows(tr: &Tracks, names: &[String], p: &mut Program) {
/// decals: the picture and its surface from the first frame; placement, colour and opacity keyed (a stain that
/// spreads, a label that fades in)
pub(crate) fn decals_rows(tr: &Tracks, p: &mut Program) {
for (k, (_, track)) in tr.decals.iter().enumerate() {
pub fn decals_rows(tracks: &[Track], p: &mut Program) {
for (k, (_, track)) in tracks.iter().enumerate() {
let its = filled(&track);
let id = format!("decal{k}");
let mut row = BTreeMap::new();
@@ -205,8 +205,8 @@ pub(crate) fn decals_rows(tr: &Tracks, p: &mut Program) {
/// footage behind the 3D (raea-render's plate: a video frame per frame on the camera's far plane, unlit): its source time
/// keyed, the clip and its lens's distortion the first frame's
pub(crate) fn plates_rows(tr: &Tracks, p: &mut Program) {
for (k, (_, track)) in tr.plates.iter().enumerate() {
pub fn plates_rows(tracks: &[Track], p: &mut Program) {
for (k, (_, track)) in tracks.iter().enumerate() {
let its = filled(&track);
let id = format!("plate{k}");
let mut row = BTreeMap::new();
@@ -223,8 +223,8 @@ pub(crate) fn plates_rows(tr: &Tracks, p: &mut Program) {
}
/// fog volumes (a <VolumetricFog>'s boxes of air): placement, density and colour keyed, the rest the first frame's
pub(crate) fn fogs_rows(tr: &Tracks, p: &mut Program) {
for (k, (_, track)) in tr.fogs.iter().enumerate() {
pub fn fogs_rows(tracks: &[Track], p: &mut Program) {
for (k, (_, track)) in tracks.iter().enumerate() {
let its = filled(&track);
let id = format!("fog{k}");
let mut row = BTreeMap::new();
@@ -253,8 +253,8 @@ pub(crate) fn fogs_rows(tr: &Tracks, p: &mut Program) {
}
/// fires (<Fire>: a flame drawn as a volume): its foot, its box's size, its clock, brightness and colour keyed
pub(crate) fn fires_rows(tr: &Tracks, p: &mut Program) {
for (k, (_, track)) in tr.fires.iter().enumerate() {
pub fn fires_rows(tracks: &[Track], p: &mut Program) {
for (k, (_, track)) in tracks.iter().enumerate() {
let its = filled(&track);
let id = format!("fire{k}");
let mut row = BTreeMap::new();
@@ -33,7 +33,7 @@ const KEYED: &[(&str, &str, f64)] = &[
/// Vector props: the prop, its three columns.
const VECS: &[(&str, [&str; 3])] = &[("wind", ["wind_x", "wind_y", "wind_z"]), ("revealFrom", ["reveal_x", "reveal_y", "reveal_z"]), ("revealAxis", ["reveal_ax", "reveal_ay", "reveal_az"])];
pub(super) fn rows(tracks: &[Track], p: &mut Program) {
pub fn rows(tracks: &[Track], p: &mut Program) {
for (k, (_, track)) in tracks.iter().enumerate() {
let its = filled(track);
let id = format!("splat{k}");
+3
View File
@@ -51,6 +51,9 @@ raea-core-alloc = { path = "../../core/alloc" }
# a composition's TSX bundled into the script the engine runs
raea-runtime-bundle = { path = "../../runtime/bundle" }
raea-core-scene = { path = "../../core/scene" }
# a long BufferMesh kept on disk by its content (read.rs names3d, docs/render-memory.feature RM8)
raea-core-shape = { path = "../../core/shape" }
xxhash-rust = { version = "0.8", features = ["xxh3"] }
raea-runtime-calls = { path = "../../runtime/calls" }
raea-runtime-shared = { path = "../../runtime/shared" }
raea-runtime-scene = { path = "../../runtime/scene" }
+1 -1
View File
@@ -41,7 +41,7 @@ thread_local! {
/// each part's data-props as last parsed: its text and the props, and the scene it was last read in
static PROPS3D: std::cell::RefCell<bevy::ecs::entity::EntityHashMap<(String, std::sync::Arc<Map<String, Value>>, u64)>> = std::cell::RefCell::new(Default::default());
/// each part's data-3d and data-shape as last read, shared
static NAMES3D: std::cell::RefCell<bevy::ecs::entity::EntityHashMap<(std::sync::Arc<str>, Option<std::sync::Arc<str>>)>> = std::cell::RefCell::new(Default::default());
static NAMES3D: std::cell::RefCell<bevy::ecs::entity::EntityHashMap<(std::sync::Arc<str>, Option<std::sync::Arc<str>>, Option<(usize, u64)>)>> = std::cell::RefCell::new(Default::default());
/// each part's data-at (an <Instances>' placements) as last read, shared while its text is the same (issue 84)
static AT3D: std::cell::RefCell<bevy::ecs::entity::EntityHashMap<std::sync::Arc<str>>> = std::cell::RefCell::new(Default::default());
/// scenes read (scene_of): what's in PROPS3D but not read in the last two is let go
+17 -5
View File
@@ -34,21 +34,33 @@ pub(crate) fn props3d(e: Entity, text: Option<&str>) -> std::sync::Arc<Map<Strin
})
}
/// A part's kind and shape, the shared ones from its last read when they're the same
/// A part's kind and shape, the shared ones from its last read when they're the same. A long <BufferMesh> shape
/// (`buffer:{json}`, raea_core_shape::KEEP_BUFFER_AT on) goes on as `buffer:@NAME`, its text kept on disk by its
/// content (kept_buffer, docs/render-memory.feature RM8), and is known again by its length and xxh3 (about 2 ms for
/// 51 MB), never named again while it's the same.
pub(crate) fn names3d(e: Entity, kind: &str, shape: Option<&str>) -> (std::sync::Arc<str>, Option<std::sync::Arc<str>>) {
let long = shape.filter(|s| s.len() >= raea_core_shape::KEEP_BUFFER_AT && s.starts_with("buffer:{"));
let sig = long.map(|s| (s.len(), xxhash_rust::xxh3::xxh3_64(s.as_bytes())));
NAMES3D.with_borrow_mut(|c| {
if let Some((k, s)) = c.get(&e)
if let Some((k, s, was)) = c.get(&e)
&& &**k == kind
&& s.as_deref() == shape
&& match sig {
Some(sig) => *was == Some(sig),
None => was.is_none() && s.as_deref() == shape,
}
{
return (k.clone(), s.clone());
}
let v: (std::sync::Arc<str>, Option<std::sync::Arc<str>>) = (kind.into(), shape.map(Into::into));
let out: Option<std::sync::Arc<str>> = match long {
Some(text) => Some(raea_core_shape::kept_buffer(text).map(Into::into).unwrap_or_else(|| text.into())),
None => shape.map(Into::into),
};
let v: (std::sync::Arc<str>, Option<std::sync::Arc<str>>) = (kind.into(), out);
// bounded well past a big scene's parts (many_cubes has 10,000; at 8,192 it was cleared every frame)
if c.len() > 1 << 17 {
c.clear();
}
c.insert(e, v.clone());
c.insert(e, (v.0.clone(), v.1.clone(), sig));
v
})
}
+2
View File
@@ -10,6 +10,8 @@ description = "A composition's 3D as raea-render rows: the camera, lights, meshe
raea-core-scene = { path = "../../core/scene" }
raea-core-program = { path = "../../core/program" }
raea-runtime-look = { path = "../look" }
# the rows of the kinds placed as a whole (models, splats, grass and the rest)
raea-runtime-kinds = { path = "../kinds" }
raea-runtime-scene2d = { path = "../scene2d" }
bevy = { version = "=0.20.0", default-features = false, features = ["std"] }
serde_json = "1"
+8 -43
View File
@@ -15,22 +15,15 @@ use raea_core_scene::*;
pub use raea_runtime_look::{camera, column, rgba_of};
use raea_runtime_look::*;
// the rows of the kinds placed as a whole (models, panels, decals, plates, fog, fire, splats, mesh sequences, grass)
use raea_runtime_kinds::*;
mod parts;
use parts::*;
mod models;
use models::*;
mod live;
pub use live::{LiveScene, Shot};
pub use raea_core_scene::{LIVE_GROUPS, cam_keyed, live_dynamic};
mod fast;
/// Gaussian splats' rows (<Splat>).
mod splat;
/// Baked simulations' and glitches' rows (<MeshSequence>, <Goo>, glitch props).
mod meshseq;
/// Fields of grass' rows (<Grass>).
mod grass;
/// The scene-wide parts placed by their parent alone, a camera column or a post effect each: node kind, item kind. An
/// <Atmosphere> is Bevy's procedural sky round the scene, a <Skybox> Bevy's cubemap sky on the camera.
const BY_PARENT: [(&str, &str); 19] = [("AmbientLight", "ambient"), ("Bloom", "bloom"), ("Atmosphere", "atmosphere"), ("Fog", "fog"), ("ToneMapping", "tonemapping"), ("DepthOfField", "dof"), ("Grade", "grade"), ("VolumetricFog", "volfog"), ("Environment", "environment"), ("Skybox", "skybox"),
@@ -176,12 +169,6 @@ fn walk(n: &Node3, parent: Mat4, out: &mut Vec<Item>) {
}
}
/// A part's SDK name as its row's `name` column: what a Bevy Entity field (a ChildOf's parent) names it by.
fn name_column(row: &mut BTreeMap<String, V>, props: &Map<String, Value>) {
if let Some(Value::String(n)) = props.get("name") {
row.insert("name".into(), V::S(n.clone()));
}
}
/// The <BevyComponent> children of a part (a Mesh, a Model, a light, the camera) onto its item as `components`: Bevy's
/// own reflected components, or a compiled-in plugin's, applied by raea-render through the TypeRegistry (plugins.rs).
@@ -224,27 +211,6 @@ pub fn items_of(scene: &[Node3]) -> Vec<Item> {
}
/// World position, rotation (Bevy's quaternion, q_x q_y q_z q_w: no Euler round trip, docs/control.feature FC1d) and
/// scale of each frame; each frame's quaternion takes the sign nearer the frame before's, so keys turn the short way.
fn placement(p: &mut Program, row: &mut BTreeMap<String, V>, id: &str, its: &[Item]) {
let mut prev = bevy::math::Quat::IDENTITY;
let per: Vec<[f64; 10]> = its.iter().map(|it| {
let (s, q, t) = it.world.to_scale_rotation_translation();
// a zero scale has no rotation (it comes out NaN, keyed on every frame since NaN never equals itself): the one before
let q = if q.is_finite() { q } else { prev };
prev = if q.dot(prev) < 0.0 { -q } else { q };
[t.x as f64, t.y as f64, t.z as f64, prev.x as f64, prev.y as f64, prev.z as f64, prev.w as f64, s.x as f64, s.y as f64, s.z as f64]
}).collect();
for (k, name) in ["x", "y", "z", "q_x", "q_y", "q_z", "q_w"].iter().enumerate() {
exact(p, row, id, name, &per.iter().map(|t| t[k]).collect::<Vec<_>>());
}
let sc: Vec<[f64; 3]> = per.iter().map(|t| [t[7], t[8], t[9]]).collect();
if sc.iter().any(|s| s.iter().any(|v| (v - 1.0).abs() > 1e-9)) {
for (k, name) in ["scale_x", "scale_y", "scale_z"].iter().enumerate() {
exact(p, row, id, name, &sc.iter().map(|s| s[k]).collect::<Vec<_>>());
}
}
}
/// The lights, meshes, models and pictures in space, as rows, from each frame's parts.
pub fn rows(all: &[Vec<Item>], p: &mut Program) {
@@ -261,7 +227,6 @@ pub fn rows(all: &[Vec<Item>], p: &mut Program) {
}
}
type Track = (String, Vec<Option<Item>>);
/// Each kind group's tracks, worked out once (a live frame worked them out twice: in rows_into and again for its ids)
struct Tracks {
@@ -315,12 +280,12 @@ fn rows_into_of(all: &[Vec<Item>], tr: &Tracks, p: &mut Program) {
meshes_rows(tr, &names, p);
entities_rows(tr, p);
texts_rows(tr, &names, p);
models_rows(tr, &names, p);
panels_rows(tr, &names, p);
decals_rows(tr, p);
plates_rows(tr, p);
fogs_rows(tr, p);
fires_rows(tr, p);
models_rows(&tr.models, &names, p);
panels_rows(&tr.panels, &names, p);
decals_rows(&tr.decals, p);
plates_rows(&tr.plates, p);
fogs_rows(&tr.fogs, p);
fires_rows(&tr.fires, p);
// fields of grass (<Grass>): grass.rs
grass::rows(&tr.grasses, p);
// gaussian splats (<Splat>): splat.rs
+12 -1
View File
@@ -134,6 +134,7 @@ pub(crate) fn meshes_rows(tr: &Tracks, names: &[String], p: &mut Program) {
let mat = |i: &Item| i.material.as_ref().map(|m| m.props.clone()).unwrap_or_default();
let mats: Vec<std::sync::Arc<Map<String, Value>>> = its.iter().map(mat).collect();
let basic = its[0].material.as_ref().is_some_and(|m| &*m.kind == "MeshBasicMaterial");
let swaps = raea_core_scene::swaps_maps(&its[0]);
let colors: Vec<String> = mats.iter().map(|m| hex(m.get("color")).unwrap_or("#cccccc".into())).collect();
row.insert("color".into(), V::S(colors[0].clone()));
if colors.iter().any(|c| *c != colors[0]) {
@@ -171,7 +172,17 @@ pub(crate) fn meshes_rows(tr: &Tracks, names: &[String], p: &mut Program) {
for (prop, col) in [("map", "map"), ("normalMap", "normal_map"), ("roughnessMap", "rough_map"), ("metalnessMap", "metal_map"), ("metallicRoughnessMap", "mr_map"), ("aoMap", "ao_map"), ("emissiveMap", "emissive_map"), ("depthMap", "depth_map"), ("clearcoatNormalMap", "clearcoat_normal_map")] {
let Some(src) = m0.get(prop).and_then(Value::as_str) else { continue };
// render images an app ping-pongs between are keyed frame by frame (R3F23c: raea-sys-rendermap); a picture is its first frame's
let srcs: Vec<String> = if src.starts_with("render:") { mats.iter().map(|m| match m.get(prop) { Some(Value::String(s)) => s.clone(), _ => src.to_string() }).collect() } else { vec![src_path(src)] };
// a swapped map (raea_core_scene::SWAPPED_MAPS on a plain standard surface: raea-sys-material's SwappedMaps,
// docs/render-memory.feature RM6) is keyed too: one texture whose picture the engine swaps, where each
// picture once cut a part of its own, all of them made at load (a pool's 96 water normal maps)
let swapped = swaps && raea_core_scene::SWAPPED_MAPS.iter().any(|(p, _)| *p == prop);
let srcs: Vec<String> = if src.starts_with("render:") {
mats.iter().map(|m| match m.get(prop) { Some(Value::String(s)) => s.clone(), _ => src.to_string() }).collect()
} else if swapped {
mats.iter().map(|m| src_path(m.get(prop).and_then(Value::as_str).filter(|s| !s.starts_with("render:")).unwrap_or(src))).collect()
} else {
vec![src_path(src)]
};
keyed_strings(p, &mut row, &id, col, &srcs);
}
if let Some(Value::Array(r)) = m0.get("repeat") {
+1
View File
@@ -10,6 +10,7 @@ description = "The 3D kinds raea's 3D SDK writes, drawn with Bevy: meshes, light
raea-io-trace = { path = "../../io/trace" }
raea-sys-frame = { path = "../../systems/frame" }
raea-sys-material = { path = "../../systems/material" }
raea-sys-toon = { path = "../../systems/toon" }
raea-sys-framepass = { path = "../../systems/framepass" }
raea-sys-compute = { path = "../../systems/compute" }
raea-sys-sampler = { path = "../../systems/sampler" }
+2 -1
View File
@@ -36,7 +36,8 @@ use raea_core_program::eval::Tup;
use raea_core_program::ir::V;
use raea_sys_frame::*;
use raea_sys_frame::bevy_api;
use raea_sys_material::{decal, surface, toon};
use raea_sys_material::{decal, surface};
use raea_sys_toon as toon;
use raea_sys_fog::{froxel, froxel_glass};
use raea_sys_post::lens;
use raea_sys_look::paint;
+6 -6
View File
@@ -149,8 +149,8 @@ fn pierce(x: &Solid, wx: &Mat4, into: &Solid, wi: &Mat4) -> Option<Hit> {
let (mut n, mut depth, mut top, mut bottom) = (0usize, 0f32, f32::MIN, f32::MAX);
let (mut dlo, mut dhi) = (Vec3::splat(f32::MAX), Vec3::splat(f32::MIN));
let mut seam = Vec::new();
for p in &x.surf {
let w = wx.transform_point3(*p);
for p in x.surf_points() {
let w = wx.transform_point3(p);
if w.cmplt(lo).any() || w.cmpgt(hi).any() {
continue;
}
@@ -200,7 +200,7 @@ fn volume(a: &Solid, wa: &Mat4, b: &Solid, wb: &Mat4) -> Option<Hit> {
let vol = |s: &Solid, k: f32| s.volume() * k.powi(3);
let small_first = vol(a, sa) <= vol(b, sb);
let (s, ws, ks, o, wo, ko) = if small_first { (a, wa, sa, b, wb, sb) } else { (b, wb, sb, a, wa, sa) };
if s.inside.is_empty() {
if s.inside == 0 {
return None;
}
let (slo, shi) = world_box(s, ws);
@@ -242,7 +242,7 @@ fn volume(a: &Solid, wa: &Mat4, b: &Solid, wb: &Mat4) -> Option<Hit> {
continue;
}
let i = ((z * s.n[1] + y) * s.n[0] + x) as u32;
let ds = s.depth[i as usize];
let ds = s.depth[i as usize] as u16;
if ds < 3 {
continue;
}
@@ -262,7 +262,7 @@ fn volume(a: &Solid, wa: &Mat4, b: &Solid, wb: &Mat4) -> Option<Hit> {
}
}
}
let share = (hits * stride) as f32 / s.inside.len() as f32;
let share = (hits * stride) as f32 / s.inside as f32;
// shallow, a sliver, or wholly inside (no seam to see: a decal in a decal, a part hidden in another)
if depth < DEPTH_SHARE * size || share < VOLUME_SHARE || share > ENCLOSED {
return None;
@@ -351,7 +351,7 @@ mod tests {
// a 1.2 m slab 3 cm thick, its fine solid closed: deepest in the middle
let sill = voxelize(&boxed(Vec3::ZERO, Vec3::new(1.2, 0.03, 0.22))).unwrap();
let f = sill.fine.as_deref().expect("a thin part's fine solid");
assert!(sill.inside.is_empty() && sill.solid(), "a cell thick at RES, solid in its fine one");
assert!(sill.inside == 0 && sill.solid(), "a cell thick at RES, solid in its fine one");
assert!(f.at(Vec3::ZERO) >= 6, "{}", f.at(Vec3::ZERO));
}
+32 -11
View File
@@ -9,12 +9,16 @@ pub(crate) struct Solid {
pub(crate) min: Vec3,
pub(crate) cell: f32,
pub(crate) n: [usize; 3],
pub(crate) depth: Vec<u16>,
/// the cells at least one cell under the surface
pub(crate) inside: Vec<u32>,
/// each cell's depth, a byte (docs/render-memory.feature RM10: a depth is at most half the grid's longest side,
/// THIN_MOST * RES / 2 in a fine solid, and is held at 255 past it; as u16 the grids were 603 MB of halcyon r109's
/// sequence, every part in view the whole shot)
pub(crate) depth: Vec<u8>,
/// how many cells are at least one cell under the surface (only counted: the list of them was 368 MB in r109)
pub(crate) inside: usize,
/// points on its real surface (from its triangles), SURF_GRAIN of a cell apart: what the pierce test puts in
/// another part
pub(crate) surf: Vec<Vec3>,
/// another part. Each kept as three u16s across lo..hi (surf_points gives them back: a 10 m part's to 0.08 mm),
/// with no spare capacity: as Vec3s grown point by point they were 301 MB in r109
pub(crate) surf: Vec<[u16; 3]>,
/// a thin part's finer solid, the pierce test's depths in it
pub(crate) fine: Option<Box<Solid>>,
pub(crate) lo: Vec3,
@@ -31,7 +35,12 @@ impl Solid {
if x >= self.n[0] || y >= self.n[1] || z >= self.n[2] {
return 0;
}
self.depth[(z * self.n[1] + y) * self.n[0] + x]
self.depth[(z * self.n[1] + y) * self.n[0] + x] as u16
}
/// The surface points in the part's own space.
pub(crate) fn surf_points(&self) -> impl Iterator<Item = Vec3> + '_ {
let step = (self.hi - self.lo) / 65535.0;
self.surf.iter().map(move |q| self.lo + Vec3::new(q[0] as f32, q[1] as f32, q[2] as f32) * step)
}
pub(crate) fn centre(&self, i: u32) -> Vec3 {
let i = i as usize;
@@ -40,12 +49,12 @@ impl Solid {
}
/// whether it has an inside at all: at RES, or in its fine solid (a sill a cell thick at RES)
pub(crate) fn solid(&self) -> bool {
!self.inside.is_empty() || self.fine.as_ref().is_some_and(|f| !f.inside.is_empty())
self.inside > 0 || self.fine.as_ref().is_some_and(|f| f.inside > 0)
}
/// its volume, from the finer of its solids
pub(crate) fn volume(&self) -> f32 {
let s = self.fine.as_deref().filter(|f| !f.inside.is_empty()).unwrap_or(self);
s.inside.len() as f32 * s.cell.powi(3)
let s = self.fine.as_deref().filter(|f| f.inside > 0).unwrap_or(self);
s.inside as f32 * s.cell.powi(3)
}
/// how far under the surface a cell of this depth is, in the part's own units (the surface was thickened a cell
/// to close pinholes)
@@ -72,13 +81,24 @@ pub(crate) fn voxelize(tris: &[[Vec3; 3]]) -> Option<Solid> {
let cell = ext.max_element() / RES;
let thin = (ext.min_element() / THIN).max(ext.max_element() / (RES * THIN_MOST));
let mut solid = grid(tris, lo, hi, cell);
solid.surf = surface(tris, cell * SURF_GRAIN);
solid.surf = quantized(&surface(tris, cell * SURF_GRAIN), lo, hi);
if thin < 0.5 * cell {
solid.fine = Some(Box::new(grid(tris, lo, hi, thin)));
}
Some(solid)
}
/// Points as three u16s each across lo..hi (Solid::surf_points reads them back), exactly as many as there are.
fn quantized(points: &[Vec3], lo: Vec3, hi: Vec3) -> Vec<[u16; 3]> {
let scale = Vec3::splat(65535.0) / (hi - lo).max(Vec3::splat(f32::MIN_POSITIVE));
let mut out = Vec::with_capacity(points.len());
out.extend(points.iter().map(|p| {
let q = ((*p - lo) * scale).round().clamp(Vec3::ZERO, Vec3::splat(65535.0));
[q.x as u16, q.y as u16, q.z as u16]
}));
out
}
/// Points on the triangles, one per `grain` cube they cross.
pub(crate) fn surface(tris: &[[Vec3; 3]], grain: f32) -> Vec<Vec3> {
let mut seen = std::collections::HashSet::new();
@@ -191,7 +211,8 @@ pub(crate) fn grid(tris: &[[Vec3; 3]], lo: Vec3, hi: Vec3, cell: f32) -> Solid {
}
}
}
let inside: Vec<u32> = (0..depth.len() as u32).filter(|&i| depth[i as usize] >= 3).collect();
let inside = depth.iter().filter(|&&d| d >= 3).count();
let depth: Vec<u8> = depth.into_iter().map(|d| d.min(255) as u8).collect();
Solid { name: String::new(), min, cell, n, depth, inside, surf: Vec::new(), fine: None, lo, hi }
}
+2
View File
@@ -11,6 +11,8 @@ description = "A frame's rows as raea's passes read them: FrameRows, the loaded
native = ["dep:raea-io-media"]
[dependencies]
# a row's per-frame tables (tables), split out at the crate limit (11-29)
raea-core-tables = { path = "../../core/tables" }
bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "3d_bevy_render", "bevy_ui"] }
raea-core-program = { path = "../../core/program" }
# cuts between cameras (systems/shots), as raea_sys_frame::shots
+3 -1
View File
@@ -33,7 +33,7 @@ pub use state::*;
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 frame
pub mod tables;
pub use raea_core_tables as tables;
/// the frames where another camera becomes the piece's (a cut between cameras, RR2)
pub use raea_sys_shots as shots;
@@ -49,6 +49,8 @@ pub struct ModelReady;
/// r-th row) and its media rows (for resolving sources).
#[derive(Resource, Clone)]
pub struct Edit {
/// the edit's size, rate and length; the engine's load leaves its rows and keys out (they are the store's and the
/// timeline's), so it doesn't hold every row a second time
pub prog: Program,
/// every frame, evaluated once per load from the base gathered out of the store (row r is the store's r-th row)
pub timeline: std::sync::Arc<raea_core_program::timeline::Timeline>,
+19 -1
View File
@@ -76,8 +76,13 @@ pub fn find(world: &World, kind: &str, id: &str) -> Option<Entity> {
/// Add a row at the end; its columns become components.
pub fn spawn(world: &mut World, t: &Tup) -> Entity {
spawn_with(world, t, t.vals.iter())
}
/// spawn, with only the columns given (the engine's load leaves its spawn_only ones out of the store).
fn spawn_with<'a>(world: &mut World, t: &Tup, cols: impl Iterator<Item = (&'a String, &'a V)>) -> Entity {
let e = world.spawn(RowKey { kind: t.kind.clone(), id: t.id.clone() }).id();
for (c, v) in &t.vals {
for (c, v) in cols {
set(world, e, c, v.clone());
}
let s = schema(world);
@@ -131,6 +136,19 @@ pub fn load(world: &mut World, rows: &[Tup]) -> Vec<Entity> {
rows.iter().map(|t| spawn(world, t)).collect()
}
/// A column the engine reads only as its row spawns, from the program's rows, never from the store or a frame: a
/// mesh's shape (one per row: a change of shape is another row). docs/render-memory.feature RM5: halcyon's shapes were
/// 274 MB of text, held by the program, the store and the evaluator's columns.
pub fn spawn_only(kind: &str, col: &str) -> bool {
kind == "mesh" && col == "shape"
}
/// load, for an engine: the rows without their spawn_only columns (the engine spawns from the rows themselves).
pub fn load_for_engine(world: &mut World, rows: &[Tup]) -> Vec<Entity> {
clear(world);
rows.iter().map(|t| spawn_with(world, t, t.vals.iter().filter(|(c, _)| !spawn_only(&t.kind, c)))).collect()
}
/// One value of a row's column (None: the row doesn't have it).
pub fn get(world: &World, e: Entity, col: &str) -> Option<V> {
let kind = &world.get::<RowKey>(e)?.kind;
+5 -9
View File
@@ -13,12 +13,8 @@ raea-sys-atlas = { path = "../atlas" }
parry3d = "0.31"
rayon = "1"
serde_json = "1"
# the paths the light is traced along (BK3)
raea-sys-lighttrace = { path = "../lighttrace" }
# a model read on its own second UVs (own.rs): its meshes, and its base colour textures decoded
gltf = { version = "1.4", default-features = false, features = ["utils", "names"] }
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
[dev-dependencies]
# the panorama the atelier's run reads (own/tests.rs)
image = { version = "0.25", default-features = false, features = ["hdr"] }
# the process's one shared GPU device, and wgpu's ray queries on it (BK3)
raea-gpu-device = { path = "../../gpu/device" }
wgpu = "=30.0.1"
bytemuck = "1"
pollster = "0.4"
+2 -3
View File
@@ -5,7 +5,6 @@
//! progress). Next: a clean map (BK4), and the bake in a composition (BK5).
// each texel's ray origin and the texels inside other geometry (BK2)
pub mod own;
pub mod texels;
#[cfg(test)]
mod trace_tests;
// the light that bounces, traced on the GPU (BK3)
pub mod trace;
-169
View File
@@ -1,169 +0,0 @@
//! A model traced on its own second UVs, a map a mesh (docs/bake.feature BK3): what lightbake.py lays out, so raea's
//! light is compared with Cycles' texel for texel. Every mesh of the .glb in world space with its materials (base
//! colour, its texture, less what's metal), and a mesh's texels at a side: those whose centre a triangle covers.
use gltf::mesh::util::ReadIndices;
use parry3d::glamx::{Mat4, Vec2, Vec3};
use std::collections::HashMap;
use std::ops::Range;
use parry3d::shape::TriMesh;
use rayon::prelude::*;
use crate::texels::starts;
use raea_sys_lighttrace::{Image, Surface};
pub struct Mesh {
pub name: String,
/// its triangles in Model::triangles
pub triangles: Range<usize>,
}
/// A .glb's meshes in the world, as World takes them, with each vertex's second UV.
#[derive(Default)]
pub struct Model {
pub positions: Vec<[f32; 3]>,
pub normals: Vec<[f32; 3]>,
pub uvs: Vec<[f32; 2]>,
pub second: Vec<[f32; 2]>,
pub triangles: Vec<[u32; 3]>,
pub surfaces: Vec<Surface>,
pub textures: Vec<Image>,
pub meshes: Vec<Mesh>,
}
/// A texel of a mesh's map whose centre a triangle covers.
pub struct At {
pub x: u32,
pub y: u32,
/// its point off the surface, the sides of its footprint and its open starts (texels::starts)
pub origin: [f32; 3],
pub sides: [[f32; 3]; 2],
pub open: u32,
/// the shading normal there (the vertices', interpolated), on the plane's side
pub normal: [f32; 3],
}
/// The model, its textures no longer a side than `most` (a bounce blurs the rest away).
pub fn read(glb: &[u8], most: u32) -> Result<Model, String> {
let g = gltf::Gltf::from_slice(glb).map_err(|e| e.to_string())?;
let blob = g.blob.clone().ok_or("a model without its binary: only a .glb is read")?;
let mut m = Model::default();
let mut images = HashMap::new();
let mut stack: Vec<(gltf::Node, Mat4)> = match g.default_scene().or(g.scenes().next()) {
Some(s) => s.nodes().map(|n| (n, Mat4::IDENTITY)).collect(),
None => return Err("a model without a scene".into()),
};
while let Some((node, up)) = stack.pop() {
let world = up * Mat4::from_cols_array_2d(&node.transform().matrix());
stack.extend(node.children().map(|c| (c, world)));
let Some(mesh) = node.mesh() else { continue };
let first = m.triangles.len();
for p in mesh.primitives() {
if p.mode() != gltf::mesh::Mode::Triangles {
continue;
}
primitive(&mut m, &p, world, &blob, &mut images, most)?;
}
m.meshes.push(Mesh { name: mesh.name().unwrap_or_default().to_string(), triangles: first..m.triangles.len() });
}
Ok(m)
}
fn primitive(m: &mut Model, p: &gltf::Primitive, world: Mat4, blob: &[u8], images: &mut HashMap<usize, u32>, most: u32) -> Result<(), String> {
let r = p.reader(|_| Some(blob));
let base = m.positions.len() as u32;
let turn = world.inverse().transpose();
m.positions.extend(r.read_positions().ok_or("a mesh without positions")?.map(|v| world.transform_point3(Vec3::from(v)).to_array()));
let n = m.positions.len() - base as usize;
match r.read_normals() {
Some(v) => m.normals.extend(v.map(|v| turn.transform_vector3(Vec3::from(v)).normalize_or_zero().to_array())),
None => m.normals.extend(vec![[0.0; 3]; n]),
}
let uv = |set: u32| r.read_tex_coords(set).map_or(vec![[0.0; 2]; n], |u| u.into_f32().collect());
let (first, second) = (uv(0), uv(1));
m.uvs.extend(first);
m.second.extend(second);
let index: Vec<u32> = match r.read_indices() {
Some(ReadIndices::U8(i)) => i.map(u32::from).collect(),
Some(ReadIndices::U16(i)) => i.map(u32::from).collect(),
Some(ReadIndices::U32(i)) => i.collect(),
None => (0..n as u32).collect(),
};
let pbr = p.material().pbr_metallic_roughness();
let [cr, cg, cb, _] = pbr.base_color_factor();
let texture = match pbr.base_color_texture() {
Some(t) => Some(texture(m, &t.texture().source(), blob, images, most)?),
None => None,
};
let e = p.material().emissive_factor();
let surface = Surface { albedo: [cr, cg, cb], emission: e, metallic: pbr.metallic_factor(), roughness: pbr.roughness_factor(), f0: 0.04, texture };
m.triangles.extend(index.chunks_exact(3).map(|t| [base + t[0], base + t[1], base + t[2]]));
m.surfaces.resize(m.triangles.len(), surface);
Ok(())
}
fn texture(m: &mut Model, image: &gltf::Image, blob: &[u8], images: &mut HashMap<usize, u32>, most: u32) -> Result<u32, String> {
if let Some(k) = images.get(&image.index()) {
return Ok(*k);
}
let gltf::image::Source::View { view, .. } = image.source() else { return Err("a texture outside the .glb".into()) };
let bytes = &blob[view.offset()..view.offset() + view.length()];
let full = image::load_from_memory(bytes).map_err(|e| format!("a texture: {e}"))?;
let small = if full.width().max(full.height()) > most { full.thumbnail(most, most) } else { full }.to_rgba8();
let rgba = small.pixels().map(|p| u32::from_le_bytes(p.0)).collect();
m.textures.push(Image { width: small.width(), height: small.height(), rgba });
let k = m.textures.len() as u32 - 1;
images.insert(image.index(), k);
Ok(k)
}
/// A mesh's texels on its second UVs at `side` by `side`, each once (the first triangle over its centre); `offset` as
/// Texels' own.
pub fn texels(m: &Model, mesh: &Mesh, world: &TriMesh, side: u32, offset: f32, whole: bool) -> Vec<At> {
let mut taken = vec![false; (side * side) as usize];
let mut out = vec![];
for tri in &m.triangles[mesh.triangles.clone()] {
let uv = tri.map(|v| m.second[v as usize].map(|c| c * side as f32));
let [pos, nor] = [&m.positions, &m.normals].map(|list| tri.map(|v| Vec3::from(list[v as usize])));
let cross = |a: [f32; 2], b: [f32; 2], c: [f32; 2]| (Vec2::from(b) - Vec2::from(a)).perp_dot(Vec2::from(c) - Vec2::from(a));
let area = cross(uv[0], uv[1], uv[2]);
let plane = (pos[1] - pos[0]).cross(pos[2] - pos[0]);
if area.abs() < 1e-9 || plane.length_squared() < 1e-24 {
continue;
}
// a texel's sides on this triangle, metres
let (e1, e2) = (Vec2::from(uv[1]) - Vec2::from(uv[0]), Vec2::from(uv[2]) - Vec2::from(uv[0]));
let sides = [((pos[1] - pos[0]) * e2.y - (pos[2] - pos[0]) * e1.y) / area, ((pos[2] - pos[0]) * e1.x - (pos[1] - pos[0]) * e2.x) / area];
let span = |k: usize| {
let (lo, hi) = uv.iter().fold((f32::MAX, f32::MIN), |(l, h), q| (l.min(q[k]), h.max(q[k])));
((lo - 0.5).ceil().max(0.0) as u32, ((hi - 0.5).floor() as i64).clamp(-1, side as i64 - 1))
};
let ((x0, x1), (y0, y1)) = (span(0), span(1));
for y in y0 as i64..=y1 {
for x in x0 as i64..=x1 {
let c = [x as f32 + 0.5, y as f32 + 0.5];
let w = [cross(uv[1], uv[2], c) / area, cross(uv[2], uv[0], c) / area, cross(uv[0], uv[1], c) / area];
let at = (y as u32 * side + x as u32) as usize;
if w.iter().any(|&v| v < 0.0) || taken[at] {
continue;
}
taken[at] = true;
let p = pos[0] * w[0] + pos[1] * w[1] + pos[2] * w[2];
let shade = (nor[0] * w[0] + nor[1] * w[1] + nor[2] * w[2]).normalize_or_zero();
let mut n = plane.normalize();
if n.dot(shade) < 0.0 {
n = -n;
}
out.push((At { x: x as u32, y: y as u32, origin: p.to_array(), sides: sides.map(|s| s.to_array()), open: 0, normal: if shade == Vec3::ZERO { n } else { shade }.to_array() }, n, pos));
}
}
}
out.into_par_iter().enumerate().map(|(k, (a, n, pos))| {
let (origin, open) = starts(world, pos, Vec3::from(a.origin), n, a.sides.map(Vec3::from), offset, k as u32, whole);
At { origin, open, ..a }
}).collect()
}
#[cfg(test)]
mod tests;
-148
View File
@@ -1,148 +0,0 @@
use super::*;
use crate::texels::tests::{cuboid, glb};
use raea_sys_lighttrace::{Settings, Sky, Starts, Sun, World, trace};
#[test]
fn a_model_reads_in_the_world_with_its_materials() {
let m = read(&glb(&[(cuboid([0.0; 3], [1.0; 3]), [0.0, 2.0, 0.0])]), 64).unwrap();
assert_eq!((m.meshes.len(), m.triangles.len(), m.surfaces.len()), (1, 12, 12));
assert!(m.positions.iter().all(|p| (2.0..=3.0).contains(&p[1])), "the node's translation");
// glTF's metallic and roughness are 1 when a material doesn't say; the rest under it has the dielectric's F0
assert_eq!(m.surfaces[0], Surface { albedo: [1.0; 3], metallic: 1.0, roughness: 1.0, f0: 0.04, ..Surface::default() });
}
#[test]
fn texels_lie_where_the_second_uvs_put_them() {
// a 2 m by 1 m wall standing at z = 3, facing +Z, over the left half of its map
let quad = [([0.0f32, 0.0, 3.0], [0.0f32, 1.0f32]), ([2.0, 0.0, 3.0], [0.5, 1.0]), ([2.0, 1.0, 3.0], [0.5, 0.5]), ([0.0, 1.0, 3.0], [0.0, 0.5])];
let m = Model {
positions: quad.iter().map(|q| q.0).collect(),
normals: vec![[0.0, 0.0, 1.0]; 4],
uvs: vec![[0.0; 2]; 4],
second: quad.iter().map(|q| q.1).collect(),
triangles: vec![[0, 1, 2], [0, 2, 3]],
surfaces: vec![Surface::default(); 2],
meshes: vec![Mesh { name: "wall".into(), triangles: 0..2 }],
..Model::default()
};
let world = parry3d::shape::TriMesh::new(m.positions.iter().map(|p| Vec3::from(*p)).collect(), m.triangles.clone()).unwrap();
let t = texels(&m, &m.meshes[0], &world, 16, 1e-4, false);
assert_eq!(t.len(), 8 * 8, "a quarter of 16 x 16, each once");
for a in &t {
let want = [(a.x as f32 + 0.5) / 8.0 * 2.0, 1.0 - (a.y as f32 + 0.5 - 8.0) / 8.0];
assert!((a.origin[0] - want[0]).abs() < 1e-2 && (a.origin[1] - want[1]).abs() < 1e-2 && (a.origin[2] - 3.0001).abs() < 1e-5, "{},{} at {:?}", a.x, a.y, a.origin);
assert_eq!(a.normal, [0.0, 0.0, 1.0]);
assert_eq!(a.sides, [[0.25, 0.0, 0.0], [0.0, -0.125, 0.0]], "a texel's sides");
}
}
fn number(name: &str, d: f32) -> f32 {
std::env::var(name).ok().and_then(|v| v.parse().ok()).unwrap_or(d)
}
/// lightbake.py's smooth: a 3 x 3 mean over the covered texels, `passes` times.
fn smooth(side: usize, map: &mut Vec<Option<[f32; 3]>>, passes: usize) {
for _ in 0..passes {
let from = map.clone();
for (i, out) in map.iter_mut().enumerate().filter(|(_, v)| v.is_some()) {
let (x, y) = ((i % side) as i32, (i / side) as i32);
let near: Vec<[f32; 3]> = (-1..=1).flat_map(|dy| (-1..=1).map(move |dx| (x + dx, y + dy))).filter(|&(a, b)| a >= 0 && b >= 0 && a < side as i32 && b < side as i32).filter_map(|(a, b)| from[b as usize * side + a as usize]).collect();
*out = Some(std::array::from_fn(|k| near.iter().map(|c| c[k]).sum::<f32>() / near.len() as f32));
}
}
}
/// The atelier's run (docs/bake.feature BK3): a model lightbake.py baked, traced on its own maps under the light its
/// .blend held, and each map against Cycles' (compare.rs's map_stops: the mean distance in stops and the signed one,
/// over the texels both cover, Cycles' clipped ones out). RAEA_BAKE_DIR holds set.glb, set.lightmaps.json and
/// lightmaps/, RAEA_BAKE_SKY the panorama; _RUNS ("512x4": samples x bounces, each in turn), _STRENGTH, _ROTATION, _SMOOTH, _SUN ("x,y,z,r,g,b")
/// _ONLY (mesh names), _OFFSET (metres), _WHOLE (a texel's buried part counts, as in Cycles), _LAMBERT (no glossy layers, for a diffuse-only reference), _DUMP (a folder: each map's luminances, raea's and Cycles', and the texel's place, as f32 threes)
/// and _OUT (each run's table, OUT-RUN.json).
#[test]
#[ignore]
fn against_cycles() {
let dir = std::path::PathBuf::from(std::env::var("RAEA_BAKE_DIR").expect("RAEA_BAKE_DIR"));
let t0 = std::time::Instant::now();
let mut m = read(&std::fs::read(dir.join("set.glb")).unwrap(), 512).unwrap();
if std::env::var("RAEA_BAKE_LAMBERT").is_ok() {
m.surfaces.iter_mut().for_each(|s| *s = Surface { albedo: s.albedo.map(|c| c * (1.0 - s.metallic)), metallic: 0.0, f0: 0.0, ..*s });
}
let listed: serde_json::Value = serde_json::from_slice(&std::fs::read(dir.join("set.lightmaps.json")).unwrap()).unwrap();
let far = m.positions.iter().flatten().fold(0.0f32, |a, v| a.max(v.abs()));
let offset = number("RAEA_BAKE_OFFSET", crate::texels::offset(far));
let hdr = image::open(std::env::var("RAEA_BAKE_SKY").expect("RAEA_BAKE_SKY")).unwrap().to_rgb32f();
let sky = Sky { width: hdr.width(), height: hdr.height(), rgb: hdr.pixels().map(|p| p.0).collect(), strength: number("RAEA_BAKE_STRENGTH", 1.0), rotation: number("RAEA_BAKE_ROTATION", 0.0) };
let sun = std::env::var("RAEA_BAKE_SUN").ok().map(|s| {
let v: Vec<f32> = s.split(',').map(|x| x.parse().unwrap()).collect();
Sun { dir: [v[0], v[1], v[2]], irradiance: [v[3], v[4], v[5]], half_angle: 0.00459 }
});
let world = parry3d::shape::TriMesh::new(m.positions.iter().map(|p| Vec3::from(*p)).collect(), m.triangles.clone()).unwrap();
let mut maps = vec![];
for l in listed["meshes"].as_array().unwrap() {
let name = l["mesh"].as_str().unwrap();
if std::env::var("RAEA_BAKE_ONLY").is_ok_and(|only| !only.split(',').any(|o| o == name)) {
continue;
}
let mesh = m.meshes.iter().find(|x| x.name == name).unwrap_or_else(|| panic!("no mesh {name}"));
let side = l["size"].as_u64().unwrap() as u32;
maps.push((name.to_string(), mesh, side, l["lightmap_exposure"].as_f64().unwrap() as f32 / 683.0, texels(&m, mesh, &world, side, offset, std::env::var("RAEA_BAKE_WHOLE").is_ok())));
}
let origin: Vec<[f32; 3]> = maps.iter().flat_map(|x| x.4.iter().map(|a| a.origin)).collect();
let sides: Vec<[[f32; 3]; 2]> = maps.iter().flat_map(|x| x.4.iter().map(|a| a.sides)).collect();
let open: Vec<u32> = maps.iter().flat_map(|x| x.4.iter().map(|a| a.open)).collect();
let normal: Vec<[f32; 3]> = maps.iter().flat_map(|x| x.4.iter().map(|a| a.normal)).collect();
println!("{} meshes, {} triangles, {} texels, {} inside, {} textures; read and laid in {:.1} s", m.meshes.len(), m.triangles.len(), origin.len(), open.iter().filter(|m| **m == 0).count(), m.textures.len(), t0.elapsed().as_secs_f64());
let runs = std::env::var("RAEA_BAKE_RUNS").unwrap_or("512x4".into());
let w = World { positions: &m.positions, triangles: &m.triangles, surfaces: &m.surfaces, uvs: &m.uvs, textures: &m.textures };
for run in runs.split(',') {
let [samples, bounces] = run.split('x').collect::<Vec<_>>().try_into().expect("SAMPLESxBOUNCES");
let s = Settings { samples: samples.parse().unwrap(), bounces: bounces.parse().unwrap(), per_pass: 8, sky: sky.clone(), sun };
let t1 = std::time::Instant::now();
let light = trace(&w, &Starts { origin: &origin, normal: &normal, sides: &sides, open: &open, offset }, &s, &mut |_, _| {}).unwrap();
let seconds = t1.elapsed().as_secs_f64();
println!("{} values that aren't finite", light.iter().flatten().filter(|v| !v.is_finite()).count());
println!("{run}: traced {} samples, {} bounces in {seconds:.1} s", s.samples, s.bounces);
let passes = number("RAEA_BAKE_SMOOTH", 2.0) as usize;
let (mut first, mut rows) = (0, vec![]);
let (mut abs, mut signed, mut n, mut zeros) = (0.0f64, 0.0f64, 0usize, 0usize);
for (name, mesh, side, scale, at) in &maps {
let side = *side as usize;
let mut mine = vec![None; side * side];
for (k, a) in at.iter().enumerate() {
if open[first + k] != 0 {
mine[a.y as usize * side + a.x as usize] = Some(light[first + k]);
}
}
first += at.len();
smooth(side, &mut mine, passes);
let file = listed["meshes"].as_array().unwrap().iter().find(|l| l["mesh"] == name.as_str()).unwrap()["map"].as_str().unwrap().rsplit('/').next().unwrap().to_string();
let theirs = image::open(dir.join("lightmaps").join(file)).unwrap().to_rgb16();
let lum = |c: [f32; 3]| 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];
let (mut a, mut b, mut k) = (0.0f64, 0.0f64, 0usize);
let mut pairs: Vec<f32> = vec![];
for (i, v) in mine.iter().enumerate() {
let q = theirs.get_pixel((i % side) as u32, (i / side) as u32).0;
let (Some(v), false) = (v, q.contains(&u16::MAX)) else { continue };
let (x, y) = (lum(*v), lum(q.map(|c| c as f32 / 65535.0 * scale)));
pairs.extend([x, y, i as f32]);
if x <= 0.0 || y <= 0.0 {
zeros += 1;
continue;
}
let st = (x / y).log2() as f64;
(a, b, k) = (a + st.abs(), b + st, k + 1);
}
if let Ok(d) = std::env::var("RAEA_BAKE_DUMP") {
std::fs::write(format!("{d}/{run}-{name}.f32"), pairs.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>()).unwrap();
}
let s0 = m.surfaces[mesh.triangles.start];
(abs, signed, n) = (abs + a, signed + b, n + k);
rows.push(serde_json::json!({ "mesh": name, "side": side, "texels": k, "mean_stops": a / k.max(1) as f64, "bias_stops": b / k.max(1) as f64, "textured": s0.texture.is_some(), "albedo": s0.albedo }));
}
let over = rows.iter().filter(|r| r["texels"].as_u64().unwrap() > 0 && r["mean_stops"].as_f64().unwrap() > 1.0 / 3.0).count();
println!("{n} texels compared ({zeros} left out, one side exactly 0): mean {:.3} stops, bias {:+.3}; {over} of {} meshes over 1/3 stop", abs / n as f64, signed / n as f64, rows.len());
if let Ok(out) = std::env::var("RAEA_BAKE_OUT") {
std::fs::write(format!("{out}-{run}.json"), serde_json::json!({ "samples": s.samples, "bounces": s.bounces, "trace_seconds": seconds, "mean_stops": abs / n as f64, "bias_stops": signed / n as f64, "meshes": rows }).to_string()).unwrap();
}
}
}
+12 -55
View File
@@ -13,7 +13,6 @@ use rayon::prelude::*;
use serde_json::{Value, json};
use raea_sys_atlas::rays::{hemi, sample};
use raea_sys_lighttrace::CENTRE;
pub use raea_sys_atlas::{Layout, Texel};
/// Rays each texel casts for the inside test: cosine-weighted, the atlas's rotated R2 sequence per texel.
@@ -24,11 +23,9 @@ pub struct Texels {
pub layout: Layout,
/// each texel's ray origin: its surface point, four offsets in from its triangle's edges, moved `offset` along its normal
pub origin: Vec<[f32; 3]>,
/// the two sides of each texel's footprint, and which of the points over it are open (0 inside other geometry: their
/// rays meet back faces, left for BK4 to fill), as raea_sys_lighttrace::Starts takes them
pub sides: Vec<[[f32; 3]; 2]>,
pub open: Vec<u32>,
/// metres off the surface: `offset` of the model's size or of its farthest coordinate
/// the texels inside other geometry (their rays meet back faces), left for BK4 to fill
pub inside: Vec<bool>,
/// metres off the surface: 1e-5 of the model's size or of its farthest coordinate, at least 10 microns
pub offset: f32,
/// the model's triangles in world space, for the trace (BK3)
pub mesh: TriMesh,
@@ -40,19 +37,6 @@ pub fn request(texels: f32, max_side: u32) -> Value {
json!({ "env": { "density": texels, "max_side": max_side } })
}
impl Texels {
/// Which texels are inside other geometry, in the layout's order.
pub fn inside(&self) -> Vec<bool> {
self.open.iter().map(|&m| m == 0).collect()
}
}
/// How far off a surface a ray starts in a model of this size, metres: three times what its floats round to
/// (a_surface_never_meets_itself), and well under the gaps things are stacked with (0.2 mm in a 15 m room).
pub fn offset(size: f32) -> f32 {
(1e-6 * size).max(1e-6)
}
/// Every texel of the model's atlas in the world: its origin and whether it's inside other geometry.
pub fn texels(glb: &[u8], req: &Value) -> Result<Texels, String> {
let (layout, mesh) = raea_sys_atlas::laid(glb, req)?;
@@ -60,24 +44,20 @@ pub fn texels(glb: &[u8], req: &Value) -> Result<Texels, String> {
for &v in mesh.vertices() {
(lo, hi, far) = (lo.min(v), hi.max(v), far.max(v.abs().max_element()));
}
let offset = offset((hi - lo).length().max(far));
// a texel of the atlas is a square of its density; its turn on the surface doesn't matter to its footprint
let sides: Vec<[[f32; 3]; 2]> = layout.texels.iter().map(|t| {
let n = Vec3::from(t.n);
let u = n.any_orthonormal_vector() / layout.density;
[u.to_array(), n.cross(u).to_array()]
}).collect();
let (origin, open) = layout.texels.par_iter().zip(&sides).enumerate().map(|(i, (t, s))| {
let offset = (1e-5 * (hi - lo).length().max(far)).max(1e-5);
let half = 0.5 / layout.density;
let origin: Vec<[f32; 3]> = layout.texels.iter().map(|t| {
let tri = mesh.indices()[t.tri as usize].map(|v| mesh.vertices()[v as usize]);
starts(&mesh, tri, Vec3::from(t.p), Vec3::from(t.n), s.map(Vec3::from), offset, i as u32, false)
}).unzip();
Ok(Texels { layout, origin, sides, open, offset, mesh })
(off_edges(tri, Vec3::from(t.p), 4.0 * offset, half) + Vec3::from(t.n) * offset).to_array()
}).collect();
let inside = layout.texels.par_iter().zip(&origin).enumerate().map(|(i, (t, &o))| inside(&mesh, Vec3::from(o), Vec3::from(t.n), i as u32)).collect();
Ok(Texels { layout, origin, inside, offset, mesh })
}
/// Whether a texel is inside other geometry: of its rays that meet anything, at least half meet a back face and more
/// meet back faces than front ones. A foot inside a closed floor slab meets back faces every way; one under a floor
/// that is a single plane meets its underside upwards and nothing downwards, and is inside too.
pub(crate) fn inside(mesh: &TriMesh, o: Vec3, n: Vec3, seed: u32) -> bool {
fn inside(mesh: &TriMesh, o: Vec3, n: Vec3, seed: u32) -> bool {
let (mut back, mut front) = (0, 0);
for j in 0..RAYS {
let d = hemi(n, sample(seed, j));
@@ -89,34 +69,11 @@ pub(crate) fn inside(mesh: &TriMesh, o: Vec3, n: Vec3, seed: u32) -> bool {
back * 2 >= RAYS && back > front
}
/// Where a texel's samples start: its point off the surface, and which of the 4 x 4 points of its footprint are open
/// (on its triangle, clear of its edges, not inside other geometry). A texel half buried keeps only its open half:
/// what it's averaged over is what can be seen (`whole` takes the buried part too, as Cycles does: for comparing). A
/// corner and the centre that agree stand for the rest.
pub(crate) fn starts(mesh: &TriMesh, tri: [Vec3; 3], p: Vec3, n: Vec3, [u, v]: [Vec3; 2], offset: f32, seed: u32, whole: bool) -> ([f32; 3], u32) {
let gap = 4.0 * offset;
let centre = off_edges(tri, p, gap, 0.5 * u.length().max(v.length())) + n * offset;
let at = |c: u32| p + u * ((c % 4) as f32 / 4.0 - 0.375) + v * ((c / 4) as f32 / 4.0 - 0.375);
let cells: Vec<u32> = (0..16).filter(|&c| off_edges(tri, at(c), gap, f32::MAX).distance(at(c)) < 0.5 * offset).collect();
if whole && !cells.is_empty() {
return ((p + n * offset).to_array(), cells.iter().fold(0, |m, c| m | 1 << c));
}
let hid = inside(mesh, centre, n, seed);
let buried = |c: u32| inside(mesh, at(c) + n * offset, n, seed ^ (c + 1).wrapping_mul(0x9e37_79b9));
if cells.is_empty() {
return (centre.to_array(), if hid { 0 } else { CENTRE });
}
let corners: Vec<u32> = cells.iter().copied().filter(|c| [0, 3, 12, 15].contains(c)).collect();
let mixed = corners.iter().any(|&c| buried(c) != hid) || (corners.is_empty() && cells.len() < 16);
let open = if !mixed { if hid { 0 } else { cells.iter().fold(0, |m, c| m | 1 << c) } } else { cells.iter().filter(|&&c| !buried(c)).fold(0, |m, c| m | 1 << c) };
if open == 0 { (centre.to_array(), if hid { 0 } else { CENTRE }) } else { ((p + n * offset).to_array(), open) }
}
/// p moved along its triangle until it's `gap` from each edge, or by `most` (half a texel: its own footprint; a needle
/// narrower than the gap would send it to its far end). A chart's
/// edge band takes its texels from the edge itself, and a point on the edge of a floor is in the plane of the wall
/// standing on it: its rays started in that wall and half of them left the room.
pub(crate) fn off_edges([a, b, c]: [Vec3; 3], p: Vec3, gap: f32, most: f32) -> Vec3 {
fn off_edges([a, b, c]: [Vec3; 3], p: Vec3, gap: f32, most: f32) -> Vec3 {
let n = (b - a).cross(c - a);
let area = n.length_squared().max(f32::MIN_POSITIVE);
// barycentric weights, each raised to what stands `gap` from the edge opposite its corner (its height: area / edge)
+4 -4
View File
@@ -100,7 +100,7 @@ fn a_point_on_an_edge_is_moved_off_it_and_never_far() {
fn texels_inside_the_slab_are_marked_and_those_in_the_open_are_not() {
let t = texels(&set(), &request(16.0, 1024)).unwrap();
let (mut sunk, mut open, mut under) = (0, 0, 0);
for (x, &inside) in t.layout.texels.iter().zip(&t.inside()) {
for (x, &inside) in t.layout.texels.iter().zip(&t.inside) {
let [px, py, pz] = x.p;
if (-0.18..-0.02).contains(&py) && px.abs() < 0.26 && pz.abs() < 0.26 {
// the block's sides within the slab's thickness, away from its faces
@@ -123,7 +123,7 @@ fn texels_inside_the_slab_are_marked_and_those_in_the_open_are_not() {
#[test]
fn the_same_model_gives_the_same_texels() {
let (a, b) = (texels(&set(), &request(16.0, 1024)).unwrap(), texels(&set(), &request(16.0, 1024)).unwrap());
assert!(a.layout == b.layout && a.origin == b.origin && a.open == b.open);
assert!(a.layout == b.layout && a.origin == b.origin && a.inside == b.inside);
}
#[test]
@@ -143,11 +143,11 @@ fn measured() {
let layout = raea_sys_atlas::layout(&glb, &request(64.0, 4096)).unwrap();
let t1 = std::time::Instant::now();
let t = texels(&glb, &request(64.0, 4096)).unwrap();
let inside = t.inside().iter().filter(|&&i| i).count();
let inside = t.inside.iter().filter(|&&i| i).count();
if let Ok(out) = std::env::var("RAEA_BAKE_OUT") {
// the atlas: grey where a texel is in the open, red where it's inside, black where there's none (a PPM)
let mut img = vec![0u8; (layout.w * layout.h * 3) as usize];
for (x, &i) in t.layout.texels.iter().zip(&t.inside()) {
for (x, &i) in t.layout.texels.iter().zip(&t.inside) {
let k = 3 * (x.y as usize * layout.w as usize + x.x as usize);
img[k..k + 3].copy_from_slice(if i { &[230, 40, 30] } else { &[150, 150, 150] });
}
@@ -4,86 +4,32 @@
//! systems/rt's from a Bevy render world; the kernel's WGSL (wgsl/diffuse.wgsl) is a module rt can include as it is.
//! A device without ray queries is refused with the reason, and the composition renders unbaked.
pub mod glossy;
#[cfg(test)]
mod tests;
use wgpu::util::DeviceExt;
/// What a triangle sends on: its base colour (times its texture's, when it has one) and the light it gives off, linear RGB;
/// how much of it is a metal, how rough its glossy layers are, and the F0 of the dielectric layer over the rest (0: none,
/// and with no metal either it's Lambert).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
/// What a triangle sends on: the share of light it reflects (diffuse) and the light it gives off, linear RGB.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Surface {
pub albedo: [f32; 3],
pub emission: [f32; 3],
pub metallic: f32,
pub roughness: f32,
pub f0: f32,
/// its texture's place in `World::textures`
pub texture: Option<u32>,
}
/// A colour texture: sRGB, 8 bits a channel (red in the low byte), top row first.
pub struct Image {
pub width: u32,
pub height: u32,
pub rgba: Vec<u32>,
}
/// The world a bake traces: triangles in world space, each with its surface; a UV a vertex (or none at all).
/// The world a bake traces: triangles in world space, each with its surface.
pub struct World<'a> {
pub positions: &'a [[f32; 3]],
pub triangles: &'a [[u32; 3]],
pub surfaces: &'a [Surface],
pub uvs: &'a [[f32; 2]],
pub textures: &'a [Image],
}
/// The sky: a panorama (its middle straight ahead, -Z) at its strength, turned counter-clockwise from above.
#[derive(Clone, Debug)]
pub struct Sky {
pub width: u32,
pub height: u32,
/// linear RGB, top row first
pub rgb: Vec<[f32; 3]>,
pub strength: f32,
pub rotation: f32,
}
impl Sky {
/// One light from everywhere.
pub fn even(rgb: [f32; 3]) -> Sky {
Sky { width: 1, height: 1, rgb: vec![rgb], strength: 1.0, rotation: 0.0 }
}
}
/// The sun: out at the texel (it stays live), in at every bounce after.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Sun {
/// toward it
pub dir: [f32; 3],
/// its irradiance on a surface facing it, linear RGB, in the sky's units
pub irradiance: [f32; 3],
/// half its disk's angle, radians
pub half_angle: f32,
}
/// A texel that starts only at its point (`Starts::open`).
pub const CENTRE: u32 = 1 << 16;
/// What's traced from: each texel's point (BK2, already off its surface) and normal; the two sides of its footprint,
/// and which of the 4 x 4 points over it are open (a bit each, row by row; `CENTRE` alone for its point only, 0 when it's
/// inside other geometry and left at zero for BK4 to fill); and the offset each bounce leaves its surface by.
/// What's traced from: each texel's origin (BK2, already off its surface), its normal, and whether it's inside other
/// geometry (left at zero for BK4 to fill), and the offset each bounce leaves its surface by.
pub struct Starts<'a> {
pub origin: &'a [[f32; 3]],
pub normal: &'a [[f32; 3]],
pub sides: &'a [[[f32; 3]; 2]],
pub open: &'a [u32],
pub inside: &'a [bool],
pub offset: f32,
}
#[derive(Clone, Debug)]
#[derive(Clone, Copy, Debug)]
pub struct Settings {
/// samples a texel
pub samples: u32,
@@ -91,13 +37,13 @@ pub struct Settings {
pub bounces: u32,
/// samples a texel in each pass: a pass short enough that the machine stays responsive
pub per_pass: u32,
pub sky: Sky,
pub sun: Option<Sun>,
/// the sky's light, linear RGB (the composition's <Environment> comes in BK3's next step)
pub sky: [f32; 3],
}
impl Default for Settings {
fn default() -> Self {
Self { samples: 512, bounces: 4, per_pass: 16, sky: Sky::even([1.0; 3]), sun: None }
Self { samples: 512, bounces: 4, per_pass: 16, sky: [1.0; 3] }
}
}
@@ -107,15 +53,8 @@ const CHUNK: u32 = 1 << 18;
/// The light reaching each texel (the mean its cosine-weighted rays bring back), in `from`'s order; inside texels 0.
pub fn trace(world: &World, from: &Starts, s: &Settings, progress: &mut dyn FnMut(u32, u32)) -> Result<Vec<[f32; 3]>, String> {
let n = from.origin.len();
if from.normal.len() != n || from.open.len() != n || from.sides.len() != n || world.surfaces.len() != world.triangles.len() {
return Err("trace: the texels' origins, normals, sides and open starts, and the triangles' surfaces, must match".into());
}
if s.sky.rgb.is_empty() || s.sky.rgb.len() != (s.sky.width * s.sky.height) as usize {
return Err("trace: the sky's picture doesn't match its size".into());
}
let textured = world.surfaces.iter().any(|s| s.texture.is_some());
if (textured && world.uvs.len() != world.positions.len()) || world.surfaces.iter().any(|s| s.texture.is_some_and(|t| t as usize >= world.textures.len())) {
return Err("trace: a textured surface needs its texture and a UV on every vertex".into());
if from.normal.len() != n || from.inside.len() != n || world.surfaces.len() != world.triangles.len() {
return Err("trace: the texels' origins, normals and inside marks, and the triangles' surfaces, must match".into());
}
if n == 0 || world.triangles.is_empty() {
return Ok(vec![[0.0; 3]; n]);
@@ -140,27 +79,9 @@ fn dispatch(device: &wgpu::Device, queue: &wgpu::Queue, world: &World, from: &St
let n = from.origin.len();
let tlas = accel(device, queue, world);
let vec4 = |v: [f32; 3], w: f32| [v[0], v[1], v[2], w];
let mut uvs = world.uvs.to_vec();
uvs.resize(world.positions.len(), [0.0; 2]);
let positions: Vec<[f32; 4]> = world.positions.iter().zip(&uvs).map(|(p, uv)| vec4(*p, uv[0])).collect();
let vs: Vec<f32> = uvs.iter().map(|uv| uv[1]).collect();
let firsts: Vec<u32> = world.textures.iter().scan(0u32, |at, t| Some(std::mem::replace(at, *at + t.rgba.len() as u32))).collect();
let surfaces: Vec<[u32; 16]> = world.surfaces.iter().map(|s| {
let tex = s.texture.map_or([0; 4], |k| [1, firsts[k as usize], world.textures[k as usize].width, world.textures[k as usize].height]);
let mut row = [0u32; 16];
for k in 0..3 {
(row[k], row[4 + k]) = (s.albedo[k].to_bits(), s.emission[k].to_bits());
}
row[8..12].copy_from_slice(&tex);
row[12..15].copy_from_slice(&[s.metallic, s.roughness, s.f0].map(f32::to_bits));
row
}).collect();
let mut images: Vec<u32> = world.textures.iter().flat_map(|t| t.rgba.iter().copied()).collect();
if images.is_empty() {
images.push(0);
}
let sky: Vec<[f32; 4]> = s.sky.rgb.iter().map(|c| vec4(c.map(|x| x * s.sky.strength), 0.0)).chain(glossy::table()).collect();
let texels: Vec<[f32; 4]> = (0..n).flat_map(|i| [vec4(from.origin[i], f32::from_bits(from.open[i])), vec4(from.normal[i], 0.0), vec4(from.sides[i][0], 0.0), vec4(from.sides[i][1], 0.0)]).collect();
let positions: Vec<[f32; 4]> = world.positions.iter().map(|p| vec4(*p, 1.0)).collect();
let surfaces: Vec<[f32; 4]> = world.surfaces.iter().flat_map(|s| [vec4(s.albedo, 0.0), vec4(s.emission, 0.0)]).collect();
let texels: Vec<[f32; 4]> = (0..n).flat_map(|i| [vec4(from.origin[i], from.inside[i] as u32 as f32), vec4(from.normal[i], 0.0)]).collect();
let storage = |label: &str, bytes: &[u8], usage: wgpu::BufferUsages| device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some(label), contents: bytes, usage: wgpu::BufferUsages::STORAGE | usage });
let index: Vec<u32> = world.triangles.iter().flatten().copied().collect();
let bufs = [
@@ -170,34 +91,24 @@ fn dispatch(device: &wgpu::Device, queue: &wgpu::Queue, world: &World, from: &St
storage("lightbake texels", bytemuck::cast_slice(&texels), wgpu::BufferUsages::empty()),
storage("lightbake accum", &vec![0u8; n * 16], wgpu::BufferUsages::COPY_SRC),
];
let more = [
storage("lightbake vs", bytemuck::cast_slice(&vs), wgpu::BufferUsages::empty()),
storage("lightbake textures", bytemuck::cast_slice(&images), wgpu::BufferUsages::empty()),
storage("lightbake sky", bytemuck::cast_slice(&sky), wgpu::BufferUsages::empty()),
];
let params = device.create_buffer(&wgpu::BufferDescriptor { label: Some("lightbake params"), size: 80, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
let src = format!("enable wgpu_ray_query;\n{}\n{}\n{}", include_str!("wgsl/diffuse.wgsl"), include_str!("wgsl/glossy.wgsl"), include_str!("wgsl/trace.wgsl"));
let params = device.create_buffer(&wgpu::BufferDescriptor { label: Some("lightbake params"), size: 48, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
let src = format!("enable wgpu_ray_query;\n{}\n{}", include_str!("wgsl/diffuse.wgsl"), include_str!("wgsl/trace.wgsl"));
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("lightbake trace"), source: wgpu::ShaderSource::Wgsl(src.into()) });
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some("lightbake trace"), layout: None, module: &module, entry_point: Some("main"), compilation_options: Default::default(), cache: None });
let mut entries = vec![wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::AccelerationStructure(&tlas) }];
let all = bufs.iter().chain(std::iter::once(&params)).chain(&more);
entries.extend(all.enumerate().map(|(k, b)| wgpu::BindGroupEntry { binding: k as u32 + 1, resource: b.as_entire_binding() }));
entries.extend(bufs.iter().enumerate().map(|(k, b)| wgpu::BindGroupEntry { binding: k as u32 + 1, resource: b.as_entire_binding() }));
entries.push(wgpu::BindGroupEntry { binding: 6, resource: params.as_entire_binding() });
let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("lightbake trace"), layout: &pipeline.get_bind_group_layout(0), entries: &entries });
let passes = s.samples.div_ceil(s.per_pass.max(1));
for pass in 0..passes {
let per = s.per_pass.max(1).min(s.samples - pass * s.per_pass.max(1));
for first in (0..n as u32).step_by(CHUNK as usize) {
let mut p = [0u32; 20];
if let Some(sun) = &s.sun {
let l = sun.dir.iter().map(|x| x * x).sum::<f32>().sqrt();
for k in 0..3 {
(p[k], p[4 + k]) = ((sun.dir[k] / l).to_bits(), sun.irradiance[k].to_bits());
}
p[3] = sun.half_angle.cos().to_bits();
let mut p = [0u32; 12];
for (k, v) in s.sky.iter().enumerate() {
p[k] = v.to_bits();
}
let end = (first + CHUNK).min(n as u32);
(p[8], p[9], p[10], p[11], p[12], p[13]) = (end, pass * s.per_pass.max(1), per, s.bounces, from.offset.to_bits(), first);
(p[14], p[15], p[16]) = (s.sky.width, s.sky.height, s.sky.rotation.to_bits());
(p[4], p[5], p[6], p[7], p[8], p[9]) = (end, pass, per, s.bounces, from.offset.to_bits(), first);
queue.write_buffer(&params, 0, bytemuck::cast_slice(&p));
let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("lightbake pass") });
{
@@ -213,11 +124,6 @@ fn dispatch(device: &wgpu::Device, queue: &wgpu::Queue, world: &World, from: &St
}
let acc = read(device, queue, &bufs[4], n * 16)?;
let acc: &[[f32; 4]] = bytemuck::cast_slice(&acc);
// a pass the GPU dropped, or light that isn't a number, is an error here: never kept as a dark or a broken map
let wrong = acc.iter().zip(from.open).filter(|(a, open)| a[3] != if **open == 0 { 0.0 } else { s.samples as f32 } || !a.iter().all(|c| c.is_finite())).count();
if wrong > 0 {
return Err(format!("the light bake's trace came back wrong on {wrong} of {n} texels (not {} samples each, or light that isn't finite)", s.samples));
}
Ok(acc.iter().map(|a| if a[3] > 0.0 { [a[0] / a[3], a[1] / a[3], a[2] / a[3]] } else { [0.0; 3] }).collect())
}
@@ -256,3 +162,6 @@ fn read(device: &wgpu::Device, queue: &wgpu::Queue, buf: &wgpu::Buffer, size: us
let bytes = back.slice(..).get_mapped_range().map_err(|e| format!("the light bake's readback: {e}"))?.to_vec();
Ok(bytes)
}
#[cfg(test)]
mod tests;
+107
View File
@@ -0,0 +1,107 @@
use super::*;
use crate::texels::tests::{cuboid, glb, set};
use crate::texels::{request, texels};
fn world(mesh: &parry3d::shape::TriMesh, surfaces: &[Surface]) -> (Vec<[f32; 3]>, Vec<[u32; 3]>, Vec<Surface>) {
(mesh.vertices().iter().map(|v| v.to_array()).collect(), mesh.indices().to_vec(), surfaces.to_vec())
}
/// The light on t's texels, each triangle's surface given by its centroid.
fn run(t: &crate::texels::Texels, surface: impl Fn([f32; 3]) -> Surface, s: &Settings) -> Vec<[f32; 3]> {
let v = t.mesh.vertices();
let surfaces: Vec<Surface> = t.mesh.indices().iter().map(|i| surface(std::array::from_fn(|k| i.iter().map(|&j| v[j as usize][k]).sum::<f32>() / 3.0))).collect();
let (p, i, s2) = world(&t.mesh, &surfaces);
let normal: Vec<[f32; 3]> = t.layout.texels.iter().map(|x| x.n).collect();
let starts = Starts { origin: &t.origin, normal: &normal, inside: &t.inside, offset: t.offset };
trace(&World { positions: &p, triangles: &i, surfaces: &s2 }, &starts, s, &mut |_, _| {}).unwrap()
}
/// A white set under a white sky: whatever bounces, every texel's light is the sky's (a white furnace). The block sunk
/// in the slab and the box set by its node make real concave corners; paths there bounce until they find the sky.
#[test]
fn a_white_furnace_is_the_sky_at_every_texel() {
let t = texels(&set(), &request(8.0, 1024)).unwrap();
let s = Settings { samples: 64, bounces: 64, per_pass: 16, sky: [1.0; 3] };
let light = run(&t, |_| Surface { albedo: [1.0; 3], emission: [0.0; 3] }, &s);
let open: Vec<[f32; 3]> = light.iter().zip(&t.inside).filter(|(_, i)| !**i).map(|(l, _)| *l).collect();
let off = open.iter().filter(|l| l.iter().any(|c| (c - 1.0).abs() > 0.01)).count();
println!("furnace: {off} of {} off by more than 1%", open.len());
let worst = open.iter().flatten().fold(0.0f32, |m, c| m.max((c - 1.0).abs()));
println!("furnace: worst {worst}, mean {}", open.iter().map(|l| l[0]).sum::<f32>() / open.len() as f32);
assert!(open.len() > 500 && off == 0, "{off} of {} texels more than 1% off the sky, worst {worst}", open.len());
}
/// A black wall 40 m long and 2 m high on a black floor under a white sky: the floor's light at a distance d from its
/// foot is what the sky leaves, 1/2 (1 + d / sqrt(d^2 + h^2)) (an endless wall's form factor), which only cosine-weighted
/// rays give.
#[test]
fn a_walls_shadow_on_the_floor_is_its_form_factor() {
let set = glb(&[(cuboid([0.0, -0.1, -20.0], [6.0, 0.0, 20.0]), [0.0; 3]), (cuboid([-0.2, -0.1, -20.0], [0.0, 2.0, 20.0]), [0.0; 3])]);
let t = texels(&set, &request(4.0, 1024)).unwrap();
let light = run(&t, |_| Surface { albedo: [0.0; 3], emission: [0.0; 3] }, &Settings { samples: 512, ..Settings::default() });
for d in [0.5f32, 1.0, 2.0, 4.0] {
let v: Vec<(f32, f32)> = t.layout.texels.iter().zip(&light).filter(|(x, _)| x.p[1].abs() < 1e-3 && x.n[1] > 0.9 && x.p[2].abs() < 4.0 && (x.p[0] - d).abs() < 0.13).map(|(x, l)| (0.5 * (1.0 + x.p[0] / (x.p[0] * x.p[0] + 4.0).sqrt()), l[0])).collect();
let (want, got) = v.iter().fold((0.0, 0.0), |(a, b), (w, g)| (a + w / v.len() as f32, b + g / v.len() as f32));
println!("wall: d {d} m: {got:.4} for {want:.4} over {} texels", v.len());
assert!(v.len() > 20 && (got - want).abs() < 0.01, "{d} m from the wall the floor gets {got}, not {want}");
}
}
/// A closed box glowing 1 all round with an albedo of a half: every point inside gets 1 + 1/2 + 1/4 ... = 2.
#[test]
fn a_glowing_box_adds_up_its_bounces() {
let inward = cuboid([-1.0; 3], [1.0; 3]).into_iter().map(|[a, b, c]| [a, c, b]).collect();
let t = texels(&glb(&[(inward, [0.0; 3])]), &request(8.0, 1024)).unwrap();
let light = run(&t, |_| Surface { albedo: [0.5; 3], emission: [1.0; 3] }, &Settings { samples: 64, bounces: 64, per_pass: 16, sky: [0.0; 3] });
let mean = light.iter().zip(&t.inside).filter(|(_, i)| !**i).map(|(l, _)| l[0]).sum::<f32>() / t.inside.iter().filter(|i| !**i).count() as f32;
println!("box: {mean:.4} for 2, {} of {} texels marked inside", t.inside.iter().filter(|i| **i).count(), t.inside.len());
assert!((mean - 2.0).abs() < 0.01, "the glowing box's light is {mean}, not 2");
}
/// A white floor beside a red wall: the floor near the wall gets redder than the floor far from it.
#[test]
fn a_red_wall_bleeds_onto_the_floor() {
let floor = cuboid([-1.0, -0.1, -2.0], [1.0, 0.0, 2.0]);
let wall = cuboid([-1.0, 0.0, -2.0], [-0.9, 2.0, 2.0]);
let t = texels(&glb(&[(floor, [0.0; 3]), (wall, [0.0; 3])]), &request(16.0, 1024)).unwrap();
let red = |c: [f32; 3]| Surface { albedo: if c[1] > 0.5 { [0.9, 0.0, 0.0] } else { [0.9; 3] }, emission: [0.0; 3] };
let light = run(&t, red, &Settings { samples: 128, bounces: 4, per_pass: 32, sky: [1.0; 3] });
// floor top texels near the wall (x -0.9..-0.7) and far (x > 0.6)
let mean = |near: bool| {
let v: Vec<f32> = t.layout.texels.iter().zip(&light).zip(&t.inside).filter(|((x, _), i)| !**i && x.p[1].abs() < 1e-3 && x.n[1] > 0.9 && if near { x.p[0] < -0.7 } else { x.p[0] > 0.6 }).map(|((_, l), _)| l[1] / l[0]).collect();
v.iter().sum::<f32>() / v.len() as f32
};
let (near, far) = (mean(true), mean(false));
assert!(near < far * 0.97, "green over red near the red wall {near}, far from it {far}");
}
#[test]
fn the_same_bake_gives_the_same_bytes() {
let t = texels(&set(), &request(8.0, 1024)).unwrap();
let s = Settings { samples: 16, per_pass: 8, ..Settings::default() };
let surf = |c: [f32; 3]| Surface { albedo: [0.5 + 0.1 * c[0].abs().fract(); 3], emission: [0.0; 3] };
let (a, b) = (run(&t, surf, &s), run(&t, surf, &s));
assert!(a.iter().any(|l| l[0] > 0.1), "no light at all");
assert_eq!(a, b);
}
#[test]
fn mismatched_inputs_are_refused() {
let starts = Starts { origin: &[[0.0; 3]], normal: &[], inside: &[], offset: 1e-4 };
assert!(trace(&World { positions: &[], triangles: &[], surfaces: &[] }, &starts, &Settings::default(), &mut |_, _| {}).is_err());
}
/// The measured run (docs/bake.feature BK3): RAEA_BAKE_GLB at 64 texels a metre, every surface 0.7 grey under a white
/// sky, RAEA_BAKE_SAMPLES (default 512) a texel: the trace's time alone.
/// `cargo test -p raea-sys-lightbake trace::tests::measured -- --ignored --nocapture`
#[test]
#[ignore]
fn measured() {
let glb = std::fs::read(std::env::var("RAEA_BAKE_GLB").expect("RAEA_BAKE_GLB: a .glb")).unwrap();
let samples = std::env::var("RAEA_BAKE_SAMPLES").ok().and_then(|v| v.parse().ok()).unwrap_or(512);
let t = texels(&glb, &request(64.0, 4096)).unwrap();
let t0 = std::time::Instant::now();
let light = run(&t, |_| Surface { albedo: [0.7; 3], emission: [0.0; 3] }, &Settings { samples, ..Settings::default() });
let lit = light.iter().zip(&t.inside).filter(|(_, i)| !**i).map(|(l, _)| l[0]).collect::<Vec<_>>();
println!("{} texels, {} triangles, {samples} samples, 4 bounces: {:.2} s, mean light {:.3}", light.len(), t.mesh.indices().len(), t0.elapsed().as_secs_f64(), lit.iter().sum::<f32>() / lit.len() as f32);
}
-212
View File
@@ -1,212 +0,0 @@
use raea_sys_lighttrace::*;
use crate::texels::tests::{cuboid, glb, set};
use crate::texels::{request, starts, texels};
use parry3d::glamx::Vec3;
fn world(mesh: &parry3d::shape::TriMesh, surfaces: &[Surface]) -> (Vec<[f32; 3]>, Vec<[u32; 3]>, Vec<Surface>) {
(mesh.vertices().iter().map(|v| v.to_array()).collect(), mesh.indices().to_vec(), surfaces.to_vec())
}
/// The light on t's texels, each triangle's surface given by its centroid.
fn run(t: &crate::texels::Texels, surface: impl Fn([f32; 3]) -> Surface, s: &Settings) -> Vec<[f32; 3]> {
let v = t.mesh.vertices();
let surfaces: Vec<Surface> = t.mesh.indices().iter().map(|i| surface(std::array::from_fn(|k| i.iter().map(|&j| v[j as usize][k]).sum::<f32>() / 3.0))).collect();
let (p, i, s2) = world(&t.mesh, &surfaces);
let normal: Vec<[f32; 3]> = t.layout.texels.iter().map(|x| x.n).collect();
let starts = Starts { origin: &t.origin, normal: &normal, sides: &t.sides, open: &t.open, offset: t.offset };
trace(&World { positions: &p, triangles: &i, surfaces: &s2, uvs: &[], textures: &[] }, &starts, s, &mut |_, _| {}).unwrap()
}
/// A white set under a white sky: whatever bounces, every texel's light is the sky's (a white furnace). The block sunk
/// in the slab and the box set by its node make real concave corners; paths there bounce until they find the sky.
#[test]
fn a_white_furnace_is_the_sky_at_every_texel() {
let t = texels(&set(), &request(8.0, 1024)).unwrap();
let s = Settings { samples: 64, bounces: 64, per_pass: 16, sky: Sky::even([1.0; 3]), ..Settings::default() };
let light = run(&t, |_| Surface { albedo: [1.0; 3], ..Surface::default() }, &s);
let open: Vec<[f32; 3]> = light.iter().zip(&t.inside()).filter(|(_, i)| !**i).map(|(l, _)| *l).collect();
let off = open.iter().filter(|l| l.iter().any(|c| (c - 1.0).abs() > 0.01)).count();
println!("furnace: {off} of {} off by more than 1%", open.len());
let worst = open.iter().flatten().fold(0.0f32, |m, c| m.max((c - 1.0).abs()));
println!("furnace: worst {worst}, mean {}", open.iter().map(|l| l[0]).sum::<f32>() / open.len() as f32);
assert!(open.len() > 500 && off == 0, "{off} of {} texels more than 1% off the sky, worst {worst}", open.len());
}
/// A black wall 40 m long and 2 m high on a black floor under a white sky: the floor's light at a distance d from its
/// foot is what the sky leaves, 1/2 (1 + d / sqrt(d^2 + h^2)) (an endless wall's form factor), which only cosine-weighted
/// rays give.
#[test]
fn a_walls_shadow_on_the_floor_is_its_form_factor() {
let set = glb(&[(cuboid([0.0, -0.1, -20.0], [6.0, 0.0, 20.0]), [0.0; 3]), (cuboid([-0.2, -0.1, -20.0], [0.0, 2.0, 20.0]), [0.0; 3])]);
let t = texels(&set, &request(4.0, 1024)).unwrap();
let light = run(&t, |_| Surface { albedo: [0.0; 3], ..Surface::default() }, &Settings { samples: 512, ..Settings::default() });
for d in [0.5f32, 1.0, 2.0, 4.0] {
let v: Vec<(f32, f32)> = t.layout.texels.iter().zip(&light).filter(|(x, _)| x.p[1].abs() < 1e-3 && x.n[1] > 0.9 && x.p[2].abs() < 4.0 && (x.p[0] - d).abs() < 0.13).map(|(x, l)| (0.5 * (1.0 + x.p[0] / (x.p[0] * x.p[0] + 4.0).sqrt()), l[0])).collect();
let (want, got) = v.iter().fold((0.0, 0.0), |(a, b), (w, g)| (a + w / v.len() as f32, b + g / v.len() as f32));
println!("wall: d {d} m: {got:.4} for {want:.4} over {} texels", v.len());
assert!(v.len() > 20 && (got - want).abs() < 0.01, "{d} m from the wall the floor gets {got}, not {want}");
}
}
/// A closed box glowing 1 all round with an albedo of a half: every point inside gets 1 + 1/2 + 1/4 ... = 2.
#[test]
fn a_glowing_box_adds_up_its_bounces() {
let inward = cuboid([-1.0; 3], [1.0; 3]).into_iter().map(|[a, b, c]| [a, c, b]).collect();
let t = texels(&glb(&[(inward, [0.0; 3])]), &request(8.0, 1024)).unwrap();
let light = run(&t, |_| Surface { albedo: [0.5; 3], emission: [1.0; 3], ..Surface::default() }, &Settings { samples: 64, bounces: 64, per_pass: 16, sky: Sky::even([0.0; 3]), ..Settings::default() });
let mean = light.iter().zip(&t.inside()).filter(|(_, i)| !**i).map(|(l, _)| l[0]).sum::<f32>() / t.inside().iter().filter(|i| !**i).count() as f32;
println!("box: {mean:.4} for 2, {} of {} texels marked inside", t.inside().iter().filter(|i| **i).count(), t.inside().len());
assert!((mean - 2.0).abs() < 0.01, "the glowing box's light is {mean}, not 2");
}
/// A white floor beside a red wall: the floor near the wall gets redder than the floor far from it.
#[test]
fn a_red_wall_bleeds_onto_the_floor() {
let floor = cuboid([-1.0, -0.1, -2.0], [1.0, 0.0, 2.0]);
let wall = cuboid([-1.0, 0.0, -2.0], [-0.9, 2.0, 2.0]);
let t = texels(&glb(&[(floor, [0.0; 3]), (wall, [0.0; 3])]), &request(16.0, 1024)).unwrap();
let red = |c: [f32; 3]| Surface { albedo: if c[1] > 0.5 { [0.9, 0.0, 0.0] } else { [0.9; 3] }, ..Surface::default() };
let light = run(&t, red, &Settings { samples: 128, bounces: 4, per_pass: 32, sky: Sky::even([1.0; 3]), ..Settings::default() });
// floor top texels near the wall (x -0.9..-0.7) and far (x > 0.6)
let mean = |near: bool| {
let v: Vec<f32> = t.layout.texels.iter().zip(&light).zip(&t.inside()).filter(|((x, _), i)| !**i && x.p[1].abs() < 1e-3 && x.n[1] > 0.9 && if near { x.p[0] < -0.7 } else { x.p[0] > 0.6 }).map(|((_, l), _)| l[1] / l[0]).collect();
v.iter().sum::<f32>() / v.len() as f32
};
let (near, far) = (mean(true), mean(false));
assert!(near < far * 0.97, "green over red near the red wall {near}, far from it {far}");
}
#[test]
fn the_same_bake_gives_the_same_bytes() {
let t = texels(&set(), &request(8.0, 1024)).unwrap();
let s = Settings { samples: 16, per_pass: 8, ..Settings::default() };
let surf = |c: [f32; 3]| Surface { albedo: [0.5 + 0.1 * c[0].abs().fract(); 3], ..Surface::default() };
let (a, b) = (run(&t, surf, &s), run(&t, surf, &s));
assert!(a.iter().any(|l| l[0] > 0.1), "no light at all");
assert_eq!(a, b);
}
#[test]
fn mismatched_inputs_are_refused() {
let starts = Starts { origin: &[[0.0; 3]], normal: &[], sides: &[], open: &[], offset: 1e-4 };
assert!(trace(&World { positions: &[], triangles: &[], surfaces: &[], uvs: &[], textures: &[] }, &starts, &Settings::default(), &mut |_, _| {}).is_err());
}
/// A floor, and something on it: the light on a texel 0.4 m a side whose centre is 0.1 m under its edge at x = 0, by
/// its starts, and which of them are open.
fn half_covered(on_it: &[crate::texels::tests::Tri], samples_at_centre: bool) -> (f32, u32) {
let floor = [[-40.0, 0.0, -40.0], [-40.0, 0.0, 80.0], [80.0, 0.0, -40.0]];
let mesh = parry3d::shape::TriMesh::new(std::iter::once(floor).chain(on_it.iter().copied()).flatten().map(Vec3::from).collect(), (0..on_it.len() as u32 + 1).map(|k| [3 * k, 3 * k + 1, 3 * k + 2]).collect()).unwrap();
let sides = [[0.4, 0.0, 0.0], [0.0, 0.0, 0.4]];
let (origin, open) = starts(&mesh, floor.map(Vec3::from), Vec3::new(0.1, 0.0, 0.0), Vec3::Y, sides.map(Vec3::from), 1e-4, 7, false);
let (p, i, s) = world(&mesh, &vec![Surface::default(); mesh.indices().len()]);
let st = Starts { origin: &[origin], normal: &[[0.0, 1.0, 0.0]], sides: &[sides], open: &[if samples_at_centre { CENTRE } else { open }], offset: 1e-4 };
let l = trace(&World { positions: &p, triangles: &i, surfaces: &s, uvs: &[], textures: &[] }, &st, &Settings { samples: 4096, ..Settings::default() }, &mut |_, _| {}).unwrap();
(l[0][0], open)
}
/// A texel with a sheet 0.2 mm over three quarters of it (a stack's ledge): a quarter of the sky, as Cycles' jittered
/// samples see, where its centre alone sees nothing.
#[test]
fn a_texel_under_a_sheets_edge_sees_the_part_that_is_open() {
let sheet = cuboid([0.0, 0.0002, -10.0], [10.0, 0.0052, 10.0]);
let (centre, _) = half_covered(&sheet, true);
let (over, open) = half_covered(&sheet, false);
println!("ledge: centre {centre:.4}, over the texel {over:.4} for 0.249, open {open:#x}");
assert!(centre < 0.01 && (over - 0.249).abs() < 0.01 && open == 0xffff, "{centre} {over} {open:#x}");
}
/// A texel three quarters inside a block sunk in the floor: only its open quarter counts, not that quarter averaged with
/// the dark inside.
#[test]
fn a_texel_half_buried_is_lit_by_its_open_part() {
let block = cuboid([0.0, -1.0, -10.0], [10.0, 1.0, 10.0]);
let (over, open) = half_covered(&block, false);
println!("block: {over:.4} over its open part, open {open:#x}");
assert!(open == 0x1111 && (0.48..0.58).contains(&over), "{over} {open:#x}");
}
/// A 40 m floor lit by the sun at 45 degrees and nothing else: a point 0.1 m over it looking down gets the sunlit
/// floor's light, albedo x irradiance x cos 45 / pi; a point on the floor gets nothing, its own sun being live.
#[test]
fn the_sun_lights_what_it_bounces_to_and_not_the_texel_itself() {
let p = [[-20.0, 0.0, -20.0], [20.0, 0.0, -20.0], [20.0, 0.0, 20.0], [-20.0, 0.0, 20.0]];
let surfaces = [Surface { albedo: [0.5; 3], ..Surface::default() }; 2];
let world = World { positions: &p, triangles: &[[0, 2, 1], [0, 3, 2]], surfaces: &surfaces, uvs: &[], textures: &[] };
let starts = Starts { origin: &[[0.0, 0.1, 0.0], [8.0, 1e-4, 0.0]], normal: &[[0.0, -1.0, 0.0], [0.0, 1.0, 0.0]], sides: &[[[0.0; 3]; 2]; 2], open: &[CENTRE; 2], offset: 1e-4 };
let sun = Sun { dir: [1.0, 1.0, 0.0], irradiance: [std::f32::consts::PI, 0.0, 0.0], half_angle: 0.0046 };
let s = Settings { samples: 4096, per_pass: 64, bounces: 1, sky: Sky::even([0.0; 3]), sun: Some(sun), ..Settings::default() };
let l = trace(&world, &starts, &s, &mut |_, _| {}).unwrap();
println!("sun: over the floor {:?} for 0.3536, on it {:?} for 0", l[0], l[1]);
assert!((l[0][0] - 0.3536).abs() < 0.005 && l[0][1] == 0.0 && l[1] == [0.0; 3], "{l:?}");
}
/// A sky lit only in its left-to-right middle half (straight ahead, -Z): a wall facing -Z gets the light, one facing +Z
/// none; turned a quarter counter-clockwise from above the light comes from -X.
#[test]
fn the_panorama_faces_ahead_and_turns_counter_clockwise() {
let set = glb(&[(cuboid([-0.5, 0.0, -0.5], [0.5, 1.0, 0.5]), [0.0; 3])]);
let t = texels(&set, &request(8.0, 512)).unwrap();
let sky = |rotation| Sky { width: 64, height: 1, rgb: (0..64).map(|x| if (16..48).contains(&x) { [1.0; 3] } else { [0.0; 3] }).collect(), strength: 1.0, rotation };
let faces = |rotation: f32| {
let light = run(&t, |_| Surface::default(), &Settings { samples: 256, sky: sky(rotation), ..Settings::default() });
[[0.0, 0.0, -1.0], [0.0, 0.0, 1.0], [-1.0, 0.0, 0.0], [1.0, 0.0, 0.0]].map(|n: [f32; 3]| {
let v: Vec<f32> = t.layout.texels.iter().zip(&light).filter(|(x, _)| (0..3).all(|k| (x.n[k] - n[k]).abs() < 0.1)).map(|(_, l)| l[0]).collect();
v.iter().sum::<f32>() / v.len() as f32
})
};
let (ahead, turned) = (faces(0.0), faces(std::f32::consts::FRAC_PI_2));
println!("sky: -Z +Z -X +X {ahead:?}, turned {turned:?}");
assert!(ahead[0] > 0.97 && ahead[1] < 0.03 && (ahead[2] - 0.5).abs() < 0.03, "{ahead:?}");
assert!(turned[2] > 0.97 && turned[3] < 0.03 && (turned[0] - 0.5).abs() < 0.03, "{turned:?}");
}
/// Points looking straight up under an even sky, 134 million rays: one in 2^24 goes exactly up, where the panorama's
/// longitude is atan2(0, 0), which Metal gave as NaN (a whole texel lost on the atelier at 1024 samples).
#[test]
fn a_ray_straight_up_sees_the_sky() {
let p = [[0.0, -5.0, 0.0], [1.0, -5.0, 0.0], [0.0, -5.0, 1.0]];
let world = World { positions: &p, triangles: &[[0, 1, 2]], surfaces: &[Surface::default()], uvs: &[], textures: &[] };
let n = 16384;
let (origin, normal, sides, open) = (vec![[0.0; 3]; n], vec![[0.0, 1.0, 0.0]; n], vec![[[0.0; 3]; 2]; n], vec![CENTRE; n]);
let l = trace(&world, &Starts { origin: &origin, normal: &normal, sides: &sides, open: &open, offset: 1e-4 }, &Settings { samples: 8192, per_pass: 128, ..Settings::default() }, &mut |_, _| {}).unwrap();
assert_eq!(l.iter().flatten().filter(|v| !v.is_finite()).count(), 0, "values that aren't finite");
assert!(l.iter().all(|c| (c[0] - 1.0).abs() < 1e-3), "not the sky: {:?}", l.iter().find(|c| (c[0] - 1.0).abs() >= 1e-3));
}
/// A floor textured red on its left half and green on its right (sRGB 188 is 0.5 linear): the underside of a plate
/// over each half sees that half's colour.
#[test]
fn a_textured_floor_bounces_its_texture() {
let (mut p, mut tri, mut uv) = (vec![], vec![], vec![]);
for (x, z) in [(-20.0f32, -20.0f32), (20.0, -20.0), (20.0, 20.0), (-20.0, 20.0)] {
p.push([x, 0.0, z]);
uv.push([(x + 20.0) / 40.0, (z + 20.0) / 40.0]);
}
tri.extend([[0u32, 2, 1], [0, 3, 2]]);
let image = Image { width: 2, height: 1, rgba: vec![0xff00_00bc, 0xff00_bc00] };
let surfaces = vec![Surface { albedo: [1.0; 3], texture: Some(0), ..Surface::default() }; 2];
let origin: Vec<[f32; 3]> = [-10.0, 10.0].into_iter().map(|x| [x, 0.1, 0.0]).collect();
let starts = Starts { origin: &origin, normal: &[[0.0, -1.0, 0.0]; 2], sides: &[[[0.0; 3]; 2]; 2], open: &[CENTRE; 2], offset: 1e-4 };
let s = Settings { samples: 4096, per_pass: 64, bounces: 2, ..Settings::default() };
let l = trace(&World { positions: &p, triangles: &tri, surfaces: &surfaces, uvs: &uv, textures: &[image] }, &starts, &s, &mut |_, _| {}).unwrap();
println!("textured: {l:?}");
assert!((l[0][0] - 0.5029).abs() < 0.01 && l[0][1] < 0.01 && (l[1][1] - 0.5029).abs() < 0.01 && l[1][0] < 0.01, "{l:?}");
let bad = trace(&World { positions: &p, triangles: &tri, surfaces: &surfaces, uvs: &[], textures: &[] }, &starts, &s, &mut |_, _| {});
assert!(bad.is_err());
}
/// The measured run (docs/bake.feature BK3): RAEA_BAKE_GLB at 64 texels a metre, every surface 0.7 grey under a white
/// sky, RAEA_BAKE_SAMPLES (default 512) a texel: the trace's time alone.
/// `cargo test -p raea-sys-lightbake trace_tests::measured -- --ignored --nocapture`
#[test]
#[ignore]
fn measured() {
let glb = std::fs::read(std::env::var("RAEA_BAKE_GLB").expect("RAEA_BAKE_GLB: a .glb")).unwrap();
let samples = std::env::var("RAEA_BAKE_SAMPLES").ok().and_then(|v| v.parse().ok()).unwrap_or(512);
let t = texels(&glb, &request(64.0, 4096)).unwrap();
let t0 = std::time::Instant::now();
let light = run(&t, |_| Surface { albedo: [0.7; 3], ..Surface::default() }, &Settings { samples, ..Settings::default() });
let lit = light.iter().zip(&t.inside()).filter(|(_, i)| !**i).map(|(l, _)| l[0]).collect::<Vec<_>>();
println!("{} texels, {} triangles, {samples} samples, 4 bounces: {:.2} s, mean light {:.3}", light.len(), t.mesh.indices().len(), t0.elapsed().as_secs_f64(), lit.iter().sum::<f32>() / lit.len() as f32);
}
+93
View File
@@ -0,0 +1,93 @@
// The light that bounces, per texel (docs/bake.feature BK3): paths from the texel's origin through the model's own
// triangles (one BLAS, one TLAS) by wgpu's ray queries. What a texel keeps is the mean light its cosine-weighted rays
// bring back, so the lightmap times a surface's albedo is the light it sends on. At each hit the surface's emission
// is added and the path goes on weighted by its albedo (Lambert, diffuse.wgsl); a miss sees the sky; after the
// second bounce Russian roulette ends paths by their weight, unbiased. Passes add to `accum` (rgb, samples).
struct Params {
sky: vec4<f32>,
count: u32,
pass_index: u32,
per_pass: u32,
bounces: u32,
offset: f32,
// the first texel of this dispatch (a bake's texels go in chunks)
first: u32,
_pad1: f32,
_pad2: f32,
}
struct Surface {
albedo: vec4<f32>,
emission: vec4<f32>,
}
@group(0) @binding(0) var tlas: acceleration_structure;
@group(0) @binding(1) var<storage, read> positions: array<vec4<f32>>;
@group(0) @binding(2) var<storage, read> indices: array<u32>;
@group(0) @binding(3) var<storage, read> surfaces: array<Surface>;
// per texel: origin (w: 1 when inside other geometry) and normal
@group(0) @binding(4) var<storage, read> texels: array<vec4<f32>>;
@group(0) @binding(5) var<storage, read_write> accum: array<vec4<f32>>;
@group(0) @binding(6) var<uniform> params: Params;
// The nearest hit. Its own function: a ray_query declared in a loop is zeroed again each turn, which naga writes for
// Metal as an assignment Metal's intersection_query deletes.
fn nearest(o: vec3<f32>, d: vec3<f32>) -> RayIntersection {
var rq: ray_query;
rayQueryInitialize(&rq, tlas, RayDesc(0u, 0xffu, 0.0, 1.0e30, o, d));
while (rayQueryProceed(&rq)) {}
return rayQueryGetCommittedIntersection(&rq);
}
@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
let i = params.first + gid.x;
if (i >= params.count) {
return;
}
let at = texels[2u * i];
if (at.w > 0.5) {
return;
}
let n0 = texels[2u * i + 1u].xyz;
var sum = vec3<f32>(0.0);
for (var s = 0u; s < params.per_pass; s = s + 1u) {
var rng = raea_hash(i * 0x9e3779b9u ^ raea_hash(params.pass_index * params.per_pass + s));
var o = at.xyz;
var n = n0;
var weight = vec3<f32>(1.0);
var light = vec3<f32>(0.0);
for (var b = 0u; b < params.bounces; b = b + 1u) {
let d = raea_diffuse_sample(n, vec2<f32>(raea_rand(&rng), raea_rand(&rng)));
let hit = nearest(o, d);
if (hit.kind == RAY_QUERY_INTERSECTION_NONE) {
light = light + weight * params.sky.rgb;
break;
}
let p = hit.primitive_index;
let srf = surfaces[p];
light = light + weight * srf.emission.rgb;
let a = positions[indices[3u * p]].xyz;
let bb = positions[indices[3u * p + 1u]].xyz;
let c = positions[indices[3u * p + 2u]].xyz;
var ng = normalize(cross(bb - a, c - a));
if (dot(ng, d) > 0.0) {
ng = -ng;
}
let w = hit.barycentrics;
o = a * (1.0 - w.x - w.y) + bb * w.x + c * w.y + ng * params.offset;
n = ng;
weight = weight * srf.albedo.rgb;
if (b >= 2u) {
let q = max(weight.r, max(weight.g, weight.b));
if (raea_rand(&rng) >= q) {
break;
}
weight = weight / q;
}
}
sum = sum + light;
}
accum[i] = accum[i] + vec4<f32>(sum, f32(params.per_pass));
}
-14
View File
@@ -1,14 +0,0 @@
[package]
name = "raea-sys-lighttrace"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "Light paths traced on the GPU: what a triangle bounces, the sky, the sun and emission, by wgpu's ray queries (docs/bake.feature BK3)"
[dependencies]
# the process's one shared GPU device, and wgpu's ray queries on it
raea-gpu-device = { path = "../../gpu/device" }
wgpu = "=30.0.1"
bytemuck = "1"
pollster = "0.4"
-120
View File
@@ -1,120 +0,0 @@
//! The GGX the kernel's glossy bounces use (docs/bake.feature BK3), on the CPU: the directional albedo a rough metal or
//! dielectric layer keeps, tabled, so the kernel can give back what a single scatter loses and keep what's under a
//! dielectric's layer. The functions are Cycles' (github.com/blender/cycles, BSD-3-Clause, see NOTICE:
//! kernel/closure/bsdf_microfacet.h, bsdf_util.h, kernel/sample/mapping.h), written here in Rust and in wgsl/glossy.wgsl until
//! tools/cycles-port is on main, and held to its own output below.
use std::f32::consts::PI;
/// Rows and columns of the table: roughness, then the cosine to the viewer.
pub const STEPS: usize = 32;
pub fn lambda(a2: f32, c: f32) -> f32 {
0.5 * ((1.0 + a2 * (1.0 / (c * c) - 1.0).max(0.0)).sqrt() - 1.0)
}
/// Cycles' bsdf_G: the combined masking and shadowing of the two directions.
pub fn g2(a2: f32, ci: f32, co: f32) -> f32 {
1.0 / (1.0 + lambda(a2, ci) + lambda(a2, co))
}
pub fn d(a2: f32, c: f32) -> f32 {
let c2 = (c * c).min(1.0);
a2 / (PI * (1.0 - c2 + a2 * c2).powi(2))
}
/// A microfacet normal from the ones visible from `wi` (Heitz 2018, as Cycles samples it), in the shading frame.
pub fn vndf(wi: [f32; 3], [ax, ay]: [f32; 2], r: [f32; 2]) -> [f32; 3] {
let n = |v: [f32; 3]| {
let l = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
[v[0] / l, v[1] / l, v[2] / l]
};
let w = n([ax * wi[0], ay * wi[1], wi[2]]);
let l2 = w[0] * w[0] + w[1] * w[1];
let t1 = if l2 > 1e-7 { [-w[1] / l2.sqrt(), w[0] / l2.sqrt(), 0.0] } else { [1.0, 0.0, 0.0] };
let t2 = [w[1] * t1[2] - w[2] * t1[1], w[2] * t1[0] - w[0] * t1[2], w[0] * t1[1] - w[1] * t1[0]];
let (a1, b1) = (2.0 * r[0] - 1.0, 2.0 * r[1] - 1.0);
let (rad, phi) = if a1 == 0.0 && b1 == 0.0 { (0.0, 0.0) } else if a1 * a1 > b1 * b1 { (a1, PI / 4.0 * (b1 / a1)) } else { (b1, PI / 2.0 - PI / 4.0 * (a1 / b1)) };
let x = rad * phi.cos();
let s = 0.5 * (1.0 + w[2]);
let y = (1.0 - x * x).max(0.0).sqrt() * (1.0 - s) + rad * phi.sin() * s;
let z = (1.0 - x * x - y * y).max(0.0).sqrt();
let h: [f32; 3] = std::array::from_fn(|k| x * t1[k] + y * t2[k] + z * w[k]);
n([ax * h[0], ay * h[1], h[2].max(0.0)])
}
/// Where a dielectric of IOR 1.5 stands between its F0 (0.04) and 1 (Cycles' fresnel_dielectric_cos).
pub fn dielectric(c: f32) -> f32 {
let g = (1.25 + c * c).sqrt();
let (a, b) = ((g - c) / (g + c), (c * (g + c) - 1.0) / (c * (g - c) + 1.0));
((0.5 * a * a * (1.0 + b * b) - 0.04) / 0.96).clamp(0.0, 1.0)
}
/// The table, a row a roughness (0 to 1) and a column the square root of the cosine to the viewer (0 to 1): a white lobe's albedo (single scatter), the part of
/// it Schlick's (1 - c)^5 weighs, the part `dielectric` weighs, and the row's mean albedo over the cosines.
pub fn table() -> Vec<[f32; 4]> {
const N: u32 = 1024;
let mut out = vec![[0.0f32; 4]; STEPS * STEPS];
for (i, row) in out.chunks_mut(STEPS).enumerate() {
let a = (i as f32 / (STEPS - 1) as f32).powi(2).max(1e-3);
for (j, cell) in row.iter_mut().enumerate() {
let mu = (j as f32 / (STEPS - 1) as f32).powi(2).max(1e-4);
let wo = [(1.0 - mu * mu).sqrt(), 0.0, mu];
for k in 0..N {
let h = vndf(wo, [a, a], [(k as f32 + 0.5) / N as f32, k.reverse_bits() as f32 / 4294967296.0]);
let c = wo[0] * h[0] + wo[1] * h[1] + wo[2] * h[2];
let z = 2.0 * c * h[2] - wo[2];
if z > 0.0 {
let g = g2(a * a, z, mu) * (1.0 + lambda(a * a, mu)) / N as f32;
for (sum, f) in cell.iter_mut().zip([1.0, (1.0 - c).clamp(0.0, 1.0).powi(5), dielectric(c)]) {
*sum += f * g;
}
}
}
}
// the mean of E over the cosines, 2 mu dmu with mu = y^2, a trapezoid between the nodes
let y = |j: usize| j as f32 / (STEPS - 1) as f32;
let at = |j: usize| 4.0 * row[j][0] * y(j).powi(3);
let mean = (1..STEPS).map(|j| (at(j - 1) + at(j)) / 2.0 / (STEPS - 1) as f32).sum::<f32>();
row.iter_mut().for_each(|c| c[3] = mean);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
/// Cases of tools/cycles-port's oracle (Cycles 6ea3d9bcd81a, built as C++): the two alphas, a cosine, wi, the disk's two
/// numbers; then D, G (with wi.z), lambda and the sampled normal.
#[test]
fn the_ggx_is_cycles() {
#[rustfmt::skip]
let cases: [([f32; 2], f32, [f32; 3], [f32; 2], [f32; 3], [f32; 3]); 3] = [
([0.030198643, 0.0263823215], 0.547724247, [0.16266492, -0.762519956, 0.626181662], [0.495889366, 0.548348844], [0.000591959222, 0.999115765, 0.000531673431], [-0.000647504407, 0.00159752904, 0.999998569]),
([0.982707202, 0.182275727], 0.108885549, [-0.725084424, 0.324529201, 0.607398808], [0.56473726, 0.590222061], [0.307646185, 0.187696591, 4.01351929], [-0.52829963, -0.00960596558, 0.849003613]),
([0.342305034, 0.509727001], 0.47010687, [-0.767907083, -0.492557466, 0.409519047], [0.999985695, 0.494606256], [0.0575702898, 0.817566216, 0.0943524837], [0.531567872, -0.846983373, 0.0074105612]),
];
for (a, c, wi, r, want, normal) in cases {
let a2 = a[0] * a[0];
for (got, want) in [d(a2, c), g2(a2, c, wi[2]), lambda(a2, c)].into_iter().zip(want) {
assert!((got - want).abs() <= (2e-5 * want.abs()).max(2e-6), "{got} for {want}");
}
let h = vndf(wi, a, r);
assert!(h.iter().zip(normal).all(|(g, w)| (g - w).abs() < 1e-4), "{h:?} for {normal:?}");
}
// the dielectric at eta 1.5 the kernel fixes, by its own closed forms: F0 at normal incidence and 1 at grazing
assert!(dielectric(1.0).abs() < 1e-5 && (dielectric(0.0) - 1.0).abs() < 1e-5);
}
/// A white lobe keeps all its light when it's smooth, loses some when rough, and its parts stay inside it.
#[test]
fn the_table_is_a_lobes_albedo() {
let t = table();
assert!((t[STEPS - 1][0] - 1.0).abs() < 0.01, "smooth, face on: {}", t[STEPS - 1][0]);
// at alpha 1, seen face on, D is 1/pi and G 2z/(1 + z): the albedo is 1 - ln 2
let rough = t[STEPS * STEPS - 1][0];
assert!((rough - (1.0 - std::f32::consts::LN_2)).abs() < 2e-3, "rough, face on: {rough}");
assert!(t.iter().all(|c| c[0] <= 1.002 && c[1] <= c[0] && c[2] <= c[0] && c[3] > 0.0 && c[3] <= 1.002));
}
}
-151
View File
@@ -1,151 +0,0 @@
use crate::glossy::{STEPS, d, dielectric, g2, table};
use crate::*;
// (a floor of 20 km puts its rays' starts within its own rounding at this offset, and they meet it)
const FLOOR: f32 = 400.0;
fn surface(base: f32, metallic: f32, roughness: f32, f0: f32) -> Surface {
Surface { albedo: [base; 3], metallic, roughness, f0, ..Surface::default() }
}
/// The light on a point half a metre over a wide floor, facing it, with a panel glowing 1 over it or not.
fn over_a_floor(floor: Surface, panel: bool, s: &Settings) -> f32 {
let mut p = vec![[-FLOOR, 0.0, -FLOOR], [-FLOOR, 0.0, 3.0 * FLOOR], [3.0 * FLOOR, 0.0, -FLOOR]];
let mut t = vec![[0, 1, 2]];
let mut surfaces = vec![floor];
if panel {
p.extend(PANEL);
t.extend([[3, 4, 5], [3, 5, 6]]);
surfaces.extend([Surface { emission: [1.0; 3], ..Surface::default() }; 2]);
}
let st = Starts { origin: &[[0.0, 0.5, 0.0]; 64], normal: &[[0.0, -1.0, 0.0]; 64], sides: &[[[0.0; 3]; 2]; 64], open: &[CENTRE; 64], offset: 1e-4 };
let l = trace(&World { positions: &p, triangles: &t, surfaces: &surfaces, uvs: &[], textures: &[] }, &st, s, &mut |_, _| {}).unwrap();
l.iter().map(|l| l[0]).sum::<f32>() / 64.0
}
const PANEL: [[f32; 3]; 4] = [[2.0, 4.0, -2.0], [6.0, 4.0, -2.0], [6.0, 4.0, 2.0], [2.0, 4.0, 2.0]];
const KINDS: [(&str, f32, f32, f32, f32); 5] = [("rough metal", 0.8, 1.0, 0.9, 0.0), ("smooth metal", 0.8, 1.0, 0.1, 0.0), ("plastic", 0.5, 0.0, 0.3, 0.04), ("half metal", 0.6, 0.5, 0.6, 0.04), ("chalk", 0.5, 0.0, 1.0, 0.0)];
/// What the kernel should send from wi to wo (its z the normal), the cosine included, after a turn of density `likely`.
fn sent(t: &[[f32; 4]], (_, base, metallic, rough, f0): (&str, f32, f32, f32, f32), likely: f32, wo: [f32; 3], wi: [f32; 3]) -> f32 {
let mu = wo[2];
if wi[2] <= 0.0 || mu <= 0.0 {
return 0.0;
}
if metallic == 0.0 && f0 == 0.0 {
return base * wi[2] / std::f32::consts::PI;
}
let a = (rough * rough).max(0.5 * (1.0 - likely).max(0.0).sqrt());
let at = [mu.sqrt(), a.sqrt()].map(|x| x.min(1.0) * (STEPS - 1) as f32);
let [j, i] = at.map(|x| (x as usize).min(STEPS - 2));
let (f, g) = (at[0] - j as f32, at[1] - i as f32);
let cell = |k: usize| (t[i * STEPS + j][k] * (1.0 - f) + t[i * STEPS + j + 1][k] * f) * (1.0 - g) + (t[(i + 1) * STEPS + j][k] * (1.0 - f) + t[(i + 1) * STEPS + j + 1][k] * f) * g;
let mix = |a: f32, b: f32, s: f32| a + (b - a) * s;
let kept = |fss: f32| 1.0 + fss * cell(3) / (1.0 - fss * (1.0 - cell(3))) * (1.0 - cell(0)) / cell(0);
let h: [f32; 3] = std::array::from_fn(|k| wo[k] + wi[k]);
let l = h.iter().map(|x| x * x).sum::<f32>().sqrt();
let c = (0..3).map(|k| wo[k] * h[k] / l).sum::<f32>();
let coat = if f0 > 0.0 { (1.0 - metallic) * kept(mix(f0, 1.0, (0.0894977 - 0.04) / 0.96)) } else { 0.0 };
let diffuse = base * (1.0 - metallic - coat * (f0 * cell(0) + (1.0 - f0) * cell(2))).max(0.0);
let fresnel = metallic * kept(mix(base, 1.0, 1.0 / 21.0)) * mix(base, 1.0, (1.0 - c).clamp(0.0, 1.0).powi(5)) + coat * mix(f0, 1.0, dielectric(c));
diffuse * wi[2] / std::f32::consts::PI + fresnel * d(a * a, h[2] / l) * g2(a * a, mu, wi[2]) / (4.0 * mu)
}
/// The mean over the point's own rays of `at` (the ray from the floor up to the point, its cosine over pi, where it hit).
fn over_rays(at: impl Fn([f32; 3], f32, [f32; 3], u32) -> f32) -> f32 {
const N: u32 = 1 << 20;
let total: f64 = (0..N).map(|k| {
let (u, v) = ((k as f32 + 0.5) / N as f32, k.reverse_bits() as f32 / 4294967296.0);
let (r, phi, z) = (u.sqrt(), std::f32::consts::TAU * v, (1.0 - u).sqrt().max(1e-3));
let wo = [r * phi.cos(), r * phi.sin(), z];
at(wo, z / std::f32::consts::PI, [-wo[0] * 0.5 / z, -wo[1] * 0.5 / z, 0.0], k) as f64
}).sum();
(total / N as f64) as f32
}
/// Whatever the surface, white ones send on all they get: a point over one sees the sky's 1.
#[test]
fn white_glossy_surfaces_send_on_all_their_light() {
let s = Settings { samples: 4096, per_pass: 64, bounces: 4, ..Settings::default() };
let mut off = 0;
for (name, metallic, f0) in [("metal", 1.0, 0.0), ("dielectric", 0.0, 0.04), ("half", 0.5, 0.04)] {
for rough in [0.1, 0.5, 0.75, 1.0] {
let l = over_a_floor(surface(1.0, metallic, rough, f0), false, &s);
println!("{name} of roughness {rough}: {l:.4} for 1");
off += ((l - 1.0).abs() >= 0.01) as u32;
}
}
assert_eq!(off, 0, "white surfaces off by 1% or more");
}
/// The sun off a floor, against the same light summed on the CPU with the functions held to Cycles' (glossy.rs).
#[test]
fn the_suns_glint_is_the_lobes_own() {
let t = table();
let toward = [0.6f32, 0.8, 0.0];
let sun = Sun { dir: toward, irradiance: [1.0; 3], half_angle: 1e-3 };
let s = Settings { samples: 16384, per_pass: 64, bounces: 1, sky: Sky::even([0.0; 3]), sun: Some(sun) };
for kind in KINDS {
let got = over_a_floor(surface(kind.1, kind.2, kind.3, kind.4), false, &s);
// the floor's frame here: x, z of the world, then up
let want = over_rays(|wo, likely, _, _| sent(&t, kind, likely, wo, [toward[0], toward[2], toward[1]]));
println!("sun, {}: {got:.5} for {want:.5}", kind.0);
assert!((got / want - 1.0).abs() < 0.01, "{}: {got} for {want}", kind.0);
}
}
/// A glowing panel found by the paths' own turns, against the same light summed over the panel.
#[test]
fn a_panels_reflection_is_found_by_its_turns() {
let t = table();
let s = Settings { samples: 16384, per_pass: 64, bounces: 2, sky: Sky::even([0.0; 3]), sun: None };
let mut off = 0;
for kind in KINDS {
let got = over_a_floor(surface(kind.1, kind.2, kind.3, kind.4), true, &s);
let want = over_rays(|wo, likely, p, k| {
let [u, v] = [0.754_877_666_246_693, 0.569_840_290_998_053].map(|g: f64| (k as f64 * g).fract() as f32);
let to = [PANEL[0][0] + 4.0 * u - p[0], PANEL[0][2] + 4.0 * v - p[1], PANEL[0][1]];
let r2 = to.iter().map(|x| x * x).sum::<f32>();
let wi = to.map(|x| x / r2.sqrt());
sent(&t, kind, likely, wo, wi) * wi[2] * 16.0 / r2
});
println!("panel, {}: {got:.5} for {want:.5}", kind.0);
off += ((got / want - 1.0).abs() >= 0.015) as u32;
}
assert_eq!(off, 0, "kinds off by 1.5% or more");
}
/// The share of rays that meet the plane they leave, off a tilted triangle `far` m from the origin, at an offset of `rel`
/// of that: from the texels themselves, and from where a bounce lands (a point over it, the plane half grey).
fn meets_itself(far: f32, rel: f32) -> [f32; 2] {
let [u, v] = [[0.64f32, 0.48, 0.6], [-0.6, 0.8, 0.0]];
let n = [-0.48f32, -0.36, 0.8];
let at = |a: f32, b: f32, h: f32| -> [f32; 3] { std::array::from_fn(|k| [0.6, 0.64, 0.48][k] * far + (u[k] * a + v[k] * b + n[k] * h) * far) };
let p = [at(-0.4, -0.4, 0.0), at(1.0, -0.4, 0.0), at(-0.4, 1.0, 0.0)];
let hash = |k: u32| (k.wrapping_mul(0x9e37_79b9) >> 8) as f32 / 16777216.0;
let origin: Vec<[f32; 3]> = (0..4096).map(|k| at(0.3 * hash(k) - 0.2, 0.3 * hash(k + 7919) - 0.2, rel)).collect();
let over: Vec<[f32; 3]> = (0..4096).map(|k| at(0.1 * hash(k) - 0.1, 0.1 * hash(k + 7919) - 0.1, 1e-3)).collect();
let run = |from: &[[f32; 3]], normal: [f32; 3], albedo: f32, bounces: u32| {
let m = from.len();
let st = Starts { origin: from, normal: &vec![normal; m], sides: &vec![[[0.0; 3]; 2]; m], open: &vec![CENTRE; m], offset: rel * far };
let l = trace(&World { positions: &p, triangles: &[[0, 1, 2]], surfaces: &[Surface { albedo: [albedo; 3], ..Surface::default() }], uvs: &[], textures: &[] }, &st, &Settings { samples: 256, bounces, ..Settings::default() }, &mut |_, _| {}).unwrap();
l.iter().map(|l| l[0]).sum::<f32>() / m as f32
};
let direct = 1.0 - run(&origin, n, 0.0, 1);
// half grey once: 0.5 of the sky; every further meeting halves it
let bounced = 1.0 - run(&over, n.map(|c| -c), 0.5, 3) / 0.5;
[direct, bounced]
}
#[test]
fn a_surface_never_meets_itself() {
let mut off = 0;
for far in [1.0, 15.0, 300.0, 5000.0] {
for rel in [1e-5, 1e-6, 3e-7, 1e-7] {
let [direct, bounced] = meets_itself(far, rel);
println!("{far} m, offset {rel:e} of it: {direct:.5} of the texels' rays, {bounced:.5} of the bounces'");
off += (rel >= 1e-6 && (direct.abs() > 1e-3 || bounced.abs() > 5e-3)) as u32;
}
}
assert_eq!(off, 0);
}
-120
View File
@@ -1,120 +0,0 @@
// The glossy layers of a surface (docs/bake.feature BK3), after Cycles' Principled: a metal (GGX, F82 with a white edge
// tint, which is Schlick) and a dielectric layer of IOR 1.5 over Lambert. The GGX, its sampling and the Fresnels are
// Cycles' (github.com/blender/cycles 6ea3d9bcd81a, kernel/closure/bsdf_microfacet.h, bsdf_util.h and
// kernel/sample/mapping.h, BSD-3-Clause: see NOTICE), written here until tools/cycles-port is on main. What a single
// scatter loses is given back from glossy.rs's table. It needs raea_layers_at(i), that table's cells, STEPS by STEPS:
// by roughness and the cosine's square root: the albedo of a white lobe
// (E), its Schlick part, its dielectric part, and E's mean over the cosines.
const RAEA_STEPS: i32 = 32;
fn raea_ggx_lambda(a2: f32, c: f32) -> f32 {
return 0.5 * (sqrt(1.0 + a2 * max(1.0 / (c * c) - 1.0, 0.0)) - 1.0);
}
fn raea_ggx_d(a2: f32, c: f32) -> f32 {
let c2 = min(c * c, 1.0);
let q = 1.0 - c2 + a2 * c2;
return a2 / (3.141592654 * q * q);
}
// A microfacet normal from the ones visible from w (Heitz 2018), in the shading frame (z the normal).
fn raea_ggx_sample(w: vec3<f32>, a: f32, r: vec2<f32>) -> vec3<f32> {
let v = normalize(vec3<f32>(a * w.x, a * w.y, w.z));
let l2 = v.x * v.x + v.y * v.y;
var t1 = vec3<f32>(1.0, 0.0, 0.0);
if (l2 > 1e-7) {
t1 = vec3<f32>(-v.y, v.x, 0.0) * inverseSqrt(l2);
}
let p = 2.0 * r - 1.0;
var rad = 0.0;
var phi = 0.0;
if (p.x * p.x > p.y * p.y) {
rad = p.x;
phi = 0.785398163 * (p.y / p.x);
} else if (p.y != 0.0) {
rad = p.y;
phi = 1.570796327 - 0.785398163 * (p.x / p.y);
}
let x = rad * cos(phi);
let y = mix(sqrt(max(1.0 - x * x, 0.0)), rad * sin(phi), 0.5 * (1.0 + v.z));
let h = x * t1 + y * cross(v, t1) + sqrt(max(1.0 - x * x - y * y, 0.0)) * v;
return normalize(vec3<f32>(a * h.x, a * h.y, max(0.0, h.z)));
}
// Where a dielectric of IOR 1.5 stands between its F0 and 1 at this cosine (Cycles' generalized Schlick, exponent < 0).
fn raea_dielectric(cosine: f32) -> f32 {
let c = abs(cosine);
let g = sqrt(1.25 + c * c);
let a = (g - c) / (g + c);
let b = (c * (g + c) - 1.0) / (c * (g - c) + 1.0);
return clamp((0.5 * a * a * (1.0 + b * b) - 0.04) / 0.96, 0.0, 1.0);
}
fn raea_layer(rough: f32, mu: f32) -> vec4<f32> {
let at = clamp(vec2<f32>(sqrt(mu), rough), vec2<f32>(0.0), vec2<f32>(1.0)) * f32(RAEA_STEPS - 1);
let i = min(vec2<i32>(at), vec2<i32>(RAEA_STEPS - 2));
let f = at - vec2<f32>(i);
let k = i.y * RAEA_STEPS + i.x;
return mix(mix(raea_layers_at(k), raea_layers_at(k + 1), f.x), mix(raea_layers_at(k + RAEA_STEPS), raea_layers_at(k + RAEA_STEPS + 1), f.x), f.y);
}
// A surface seen from one direction: its lobes' weights, and how often the glossy ones are sampled.
struct Lobes {
diffuse: vec3<f32>,
metal: vec3<f32>,
base: vec3<f32>,
f0: f32,
coat: f32,
a: f32,
p: f32,
}
// What the compensation multiplies a single scatter by (1 + Cycles' Fms times what's missing of the lobe).
fn raea_kept(fss: vec3<f32>, t: vec4<f32>) -> vec3<f32> {
return 1.0 + fss * t.w / (1.0 - fss * (1.0 - t.w)) * (1.0 - t.x) / t.x;
}
// `gloss`: metallic, roughness, the dielectric's F0 (0: no such layer). `a_least`: the least alpha (filter glossy).
fn raea_lobes(base: vec3<f32>, gloss: vec3<f32>, a_least: f32, mu: f32) -> Lobes {
var l: Lobes;
l.base = base;
l.diffuse = base * (1.0 - gloss.x);
if (gloss.x <= 0.0 && gloss.z <= 0.0) {
return l;
}
l.a = max(max(gloss.y * gloss.y, a_least), 0.002);
l.f0 = gloss.z;
let t = raea_layer(sqrt(l.a), mu);
l.metal = gloss.x * raea_kept(mix(base, vec3<f32>(1.0), 1.0 / 21.0), t);
var seen = l.metal * (base * t.x + (1.0 - base) * t.y);
if (gloss.z > 0.0) {
// 0.05156: Cycles' average dielectric Fresnel at 1.5 (fresnel_dielectric_Fss) between F0 and 1
l.coat = (1.0 - gloss.x) * raea_kept(vec3<f32>(mix(gloss.z, 1.0, 0.05156)), t).x;
let c = l.coat * (gloss.z * t.x + (1.0 - gloss.z) * t.z);
l.diffuse = base * max(1.0 - gloss.x - c, 0.0);
seen = seen + c;
}
let g = dot(seen, vec3<f32>(1.0));
l.p = g / max(g + dot(l.diffuse, vec3<f32>(1.0)), 1e-6);
return l;
}
// The light sent from wi to wo, cosine included, and (w) the density with which raea_lobes_sample picks wi.
fn raea_lobes_eval(l: Lobes, wo: vec3<f32>, wi: vec3<f32>) -> vec4<f32> {
if (wi.z <= 0.0) {
return vec4<f32>(0.0);
}
let d = wi.z / 3.141592654;
if (l.p <= 0.0) {
return vec4<f32>(l.diffuse * d, d);
}
let h = normalize(wo + wi);
let c = dot(wo, h);
let a2 = l.a * l.a;
let lo = raea_ggx_lambda(a2, wo.z);
let one = raea_ggx_d(a2, h.z) / (4.0 * wo.z);
let s5 = pow(clamp(1.0 - c, 0.0, 1.0), 5.0);
let f = l.metal * mix(l.base, vec3<f32>(1.0), s5) + l.coat * mix(l.f0, 1.0, raea_dielectric(c));
return vec4<f32>(l.diffuse * d + f * (one / (1.0 + lo + raea_ggx_lambda(a2, wi.z))), l.p * one / (1.0 + lo) + (1.0 - l.p) * d);
}
-216
View File
@@ -1,216 +0,0 @@
// The light that bounces, per texel (docs/bake.feature BK3): paths from the texel's origin through the model's own
// triangles (one BLAS, one TLAS) by wgpu's ray queries. What a texel keeps is the mean light its cosine-weighted rays
// bring back, so the lightmap times a surface's albedo is the light it sends on. At each hit the surface's emission
// is added and the path goes on by its BSDF (Lambert, diffuse.wgsl, under the glossy layers of glossy.wgsl); a miss sees
// the sky; after the second bounce Russian roulette ends paths by their weight, unbiased. As Cycles does by default
// (filter glossy 1), a lobe is no sharper than its path's least likely turn: a caustic is blurred, not a firefly. Passes add to `accum` (rgb, samples).
struct Params {
// toward the sun (w: the cosine of its half angle) and its irradiance facing it, all zero when there's none
sun_dir: vec4<f32>,
sun: vec4<f32>,
count: u32,
// the first sample of this pass (the random numbers are a sample's own)
base: u32,
per_pass: u32,
bounces: u32,
offset: f32,
// the first texel of this dispatch (a bake's texels go in chunks)
first: u32,
sky_w: u32,
sky_h: u32,
rotation: f32,
_pad0: f32,
_pad1: f32,
_pad2: f32,
}
// tex: 1 when textured, then the texture's first word, width and height; gloss: metallic, roughness, the dielectric's F0
struct Surface {
albedo: vec4<f32>,
emission: vec4<f32>,
tex: vec4<u32>,
gloss: vec4<f32>,
}
@group(0) @binding(0) var tlas: acceleration_structure;
// each vertex's place, and its u in w
@group(0) @binding(1) var<storage, read> positions: array<vec4<f32>>;
@group(0) @binding(2) var<storage, read> indices: array<u32>;
@group(0) @binding(3) var<storage, read> surfaces: array<Surface>;
// per texel: its point off the surface (w: which starts are open, see `start`), the hemisphere's normal, and its
// footprint's two sides
@group(0) @binding(4) var<storage, read> texels: array<vec4<f32>>;
@group(0) @binding(5) var<storage, read_write> accum: array<vec4<f32>>;
@group(0) @binding(6) var<uniform> params: Params;
// each vertex's v
@group(0) @binding(7) var<storage, read> vs: array<f32>;
// the textures one after another, sRGB, 8 bits a channel
@group(0) @binding(8) var<storage, read> images: array<u32>;
// the panorama, top row first, its light already at its strength; then glossy.rs's table
@group(0) @binding(9) var<storage, read> sky: array<vec4<f32>>;
fn raea_layers_at(k: i32) -> vec4<f32> {
return sky[params.sky_w * params.sky_h + u32(k)];
}
// The nearest hit. Its own function: a ray_query declared in a loop is zeroed again each turn, which naga writes for
// Metal as an assignment Metal's intersection_query deletes.
fn nearest(o: vec3<f32>, d: vec3<f32>) -> RayIntersection {
var rq: ray_query;
rayQueryInitialize(&rq, tlas, RayDesc(0u, 0xffu, 0.0, 1.0e30, o, d));
while (rayQueryProceed(&rq)) {}
return rayQueryGetCommittedIntersection(&rq);
}
fn blocked(o: vec3<f32>, d: vec3<f32>) -> bool {
var rq: ray_query;
rayQueryInitialize(&rq, tlas, RayDesc(RAY_FLAG_TERMINATE_ON_FIRST_HIT, 0xffu, 0.0, 1.0e30, o, d));
while (rayQueryProceed(&rq)) {}
return rayQueryGetCommittedIntersection(&rq).kind != RAY_QUERY_INTERSECTION_NONE;
}
// The panorama as raea draws it (systems/environment): its middle straight ahead (-Z), its right half to +X, turned
// counter-clockwise from above by `rotation`; bilinear, wrapping round.
fn sky_at(d: vec3<f32>) -> vec3<f32> {
let size = vec2<f32>(f32(params.sky_w), f32(params.sky_h));
// straight up or down has no longitude, and atan2(0, 0) may be NaN: any will do
var lon = 0.0;
if (d.x != 0.0 || d.z != 0.0) {
lon = atan2(d.x, -d.z);
}
let u = fract(0.5 + (lon + params.rotation) / 6.283185307);
let v = acos(clamp(d.y, -1.0, 1.0)) / 3.141592654;
let at = vec2<f32>(u, v) * size - 0.5;
let f = fract(at);
let i = vec2<i32>(floor(at));
let w = i32(params.sky_w);
let x0 = u32((i.x + w) % w);
let x1 = u32((i.x + 1 + w) % w);
let y0 = u32(clamp(i.y, 0, i32(params.sky_h) - 1)) * params.sky_w;
let y1 = u32(clamp(i.y + 1, 0, i32(params.sky_h) - 1)) * params.sky_w;
return mix(mix(sky[y0 + x0].rgb, sky[y0 + x1].rgb, f.x), mix(sky[y1 + x0].rgb, sky[y1 + x1].rgb, f.x), f.y);
}
// A texture's colour at uv, linear, its nearest texel, repeating.
fn image_at(tex: vec4<u32>, uv: vec2<f32>) -> vec3<f32> {
let q = fract(uv);
let x = min(u32(q.x * f32(tex.z)), tex.z - 1u);
let y = min(u32(q.y * f32(tex.w)), tex.w - 1u);
let c = unpack4x8unorm(images[tex.y + y * tex.z + x]).rgb;
return select(pow((c + 0.055) / 1.055, vec3<f32>(2.4)), c / 12.92, c <= vec3<f32>(0.04045));
}
// Where a sample starts: one of the texel's 4 x 4 points, the open ones in turn (Cycles jitters its samples over the
// texel too: a ledge narrower than a texel is half of it, not all or nothing). Bit 16 alone is the centre.
fn start(i: u32, at: vec3<f32>, open: u32, turn: u32) -> vec3<f32> {
var left = open & 0xffffu;
if (left == 0u) {
return at;
}
for (var k = turn % countOneBits(left); k > 0u; k = k - 1u) {
left = left & (left - 1u);
}
let c = firstTrailingBit(left);
let q = (vec2<f32>(f32(c % 4u), f32(c / 4u)) + 0.5) / 4.0 - 0.5;
return at + texels[4u * i + 2u].xyz * q.x + texels[4u * i + 3u].xyz * q.y;
}
@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
let i = params.first + gid.x;
if (i >= params.count) {
return;
}
let at = texels[4u * i];
let open = bitcast<u32>(at.w);
if (open == 0u) {
return;
}
let n0 = texels[4u * i + 1u].xyz;
var sum = vec3<f32>(0.0);
for (var s = 0u; s < params.per_pass; s = s + 1u) {
var rng = raea_hash(i * 0x9e3779b9u ^ raea_hash(params.base + s));
var o = start(i, at.xyz, open, params.base + s + raea_hash(i));
var n = n0;
var weight = vec3<f32>(1.0);
var light = vec3<f32>(0.0);
var d = raea_diffuse_sample(n, vec2<f32>(raea_rand(&rng), raea_rand(&rng)));
var likely = dot(n, d) / 3.141592654;
for (var b = 0u; b < params.bounces; b = b + 1u) {
let hit = nearest(o, d);
if (hit.kind == RAY_QUERY_INTERSECTION_NONE) {
light = light + weight * sky_at(d);
break;
}
let p = hit.primitive_index;
let srf = surfaces[p];
light = light + weight * srf.emission.rgb;
let a = positions[indices[3u * p]].xyz;
let bb = positions[indices[3u * p + 1u]].xyz;
let c = positions[indices[3u * p + 2u]].xyz;
var ng = normalize(cross(bb - a, c - a));
if (dot(ng, d) > 0.0) {
ng = -ng;
}
let w = hit.barycentrics;
o = a * (1.0 - w.x - w.y) + bb * w.x + c * w.y + ng * params.offset;
n = ng;
var albedo = srf.albedo.rgb;
if (srf.tex.x == 1u) {
let i0 = indices[3u * p];
let i1 = indices[3u * p + 1u];
let i2 = indices[3u * p + 2u];
let k = 1.0 - w.x - w.y;
albedo = albedo * image_at(srf.tex, vec2<f32>(positions[i0].w * k + positions[i1].w * w.x + positions[i2].w * w.y, vs[i0] * k + vs[i1] * w.x + vs[i2] * w.y));
}
let x = normalize(cross(n, select(vec3<f32>(0.0, 1.0, 0.0), vec3<f32>(1.0, 0.0, 0.0), abs(n.x) < 0.9)));
let frame = mat3x3<f32>(x, cross(n, x), n);
var wo = -d * frame;
wo.z = max(wo.z, 1e-4);
let lobes = raea_lobes(albedo, srf.gloss.xyz, 0.5 * sqrt(max(0.0, 1.0 - likely)), wo.z);
// the sun at the hit (never at the texel: its direct light stays live), from a point of its disk
let toward = params.sun_dir.xyz;
let facing = dot(n, toward);
if (params.sun_dir.w > 0.0 && facing > 0.0) {
let z = 1.0 - raea_rand(&rng) * (1.0 - params.sun_dir.w);
let phi = 6.283185307 * raea_rand(&rng);
let r = sqrt(max(0.0, 1.0 - z * z));
let sa = select(vec3<f32>(0.0, 1.0, 0.0), vec3<f32>(1.0, 0.0, 0.0), abs(toward.x) < 0.9);
let st = normalize(cross(toward, sa));
let sd = normalize(st * (r * cos(phi)) + cross(toward, st) * (r * sin(phi)) + toward * z);
if (!blocked(o, sd)) {
light = light + weight * params.sun.rgb * raea_lobes_eval(lobes, wo, sd * frame).rgb;
}
}
let u = vec2<f32>(raea_rand(&rng), raea_rand(&rng));
if (lobes.p <= 0.0) {
d = raea_diffuse_sample(n, u);
weight = weight * lobes.diffuse;
likely = min(likely, dot(n, d) / 3.141592654);
} else {
if (raea_rand(&rng) < lobes.p) {
d = reflect(-wo, raea_ggx_sample(wo, lobes.a, u));
} else {
d = raea_diffuse_sample(vec3<f32>(0.0, 0.0, 1.0), u);
}
let f = raea_lobes_eval(lobes, wo, d);
if (f.w <= 0.0) {
break;
}
weight = weight * f.rgb / f.w;
likely = min(likely, f.w);
d = normalize(frame * d);
}
if (b >= 2u) {
let q = min(max(weight.r, max(weight.g, weight.b)), 1.0);
if (raea_rand(&rng) >= q) {
break;
}
weight = weight / q;
}
}
sum = sum + light;
}
accum[i] = accum[i] + vec4<f32>(sum, f32(params.per_pass));
}
+5 -1
View File
@@ -23,8 +23,12 @@ bevy = { version = "=0.20.0", default-features = false, features = ["std", "defa
serde_json = "1"
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "hdr"] }
raea-io-net = { path = "../../io/net" }
raea-core-shape = { path = "../../core/shape" }
raea-sys-mesh = { path = "../mesh" }
# BC7 maps (maps.rs bc7_chain, docs/render-memory.feature RM9): Intel's ISPC texture kernels, prebuilt for macOS, Linux
# and Windows on x86_64 and arm64; content names for the encoded blocks kept in raea's caches
intel_tex_2 = "0.5"
blake3 = "1.8"
raea-io-home = { path = "../../io/home" }
# a texture given as a data:image/svg+xml URL, drawn on the CPU (the resvg raea-runtime-js draws SVG with)
resvg = { version = "=0.48.1", default-features = false, features = ["text"], optional = true }
+1 -1
View File
@@ -17,7 +17,7 @@ pub mod lightmap;
pub mod maps;
pub use raea_sys_mesh as mesh;
pub mod surface;
pub mod toon;
pub mod swapped;
pub mod shadow_only;
pub mod shadow_catch;
pub mod shader_material;
+127 -193
View File
@@ -3,6 +3,10 @@ use std::path::Path;
use raea_core_program::eval::Tup;
use bevy::render::render_resource::TextureFormat;
// pictures given inline (data: URLs, SVG) and a panel's, with their mip chain
mod pictures;
pub use pictures::*;
/// A material's maps, made once per load (file or data: URL, colour or data, clamped or repeating): a floor of tiles
/// and its plinths share one texture each. Cleared at each load, so a reload frees the last one's.
#[derive(Resource, Default)]
@@ -26,13 +30,25 @@ pub enum MapKind {
pub fn map_image(pic: image::RgbaImage, kind: MapKind, repeat: bool, sampling: Option<&raea_sys_sampler::Sampling>) -> Image {
let (w, h) = pic.dimensions();
let srgb = kind == MapKind::Colour;
let (data, levels) = mips_rgba8(pic.into_raw(), w, h, srgb);
// RM9: block-compressed (BC7) where the GPU reads it, a quarter of RGBA8's bytes; else RGBA8 with its mips
let (data, levels, format, w, h) = match bc7_chain(&pic, srgb) {
Some((data, levels, bw, bh)) => (data, levels, if srgb { TextureFormat::Bc7RgbaUnormSrgb } else { TextureFormat::Bc7RgbaUnorm }, bw, bh),
None => {
let (data, levels) = mips_rgba8(pic.into_raw(), w, h, srgb);
(data, levels, if srgb { TextureFormat::Rgba8UnormSrgb } else { TextureFormat::Rgba8Unorm }, w, h)
}
};
let mut img = Image::new(
bevy::render::render_resource::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
bevy::render::render_resource::TextureDimension::D2,
data,
if srgb { TextureFormat::Rgba8UnormSrgb } else { TextureFormat::Rgba8Unorm },
bevy::asset::RenderAssetUsages::default(),
format,
// RM1 (docs/render-memory.feature): the GPU's copy alone. Nothing on the CPU reads a material's map once it's
// made (its mips are made here; texture arrays are raea-sys-sampler's own pictures), and the main-world copy
// was the whole picture again for the render's length: 2.4 GB of halcyon r109's 21.5 as a sequence, where every
// frame's pool maps (96 of each) are loaded at its start
// RAEA_KEEP_CPU_ASSETS=1 keeps the main-world copy too (the A/B control, or a reader found to need it)
if std::env::var_os("RAEA_KEEP_CPU_ASSETS").is_some() { bevy::asset::RenderAssetUsages::default() } else { bevy::asset::RenderAssetUsages::RENDER_WORLD },
);
img.texture_descriptor.mip_level_count = levels;
let address = if repeat { bevy::image::ImageAddressMode::Repeat } else { bevy::image::ImageAddressMode::ClampToEdge };
@@ -50,6 +66,114 @@ pub fn map_image(pic: image::RgbaImage, kind: MapKind, repeat: bool, sampling: O
img
}
/// Whether the device samples BC textures (wgpu's TEXTURE_COMPRESSION_BC): set by the engine from its RenderDevice
/// before an edit's maps are made (set_block_compression); off until then, so a map is RGBA8 where nothing said.
static BLOCK_COMPRESSION: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// The device's answer for BC textures, given once it's made.
pub fn set_block_compression(on: bool) {
BLOCK_COMPRESSION.store(on, std::sync::atomic::Ordering::Relaxed);
}
/// A map as BC7 with its mip chain (docs/render-memory.feature RM9): 16 bytes for each 4x4 texels, a quarter of
/// RGBA8's, on the GPU and in the bandwidth every sample reads. halcyon r109's 87 maps were 733 MB as RGBA8. BC7 keeps
/// all four channels, so a normal map or a metallic-roughness map is read as it was by Bevy's shaders and Solari's.
/// Encoded once (Intel's ISPC kernels, intel_tex_2, on every core) and kept in raea's caches by the picture's content
/// (maps/NAME.bc7), so a later run reads the blocks and makes no mips. BC's blocks need each side of the base level a
/// multiple of 4, so a picture that isn't is resampled to the next one up (8775 texels to 8776: the picture still
/// runs 0 to 1 across the part, so nothing moves; halcyon's two widest surfaces, 8775 and 5849 across, were 223 MB
/// of RGBA8 for this alone). The blocks and the size they're for; None where the device has no BC, or RAEA_NO_BC=1
/// (the A/B control).
fn bc7_chain(pic: &image::RgbaImage, srgb: bool) -> Option<(Vec<u8>, u32, u32, u32)> {
let (w0, h0) = pic.dimensions();
if !BLOCK_COMPRESSION.load(std::sync::atomic::Ordering::Relaxed) || std::env::var_os("RAEA_NO_BC").is_some() || w0 == 0 || h0 == 0 {
return None;
}
let (w, h) = (w0.next_multiple_of(4), h0.next_multiple_of(4));
let mut hasher = blake3::Hasher::new();
hasher.update(&[srgb as u8, 1]); // 1: this encoding (opaque or alpha basic, box mips); bump to make them again
hasher.update(&w.to_le_bytes());
hasher.update(&h.to_le_bytes());
hasher.update(&w0.to_le_bytes());
hasher.update(&h0.to_le_bytes());
hasher.update(pic.as_raw());
let name = hasher.finalize().to_hex();
let dir = raea_io_home::caches().map(|c| c.join("maps"));
let path = dir.as_ref().map(|d| d.join(format!("{}.bc7", &name.as_str()[..32])));
let levels = 32 - w.max(h).leading_zeros();
let size: usize = (0..levels).map(|l| (((w >> l).max(1) + 3) / 4 * (((h >> l).max(1) + 3) / 4) * 16) as usize).sum();
if let Some(p) = &path
&& let Ok(b) = std::fs::read(p)
&& b.len() == size
{
return Some((b, levels, w, h));
}
let resized;
let pic = if (w, h) == (w0, h0) {
pic
} else {
resized = image::imageops::resize(pic, w, h, image::imageops::FilterType::CatmullRom);
&resized
};
let opaque = pic.as_raw().chunks_exact(4).all(|p| p[3] == 255);
let settings = if opaque { intel_tex_2::bc7::opaque_basic_settings() } else { intel_tex_2::bc7::alpha_basic_settings() };
let (data, mip_levels) = mips_rgba8(pic.as_raw().clone(), w, h, srgb);
if mip_levels != levels {
return None;
}
let mut out = Vec::with_capacity(size);
let mut at = 0usize;
for l in 0..levels {
let (lw, lh) = ((w >> l).max(1), (h >> l).max(1));
let texels = &data[at..at + (lw * lh * 4) as usize];
at += (lw * lh * 4) as usize;
out.extend_from_slice(&bc7_level(&settings, texels, lw, lh));
}
if out.len() != size {
return None;
}
if let Some(p) = &path {
let _ = raea_io_home::write_whole(p, &out);
}
Some((out, levels, w, h))
}
/// One mip level's BC7 blocks, row by row of blocks: a level under 4 texels a side padded out by its edge texels, and
/// a big one cut into bands of block rows encoded on as many threads as there are cores.
fn bc7_level(settings: &intel_tex_2::bc7::EncodeSettings, texels: &[u8], w: u32, h: u32) -> Vec<u8> {
let (pw, ph) = ((w + 3) / 4 * 4, (h + 3) / 4 * 4);
let padded: std::borrow::Cow<[u8]> = if (pw, ph) == (w, h) {
std::borrow::Cow::Borrowed(texels)
} else {
let mut p = vec![0u8; (pw * ph * 4) as usize];
for y in 0..ph {
for x in 0..pw {
let s = (((y.min(h - 1)) * w + x.min(w - 1)) * 4) as usize;
let d = ((y * pw + x) * 4) as usize;
p[d..d + 4].copy_from_slice(&texels[s..s + 4]);
}
}
std::borrow::Cow::Owned(p)
};
let block_rows = ph / 4;
let row_bytes = (pw / 4 * 16) as usize;
let mut out = vec![0u8; block_rows as usize * row_bytes];
let threads = std::thread::available_parallelism().map(|n| n.get() as u32).unwrap_or(4).min(block_rows).max(1);
let band = block_rows.div_ceil(threads);
std::thread::scope(|sc| {
for (i, chunk) in out.chunks_mut(band as usize * row_bytes).enumerate() {
let y0 = i as u32 * band * 4;
let rows = (chunk.len() / row_bytes) as u32 * 4;
let src = &padded[(y0 * pw * 4) as usize..((y0 + rows) * pw * 4) as usize];
sc.spawn(move || {
let surface = intel_tex_2::RgbaSurface { data: src, width: pw, height: rows, stride: pw * 4 };
intel_tex_2::bc7::compress_blocks_into(settings, &surface, chunk);
});
}
});
out
}
/// RGBA8 texels with every mip level after them (2x2 box averages; in linear light when `srgb`): the data and the
/// level count.
pub fn mips_rgba8(mut data: Vec<u8>, w: u32, h: u32, srgb: bool) -> (Vec<u8>, u32) {
@@ -296,193 +420,3 @@ pub fn material(world: &mut World, t: &Tup, inserted: &[Tup], dir: &Path) -> Res
super::fields::apply(&mut m, vals, &format!("mesh {}", t.id))?;
Ok(m)
}
/// A picture given inline as a data: URL (`data:image/png;base64,...`, `data:image/svg+xml;utf8,<svg ...>`), decoded in
/// memory: a raster through `image`, an SVG drawn by usvg and vello_cpu at its own size (at least 512 px on its long
/// side, at most 4096). Before this a data: URL was read as a file path and failed ("map: .../data:image/svg+xml...: No
/// such file"), the way the legacy app's agent first wrote a label into a perfume shot.
pub fn data_picture(src: &str) -> Result<image::RgbaImage, String> {
let (mime, bytes) = raea_io_net::data_url(src).ok_or("a data: URL that doesn't decode")?;
let svg = mime == "image/svg+xml" || (mime.is_empty() && bytes.trim_ascii_start().starts_with(b"<svg"));
if !svg {
return image::load_from_memory(&bytes).map(|i| i.to_rgba8()).map_err(|e| format!("a {mime} picture: {e}"));
}
svg_picture(&bytes)
}
/// An SVG's bytes drawn by resvg, at least 512 px on its long side, at most 4096.
#[cfg(feature = "native")]
pub fn svg_picture(bytes: &[u8]) -> Result<image::RgbaImage, String> {
let tree = resvg::usvg::Tree::from_data(bytes, &resvg::usvg::Options::default()).map_err(|e| format!("its SVG: {e}"))?;
let (sw, sh) = (tree.size().width().max(1.0), tree.size().height().max(1.0));
let k = (512.0 / sw.max(sh)).max(1.0).min(4096.0 / sw.max(sh));
let (w, h) = ((sw * k).round().max(1.0) as u32, (sh * k).round().max(1.0) as u32);
let mut pm = resvg::tiny_skia::Pixmap::new(w, h).ok_or("the SVG's size")?;
resvg::render(&tree, resvg::tiny_skia::Transform::from_scale(k, k), &mut pm.as_mut());
let mut px = pm.take();
// resvg paints premultiplied alpha; a texture wants it straight
for p in px.chunks_exact_mut(4) {
let a = p[3] as u32;
if a > 0 && a < 255 {
for c in &mut p[..3] {
*c = ((*c as u32 * 255 + a / 2) / a).min(255) as u8;
}
}
}
image::RgbaImage::from_raw(w, h, px).ok_or_else(|| "the SVG's pixels".to_string())
}
/// Without native the CPU's SVG renderer isn't linked (a browser build can draw an SVG in the page instead).
#[cfg(not(feature = "native"))]
pub fn svg_picture(_bytes: &[u8]) -> Result<image::RgbaImage, String> {
Err("an SVG picture: SVG textures are drawn only in the native build".into())
}
#[cfg(all(test, feature = "native"))]
mod data_url_tests {
/// data: URL pictures decode in memory: an SVG (utf8, percent-escaped) drawn at least 512 px wide with its fill, and
/// a base64 PNG to its own pixels
#[test]
fn data_pictures_decode() {
let svg = super::data_picture("data:image/svg+xml;utf8,<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"64\" height=\"32\"><rect width=\"64\" height=\"32\" fill=\"%23ff0000\"/></svg>").unwrap();
assert_eq!(svg.dimensions(), (512, 256));
assert_eq!(svg.get_pixel(100, 100).0, [255, 0, 0, 255]);
let mut png = Vec::new();
image::RgbaImage::from_pixel(3, 2, image::Rgba([0, 128, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
use base64::Engine as _;
let url = format!("data:image/png;base64,{}", base64::engine::general_purpose::STANDARD.encode(&png));
let pic = super::data_picture(&url).unwrap();
assert_eq!((pic.dimensions(), pic.get_pixel(2, 1).0), ((3, 2), [0, 128, 255, 255]));
assert!(super::data_picture("data:image/png;base64,!!!").is_err());
}
}
/// A panel's picture: inline (a data: URL, raster or SVG) or a file.
pub fn panel_picture(src: &str, inserted: &[Tup], dir: &Path) -> Result<image::RgbaImage, String> {
if src.starts_with("data:") {
return data_picture(src).map_err(|e| format!("src (a data: URL): {e}"));
}
let path = resolve_src(inserted, src, dir)?;
Ok(image::open(&path).map_err(|e| format!("{}: {e}", path.display()))?.to_rgba8())
}
/// A panel's texture. A panel is usually drawn smaller than it was painted: a full mip chain and trilinear, anisotropic
/// sampling keep its text from shimmering as it moves (without them a 2x minified glyph flickers).
pub fn panel_image(pic: image::RgbaImage) -> Image {
let (pw, ph) = pic.dimensions();
let (data, levels) = mip_chain(pic.into_raw(), pw, ph);
let mut img = Image::new(
bevy::render::render_resource::Extent3d { width: pw, height: ph, depth_or_array_layers: 1 },
bevy::render::render_resource::TextureDimension::D2,
data,
TextureFormat::Rgba8UnormSrgb,
bevy::asset::RenderAssetUsages::default(),
);
img.texture_descriptor.mip_level_count = levels;
img.sampler = bevy::image::ImageSampler::Descriptor(bevy::image::ImageSamplerDescriptor {
anisotropy_clamp: 16,
..bevy::image::ImageSamplerDescriptor::linear()
});
img
}
/// Straight-alpha RGBA8 (sRGB) as premultiplied-alpha RGBA8 (the colour premultiplied in linear light, then encoded), with
/// every mip level after it (2x2 box averages of the premultiplied linear values): the data and the level count, for a
/// texture sampled trilinearly and blended premultiplied.
pub fn mip_chain(data: Vec<u8>, w: u32, h: u32) -> (Vec<u8>, u32) {
let to_lin: Vec<f32> = (0..256).map(|i| {
let c = i as f32 / 255.0;
if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) }
}).collect();
let to_srgb = |l: f32| -> u8 {
let c = if l <= 0.0031308 { l * 12.92 } else { 1.055 * l.powf(1.0 / 2.4) - 0.055 };
(c.clamp(0.0, 1.0) * 255.0 + 0.5) as u8
};
// level 0, premultiplied, kept in linear floats for the averages
let mut cur: Vec<[f32; 4]> = data.chunks_exact(4).map(|p| {
let a = p[3] as f32 / 255.0;
[to_lin[p[0] as usize] * a, to_lin[p[1] as usize] * a, to_lin[p[2] as usize] * a, a]
}).collect();
let encode = |px: &[[f32; 4]], out: &mut Vec<u8>| {
for p in px {
out.extend_from_slice(&[to_srgb(p[0]), to_srgb(p[1]), to_srgb(p[2]), (p[3].clamp(0.0, 1.0) * 255.0 + 0.5) as u8]);
}
};
let mut out = Vec::with_capacity(data.len() * 4 / 3 + 16);
encode(&cur, &mut out);
let (mut cw, mut ch) = (w as usize, h as usize);
let mut levels = 1;
while cw > 1 || ch > 1 {
let (nw, nh) = ((cw / 2).max(1), (ch / 2).max(1));
let mut next = vec![[0f32; 4]; nw * nh];
for y in 0..nh {
for x in 0..nw {
let mut acc = [0f32; 4];
for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
let p = cur[(y * 2 + dy).min(ch - 1) * cw + (x * 2 + dx).min(cw - 1)];
for c in 0..4 {
acc[c] += p[c] / 4.0;
}
}
next[y * nw + x] = acc;
}
}
encode(&next, &mut out);
cur = next;
(cw, ch) = (nw, nh);
levels += 1;
}
(out, levels)
}
#[cfg(test)]
mod screen_map_tests {
use super::*;
#[derive(Resource)]
struct Panel(Handle<Image>);
fn named(world: &mut World, src: &str) -> Option<Handle<Image>> {
(src == "raea-screen:panel@8x4").then(|| world.resource::<Panel>().0.clone())
}
/// A UiTexture's image (raea-screen:name@WxH) is the texture of whichever map names it, the same handle its UI is
/// drawn into: as the emissive map a panel glows, and shows under Solari, which draws no unlit surface. Before, only
/// the base colour looked it up and an emissive one was refused as a missing file.
#[test]
fn a_screen_image_is_the_texture_of_any_map() {
let mut world = World::new();
world.init_resource::<Assets<Image>>();
let h = world.resource_mut::<Assets<Image>>().add(Image::default());
world.insert_resource(Panel(h.clone()));
world.insert_resource(NamedImages(named));
let mut vals = BTreeMap::new();
for k in ["map", "emissive_map", "normal_map", "ao_map", "mr_map"] {
vals.insert(k.to_string(), V::S("raea-screen:panel@8x4".into()));
}
let t = Tup { kind: "mesh".into(), id: "panel".into(), vals };
let m = material(&mut world, &t, &[], Path::new(".")).unwrap();
for (slot, tex) in [("map", &m.base_color_texture), ("emissive", &m.emissive_texture), ("normal", &m.normal_map_texture), ("ao", &m.occlusion_texture), ("mr", &m.metallic_roughness_texture)] {
assert_eq!(tex.as_ref(), Some(&h), "{slot}");
}
// a screen nobody draws is still a file name, and a missing file is refused
let mut vals = BTreeMap::new();
vals.insert("emissive_map".to_string(), V::S("raea-screen:other@8x4".into()));
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));
}
}
+213
View File
@@ -0,0 +1,213 @@
//! Pictures given inline (a data: URL, raster or SVG) and a panel's, as RGBA, and the mip chain a panel's texture takes.
use super::*;
/// A picture given inline as a data: URL (`data:image/png;base64,...`, `data:image/svg+xml;utf8,<svg ...>`), decoded in
/// memory: a raster through `image`, an SVG drawn by usvg and vello_cpu at its own size (at least 512 px on its long
/// side, at most 4096). Before this a data: URL was read as a file path and failed ("map: .../data:image/svg+xml...: No
/// such file"), the way the legacy app's agent first wrote a label into a perfume shot.
pub fn data_picture(src: &str) -> Result<image::RgbaImage, String> {
let (mime, bytes) = raea_io_net::data_url(src).ok_or("a data: URL that doesn't decode")?;
let svg = mime == "image/svg+xml" || (mime.is_empty() && bytes.trim_ascii_start().starts_with(b"<svg"));
if !svg {
return image::load_from_memory(&bytes).map(|i| i.to_rgba8()).map_err(|e| format!("a {mime} picture: {e}"));
}
svg_picture(&bytes)
}
/// An SVG's bytes drawn by resvg, at least 512 px on its long side, at most 4096.
#[cfg(feature = "native")]
pub fn svg_picture(bytes: &[u8]) -> Result<image::RgbaImage, String> {
let tree = resvg::usvg::Tree::from_data(bytes, &resvg::usvg::Options::default()).map_err(|e| format!("its SVG: {e}"))?;
let (sw, sh) = (tree.size().width().max(1.0), tree.size().height().max(1.0));
let k = (512.0 / sw.max(sh)).max(1.0).min(4096.0 / sw.max(sh));
let (w, h) = ((sw * k).round().max(1.0) as u32, (sh * k).round().max(1.0) as u32);
let mut pm = resvg::tiny_skia::Pixmap::new(w, h).ok_or("the SVG's size")?;
resvg::render(&tree, resvg::tiny_skia::Transform::from_scale(k, k), &mut pm.as_mut());
let mut px = pm.take();
// resvg paints premultiplied alpha; a texture wants it straight
for p in px.chunks_exact_mut(4) {
let a = p[3] as u32;
if a > 0 && a < 255 {
for c in &mut p[..3] {
*c = ((*c as u32 * 255 + a / 2) / a).min(255) as u8;
}
}
}
image::RgbaImage::from_raw(w, h, px).ok_or_else(|| "the SVG's pixels".to_string())
}
/// Without native the CPU's SVG renderer isn't linked (a browser build can draw an SVG in the page instead).
#[cfg(not(feature = "native"))]
pub fn svg_picture(_bytes: &[u8]) -> Result<image::RgbaImage, String> {
Err("an SVG picture: SVG textures are drawn only in the native build".into())
}
#[cfg(all(test, feature = "native"))]
mod data_url_tests {
/// data: URL pictures decode in memory: an SVG (utf8, percent-escaped) drawn at least 512 px wide with its fill, and
/// a base64 PNG to its own pixels
#[test]
fn data_pictures_decode() {
let svg = super::data_picture("data:image/svg+xml;utf8,<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"64\" height=\"32\"><rect width=\"64\" height=\"32\" fill=\"%23ff0000\"/></svg>").unwrap();
assert_eq!(svg.dimensions(), (512, 256));
assert_eq!(svg.get_pixel(100, 100).0, [255, 0, 0, 255]);
let mut png = Vec::new();
image::RgbaImage::from_pixel(3, 2, image::Rgba([0, 128, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
use base64::Engine as _;
let url = format!("data:image/png;base64,{}", base64::engine::general_purpose::STANDARD.encode(&png));
let pic = super::data_picture(&url).unwrap();
assert_eq!((pic.dimensions(), pic.get_pixel(2, 1).0), ((3, 2), [0, 128, 255, 255]));
assert!(super::data_picture("data:image/png;base64,!!!").is_err());
}
}
/// A panel's picture: inline (a data: URL, raster or SVG) or a file.
pub fn panel_picture(src: &str, inserted: &[Tup], dir: &Path) -> Result<image::RgbaImage, String> {
if src.starts_with("data:") {
return data_picture(src).map_err(|e| format!("src (a data: URL): {e}"));
}
let path = resolve_src(inserted, src, dir)?;
Ok(image::open(&path).map_err(|e| format!("{}: {e}", path.display()))?.to_rgba8())
}
/// A panel's texture. A panel is usually drawn smaller than it was painted: a full mip chain and trilinear, anisotropic
/// sampling keep its text from shimmering as it moves (without them a 2x minified glyph flickers).
pub fn panel_image(pic: image::RgbaImage) -> Image {
let (pw, ph) = pic.dimensions();
let (data, levels) = mip_chain(pic.into_raw(), pw, ph);
let mut img = Image::new(
bevy::render::render_resource::Extent3d { width: pw, height: ph, depth_or_array_layers: 1 },
bevy::render::render_resource::TextureDimension::D2,
data,
TextureFormat::Rgba8UnormSrgb,
bevy::asset::RenderAssetUsages::default(),
);
img.texture_descriptor.mip_level_count = levels;
img.sampler = bevy::image::ImageSampler::Descriptor(bevy::image::ImageSamplerDescriptor {
anisotropy_clamp: 16,
..bevy::image::ImageSamplerDescriptor::linear()
});
img
}
/// Straight-alpha RGBA8 (sRGB) as premultiplied-alpha RGBA8 (the colour premultiplied in linear light, then encoded), with
/// every mip level after it (2x2 box averages of the premultiplied linear values): the data and the level count, for a
/// texture sampled trilinearly and blended premultiplied.
pub fn mip_chain(data: Vec<u8>, w: u32, h: u32) -> (Vec<u8>, u32) {
let to_lin: Vec<f32> = (0..256).map(|i| {
let c = i as f32 / 255.0;
if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) }
}).collect();
let to_srgb = |l: f32| -> u8 {
let c = if l <= 0.0031308 { l * 12.92 } else { 1.055 * l.powf(1.0 / 2.4) - 0.055 };
(c.clamp(0.0, 1.0) * 255.0 + 0.5) as u8
};
// level 0, premultiplied, kept in linear floats for the averages
let mut cur: Vec<[f32; 4]> = data.chunks_exact(4).map(|p| {
let a = p[3] as f32 / 255.0;
[to_lin[p[0] as usize] * a, to_lin[p[1] as usize] * a, to_lin[p[2] as usize] * a, a]
}).collect();
let encode = |px: &[[f32; 4]], out: &mut Vec<u8>| {
for p in px {
out.extend_from_slice(&[to_srgb(p[0]), to_srgb(p[1]), to_srgb(p[2]), (p[3].clamp(0.0, 1.0) * 255.0 + 0.5) as u8]);
}
};
let mut out = Vec::with_capacity(data.len() * 4 / 3 + 16);
encode(&cur, &mut out);
let (mut cw, mut ch) = (w as usize, h as usize);
let mut levels = 1;
while cw > 1 || ch > 1 {
let (nw, nh) = ((cw / 2).max(1), (ch / 2).max(1));
let mut next = vec![[0f32; 4]; nw * nh];
for y in 0..nh {
for x in 0..nw {
let mut acc = [0f32; 4];
for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
let p = cur[(y * 2 + dy).min(ch - 1) * cw + (x * 2 + dx).min(cw - 1)];
for c in 0..4 {
acc[c] += p[c] / 4.0;
}
}
next[y * nw + x] = acc;
}
}
encode(&next, &mut out);
cur = next;
(cw, ch) = (nw, nh);
levels += 1;
}
(out, levels)
}
#[cfg(test)]
mod screen_map_tests {
use super::*;
#[derive(Resource)]
struct Panel(Handle<Image>);
fn named(world: &mut World, src: &str) -> Option<Handle<Image>> {
(src == "raea-screen:panel@8x4").then(|| world.resource::<Panel>().0.clone())
}
/// A UiTexture's image (raea-screen:name@WxH) is the texture of whichever map names it, the same handle its UI is
/// drawn into: as the emissive map a panel glows, and shows under Solari, which draws no unlit surface. Before, only
/// the base colour looked it up and an emissive one was refused as a missing file.
#[test]
fn a_screen_image_is_the_texture_of_any_map() {
let mut world = World::new();
world.init_resource::<Assets<Image>>();
let h = world.resource_mut::<Assets<Image>>().add(Image::default());
world.insert_resource(Panel(h.clone()));
world.insert_resource(NamedImages(named));
let mut vals = BTreeMap::new();
for k in ["map", "emissive_map", "normal_map", "ao_map", "mr_map"] {
vals.insert(k.to_string(), V::S("raea-screen:panel@8x4".into()));
}
let t = Tup { kind: "mesh".into(), id: "panel".into(), vals };
let m = material(&mut world, &t, &[], Path::new(".")).unwrap();
for (slot, tex) in [("map", &m.base_color_texture), ("emissive", &m.emissive_texture), ("normal", &m.normal_map_texture), ("ao", &m.occlusion_texture), ("mr", &m.metallic_roughness_texture)] {
assert_eq!(tex.as_ref(), Some(&h), "{slot}");
}
// a screen nobody draws is still a file name, and a missing file is refused
let mut vals = BTreeMap::new();
vals.insert("emissive_map".to_string(), V::S("raea-screen:other@8x4".into()));
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));
}
/// RM9: a map's BC7 chain is 16 bytes a block on every level (a level under 4 texels a side is one block), is
/// the same blocks read back from the cache, and a picture whose sides aren't multiples of 4 is resampled to whole blocks
#[test]
fn a_map_is_bc7_with_its_mips_and_read_back_the_same() {
super::set_block_compression(true);
let pic = image::RgbaImage::from_fn(64, 16, |x, y| image::Rgba([(x * 4) as u8, (y * 16) as u8, ((x ^ y) * 9) as u8, 255]));
let Some((a, levels, ..)) = super::bc7_chain(&pic, true) else { panic!("no BC7 chain") };
assert_eq!(levels, 7, "64x16 to 1x1");
// 16x4 blocks, 8x2, 4x1, 2x1, 1x1, 1x1, 1x1
assert_eq!(a.len(), (64 + 16 + 4 + 2 + 1 + 1 + 1) * 16);
let (b, ..) = super::bc7_chain(&pic, true).unwrap();
assert_eq!(a, b, "the kept blocks are the ones made");
let odd = image::RgbaImage::from_pixel(30, 15, image::Rgba([9, 9, 9, 255]));
let (_, _, w, h) = super::bc7_chain(&odd, false).unwrap();
assert_eq!((w, h), (32, 16), "resampled up to whole blocks");
let img = super::map_image(pic, super::MapKind::Data, true, None);
assert_eq!(img.texture_descriptor.format, TextureFormat::Bc7RgbaUnorm);
assert_eq!(img.texture_descriptor.mip_level_count, 7);
}
}
+107
View File
@@ -0,0 +1,107 @@
//! A standard material's maps whose picture changes frame by frame, swapped on one material (docs/render-memory.feature
//! RM6). raea-runtime-scene's parts.rs keys such a map's column (`normal_maps`, one picture a line, and `normal_map_k`,
//! keyed by step: raea-core-scene's SWAPPED_MAPS) where each picture once cut the part into a row of its own, every one
//! of them spawned with its own material and textures at load: halcyon's pool water (96 normal maps) held 96 meshes and
//! 186 textures, 1.7 GB on the GPU, in every shot of the reel, the pool in view or not. Now the part is one row and
//! one material, and the frame's picture is made when the frame shows it; the last one goes when nothing holds it.
use std::path::PathBuf;
use bevy::prelude::*;
use raea_core_program::eval::Tup;
use raea_core_program::ir::V;
use raea_sys_frame::FrameRows;
use crate::maps::{map_image, panel_picture, MapKind};
/// One map of a part whose picture is keyed: its column, how it's read, and the picture it shows now.
struct Slot {
col: &'static str,
kind: MapKind,
sampling: Option<raea_sys_sampler::Sampling>,
shown: String,
}
/// The part's swapped maps (spawned with the row when one of its maps is keyed) and where its pictures are found.
#[derive(Component)]
pub struct SwappedMaps {
slots: Vec<Slot>,
repeat: bool,
dir: PathBuf,
}
/// The maps a mesh row swaps, by column, with how each is read (as maps::material makes them).
const COLS: [(&str, &str, MapKind); 5] = [("map", "map", MapKind::Colour), ("normal_map", "normalMap", MapKind::Data), ("mr_map", "metallicRoughnessMap", MapKind::Data), ("ao_map", "aoMap", MapKind::Data), ("emissive_map", "emissiveMap", MapKind::Colour)];
/// The row's swapped maps, if any of its maps is keyed (`{col}s`): put on the part's entity as it spawns.
pub fn of(t: &Tup, dir: &std::path::Path) -> Result<Option<SwappedMaps>, String> {
let vals = &t.vals;
let all = raea_sys_sampler::Sampling::col(vals, "sampler").map_err(|e| format!("mesh {}: {e}", t.id))?;
let own: std::collections::BTreeMap<String, raea_sys_sampler::Sampling> = match vals.get("samplers") {
Some(V::S(js)) => {
let o: serde_json::Map<String, serde_json::Value> = serde_json::from_str(js).map_err(|e| format!("mesh {}: samplers: {e}", t.id))?;
o.iter().filter_map(|(k, v)| raea_sys_sampler::Sampling::of(v).ok().map(|s| (k.clone(), s))).collect()
}
_ => Default::default(),
};
let slots: Vec<Slot> = COLS
.iter()
.filter(|(col, ..)| matches!(vals.get(&format!("{col}s")), Some(V::S(_))))
.filter_map(|&(col, prop, kind)| match vals.get(col) {
Some(V::S(s)) if !s.is_empty() && !s.starts_with("render:") => Some(Slot { col, kind, sampling: own.get(prop).or(all.as_ref()).cloned(), shown: s.clone() }),
_ => None,
})
.collect();
if slots.is_empty() {
return Ok(None);
}
let g = |k: &str| match vals.get(k) { Some(V::N(n)) => *n as f32, _ => 1.0 };
Ok(Some(SwappedMaps { slots, repeat: g("repeat_u") != 1.0 || g("repeat_v") != 1.0, dir: dir.to_path_buf() }))
}
/// The frame's picture on each swapped map: made when the frame names another than the one shown. A material shared
/// with other parts (one per value: share.rs) is made the part's own first, so the swap shows on this part alone.
pub fn sync_swapped_maps(
frame: Res<FrameRows>,
mut q: Query<(Entity, &mut SwappedMaps, &mut MeshMaterial3d<StandardMaterial>)>,
mut mats: ResMut<Assets<StandardMaterial>>,
mut images: ResMut<Assets<Image>>,
) {
if q.is_empty() {
return;
}
for (e, mut sw, mut mat) in &mut q {
let Some(v) = frame.vals(e) else { continue };
let mut changed: Vec<(usize, Handle<Image>)> = Vec::new();
for (i, slot) in sw.slots.iter().enumerate() {
let Some(src) = raea_sys_frame::keyed(|c| v.get(c).cloned(), slot.col) else { continue };
if src == slot.shown || src.is_empty() || src.starts_with("render:") {
continue;
}
let pic = panel_picture(&src, &[], &sw.dir);
match pic {
Ok(pic) => changed.push((i, images.add(map_image(pic, slot.kind, sw.repeat, slot.sampling.as_ref())))),
Err(err) => warn!("a swapped map ({}): {src}: {err}", slot.col),
}
}
if changed.is_empty() {
continue;
}
let Some(cur) = mats.get(&mat.0).cloned() else { continue };
let mut own = cur;
for (i, h) in changed {
let slot = &mut sw.slots[i];
match slot.col {
"map" => own.base_color_texture = Some(h),
"normal_map" => own.normal_map_texture = Some(h),
"mr_map" => own.metallic_roughness_texture = Some(h),
"ao_map" => own.occlusion_texture = Some(h),
_ => own.emissive_texture = Some(h),
}
slot.shown = raea_sys_frame::keyed(|c| v.get(c).cloned(), slot.col).unwrap_or_default();
}
// a material of its own with the frame's pictures: a shared one is left to the parts that share it, and the
// part's last material and the pictures it showed go with their last holder
mat.0 = mats.add(own);
}
}
+10
View File
@@ -0,0 +1,10 @@
[package]
name = "raea-sys-memtally"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "Where a render's memory goes (docs/render-memory.feature RM0): after each RAEA_MEM_MARKS mark, each App's meshes, images and storage buffers with their CPU bytes, and its render world's meshes and images with their GPU bytes"
[dependencies]
bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "3d_bevy_render"] }
+131
View File
@@ -0,0 +1,131 @@
//! RM0 (docs/render-memory.feature): where a render's memory goes, by world and by copy. With RAEA_MEM_MARKS, every
//! mark (`mem_mark`) is followed, at each world's next update, by a `mem_assets` line per world: its main world's
//! meshes, images and storage buffers with the bytes they still hold on the CPU, and its render world's meshes and
//! images with the bytes they take on the GPU. A sequence opens more than one App (React's, the 3D's), so each line
//! names its App by the order it opened in.
use bevy::prelude::*;
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
/// Marks made so far: a world prints its tally when this has moved since it last did.
static MARKS: AtomicU64 = AtomicU64::new(0);
/// Apps tallied so far, to name each one.
static APPS: AtomicU32 = AtomicU32::new(0);
/// A mark was made (raea-render's `mem_mark`): each App tallied prints its assets at its next update.
pub fn marked() {
MARKS.fetch_add(1, Ordering::Relaxed);
}
/// The App's tally systems (the caller adds them only with RAEA_MEM_MARKS): its main world's in Last, its render
/// world's after it renders.
pub fn install(app: &mut App) {
let n = APPS.fetch_add(1, Ordering::Relaxed);
app.add_systems(Last, main_tally(n));
if let Some(sub) = app.get_sub_app_mut(bevy::render::RenderApp) {
sub.add_systems(bevy::render::Render, render_tally(n).after(bevy::render::RenderSystems::Render));
}
}
fn mb(b: u64) -> f64 {
b as f64 / 1048576.0
}
/// A mesh's bytes still on the CPU: its attributes and indices (none once its data went to the GPU alone).
pub fn mesh_cpu_bytes(m: &Mesh) -> u64 {
let attrs = m.try_attributes().map(|a| a.map(|(_, v)| v.get_bytes().len() as u64).sum()).unwrap_or(0);
let idx = match m.try_indices_option() {
Ok(Some(bevy::mesh::Indices::U16(v))) => v.len() as u64 * 2,
Ok(Some(bevy::mesh::Indices::U32(v))) => v.len() as u64 * 4,
_ => 0,
};
attrs + idx
}
fn main_tally(app: u32) -> impl FnMut(Res<Assets<Mesh>>, Res<Assets<Image>>, Option<Res<Assets<bevy::render::storage::ShaderBuffer>>>) {
let mut seen = 0u64;
move |meshes, images, buffers| {
let now = MARKS.load(Ordering::Relaxed);
if now == seen {
return;
}
seen = now;
let (mut mn, mut mk, mut mbytes) = (0u64, 0u64, 0u64);
for (_, m) in meshes.iter() {
let b = mesh_cpu_bytes(m);
mn += 1;
mk += (b > 0) as u64;
mbytes += b;
}
let (mut inn, mut ik, mut ibytes) = (0u64, 0u64, 0u64);
for (_, i) in images.iter() {
let b = i.data.as_ref().map_or(0, |d| d.len() as u64);
inn += 1;
ik += (b > 0) as u64;
ibytes += b;
}
let (mut bn, mut bbytes) = (0u64, 0u64);
for (_, s) in buffers.iter().flat_map(|b| b.iter()) {
bn += 1;
if let bevy::render::storage::ShaderBufferData::Initialized { data, .. } = &s.data {
bbytes += data.len() as u64;
}
}
eprintln!(
"mem_assets app {app} main: meshes {mn} ({mk} on the CPU) {:.1} MB, images {inn} ({ik} on the CPU) {:.1} MB, buffers {bn} {:.1} MB",
mb(mbytes),
mb(ibytes),
mb(bbytes)
);
}
}
/// A texture's bytes on the GPU: every mip level of every layer, by its format's blocks.
pub fn texture_bytes(d: &bevy::render::render_resource::TextureDescriptor) -> u64 {
let (bw, bh) = d.format.block_dimensions();
let block = d.format.block_copy_size(None).unwrap_or(4) as u64;
let layers = if d.dimension == bevy::render::render_resource::TextureDimension::D3 { 1 } else { d.size.depth_or_array_layers as u64 };
let mut sum = 0u64;
for l in 0..d.mip_level_count.max(1) {
let w = (d.size.width >> l).max(1);
let h = (d.size.height >> l).max(1);
let z = if d.dimension == bevy::render::render_resource::TextureDimension::D3 { (d.size.depth_or_array_layers >> l).max(1) as u64 } else { 1 };
sum += w.div_ceil(bw) as u64 * h.div_ceil(bh) as u64 * block * z;
}
sum * layers
}
fn render_tally(app: u32) -> impl FnMut(Res<bevy::render::render_asset::RenderAssets<bevy::render::mesh::RenderMesh>>, Res<bevy::render::render_asset::RenderAssets<bevy::render::texture::GpuImage>>) {
let mut seen = 0u64;
move |meshes, images| {
let now = MARKS.load(Ordering::Relaxed);
if now == seen {
return;
}
seen = now;
let (mut mn, mut mbytes) = (0u64, 0u64);
for (_, m) in meshes.iter() {
mn += 1;
mbytes += m.vertex_count as u64 * m.layout.0.layout().array_stride;
if let bevy::render::mesh::RenderMeshBufferInfo::Indexed { count, index_format } = m.buffer_info {
mbytes += count as u64 * if index_format == bevy::render::render_resource::IndexFormat::Uint16 { 2 } else { 4 };
}
}
let (mut inn, mut ibytes) = (0u64, 0u64);
let mut each: Vec<(u64, String)> = Vec::new();
for (_, i) in images.iter() {
inn += 1;
let d = &i.texture_descriptor;
let b = texture_bytes(d);
ibytes += b;
each.push((b, format!("{}x{}x{} {:?} mips {}{}", d.size.width, d.size.height, d.size.depth_or_array_layers, d.format, d.mip_level_count, d.label.map(|l| format!(" ({l})")).unwrap_or_default())));
}
eprintln!("mem_assets app {app} render: meshes {mn} {:.1} MB, images {inn} {:.1} MB", mb(mbytes), mb(ibytes));
// the biggest images, by what they are: which ones to make smaller next
each.sort_by(|a, b| b.0.cmp(&a.0));
let top: Vec<String> = each.iter().take(12).map(|(b, what)| format!("{:.1} MB {what}", mb(*b))).collect();
if !top.is_empty() {
eprintln!("mem_images app {app} render, biggest: {}", top.join("; "));
}
}
}
+70 -5
View File
@@ -230,6 +230,24 @@ pub fn box_uvs(pos: &[[f32; 3]], nor: &[[f32; 3]]) -> Vec<[f32; 2]> {
}
/// Triangle corners as an indexed mesh: each distinct (place, normal) once, by its exact bits, and each corner's index.
pub fn welded(pos: &[[f32; 3]], nor: &[[f32; 3]]) -> (Vec<[f32; 3]>, Vec<[f32; 3]>, Vec<u32>) {
let n = pos.len().min(nor.len());
let mut at: std::collections::HashMap<[u32; 6], u32> = std::collections::HashMap::with_capacity(n / 3);
let (mut p, mut q, mut idx) = (Vec::with_capacity(n / 3), Vec::with_capacity(n / 3), Vec::with_capacity(n));
for i in 0..n {
let (a, b) = (pos[i], nor[i]);
let key = [a[0].to_bits(), a[1].to_bits(), a[2].to_bits(), b[0].to_bits(), b[1].to_bits(), b[2].to_bits()];
let k = *at.entry(key).or_insert_with(|| {
p.push(a);
q.push(b);
(p.len() - 1) as u32
});
idx.push(k);
}
(p, q, idx)
}
/// A mesh row's shape as a Bevy Mesh (docs/media.feature M2): a sphere alone is Bevy's Sphere::mesh() (icosphere or UV
/// sphere), a cuboid alone its Cuboid's (UVs a face each) and a cylinder its Cylinder's, as a Bevy Mesh3d's; a <BufferMesh> ("buffer:{positions,
/// indices, normals, uvs, colors}") its own vertex buffers; anything else Manifold's, flat-shaded. `uvs` gives it
@@ -248,13 +266,15 @@ pub fn shape_mesh(id: &str, expr: &str, uvs: bool, tangents: bool) -> Result<Mes
}
return Ok(m);
}
if let Some(mut m) = expr.strip_prefix("buffer:").map(|b| indexed::buffer_indexed(b, uvs, vertex_colors)).transpose().map_err(|e| format!("mesh {id}: {e}"))?.flatten() {
// a <BufferMesh>'s JSON, its own text or the kept file it names (raea-core-shape kept_buffer, RM8)
let buffer = expr.strip_prefix("buffer:").map(raea_core_shape::buffer_json).transpose().map_err(|e| format!("mesh {id}: {e}"))?;
if let Some(mut m) = buffer.as_deref().map(|b| indexed::buffer_indexed(b, uvs, vertex_colors)).transpose().map_err(|e| format!("mesh {id}: {e}"))?.flatten() {
if tangents {
m.generate_tangents().map_err(|e| format!("mesh {id}: normalMap: its tangents: {e}"))?;
}
return Ok(m);
}
let (tris, own_uvs, own_colors) = match expr.strip_prefix("buffer:") {
let (tris, own_uvs, own_colors) = match buffer.as_deref() {
Some(b) => {
let c = buffer_colors(b).map_err(|e| format!("mesh {id}: {e}"))?;
let (t, u) = buffer_tris(b).map_err(|e| format!("mesh {id}: {e}"))?;
@@ -263,17 +283,62 @@ pub fn shape_mesh(id: &str, expr: &str, uvs: bool, tangents: bool) -> Result<Mes
None => (raea_core_shape::cached(expr).map_err(|e| format!("mesh {id}: {e}"))?, None, None),
};
let mut m = Mesh::new(bevy::render::render_resource::PrimitiveTopology::TriangleList, bevy::asset::RenderAssetUsages::default());
m.insert_attribute(Mesh::ATTRIBUTE_POSITION, tris.positions.clone());
m.insert_attribute(Mesh::ATTRIBUTE_NORMAL, tris.normals.clone());
// Manifold's triangles welded where a corner is another's exactly (its place and its normal), as an indexed mesh
// (docs/render-memory.feature RM7): halcyon's shapes had 4.65 corners to each distinct vertex, so the welded mesh
// is about a third of the bytes on the CPU, on the GPU and in Solari's traced copy, and a third of the vertices
// to shade. Only a shape with nothing given per corner (a <BufferMesh>'s own UVs or colours) is welded; box UVs
// are a vertex's own (from its place and normal), so welded corners had the same ones. RAEA_NO_WELD=1 draws them
// unwelded (the A/B control).
let weld = own_uvs.is_none() && own_colors.is_none() && std::env::var_os("RAEA_NO_WELD").is_none();
let (pos, nor) = if weld {
let (pos, nor, idx) = welded(&tris.positions, &tris.normals);
m.insert_indices(bevy::mesh::Indices::U32(idx));
(std::borrow::Cow::Owned(pos), std::borrow::Cow::Owned(nor))
} else {
(std::borrow::Cow::Borrowed(&tris.positions), std::borrow::Cow::Borrowed(&tris.normals))
};
m.insert_attribute(Mesh::ATTRIBUTE_POSITION, pos.to_vec());
m.insert_attribute(Mesh::ATTRIBUTE_NORMAL, nor.to_vec());
// a <BufferMesh colors>: per-vertex colours, which StandardMaterial multiplies its colour by
if let Some(c) = own_colors {
m.insert_attribute(Mesh::ATTRIBUTE_COLOR, c);
}
if own_uvs.is_some() || uvs {
m.insert_attribute(Mesh::ATTRIBUTE_UV_0, own_uvs.unwrap_or_else(|| box_uvs(&tris.positions, &tris.normals)));
m.insert_attribute(Mesh::ATTRIBUTE_UV_0, own_uvs.unwrap_or_else(|| box_uvs(&pos, &nor)));
if tangents {
m.generate_tangents().map_err(|e| format!("mesh {id}: normalMap: its tangents: {e}"))?;
}
}
Ok(m)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_shapes_corners_weld_where_place_and_normal_are_the_same() {
// a square as two triangles: six corners, four vertices; the crease's other side (another normal) stays apart
let up = [0.0, 1.0, 0.0];
let pos = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 0.0, 1.0], [0.0, 0.0, 0.0], [1.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, -1.0, 0.0]];
let nor = [up, up, up, up, up, up, [0.0, 0.0, -1.0], [0.0, 0.0, -1.0], [0.0, 0.0, -1.0]];
let (p, n, idx) = welded(&pos, &nor);
assert_eq!(p.len(), 7, "4 on the top, 3 on the side: {p:?}");
assert_eq!(n.len(), p.len());
assert_eq!(idx.len(), 9);
for (c, &i) in idx.iter().enumerate() {
assert_eq!((p[i as usize], n[i as usize]), (pos[c], nor[c]), "corner {c} draws where it was");
}
}
#[test]
fn a_welded_shape_is_indexed_and_draws_the_same_triangles() {
let m = shape_mesh("t", "box(1, 1, 1)", true, true).unwrap();
let _ = m;
let m = shape_mesh("t", "minus(box(2, 2, 2), cylinder(0.5, 3))", true, true).unwrap();
assert!(m.indices().is_some(), "a Manifold shape is indexed");
let t = raea_core_shape::cached("minus(box(2, 2, 2), cylinder(0.5, 3))").unwrap();
assert_eq!(m.indices().unwrap().len(), t.positions.len(), "every triangle kept");
assert!(m.count_vertices() < t.positions.len(), "fewer vertices than corners: {} of {}", m.count_vertices(), t.positions.len());
}
}
-155
View File
@@ -1,155 +0,0 @@
// The colour a procedural surface draws (lib.rs), as a module with no bindings, imports, stages or derivatives, so a
// fragment shader and a compute kernel can both take it (docs/bake.feature BK3): what a pixel knows from its screen
// derivatives comes in as an argument. NOT YET USED: procmat.wesl still has its own copy, and takes this one (the copy
// deleted) in the commit that compiles it.
struct Proc {
a: vec4<f32>,
b: vec4<f32>,
gap_color: vec4<f32>,
dust_color: vec4<f32>,
dirt_color: vec4<f32>,
// kind, scale, rough_a, rough_b
k: vec4<f32>,
// bump, seed, tile_x, tile_y
t: vec4<f32>,
// gap, dust, dirt, edges
w: vec4<f32>,
}
fn proc_hash(p: vec3<f32>) -> f32 {
let q = fract(p * 0.3183099 + vec3(0.1, 0.2, 0.3));
let r = q * 17.0;
return fract(r.x * r.y * r.z * (r.x + r.y + r.z));
}
fn proc_vnoise(p: vec3<f32>) -> f32 {
let i = floor(p);
let f = fract(p);
let u = f * f * (3.0 - 2.0 * f);
let a = mix(mix(proc_hash(i), proc_hash(i + vec3(1.0, 0.0, 0.0)), u.x), mix(proc_hash(i + vec3(0.0, 1.0, 0.0)), proc_hash(i + vec3(1.0, 1.0, 0.0)), u.x), u.y);
let b = mix(mix(proc_hash(i + vec3(0.0, 0.0, 1.0)), proc_hash(i + vec3(1.0, 0.0, 1.0)), u.x), mix(proc_hash(i + vec3(0.0, 1.0, 1.0)), proc_hash(i + vec3(1.0, 1.0, 1.0)), u.x), u.y);
return mix(a, b, u.z);
}
fn proc_fbm(p: vec3<f32>) -> f32 {
var s = 0.0;
var w = 0.5;
var q = p;
for (var k = 0; k < 5; k++) {
s += w * proc_vnoise(q);
q = q * 2.03 + vec3(1.7, 9.2, 3.1);
w *= 0.5;
}
return s / 0.96875;
}
// the face's own plane: the two axes across the dominant normal (a wall's x-y, a floor's x-z)
fn proc_plane(p: vec3<f32>, n: vec3<f32>) -> vec2<f32> {
let a = abs(n);
if (a.y >= a.x && a.y >= a.z) { return p.xz; }
if (a.x >= a.z) { return vec2(p.z, p.y); }
return p.xy;
}
// (mix between a and b, gap mask, height 0..1); duv: how much of the face's plane (proc_plane) a pixel or a texel covers
fn proc_pattern(pm: Proc, p: vec3<f32>, n: vec3<f32>, duv: vec2<f32>) -> vec3<f32> {
let kind = i32(pm.k.x + 0.5);
let q = p / max(pm.k.y, 1e-4) + vec3(pm.t.y * 17.3);
let uv = proc_plane(p, n);
// wood: rings round the local y axis, wandering, and fine grain along it
if (kind == 1) {
let r = length(q.xz + vec2(proc_fbm(q * 0.4), proc_fbm(q * 0.4 + 7.0)) * 0.6) * 4.0;
let ring = smoothstep(0.0, 0.6, fract(r)) * (1.0 - smoothstep(0.75, 1.0, fract(r)));
let grain = proc_vnoise(vec3(q.x * 30.0, q.y * 1.5, q.z * 30.0));
let m = clamp(ring * 0.75 + grain * 0.35, 0.0, 1.0);
return vec3(m, 0.0, 0.3 * ring + 0.2 * grain);
}
// marble: sharp veins through soft clouding
if (kind == 2) {
let v = pow(1.0 - abs(sin(q.x * 2.0 + q.y * 0.7 + proc_fbm(q * 0.8) * 7.0)), 10.0);
let cloud = proc_fbm(q * 0.5) * 0.3;
return vec3(clamp(v + cloud, 0.0, 1.0), 0.0, 0.05 * v);
}
// stone / concrete: mottled, pitted, speckled
if (kind == 3) {
let m = proc_fbm(q);
let pits = smoothstep(0.78, 0.84, proc_vnoise(q * 9.0));
let speck = step(0.93, proc_hash(floor(q * 30.0)));
return vec3(clamp(m * 0.8 + speck * 0.4, 0.0, 1.0), pits, m * 0.6 - pits * 0.5);
}
// brick (running bond) and tiles: cells on the face's plane with gaps between, each cell its own shade
if (kind == 4 || kind == 5) {
let size = vec2(max(pm.t.z, 1e-3), max(pm.t.w, 1e-3));
var c = uv / size;
let row = floor(c.y);
if (kind == 4) { c.x += 0.5 * (row - 2.0 * floor(row / 2.0)); }
let id = floor(c);
let f = fract(c);
let g = vec2(pm.w.x) / size;
let edge = min(min(f.x, 1.0 - f.x) / max(g.x, 1e-4), min(f.y, 1.0 - f.y) / max(g.y, 1e-4));
let gap = 1.0 - smoothstep(0.5, 1.0, edge);
let shade = proc_hash(vec3(id, pm.t.y)) * 0.7 + proc_fbm(q * 2.0) * 0.3;
let bevel = smoothstep(0.5, 2.0, edge);
return vec3(shade, gap, bevel * (0.8 + 0.2 * proc_fbm(q * 3.0)));
}
// fabric: a plain weave
if (kind == 6) {
let f = uv / max(pm.k.y, 1e-4) * 6.2831;
let warp = 0.5 + 0.5 * sin(f.x) * sign(sin(f.y * 0.5));
let weft = 0.5 + 0.5 * sin(f.y) * sign(sin(f.x * 0.5 + 1.57));
// threads finer than a pixel fade to the weave's mean shade, so a distant sofa doesn't shimmer in moire
let far = smoothstep(0.8, 2.5, length(duv) / max(pm.k.y, 1e-4) * 6.2831);
let m = mix(max(warp, weft), 0.72, far);
return vec3(clamp(m * 0.6 + proc_fbm(q * 0.3) * 0.4, 0.0, 1.0), 0.0, m * (1.0 - far));
}
// brushed metal: long fine streaks along the face
if (kind == 7) {
let sy = uv.y / max(pm.k.y, 1e-4) * 60.0;
let s = mix(proc_vnoise(vec3(uv.x / max(pm.k.y, 1e-4) * 0.4, sy, pm.t.y)), 0.5, smoothstep(0.5, 1.5, duv.y / max(pm.k.y, 1e-4) * 60.0));
return vec3(s * 0.6 + proc_fbm(q * 0.2) * 0.4, 0.0, s * 0.15);
}
// plaster: soft trowel marks and fine bumps
if (kind == 8) {
let m = proc_fbm(q * 0.6);
let fine = proc_vnoise(q * 18.0);
return vec3(m, 0.0, m * 0.5 + fine * 0.2);
}
// noise: two colours by fractal noise
let m = proc_fbm(q);
return vec3(m, 0.0, m * 0.5);
}
// Where a surface is drawn: its point and normal in the mesh's own space and the world's, and how fast its normal turns
// (1 / metres: the raster's fwidth of the normal over the position's; a ray hit's, over its triangle's edges).
struct ProcAt {
p: vec3<f32>,
wp: vec3<f32>,
wn: vec3<f32>,
curve: f32,
}
// (colour, roughness) of the pattern with its use over it: dust on what faces up; dirt in the gaps, the hollows,
// undersides and along the floor line; edges worn lighter and smoother where hands and feet go
fn proc_drawn(pm: Proc, pat: vec3<f32>, at: ProcAt) -> vec4<f32> {
let t = pat.x;
let gap = pat.y;
var c = mix(pm.a.rgb, pm.b.rgb, t);
var rough = mix(pm.k.z, pm.k.w, t);
c = mix(c, pm.gap_color.rgb, gap);
rough = mix(rough, 0.95, gap);
let wq = at.p / max(pm.k.y, 1e-4) * 0.7 + vec3(pm.t.y * 3.1);
let up = smoothstep(0.55, 0.95, at.wn.y);
let dust = clamp(up * pm.w.y * (0.55 + 0.45 * proc_fbm(wq * 2.0 + 30.0)), 0.0, 0.9);
c = mix(c, pm.dust_color.rgb, dust);
rough = mix(rough, 0.95, dust);
let floor_line = 1.0 - smoothstep(0.0, 0.25, at.wp.y);
let under = clamp(-at.wn.y, 0.0, 1.0);
let dirt = clamp((gap * 0.8 + under * 0.5 + floor_line * 0.7 + smoothstep(0.6, 0.9, proc_fbm(wq * 0.8 + 50.0)) * 0.4) * pm.w.z, 0.0, 0.85) * (0.6 + 0.4 * proc_fbm(wq * 3.0 + 70.0));
c = mix(c, pm.dirt_color.rgb, dirt);
rough = mix(rough, 0.9, dirt);
let edge = smoothstep(25.0, 90.0, at.curve) * pm.w.w * (0.5 + 0.5 * proc_fbm(wq * 4.0 + 90.0));
c = mix(c, min(c * 1.35 + vec3(0.04), vec3(1.0)), edge);
rough = mix(rough, rough * 0.6, edge);
return vec4(c, rough);
}
+1 -1
View File
@@ -97,7 +97,7 @@ type Counted = HashMap<(&'static str, String, u64), i64>;
fn counted(its: &[Item]) -> Counted {
let mut m = Counted::new();
for it in its {
*m.entry((it.kind, base_ident(it).to_string(), spawn_sig(it))).or_default() += 1;
*m.entry((it.kind, base_ident(it).to_string(), spawn_sig(it, false))).or_default() += 1;
}
m
}
+1 -1
View File
@@ -243,7 +243,7 @@ impl Snaps {
if x < 0.0 || x > w || y < 0.0 || y > h {
continue;
}
by.entry((called(it), raea_core_scene::spawn_sig(it))).or_default().push((k, r * v.focal / depth, [x, y]));
by.entry((called(it), raea_core_scene::spawn_sig(it, false))).or_default().push((k, r * v.focal / depth, [x, y]));
}
for (stem, n) in links {
let c = chains.entry(stem).or_insert((k, n, n));
+14
View File
@@ -0,0 +1,14 @@
[package]
name = "raea-sys-toon"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "Toon surfaces and their ink outlines: three's MeshToonMaterial as a Bevy material, its shaders embedded where raea-sys-material had them"
[dependencies]
raea-sys-frame = { path = "../frame" }
raea-core-program = { path = "../../core/program" }
raea-core-shape = { path = "../../core/shape" }
bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "3d_bevy_render"] }
serde_json = "1"
@@ -11,7 +11,11 @@
//! keyed on a mesh, as the standard material's: col_r col_g col_b, emissive emissive_k, opacity; and the toon's own
//! sh_r sh_g sh_b (an animated shadow colour), rim_k, spec_k, outline_w
use super::*;
use std::collections::{BTreeMap, HashMap};
use bevy::prelude::*;
use raea_core_program::ir::V;
use raea_sys_frame::*;
use bevy::light::{NotShadowCaster, NotShadowReceiver};
use bevy::mesh::{MeshVertexBufferLayoutRef, VertexAttributeValues};
use bevy::pbr::{ExtendedMaterial, MaterialExtension, MaterialPipeline, MaterialPipelineKey, MaterialPlugin};
@@ -87,8 +91,11 @@ impl Material for OutlineMaterial {
/// The shaders and the two materials, on every engine (nothing is compiled until a toon part draws).
pub fn install(app: &mut App) {
bevy::asset::embedded_asset!(app, "toon.wesl");
bevy::asset::embedded_asset!(app, "toon_outline.wesl");
// embedded where raea-sys-material had them, the path a composition names (<ShaderConstants shader=...>)
let embedded = app.world_mut().resource_mut::<bevy::asset::io::embedded::EmbeddedAssetRegistry>();
for (name, src) in [("toon.wesl", include_bytes!("toon.wesl").as_slice()), ("toon_outline.wesl", include_bytes!("toon_outline.wesl").as_slice())] {
embedded.insert_asset(std::path::PathBuf::new(), &std::path::Path::new("raea_sys_material").join(name), src);
}
app.add_plugins((MaterialPlugin::<ToonMaterial>::default(), MaterialPlugin::<OutlineMaterial>::default()));
}
File renamed without changes.
File renamed without changes.
+6 -3
View File
@@ -6,6 +6,7 @@
[crates]
raea-core-program = "core"
raea-core-tables = "core"
raea-core-scene = "core"
raea-core-shape = "core"
raea-core-meshcheck = "core"
@@ -87,6 +88,9 @@ raea-sys-parity = "systems" # the parity probe, in raea's App and the examples'
raea-bench-swatch = "systems" # a Blitz widget fixture (bench/bridge/swatch) the plugin catalog declares: a leaf on vendored crates, so a runtime crate may build it in
raea-render = "runtime"
raea-render-raytrace = "runtime"
raea-render-plugins = "runtime"
raea-runtime-ecs = "runtime"
raea-runtime-kinds = "runtime"
# `raea light check`: raealism's measures (docs/realism.feature LT1)
raea-light = "runtime"
# `raea bench denoise`: each denoiser against its converged truth (docs/denoise.feature DN0), on raea light's runner
@@ -130,6 +134,7 @@ raea-sys-grab = "systems"
raea-sys-splat = "systems"
raea-sys-sprite = "systems"
raea-sys-rt = "systems"
raea-sys-memtally = "systems" # RM0: what each App holds in meshes and images, CPU and GPU, at each mark (docs/render-memory.feature)
raea-sys-gi = "systems"
raea-sys-engine-shaders = "systems"
raea-sys-lod = "systems"
@@ -147,6 +152,7 @@ raea-sys-environment = "systems"
raea-sys-look = "systems"
raea-sys-compose = "systems"
raea-sys-material = "systems"
raea-sys-toon = "systems"
raea-sys-mesh = "systems"
raea-sys-layers = "systems"
raea-sys-framepass = "systems"
@@ -222,7 +228,6 @@ raea-app-scene = "apps" # raea scene lint|explain|light|stage
raea-app-voice = "apps" # raea voice: speech to speech on this computer, as lines of JSON
raea-app-ask = "apps"
raea-app-lightbake = "apps" # raea bake light (docs/bake.feature)
raea-sys-lighttrace = "systems" # light paths on the GPU by wgpu ray queries: the kernel the bake, rt and the path tracer share (docs/bake.feature BK3)
raea-sys-lightbake = "systems" # light baked over raea/wear's atlas on raea's ray tracer (docs/bake.feature)
raea-app-double = "apps"
raea-app-solid = "apps"
@@ -337,5 +342,3 @@ raea-sys-damage = true
raea-sys-glb = true
# the atlas raea's bakes share: charts, packing, each texel's point (the cause maps and the light bake lie over it)
raea-sys-atlas = true
# the paths a bake traces its light along (the kernel and its Settings), which systems/rt and the path tracer may build on too
raea-sys-lighttrace = true
+19
View File
@@ -0,0 +1,19 @@
#!/bin/bash
# abenv.sh BIN OUT SHOT FRAME ENVVAR: the same still from one binary, twice without ENVVAR=1 (b1, b2) and twice with it
# (a1, a2), alternating; then each pair's difference: max, % of pixels off by more than 2 levels, mean.
set -uo pipefail
bin=$1; out=$2; shot=$3; f=$4; var=$5; mkdir -p "$out"
cd ~/Documents/raea/raea/projects/halcyon-motel
for run in a1 b1 a2 b2; do
case $run in a*) e="$var=1";; *) e="RAEA_AB_NOOP=1";; esac
env "$e" "$bin" render compositions/reel.tsx --composition "shot-$shot" --frame "$f" -o "$out/$run.png" >"$out/$run.log" 2>&1 || echo "$run failed: $(grep -v WARN "$out/$run.log" | tail -1)"
done
"${PY:-python3}" -I - "$out" <<'E'
import sys, numpy as np
from PIL import Image
o = sys.argv[1]
L = lambda n: np.asarray(Image.open(f"{o}/{n}.png").convert("RGB")).astype(int)
for x, y in [("a1", "a2"), ("b1", "b2"), ("a1", "b1"), ("a2", "b2")]:
d = np.abs(L(x) - L(y)).max(2)
print(f"{x}/{y} max {d.max()} px>2 {100 * (d > 2).mean():.4f}% mean {np.abs(L(x) - L(y)).mean():.4f}")
E
+29
View File
@@ -0,0 +1,29 @@
#!/bin/bash
# abseq.sh OUT SHOT BIN_A BIN_B: shot SHOT as a sequence from each binary (one at a time), then each 8th frame's
# difference (% of pixels off by more than 2 levels and by more than 16, mean), A's and B's peak footprint; the frames
# removed after.
set -uo pipefail
out=$1; shot=$2; a=$3; b=$4; mkdir -p "$out"
cd ~/Documents/raea/raea/projects/halcyon-motel
for side in a b; do
bin=$a; [ "$side" = b ] && bin=$b
RAEA_MEM_MARKS=1 "$bin" render compositions/reel.tsx --composition "shot-$shot" -o "$out/$side/" >"$out/$side.log" 2>&1 &
pid=$!; peak=0
while kill -0 "$pid" 2>/dev/null; do
mb=$(footprint -p "$pid" -f bytes 2>/dev/null | awk '/Footprint:/ { for (i = 1; i <= NF; i++) if ($i == "Footprint:") print int($(i + 1) / 1048576) }')
[ -n "$mb" ] && [ "$mb" -gt "$peak" ] && peak=$mb
sleep 2
done
wait "$pid"; echo "$side exit $? peak ${peak} MB $(grep -c '' <(ls "$out/$side" 2>/dev/null)) files"
done
"${PY:-python3}" -I - "$out" <<'E'
import sys, os, numpy as np
from PIL import Image
o = sys.argv[1]
fs = sorted(f for f in os.listdir(f"{o}/a") if f.startswith("frame-") and os.path.exists(f"{o}/b/{f}"))
for f in fs[::8]:
x = np.asarray(Image.open(f"{o}/a/{f}").convert("RGB")).astype(int); y = np.asarray(Image.open(f"{o}/b/{f}").convert("RGB")).astype(int)
d = np.abs(x - y).max(2)
print(f"{f} px>2 {100*(d>2).mean():.3f}% px>16 {100*(d>16).mean():.4f}% mean {np.abs(x-y).mean():.3f}")
E
for side in a b; do d="$out/$side"; mkdir -p "$out/keep-$side"; for f in 00000 00048 00088; do cp "$d/frame-$f.png" "$out/keep-$side/" 2>/dev/null; done; rm -rf "${d:?}"; done
+20
View File
@@ -0,0 +1,20 @@
#!/bin/bash
# heapseq.sh BIN OUTDIR [MARK]: the sequence of halcyon r109 with malloc stack logging (live allocations only); once raea
# prints MARK (default the last warm-up update) and 20 s more, the live heap's call tree is written to OUTDIR/tree.txt
# (malloc_history -callTree), then the render stopped. WAIT=S waits S seconds after MARK (20); tools/memprobe/holders.py OUTDIR/tree.txt ranks the holders.
set -uo pipefail
bin=$1; out=$2; mark=${3:-"engine: warm-up update 7"}; mkdir -p "$out"
cd ~/Documents/raea/raea/projects/halcyon-motel
MallocStackLogging=lite RAEA_MEM_MARKS=1 "$bin" render compositions/reel.tsx --composition shot-r109 -o "$out/seq/" >"$out/render.log" 2>&1 &
pid=$!
until grep -q "$mark" "$out/render.log" 2>/dev/null || ! kill -0 "$pid" 2>/dev/null; do sleep 1; done
sleep "${WAIT:-20}"
if kill -0 "$pid" 2>/dev/null; then
footprint -p "$pid" 2>/dev/null | head -30 >"$out/footprint.txt"
kill -STOP "$pid"
malloc_history "$pid" -callTree >"$out/tree.txt" 2>"$out/tree.err"
echo "tree: $(wc -c <"$out/tree.txt") bytes at $(grep mem_mark "$out/render.log" | tail -1)"
kill -9 "$pid"
else
echo "render ended first: $(grep -v WARN "$out/render.log" | tail -1)"
fi
+20
View File
@@ -0,0 +1,20 @@
#!/bin/bash
# heapwho.sh BIN OUTDIR [MARK]: a still of halcyon r109 with malloc stack logging (live allocations only); once raea
# prints MARK (default the last warm-up update) and 20 s more, the live heap's call tree is written to OUTDIR/tree.txt
# (malloc_history -callTree), then the render stopped.
set -uo pipefail
bin=$1; out=$2; mark=${3:-"engine: warm-up update 7"}; mkdir -p "$out"
cd ~/Documents/raea/raea/projects/halcyon-motel
MallocStackLogging=lite RAEA_MEM_MARKS=1 "$bin" render compositions/reel.tsx --composition shot-r109 --frame 106 -o "$out/still.png" >"$out/render.log" 2>&1 &
pid=$!
until grep -q "$mark" "$out/render.log" 2>/dev/null || ! kill -0 "$pid" 2>/dev/null; do sleep 1; done
sleep 20
if kill -0 "$pid" 2>/dev/null; then
footprint -p "$pid" 2>/dev/null | head -30 >"$out/footprint.txt"
kill -STOP "$pid"
malloc_history "$pid" -callTree >"$out/tree.txt" 2>"$out/tree.err"
echo "tree: $(wc -c <"$out/tree.txt") bytes at $(grep mem_mark "$out/render.log" | tail -1)"
kill -9 "$pid"
else
echo "render ended first: $(grep -v WARN "$out/render.log" | tail -1)"
fi
+38
View File
@@ -0,0 +1,38 @@
import sys, re, collections
# malloc_history -callTree: per line "<indent> COUNT (SIZE) FUNC (in LIB)". For each allocation leaf path we only have
# subtree totals; attribute each subtree to the deepest named raea frame whose own children are all non-raea (alloc libs).
size_re = re.compile(r'^([ +!:|]*)(\d+) \(([\d.]+)([KMGB]?)\) (.*?) \(in ([^)]*)\)')
mult = {'': 1, 'B': 1, 'K': 1e3, 'M': 1e6, 'G': 1e9}
def short(f):
ids = re.findall(r'\d+([A-Za-z_][A-Za-z0-9_]{2,})', f)
ids = [i for i in ids if not re.match(r'^(Cs|Nt|Nv|Ns|Ny|NC|Ms|Ib|IN|B[0-9])', i)]
return '::'.join(ids[-3:]) if ids else f[:80]
nodes = [] # (depth, bytes, func, lib)
for line in open(sys.argv[1], errors='replace'):
m = size_re.match(line)
if not m: continue
nodes.append((len(m.group(1)), float(m.group(3)) * mult[m.group(4)], m.group(5), m.group(6)))
# "self in raea" view: for each raea node, bytes minus bytes of raea children = allocated by it via non-raea callees
by = collections.Counter()
stack = []
for i, (d, b, f, lib) in enumerate(nodes):
while stack and stack[-1][0] >= d: stack.pop()
stack.append((d, b, f, lib))
# second pass: compute children sums of raea nodes
children = collections.defaultdict(float)
st = []
for i, (d, b, f, lib) in enumerate(nodes):
while st and nodes[st[-1]][0] >= d: st.pop()
if lib == 'raea':
# nearest raea ancestor
for j in reversed(st):
if nodes[j][3] == 'raea':
children[j] += b; break
st.append(i)
want = sys.argv[2] if len(sys.argv) > 2 else None
for i, (d, b, f, lib) in enumerate(nodes):
if lib == 'raea':
own = b - children[i]
if own > 0: by[short(f)] += own
for f, b in by.most_common(40):
print(f"{b/1e6:8.0f} MB {f}")
+19
View File
@@ -0,0 +1,19 @@
#!/bin/bash
# memprobe.sh ID FRAME OUTDIR: one still of shot ID with raea's start-up memory marks, and the process's footprint by
# category every 3 s (macOS footprint), the largest snapshot kept whole. RAEA_BIN: the binary (a copy, never target/).
set -uo pipefail
id=$1; frame=$2; out=$3
cd ~/Documents/raea/raea/projects/halcyon-motel
mkdir -p "$out"
RAEA_MEM_MARKS=1 "${RAEA_BIN:-$HOME/raea/target/release/raea}" render compositions/reel.tsx --composition "shot-$id" --frame "$frame" -o "$out/still.png" >"$out/render.log" 2>&1 &
pid=$!
best=0
while kill -0 "$pid" 2>/dev/null; do
f=$(footprint -p "$pid" -f bytes 2>/dev/null)
tot=$(echo "$f" | grep -m1 -oE "Footprint: [0-9]+" | grep -oE "[0-9]+" || echo 0)
echo "$(date +%T) $((tot / 1048576)) MB" >>"$out/timeline.txt"
if [ "${tot:-0}" -gt "$best" ]; then best=$tot; echo "$f" >"$out/peak.txt"; footprint -p "$pid" -v -f bytes >"$out/peak-regions.txt" 2>/dev/null; fi
sleep 3
done
wait "$pid"; echo "exit $? peak $((best / 1048576)) MB"
grep mem_mark "$out/render.log" | head -40
+20
View File
@@ -0,0 +1,20 @@
#!/bin/bash
# memseq.sh ID FRAMES OUTDIR [ENV=VAL ...]: a sequence render of shot ID's first FRAMES frames, its footprint split by
# category every 2 s (MB: total, malloc large, malloc small, graphics), raea's marks each frame; the frames removed.
# RAEA_BIN: the binary (a copy, never target/).
set -uo pipefail
id=$1; n=$2; out=$3; shift 3
cd ~/Documents/raea/raea/projects/halcyon-motel
mkdir -p "$out"; : >"$out/cats.txt"
env RAEA_MEM_MARKS=1 RAEA_MEM_MARKS_EVERY=1 "$@" "${RAEA_BIN:-$HOME/raea/target/release/raea}" render compositions/reel.tsx --composition "shot-$id" $( [ "$n" = all ] || echo --frames "$n" ) -o "$out/frames/" >"$out/render.log" 2>&1 &
pid=$!
t0=$(date +%s)
while kill -0 "$pid" 2>/dev/null; do
footprint -p "$pid" -f bytes 2>/dev/null | awk -v t=$(($(date +%s) - t0)) '
/Footprint:/ { for (i = 1; i <= NF; i++) if ($i == "Footprint:") tot = $(i + 1) }
/Malloc Large$/ { ml = $1 } /Malloc Small$/ { ms = $1 } /\(graphics\)$/ { g += $1 }
END { printf "%4ds total %6d mallocL %6d mallocS %6d gpu %6d\n", t, tot / 1048576, ml / 1048576, ms / 1048576, g / 1048576 }' >>"$out/cats.txt"
sleep 2
done
wait "$pid"; echo "exit $?"
d="$out/frames"; rm -rf "${d:?}"
+11
View File
@@ -0,0 +1,11 @@
#!/bin/bash
# steadyab.sh BIN OUT SHOT FRAME ENVVAR: `raea light steady` on one held frame, with ENVVAR=1 (a) and without (b): each
# side's boiling and its frames, so the last held frame of each can be compared.
set -uo pipefail
bin=$1; out=$2; shot=$3; f=$4; var=$5; mkdir -p "$out"
cd ~/Documents/raea/raea/projects/halcyon-motel
for side in a b; do
case $side in a) e="$var=1";; *) e="RAEA_AB_NOOP=1";; esac
env "$e" "$bin" light steady compositions/reel.tsx --composition "shot-$shot" --frame "$f" --frames 96 -o "$out/$side" >"$out/$side.log" 2>&1
echo "$side ($e) exit $?: $(grep -vE 'WARN|^\s*$' "$out/$side.log" | tail -3 | tr '\n' ' ' | cut -c1-400)"
done