The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.
Rust electron-alternativegame-engineglobal-illuminationgraphicsjavascript-runtimemetalpath-tracingray-tracingreal-time-renderingrenderingrustthreejstypescriptvoxelvulkanwebgpuwgpu
Textures, models, functions and lights come in place; the kernel is made beside the frames (#199)
Yujia0ceebe93ad30
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex 9b0a8c9..80fc51c 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -2776,6 +2776,35 @@ in-place tests' world, rows given back; two models in a shared pose posed again(tests/render/data/arm.glb, a skinned strip of two materials); `geometry/emitter-model-live` (a model's emittingsection that is not its first, the model a unit under software traversal).+**Textures, models, functions and lights come in place; the kernel is made beside the frames (2026-11-24).**+A game that brought a texture, a model, a material function or a light while it ran had the scene built again from+the world, and a feature a scene first used had the next frame wait for the driver's compile. On Bistro (2.8 M+triangles, 960 x 540, an M5 Pro), the frame the edit landed in:++| | before | now |+|---|---|---|+| fog appears (a kernel variant not compiled before) | 0.8 to 2.4 s | no long frame (28 ms at most) |+| a mesh with a new 256 x 256 texture | 4.5 to 4.6 s | 39 to 56 ms |+| a mesh with a new material function | 2.3 to 4.2 s | no long frame (19 ms) |+| a model the scene has not (15 k triangles, five 2048 x 2048 textures) | 4.8 to 5.2 s | 223 to 233 ms, then 85 to 138 ms |+| a point light comes | 1.5 s | no long frame (19 to 26 ms) |+| the light goes | 1.3 s | no long frame (17 to 22 ms) |++The texture pages keep where each texture lies (`texpack::Atlas`) and take another without being packed again,+growing by a copy on the GPU; a still model's materials, textures and mesh are made by the code the build and the+scene meshes' edits use; functions are numbered in the order they come; a light's entry is added, dropped or+sorted within the table as a build lists it. A new kernel variant is made on another thread while the view runs+the one it has (docs/RUNTIME.md "What comes in place" has the rules and what still rebuilds). The model's frame+is its images' decode, on the frame's thread still.+Not freed: a texture or a material nothing uses any more keeps its place until the scene loads again (the+allocator's step).+Tests: each kind of edit against a build of the edited world, state and picture (`textures_come_and_change_in_place`,+`a_model_the_scene_has_not_got_comes_in_place`, `material_functions_come_and_change_in_place`,+`lights_come_and_go_in_place`); a variant made while the frames go on; the atlas's places; the world's rules.+Mutations: 26. 25 failed a test there was; one, a texture put on a shelf too low for it, none, and has its case now.+Found by review: a translucent particle's material given another function kept the kernel's old dispatch for the+translucency pass, which has its particles' functions alone; the kernel is made again where those are others.+**A tangent is a vertex's (2026-11-23).** A triangle had one tangent, its first corner's, and a model whose filehad none had its frame made a triangle at a time where it was hit: a normal map's detail turned at every edge of acurved surface. Now each corner of a file's triangle carries its own through the build, corners that differ indiff --git a/docs/RUNTIME.md b/docs/RUNTIME.mdindex 948b6d6..54a2e6f 100644--- a/docs/RUNTIME.md+++ b/docs/RUNTIME.md@@ -803,7 +803,43 @@ core.write_stream("screen", 640, 360, &rgba)?; // LiveCore, befemission from a function keeps the live view's short history, so the screen shows this frame's picture andnot a blend of the last sixteen.- The script side has no call for it: pictures come from the app (`write_stream`), not through the script- runtime. A script's own `DataTexture` with `needsUpdate` still rebuilds, as before.+ runtime. A script's own `DataTexture` with `needsUpdate` is another texture under its number: written over the+ old one where it is as large, else placed as a new one ("What comes in place", below).++## What comes in place++An edit rewrites what it touches and nothing else; the scene is built again from the world only for what is listed+at the end. `THREERT_EDIT_LOG=1` says where a rebuild was decided, and a frame's log has its reason (`fallback`).++- **Textures.** The pages keep where each texture lies and what they have free (`texpack::Atlas`). A texture a+ material first names is decoded, placed among them (a shelf it fits, a new shelf, a new layer) and written there,+ every level; its two rows go into the texture table (`Gpu::place_texture`, `LiveCore::place_textures`). Pages+ without room become a texture with a layer more or a longer side, and what they held is copied there on the GPU.+ New pixels of the same size go over the old ones, unless another texture has the same slot. A texture no+ material names any more keeps its place until the scene is loaded again.+- **Materials.** A new one, its maps and its function with it; a material given other maps, another function or+ none. (Not one that is a particle's, `transparent`, or has vertex colours: those say where triangles are kept.)+- **Material functions.** The scene keeps its functions by number, and one that comes takes the next+ (`LiveCore::set_functions`). The kernel with them is another module.+- **The kernel's variant.** A feature a scene first uses (fog, glass, a clear coat, a texture, a cutout or a+ function on an instance), and other functions, are another variant of the kernel, which the driver compiles for+ half a second to tens of seconds. The view runs the kernel it has while the scene's is made on another thread+ (`Gpu::warm_kernel`, `LiveCore::choose_kernel`), and takes it at a frame's start once every pipeline a frame+ asks of it is there. Until then what the new variant draws is missing: a material of a function the old kernel+ has not is drawn as one without, fog comes a moment late. In lockstep (benchmarks, tests) and in a browser,+ which has no thread to give, the frame makes its kernel itself and waits.+- **Models.** A still model the scene has not got: its materials are made as the build makes them, its textures+ placed in the pages, its mesh made in the edit's room (`LiveCore::place_models`, `make_mesh`).+- **Lights.** A light that is an entry of the light table alone (not a rect light with a card, not the+ atmosphere's sun) comes, goes and changes its kind or its shadow in place: the table is listed in a build's+ order, sorted, grown where it is full, and the kernel's counts follow.+- **Groups and cameras.** A new group, and a camera that is not the scene's, draw nothing.++Still a rebuild: particle systems, volumes and density grids that come or go, and their functions and programs; a+geometry function; a posed model the scene has not got, and any new model under software traversal (its room does+not grow); a material that becomes a particle's or gets vertex colours; a rect light's card; as many shadow-casting+local lights as bring the light tiles or take them away; the scene's first instance, procedural object, instance+colours or vertex colours (the kernel's data is laid out for them); the atmosphere's sun shown or hidden.## Streaming: reading assets and adding them in place@@ -2133,7 +2169,7 @@ geometry in JS), where the runtime could move to V8 (deno_core) behind the sameare structural today: fine for small scenes or occasional changes, not every frame on a big street.2. **Warm room sessions on nodes.** `serve` keeps runtimes per room already; a node could also keep the GPU scene of aroom between jobs and apply state changes in place, as the live view does.-3. **Kernel variant warm-up.** An edit that enables a kernel feature (e.g. a dry street getting wet) compiles that- variant on first use; pre-compile likely variants in the background.+3. **Images decoded beside the frames.** A texture or a model that comes in place is decoded on the frame's+ thread (five 2048 x 2048 images: 0.2 s); the object could wait for a worker instead, as it waits for its kernel.4. **UE references for the simple scenes** came from the removed IR adapter (cached in out/ue). New ones need eitherthe scenes rebuilt in UE by hand or an engine-API binding on the UE side (the scene code driving UE actors).diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rsindex 51d4c59..d95c02b 100644--- a/renderer/src/gpu.rs+++ b/renderer/src/gpu.rs@@ -16,6 +16,20 @@ struct Pages {info: std::sync::Arc<Vec<[f32; 4]>>,/// Stream textures by name: where their pixels go (`Gpu::write_stream`).streams: Vec<(String, crate::texpack::Place)>,+ /// Where each texture is and what the pages have free (`Gpu::place_texture`).+ atlas: crate::texpack::Atlas,+ /// By slot: the texture's key, its size and whether it wraps (what `texpack::set_key` is made of).+ keys: Vec<(String, u32, u32, bool)>,+}++/// What `Gpu::place_texture` did to the pages.+pub struct PagesEdit {+ /// The texture's slot: its index among the scene's textures, its rows in `tex_info`.+ pub slot: i32,+ /// Every texture's rows as they are now, where a texture was placed.+ pub info: Option<std::sync::Arc<Vec<[f32; 4]>>>,+ /// The pages' view, where they are another texture now (they grew): bind groups hold the old one's.+ pub view: Option<wgpu::TextureView>,}#[cfg(dlss)]@@ -48,18 +62,21 @@ pub struct Gpu {/// Compiled pipelines kept between runs (`GpuOptions::pipeline_cache`), where the backend has such a cache.pipeline_cache: Option<crate::pipeline_cache::PipelineCache>,/// Kernel source (hardware or software traversal spliced in); scenes with material functions get their own module.- source: String,+ source: std::sync::Arc<String>,/// The kernel as written: a scene without features that change the source or functions of its own.module: wgpu::ShaderModule,/// The merged binding layout (merged.rs): a browser's, where a stage has eight storage buffers. Natively with/// THREERT_MERGED=1 (software traversal, the device held to eight too).pub merged: bool,/// By (material-function code hash, the features that change the source: `KernelVariant::flags`).- modules: std::sync::Mutex<std::collections::HashMap<(u64, u32), wgpu::ShaderModule>>,+ modules: ModuleCache,pipeline_layout: wgpu::PipelineLayout,/// Kernel variants by (feature mask, material-function code hash, LIVE): `FEAT` compiles out the features a scene/// does not use (they cost registers even when idle); `LIVE` = one fresh sample per dispatch for the viewport.- pipelines: std::sync::Mutex<std::collections::HashMap<(u32, u64, bool, u32), wgpu::ComputePipeline>>,+ pipelines: PipelineMap<(u32, u64, bool, u32)>,+ /// The kernels being made on another thread (`warm_kernel`): by (features, functions' hash, approximations).+ #[cfg_attr(target_arch = "wasm32", allow(dead_code))]+ warming: std::sync::Arc<std::sync::Mutex<std::collections::HashSet<(u32, u64, u32)>>>,layout: wgpu::BindGroupLayout,/// Group 1, the live viewport's: primary visibility (texture_2d<u32>), the radiance cache (`CacheBuffers`) and/// what the live passes read of a trace (`KernelBufs`). Offline renders bind `no_vis` (1x1 texture `no_vis_view`,@@ -88,9 +105,9 @@ pub struct Gpu {/// are one buffer past Metal's 29 a stage), and `no_vis` made for it.pub tl_vis_layout: Option<wgpu::BindGroupLayout>,no_vis_tl: Option<wgpu::BindGroup>,- tl_pipelines: std::sync::Mutex<std::collections::HashMap<(u32, u64, bool, u32), TranslucentPipelines>>,+ tl_pipelines: PipelineMap<(u32, u64, bool, u32), TranslucentPipelines>,/// The kernel's passes beside `main` (`kernel_pass`) by kernel variant and entry point.- kernel_passes: std::sync::Mutex<std::collections::HashMap<(u32, u64, &'static str, u32), wgpu::ComputePipeline>>,+ kernel_passes: PipelineMap<(u32, u64, &'static str, u32)>,/// The procedural blobs of the last upload (`upload_procs`).proc_cache: std::sync::Mutex<Option<ProcCache>>,/// The last upload's procedural BLASes by geometry hash (read-only once built; another upload may share them), with@@ -1457,6 +1474,109 @@ impl KernelSwitches {}}+type ModuleCache = std::sync::Arc<std::sync::Mutex<std::collections::HashMap<(u64, u32), wgpu::ShaderModule>>>;+type PipelineMap<K, V = wgpu::ComputePipeline> = std::sync::Arc<std::sync::Mutex<std::collections::HashMap<K, V>>>;++/// What a kernel variant's module and pipelines are made from and kept in: a device's, cloned to the thread that+/// makes a variant the frame does not wait for (`Gpu::warm_kernel`). A variant is looked up, made without a lock+/// held (a compile takes long, and the frame looks its own up meanwhile), then kept; made twice at once, the first+/// kept stays.+#[derive(Clone)]+struct KernelMaker {+ device: wgpu::Device,+ source: std::sync::Arc<String>,+ /// The kernel as written (`Gpu::module`).+ module: wgpu::ShaderModule,+ /// The device's part of a variant (its features 0, its guard a kernel's own).+ variant: KernelVariant,+ layout: wgpu::PipelineLayout,+ tl_layout: Option<wgpu::PipelineLayout>,+ modules: ModuleCache,+ pipelines: PipelineMap<(u32, u64, bool, u32)>,+ passes: PipelineMap<(u32, u64, &'static str, u32)>,+ tl: PipelineMap<(u32, u64, bool, u32), TranslucentPipelines>,+}++impl KernelMaker {+ /// The kernel module for a scene: the shared one, or with its material functions spliced in.+ fn module(&self, k: &Kernel) -> wgpu::ShaderModule {+ let patches = k.features & F_SOURCE;+ if patches == 0 && k.functions.is_empty() && k.volume_functions.is_empty() && k.geometry_functions.is_empty() {+ return self.module.clone();+ }+ if let Some(m) = self.modules.lock().unwrap().get(&(k.hash, patches)) {+ return m.clone();+ }+ let splice = |src: &str, marker: &str, code: &str| -> String {+ if code.is_empty() {+ return src.to_string();+ }+ let (head, rest) = src.split_once(&format!("// @{marker}-begin")).unwrap();+ let (_, tail) = rest.split_once(&format!("// @{marker}-end")).unwrap();+ format!("{head}{code}{tail}")+ };+ let src = splice(&splice(&splice(&self.source, "material-functions", &k.functions), "volume-functions", &k.volume_functions), "geometry-functions", &k.geometry_functions);+ // The variant: this device's traversal, switches, layout and loop guard, this scene's features.+ let v = KernelVariant { features: patches, guard: loop_guard_of(patches & F_UNITS != 0), ..self.variant };+ // A scene's functions that do not compile (a game's own WGSL) cost the game its functions, not the+ // app its renderer: the kernel is made without them, and the game's log says why. (A panic here took+ // the engine down, and ThreeRT for Android then took the device for one without a renderer.)+ let wgsl = try_kernel_wgsl(&src, &v).unwrap_or_else(|e| {+ let msg = format!("this scene's material, volume or geometry functions do not compile, so it is drawn without them: {e}");+ #[cfg(not(target_arch = "wasm32"))]+ crate::script::engine_log("error", &msg);+ #[cfg(target_arch = "wasm32")]+ eprintln!("{msg}");+ kernel_wgsl(&self.source, &v)+ });+ let m = unsafe { self.device.create_shader_module_trusted(wgpu::ShaderModuleDescriptor { label: Some("pathtrace+functions"), source: wgpu::ShaderSource::Wgsl(wgsl.into()) }, kernel_checks()) };+ self.modules.lock().unwrap().entry((k.hash, patches)).or_insert(m).clone()+ }++ fn make(&self, k: &Kernel, live: bool, entry: &str, label: &str, layout: Option<&wgpu::PipelineLayout>, cache: Option<&wgpu::PipelineCache>) -> wgpu::ComputePipeline {+ let (module, constants) = (self.module(k), k.constants(live));+ self.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {+ label: Some(label),+ layout,+ module: &module,+ entry_point: Some(entry),+ compilation_options: wgpu::PipelineCompilationOptions { constants: &constants, ..Default::default() },+ cache,+ })+ }++ /// The kernel's `main` for `k` (`live`: the viewport's), and whether it was made now.+ fn pipeline(&self, k: &Kernel, live: bool, cache: Option<&wgpu::PipelineCache>) -> (wgpu::ComputePipeline, bool) {+ let key = (k.features, k.hash, live, k.approx_of(live));+ if let Some(p) = self.pipelines.lock().unwrap().get(&key) {+ return (p.clone(), false);+ }+ let p = self.make(k, live, "main", if live { "pathtrace-live" } else { "pathtrace" }, Some(&self.layout), cache);+ (self.pipelines.lock().unwrap().entry(key).or_insert(p).clone(), true)+ }++ /// A live pass of `k` beside `main`, and whether it was made now.+ fn pass(&self, k: &Kernel, entry: &'static str, cache: Option<&wgpu::PipelineCache>) -> (wgpu::ComputePipeline, bool) {+ let key = (k.features, k.hash, entry, k.approx);+ if let Some(p) = self.passes.lock().unwrap().get(&key) {+ return (p.clone(), false);+ }+ let p = self.make(k, true, entry, entry, Some(&self.layout), cache);+ (self.passes.lock().unwrap().entry(key).or_insert(p).clone(), true)+ }++ /// The translucency pass's pipelines for `k`, and whether they were made now.+ fn translucent(&self, k: &Kernel, live: bool, cache: Option<&wgpu::PipelineCache>) -> (TranslucentPipelines, bool) {+ let key = (k.features, k.hash, live, k.approx_of(live));+ if let Some(p) = self.tl.lock().unwrap().get(&key) {+ return (p.clone(), false);+ }+ let make = |entry: &str| self.make(k, live, entry, entry, self.tl_layout.as_ref(), cache);+ let made = TranslucentPipelines { draw: make("translucent"), train: make("volume_train"), up: make("translucent_up") };+ (self.tl.lock().unwrap().entry(key).or_insert(made).clone(), true)+ }+}+/// The kernel's runtime checks: loop bounding alone, wgpu's default for it (every loop has a count its compiler can/// see the end of). The kernel's loops end on sound data, which does not promise a compiler that they end; without/// the bound, kernels Metal's compiler made lost the state of whole SIMD groups on a scene with cutouts, one build and@@ -1674,31 +1794,33 @@ impl Kernel {if live { self.approx } else { 0 }}- pub fn new(scene: &Scene, groups: [usize; GROUPS]) -> Kernel {+ /// A scene's material functions and their dispatch (pathtrace.wgsl `material_function` and its kin), as they are+ /// spliced into the kernel: `shaders` (name, code, helpers) in the order of their numbers; `translucent`: the+ /// functions of translucent particles' materials.+ fn material_functions(shaders: &[(String, String, String)], translucent: &std::collections::BTreeSet<i32>) -> String {let mut functions = String::new();- if !scene.shaders.is_empty() {+ if !shaders.is_empty() {let mut seen = std::collections::HashSet::new();- for (_, _, helpers) in &scene.shaders {+ for (_, _, helpers) in shaders {if !helpers.is_empty() && seen.insert(helpers.clone()) {functions.push_str(helpers);functions.push('\n');}}- for (_, code, _) in &scene.shaders {+ for (_, code, _) in shaders {functions.push_str(code);functions.push('\n');}functions.push_str("fn material_function(f: i32, i: MatIn, m: Material, base: MatOut) -> MatOut {\n switch f {\n");- for (k, (id, _, _)) in scene.shaders.iter().enumerate() {+ for (k, (id, _, _)) in shaders.iter().enumerate() {functions.push_str(&format!(" case {k} {{ return mf_{id}(i, m, base); }}\n"));}functions.push_str(" default { return base; }\n }\n}\n");// The translucency pass's (translucent.wgsl): only the functions of its particles' materials. With every// function in it, the Metal compiler failed on Tokyo's kernel once the city's ground had one (wetLayer).- let used: std::collections::BTreeSet<i32> = scene.trans_attrs.iter().filter_map(|a| scene.materials.get(a.uv[3].to_bits() as usize)).map(|m| m.tex1[3] - 1).filter(|&f| f >= 0).collect();functions.push_str("fn translucent_material_function(f: i32, i: MatIn, m: Material, base: MatOut) -> MatOut {\n switch f {\n");- for k in used {- if let Some((id, _, _)) = scene.shaders.get(k as usize) {+ for &k in translucent {+ if let Some((id, _, _)) = shaders.get(k as usize) {functions.push_str(&format!(" case {k} {{ return mf_{id}(i, m, base); }}\n"));}}@@ -1709,7 +1831,7 @@ impl Kernel {// ~0.8 ms on Tokyo, dry).for (name, field) in [("alpha_material_function", "opacity"), ("emissive_material_function", "emissive")] {functions.push_str(&format!("fn {name}(f: i32, i: MatIn, m: Material, base: MatOut) -> MatOut {{\n switch f {{\n"));- for (k, (id, code, _)) in scene.shaders.iter().enumerate() {+ for (k, (id, code, _)) in shaders.iter().enumerate() {if writes_field(code, field) {functions.push_str(&format!(" case {k} {{ return mf_{id}(i, m, base); }}\n"));}@@ -1717,6 +1839,25 @@ impl Kernel {functions.push_str(" default { return base; }\n }\n}\n");}}+ functions+ }++ /// This kernel with other material functions (a function added or changed while the scene runs): another module+ /// (`hash`), the volume and geometry functions as they are.+ pub fn with_material_functions(&self, shaders: &[(String, String, String)], translucent: &std::collections::BTreeSet<i32>) -> Kernel {+ use std::hash::{Hash, Hasher};+ let functions = legacy_wgsl(Kernel::material_functions(shaders, translucent));+ let mut h = std::collections::hash_map::DefaultHasher::new();+ functions.hash(&mut h);+ self.volume_functions.hash(&mut h);+ self.geometry_functions.hash(&mut h);+ Kernel { functions, hash: h.finish(), ..self.clone() }+ }++ pub fn new(scene: &Scene, groups: [usize; GROUPS]) -> Kernel {+ // (The translucency pass's functions: those of its particles' materials.)+ let used: std::collections::BTreeSet<i32> = scene.trans_attrs.iter().filter_map(|a| scene.materials.get(a.uv[3].to_bits() as usize)).map(|m| m.tex1[3] - 1).filter(|&f| f >= 0).collect();+ let functions = Kernel::material_functions(&scene.shaders, &used);let mut volume_functions = String::new();if !scene.volume_fns.is_empty() {let mut seen = std::collections::HashSet::new();@@ -2160,7 +2301,7 @@ impl Gpu {dlss_sdk,#[cfg(dlss)]dlss_rr,- instance, adapter, timestamps, device, queue, adapter_info, uniform_tables, whole_tables, switches, approx, approx_default: approx, pipeline_cache, source: src, module, merged, modules: Default::default(), pipeline_layout: pl, pipelines: Default::default(), layout, vis_layout, no_vis, no_vis_bufs, no_vis_view, no_grid_view, grid_layout, fill: Default::default(), hwrt, pages: Default::default(), streams: Default::default(), tl_layout, tl_pipeline_layout, tl_vis_layout, no_vis_tl, tl_pipelines: Default::default(), kernel_passes: Default::default(), proc_cache: Default::default(), proc_blases: Default::default(),+ instance, adapter, timestamps, device, queue, adapter_info, uniform_tables, whole_tables, switches, approx, approx_default: approx, pipeline_cache, source: std::sync::Arc::new(src), module, merged, modules: Default::default(), pipeline_layout: pl, pipelines: Default::default(), warming: Default::default(), layout, vis_layout, no_vis, no_vis_bufs, no_vis_view, no_grid_view, grid_layout, fill: Default::default(), hwrt, pages: Default::default(), streams: Default::default(), tl_layout, tl_pipeline_layout, tl_vis_layout, no_vis_tl, tl_pipelines: Default::default(), kernel_passes: Default::default(), proc_cache: Default::default(), proc_blases: Default::default(),})}@@ -2198,60 +2339,11 @@ impl Gpu {/// The path-tracing kernel specialised for a scene (feature mask + material functions), compiled on first use.pub fn pipeline(&self, k: &Kernel, live: bool) -> wgpu::ComputePipeline {- let mut cache = self.pipelines.lock().unwrap();- cache- .entry((k.features, k.hash, live, k.approx_of(live)))- .or_insert_with(|| {- let module = self.kernel_module(k);- let constants = k.constants(live);- let p = self.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {- label: Some(if live { "pathtrace-live" } else { "pathtrace" }),- layout: Some(&self.pipeline_layout),- module: &module,- entry_point: Some("main"),- compilation_options: wgpu::PipelineCompilationOptions { constants: &constants, ..Default::default() },- cache: self.cache(),- });- self.save_pipeline_cache();- p- })- .clone()- }-- /// The kernel module for a scene: the shared one, or with its material functions spliced in.- fn kernel_module(&self, k: &Kernel) -> wgpu::ShaderModule {- let patches = k.features & F_SOURCE;- if patches == 0 && k.functions.is_empty() && k.volume_functions.is_empty() && k.geometry_functions.is_empty() {- return self.module.clone();+ let (p, made) = self.maker().pipeline(k, live, self.cache());+ if made {+ self.save_pipeline_cache();}- let mut mods = self.modules.lock().unwrap();- mods.entry((k.hash, patches))- .or_insert_with(|| {- let splice = |src: &str, marker: &str, code: &str| -> String {- if code.is_empty() {- return src.to_string();- }- let (head, rest) = src.split_once(&format!("// @{marker}-begin")).unwrap();- let (_, tail) = rest.split_once(&format!("// @{marker}-end")).unwrap();- format!("{head}{code}{tail}")- };- let src = splice(&splice(&splice(&self.source, "material-functions", &k.functions), "volume-functions", &k.volume_functions), "geometry-functions", &k.geometry_functions);- // The variant: this device's traversal, switches, layout and loop guard, this scene's features.- let v = KernelVariant { merged: self.merged, uniform_tables: self.uniform_tables, whole_tables: self.whole_tables, guard: loop_guard_of(patches & F_UNITS != 0), ..KernelVariant::new(self.hwrt, self.switches, patches) };- // A scene's functions that do not compile (a game's own WGSL) cost the game its functions, not the- // app its renderer: the kernel is made without them, and the game's log says why. (A panic here took- // the engine down, and ThreeRT for Android then took the device for one without a renderer.)- let wgsl = try_kernel_wgsl(&src, &v).unwrap_or_else(|e| {- let msg = format!("this scene's material, volume or geometry functions do not compile, so it is drawn without them: {e}");- #[cfg(not(target_arch = "wasm32"))]- crate::script::engine_log("error", &msg);- #[cfg(target_arch = "wasm32")]- eprintln!("{msg}");- kernel_wgsl(&self.source, &v)- });- unsafe { self.device.create_shader_module_trusted(wgpu::ShaderModuleDescriptor { label: Some("pathtrace+functions"), source: wgpu::ShaderSource::Wgsl(wgsl.into()) }, kernel_checks()) }- })- .clone()+ p}/// The entries of the live passes made so far (`kernel_pass`), for tests: which were made, and when.@@ -2263,51 +2355,77 @@ impl Gpu {/// A live pass of a scene's kernel variant beside `main`: `finish` (the pixels a sample's trace left), `media_train`/// (the volume voxels) or `media_composite` (camera rays through media, after the trace).pub fn kernel_pass(&self, k: &Kernel, entry: &'static str) -> wgpu::ComputePipeline {- let mut cache = self.kernel_passes.lock().unwrap();- cache- .entry((k.features, k.hash, entry, k.approx))- .or_insert_with(|| {- let module = self.kernel_module(k);- let constants = k.constants(true);- let p = self.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {- label: Some(entry),- layout: Some(&self.pipeline_layout),- module: &module,- entry_point: Some(entry),- compilation_options: wgpu::PipelineCompilationOptions { constants: &constants, ..Default::default() },- cache: self.cache(),- });- self.save_pipeline_cache();- p- })- .clone()+ let (p, made) = self.maker().pass(k, entry, self.cache());+ if made {+ self.save_pipeline_cache();+ }+ p}/// The translucency pass's pipelines for a scene's kernel variant.pub fn translucent_pipelines(&self, k: &Kernel, live: bool) -> TranslucentPipelines {- let mut cache = self.tl_pipelines.lock().unwrap();- cache- .entry((k.features, k.hash, live, k.approx_of(live)))- .or_insert_with(|| {- let module = self.kernel_module(k);- let constants = k.constants(live);- let make = |entry: &str| {- self.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {- label: Some(entry),- layout: self.tl_pipeline_layout.as_ref(),- module: &module,- entry_point: Some(entry),- compilation_options: wgpu::PipelineCompilationOptions { constants: &constants, ..Default::default() },- cache: self.cache(),- })- };- let made = TranslucentPipelines { draw: make("translucent"), train: make("volume_train"), up: make("translucent_up") };- self.save_pipeline_cache();- made- })- .clone()+ let (p, made) = self.maker().translucent(k, live, self.cache());+ if made {+ self.save_pipeline_cache();+ }+ p+ }++ /// What makes this device's kernel modules and pipelines, for whichever thread makes them.+ fn maker(&self) -> KernelMaker {+ KernelMaker {+ device: self.device.clone(),+ source: self.source.clone(),+ module: self.module.clone(),+ variant: KernelVariant { merged: self.merged, uniform_tables: self.uniform_tables, whole_tables: self.whole_tables, ..KernelVariant::new(self.hwrt, self.switches, 0) },+ layout: self.pipeline_layout.clone(),+ tl_layout: self.tl_pipeline_layout.clone(),+ modules: self.modules.clone(),+ pipelines: self.pipelines.clone(),+ passes: self.kernel_passes.clone(),+ tl: self.tl_pipelines.clone(),+ }}+ /// Whether what a live frame asks of kernel `k` is made: its `main`, the passes named, and the translucency+ /// pass's pipelines if `translucent`.+ pub fn kernel_ready(&self, k: &Kernel, passes: &[&'static str], translucent: bool) -> bool {+ self.pipelines.lock().unwrap().contains_key(&(k.features, k.hash, true, k.approx_of(true)))+ && passes.iter().all(|e| self.kernel_passes.lock().unwrap().contains_key(&(k.features, k.hash, *e, k.approx)))+ && (!translucent || self.tl_pipelines.lock().unwrap().contains_key(&(k.features, k.hash, true, k.approx_of(true))))+ }++ /// Makes what `kernel_ready` asks of `k` on another thread, each pipeline on one of its own (a driver compiles a+ /// kernel variant for half a second to tens of seconds): the frame goes on with the kernel it has and takes this+ /// one when it is ready. Nothing if it is ready, or being made.+ #[cfg(not(target_arch = "wasm32"))]+ pub fn warm_kernel(&self, k: &Kernel, passes: &[&'static str], translucent: bool) {+ if self.kernel_ready(k, passes, translucent) || !self.warming.lock().unwrap().insert((k.features, k.hash, k.approx)) {+ return;+ }+ let (maker, k, passes, warming) = (self.maker(), k.clone(), passes.to_vec(), self.warming.clone());+ let work = move || {+ // (The module first: every pipeline is made of it.)+ let _ = maker.module(&k);+ std::thread::scope(|s| {+ s.spawn(|| maker.pipeline(&k, true, None));+ for entry in &passes {+ s.spawn(|| maker.pass(&k, entry, None));+ }+ if translucent {+ s.spawn(|| maker.translucent(&k, true, None));+ }+ });+ warming.lock().unwrap().remove(&(k.features, k.hash, k.approx));+ };+ std::thread::spawn(work);+ }++ /// (A browser has no thread to give, and its device is one thread's: its frame makes its kernel itself,+ /// live/frame.rs `choose_kernel`.)+ #[cfg(target_arch = "wasm32")]+ pub fn warm_kernel(&self, _: &Kernel, _: &[&'static str], _: bool) {}+/// The translucency pass's bind group (group 2) drawing into `target` (live: the composed image; offline: sums);/// `low`: (colour, transmittance) per traced pixel, where a live view draws below full resolution/// (`translucent_low`; translucent.wgsl `tlow`).@@ -2369,19 +2487,8 @@ impl Gpu {}}let t = Instant::now();- let d = &self.device;let packed = crate::texpack::pack(&scene.textures);- let side = packed.side;- let tex = d.create_texture(&wgpu::TextureDescriptor {- label: Some("texture pages"),- size: wgpu::Extent3d { width: side, height: side, depth_or_array_layers: packed.layers.len() as u32 },- mip_level_count: crate::texpack::MIPS,- sample_count: 1,- dimension: wgpu::TextureDimension::D2,- format: wgpu::TextureFormat::Rgba8Unorm,- usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,- view_formats: &[],- });+ let tex = self.pages_texture(packed.side, packed.layers.len() as u32);for (z, chain) in packed.layers.iter().enumerate() {for (lvl, img) in chain.iter().enumerate() {self.queue.write_texture(@@ -2402,10 +2509,101 @@ impl Gpu {}}timings.push(("texture_pages_ms".into(), t.elapsed().as_secs_f64() * 1000.0));- *cache = Some(Pages { key, texture: tex, view: view.clone(), info: info.clone(), streams: packed.streams });+ let keys = scene.textures.iter().map(|t| (t.key.clone(), t.width, t.height, t.wrap)).collect();+ *cache = Some(Pages { key, texture: tex, view: view.clone(), info: info.clone(), streams: packed.streams, atlas: packed.atlas, keys });(view, info)}+ /// The pages' texture: `layers` square layers of `side`, `texpack::MIPS` levels. (A source of copies too: the+ /// pages grow by a copy on the GPU, `place_texture`.)+ fn pages_texture(&self, side: u32, layers: u32) -> wgpu::Texture {+ self.device.create_texture(&wgpu::TextureDescriptor {+ label: Some("texture pages"),+ size: wgpu::Extent3d { width: side, height: side, depth_or_array_layers: layers },+ mip_level_count: crate::texpack::MIPS,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format: wgpu::TextureFormat::Rgba8Unorm,+ usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::COPY_SRC,+ view_formats: &[],+ })+ }++ /// The slot of texture `t` in the uploaded scene's pages; a texture they have not got is placed in them now+ /// (`texpack::Atlas::place`) and its pixels written there, every level. Nothing is packed again: where the pages+ /// have no room they become a texture with a layer more, or a longer side, and what they hold is copied there+ /// on the GPU. (A texture the scene no longer uses keeps its place until the scene is loaded again.)+ pub fn place_texture(&self, t: &crate::scene::Texture) -> Result<PagesEdit> {+ use crate::texpack::{set_key_of, stream_name, MIPS};+ let mut cache = self.pages.lock().unwrap();+ let pages = cache.as_mut().ok_or_else(|| anyhow!("no scene's pages to place a texture in"))?;+ if let Some(slot) = pages.keys.iter().position(|k| k.0 == t.key) {+ return Ok(PagesEdit { slot: slot as i32, info: None, view: None });+ }+ let rows = crate::merged::UNIFORM_TABLES.iter().find(|u| u.table == crate::heap::Table::TexInfo).map_or(u32::MAX, |u| u.len);+ if self.uniform_tables && (pages.keys.len() as u32 + 1) * 2 > rows {+ return Err(anyhow!("more textures than this device's texture table holds ({})", rows / 2));+ }+ let (side, layers) = (pages.atlas.side, pages.atlas.layers());+ // (On a copy: one that finds no room leaves the pages' record as it was.)+ let mut atlas = pages.atlas.clone();+ let place = atlas.place(t.width, t.height, t.wrap, self.device.limits().max_texture_array_layers).ok_or_else(|| anyhow!("no room in the texture pages"))?;+ pages.atlas = atlas;+ let mut view = None;+ if (pages.atlas.side, pages.atlas.layers()) != (side, layers) {+ let tex = self.pages_texture(pages.atlas.side, pages.atlas.layers());+ let mut e = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("texture pages grow") });+ for level in 0..MIPS {+ let at = |texture| wgpu::TexelCopyTextureInfo { texture, mip_level: level, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All };+ let s = (side >> level).max(1);+ e.copy_texture_to_texture(at(&pages.texture), at(&tex), wgpu::Extent3d { width: s, height: s, depth_or_array_layers: layers });+ }+ self.queue.submit([e.finish()]);+ pages.view = tex.create_view(&wgpu::TextureViewDescriptor { dimension: Some(wgpu::TextureViewDimension::D2Array), ..Default::default() });+ pages.texture = tex;+ view = Some(pages.view.clone());+ }+ // (A stream shows its last picture, as in pages packed whole.)+ let last = stream_name(&t.key).and_then(|n| self.streams.lock().unwrap().get(n).cloned());+ self.write_place(&pages.texture, &place, last.as_deref().unwrap_or(&t.rgba));+ if let Some(n) = stream_name(&t.key) {+ pages.streams.push((n.to_string(), place));+ }+ pages.keys.push((t.key.clone(), t.width, t.height, t.wrap));+ pages.key = set_key_of(pages.keys.iter().map(|k| (k.0.as_str(), k.1, k.2, k.3)));+ pages.info = std::sync::Arc::new(pages.atlas.info());+ Ok(PagesEdit { slot: pages.keys.len() as i32 - 1, info: Some(pages.info.clone()), view })+ }++ /// The slot of the texture of `key` (`scene::Texture::key_of`) in the uploaded scene's pages, if they have it.+ pub fn texture_slot(&self, key: &str) -> Option<i32> {+ self.pages.lock().unwrap().as_ref()?.keys.iter().position(|k| k.0 == key).map(|s| s as i32)+ }++ /// New pixels for the texture in `slot`, written over the old ones in the pages: where their size in the pages+ /// and their wrap are the same. False, and nothing written, where they are not (the texture is then placed as+ /// another: `place_texture`).+ pub fn rewrite_texture(&self, slot: i32, t: &crate::scene::Texture) -> bool {+ let mut cache = self.pages.lock().unwrap();+ let Some(pages) = cache.as_mut() else { return false };+ let Some(place) = pages.atlas.places.get(slot as usize).copied() else { return false };+ if crate::texpack::content_size(t.width, t.height) != place.size || t.wrap != place.wrap || crate::texpack::stream_name(&t.key).is_some() {+ return false;+ }+ self.write_place(&pages.texture, &place, &t.rgba);+ pages.keys[slot as usize] = (t.key.clone(), t.width, t.height, t.wrap);+ pages.key = crate::texpack::set_key_of(pages.keys.iter().map(|k| (k.0.as_str(), k.1, k.2, k.3)));+ true+ }++ /// The pages' textures as they are now, by slot: (key, width, height, wrap), their side and their layers.+ #[cfg(test)]+ pub fn pages_state(&self) -> (Vec<(String, u32, u32, bool)>, u32, u32, Vec<crate::texpack::Place>) {+ let cache = self.pages.lock().unwrap();+ let p = cache.as_ref().expect("pages");+ (p.keys.clone(), p.atlas.side, p.atlas.layers(), p.atlas.places.clone())+ }+fn write_place(&self, pages: &wgpu::Texture, place: &crate::texpack::Place, img: &image::RgbaImage) {for l in crate::texpack::patch(place, img) {self.queue.write_texture(diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rsindex 9b94f90..6d2832c 100644--- a/renderer/src/live/edits.rs+++ b/renderer/src/live/edits.rs@@ -229,6 +229,184 @@ pub(super) enum Placed {Skinned(scene::Instance, Vec<scene::Row>, u32),}+/// What `make_mesh` writes to.+pub(super) struct Meshing<'a, 'b> {+ g: &'a gpu::Gpu,+ edit: &'a mut EditState,+ grow: &'a Grow<'a>,+ vertices: &'a mut wgpu::Buffer,+ words: &'a mut Heap<Stream>,+ /// Software traversal's nodes (a unit's tree is written there).+ nodes: &'a wgpu::Buffer,+ top: &'a mut gpu::Top<'b>,+ meshes: &'a mut Vec<scene::InstMesh>,+ sections: &'a mut Vec<scene::Section>,+ pool_tris: &'a mut Vec<[glam::Vec3A; 3]>,+ pool_place: &'a mut Vec<[u32; 2]>,+ split: &'a mut EditSplit,+ w_vert: &'a mut Gather,+ w_index: &'a mut Gather,+ w_leaf: &'a mut Gather,+ w_colors: &'a mut Gather,+ vcolors: bool,+}++/// A mesh an edit makes, as `prepare` lays one of the pool out: its triangles by section (`data`: a scene's geometry's,+/// `scene::section_mesh`, or a model's), its vertices each once, its acceleration structure or, under software+/// traversal, its tree. In the room: a hole that fits, else its end, grown where it lacks. `same`: the mesh it+/// takes the place of where that is (as many triangles a section; `colored`: an object of it reads its colours).+/// Returns the mesh.+pub(super) fn make_mesh(cx: &mut Meshing, data: scene::MeshData, colored: bool, same: Option<u32>) -> std::result::Result<u32, String> {+ let t0 = Instant::now();+ let scene::MeshData { tris: mut t, attrs: mut a, colors: mut c, sections: sects, .. } = data;+ // Software traversal: the mesh's tree, and its triangles (their attributes, further down their+ // colours) in the tree's order, as `prepare` lays a unit's mesh out.+ let tree = match &*cx.top {+ gpu::Top::Hw(_) => None,+ gpu::Top::Sw(_) => {+ let tree = crate::units::mesh_tree(&t)?;+ t = tree.order.iter().map(|&i| t[i as usize]).collect();+ a = tree.order.iter().map(|&i| a[i as usize]).collect();+ c = c.map(|c| tree.order.iter().map(|&i| c[i as usize]).collect());+ scene::rank_in_sections(&mut a);+ Some(tree)+ }+ };+ // As `prepare` lays the pool out: the mesh's vertices, each once (indexed.rs), its triangles'+ // indices from its first vertex, and for a tree its leaves: each triangle with its section+ // and its index in it.+ let scope = crate::indexed::shared(&t, &a);+ let nv = scope.vertices.len();+ let leaves: Vec<crate::indexed::Leaf> = if tree.is_some() { t.iter().zip(&a).map(|(t, x)| crate::indexed::leaf(*t, [x.uv[3].to_bits(), x.x[3].to_bits()])).collect() } else { vec![] };+ cx.split.tris += t0.elapsed().as_secs_f64() * 1e3;+ // The same sections as the mesh it replaces (as many triangles in each: a BLAS's geometries keep+ // their sizes): rewritten where it is, its BLAS rebuilt (no room used; a geometry that moves+ // every frame, three.js's dynamic draw usage). Otherwise new triangles in the room and a new+ // BLAS.+ if sects.len() > scene::MESH_SECTIONS {+ return Err("a mesh with more than 65,536 sections".into());+ }+ let (k, first, im) = match same {+ Some(k) => {+ // (Its colours stay its own while another object of it reads them.)+ cx.meshes[k as usize].colored |= colored;+ // Its vertices where they were, if the run holds them; else another run, and its+ // BLAS made again for as many (the objects that draw it are all placed again by+ // this edit: their records and TLAS instances take what it has now).+ let old = cx.meshes[k as usize];+ if nv > old.vcount as usize {+ let vfirst = take_verts(cx.edit, cx.grow, cx.vertices, nv, cx.top.sw())?;+ cx.edit.verts.give(old.vfirst as usize, old.vcount as usize);+ (cx.meshes[k as usize].vfirst, cx.meshes[k as usize].vcount) = (vfirst as u32, nv as u32);+ if let gpu::Top::Hw(accel) = &mut *cx.top {+ cx.g.set_mesh(accel, k, cx.edit.pool_first + old.first as usize, &cx.meshes[k as usize], cx.sections);+ }+ }+ let im = cx.meshes[k as usize];+ cx.split.deformed += 1;+ // (Its tree again: the records of the objects that draw it, all placed again by+ // this edit, take the root it has now.)+ if let (gpu::Top::Sw(units), Some(tree)) = (&mut *cx.top, &tree) {+ if let Some(old) = units.drop_tree(k) {+ cx.g.fill_tree(cx.nodes, old);+ }+ let root = units.add_tree(k, tree).ok_or("edit room: tree nodes")?;+ cx.g.write_tree(cx.nodes, root, tree);+ }+ (k, cx.edit.pool_first + im.first as usize, im)+ }+ None => {+ // A hole that fits, else the room's end (grown if it lacks room).+ let first = match cx.edit.tris.take(t.len()) {+ Some(f) => f,+ // (Software traversal's room does not grow: the rebuild makes a larger one.)+ None if !cx.top.sw() && cx.grow.tris(&mut cx.edit.tris, t.len(), cx.words, cx.vcolors) => {+ cx.edit.grows += 1;+ cx.edit.rebind = true;+ cx.edit.tris.take(t.len()).ok_or("edit room: triangles")?+ }+ None => return Err(if matches!(*cx.top, gpu::Top::Sw(_)) { "edit room: triangles (software traversal's does not grow)" } else { "edit room: triangles (particles, or the device's limits)" }.into()),+ };+ let vfirst = take_verts(cx.edit, cx.grow, cx.vertices, nv, cx.top.sw())?;+ let t1 = Instant::now();+ // A freed mesh's slot (and its sections', where they are as many at least), else new ones.+ let dead = cx.edit.dead_meshes.pop();+ let n = sects.len();+ let sect_first = match dead.map(|k| cx.meshes[k as usize]).filter(|m| m.sect_count as usize >= n) {+ Some(m) => m.sect_first,+ None => {+ cx.sections.resize(cx.sections.len() + n, scene::Section { first: 0, count: 0, slot: 0 });+ (cx.sections.len() - n) as u32+ }+ };+ cx.sections[sect_first as usize..][..n].copy_from_slice(§s);+ let im = scene::InstMesh { sect_first, sect_count: n as u32, colored, vfirst: vfirst as u32, vcount: nv as u32, ..scene::own_inst_mesh(&t, (first - cx.edit.pool_first) as u32) };+ let k = match &mut *cx.top {+ gpu::Top::Hw(accel) => match dead {+ Some(k) => {+ cx.g.set_mesh(accel, k, first, &im, cx.sections);+ k+ }+ None => cx.g.add_mesh(accel, first, &im, cx.sections),+ },+ // Its tree into the mesh trees' room (a freed mesh's slot gives its tree back first).+ gpu::Top::Sw(units) => {+ let k = dead.unwrap_or(cx.meshes.len() as u32);+ let tree = tree.as_ref().expect("software traversal made the tree");+ if let Some(old) = units.drop_tree(k) {+ cx.g.fill_tree(cx.nodes, old);+ }+ let Some(root) = units.add_tree(k, tree) else {+ cx.edit.dead_meshes.extend(dead);+ cx.edit.tris.give(first, t.len());+ return Err("edit room: tree nodes".into());+ };+ cx.g.write_tree(cx.nodes, root, tree);+ k+ }+ };+ if k as usize == cx.meshes.len() {+ cx.meshes.push(im);+ } else {+ cx.meshes[k as usize] = im;+ }+ cx.edit.managed.insert(k);+ cx.split.blas += t1.elapsed().as_secs_f64() * 1e3;+ cx.split.added += 1;+ (k, first, im)+ }+ };+ let t2 = Instant::now();+ cx.w_vert.put((im.vfirst as usize * crate::indexed::VERTEX_BYTES) as u64, bytemuck::cast_slice(&scope.vertices));+ cx.w_index.put((first * 12) as u64, bytemuck::cast_slice(&scope.indices));+ // (A unit's tree's leaves; a BLAS is built from the vertices.)+ if cx.top.sw() {+ cx.w_leaf.put((first * crate::indexed::LEAF_BYTES) as u64, bytemuck::cast_slice(&leaves));+ }+ if cx.vcolors {+ // White where it has none: the room's slots may hold an earlier mesh's.+ let c = c.filter(|_| im.colored).unwrap_or_else(|| vec![scene::WHITE; t.len()]);+ cx.w_colors.put((first * 12) as u64, bytemuck::cast_slice(&c));+ }+ cx.split.upload += t2.elapsed().as_secs_f64() * 1e3;+ let rel = first - cx.edit.pool_first;+ if cx.pool_tris.len() < rel + t.len() {+ cx.pool_tris.resize(rel + t.len(), [glam::Vec3A::ZERO; 3]);+ }+ cx.pool_tris[rel..rel + t.len()].copy_from_slice(&t);+ // (Software traversal: where its tree left each triangle of its sections, `mesh_places`.)+ if cx.top.sw() {+ if cx.pool_place.len() < rel + t.len() {+ cx.pool_place.resize(rel + t.len(), [0; 2]);+ }+ for (j, x) in a.iter().enumerate() {+ cx.pool_place[rel + j] = [x.uv[3].to_bits(), x.x[3].to_bits()];+ }+ }+ let _ = im;+ Ok(k)+}+/// What `place_instance` writes to.pub(super) struct Placing<'a, 'b> {edit: &'a mut EditState,@@ -355,6 +533,8 @@ pub(super) fn drop_mesh_user(k: u32, edit: &mut EditState, tables: &mut tables::edit.tris.give(edit.pool_first + im.first as usize, im.count as usize);edit.verts.give(im.vfirst as usize, im.vcount as usize);tables.retained.own_mesh.retain(|_, v| *v != k);+ tables.retained.model_mesh.retain(|_, v| *v != k);+ tables.retained.mesh_rows.remove(&k);edit.dead_meshes.push(k);}}@@ -593,15 +773,43 @@ impl LiveCore {}}}- // New materials without textures: entries after the scene's, before the edits that place objects drawn with- // them (and the GPU's table with them, grown if it is full).+ // Material functions that came or changed: the scene's kernel with them, before the materials of them.+ if changes.functions && !changes.structural {+ self.set_functions(world);+ }+ // The textures the new and the changed materials name: those the pages have not got are placed in them now;+ // a texture that was replaced has its materials made again.+ if !changes.structural && (!changes.new_materials.is_empty() || !changes.materials.is_empty() || !changes.textures.is_empty()) {+ if let Err(why) = self.place_textures(world, &mut changes) {+ self.fallback = Some(format!("a texture that cannot be placed in the pages ({why:#})"));+ self.fallbacks += 1;+ changes.structural = true;+ }+ }+ // The materials of the models the commit adds that the scene has not got, their textures with them.+ if !changes.structural && !changes.added.is_empty() {+ match self.place_models(world, &changes) {+ Ok(true) => {+ self.upload_materials();+ self.sc.up.kernel.features = self.kernel_features();+ }+ Ok(false) => {}+ Err(why) => {+ self.fallback = Some(format!("a model whose materials cannot be made in place ({why:#})"));+ self.fallbacks += 1;+ changes.structural = true;+ }+ }+ }+ // New materials: entries after the scene's, before the edits that place objects drawn with them (and the GPU's+ // table with them, grown if it is full).if !changes.new_materials.is_empty() && !changes.structural {if self.sc.tables.add_materials(world, &changes.new_materials) {self.upload_materials();// (A clear coat, an unlit material: the kernel variant with it, compiled once.)self.sc.up.kernel.features = self.kernel_features();} else {- self.fallback = Some("a new material that cannot be added in place (it emits, is glass or a cutout)".into());+ self.fallback = Some("a new material that cannot be added in place".into());self.fallbacks += 1;if std::env::var("THREERT_EDIT_LOG").is_ok_and(|v| v == "1") && !changes.structural { eprintln!("edit: structural at edits.rs:582"); }changes.structural = true;@@ -822,6 +1030,18 @@ impl LiveCore {}applied = None;}+ // Lights that came or went past what the kernel sums exactly: the light tiles come or go with their buffers,+ // a rebuild's to make.+ if applied.is_some_and(|d| d.lights) {+ let lists = gpu::light_tiles_on() && self.sc.tables.lights.iter().filter(|l| l.pos[3] != 0.0 && l.ext[3] >= 0.5).count() > gpu::RIS_EXACT;+ if lists != (self.sc.instance_features & gpu::F_LISTS != 0) {+ self.fallback = Some("as many shadow-casting local lights as bring the light tiles, or take them away".into());+ self.fallbacks += 1;+ applied = None;+ }+ }+ // (Features the edits asked for: the scene's from now on. A rebuild finds them itself.)+ let more = self.more_features.take();let Some(d) = applied else {let t = Instant::now();self.pending_emitters.clear();@@ -835,11 +1055,34 @@ impl LiveCore {if d.materials {self.upload_materials();}+ if d.materials || changes.functions {+ self.remake_functions(changes.functions);+ }+ if more != 0 {+ self.sc.instance_features |= more;+ self.sc.up.kernel.features = self.kernel_features();+ }+ if d.lights {+ if d.lights_moved {+ self.sc.tables.regroup_lights();+ }+ // (More lights than the table has room for: it grows.)+ let l = &self.sc.tables.lights;+ let need = [(Table::Lights, std::mem::size_of_val(&l[..]) as u64), (Table::LightGroups, crate::light_groups(l).len() as u64 * 16)];+ if need.iter().any(|&(t, n)| n > self.sc.up.heap.cap(t)) {+ let cap = &self.sc.up.heap;+ let want = need.map(|(t, n)| (t, if n > cap.cap(t) { n * 2 } else { cap.cap(t) }));+ self.sc.up.heap.grow_all(&self.g.device, &self.g.queue, &want);+ self.g.rebind_scene(&mut self.sc.up);+ }+ // The kernel's counts of them: all, the directional ones, where the shadowed ones start.+ let l = &self.sc.tables.lights;+ self.sc.base.counts[0] = l.len() as u32;+ self.sc.base.counts2[0] = l.iter().filter(|l| l.pos[3] == 0.0).count() as u32;+ self.sc.base.counts2[3] = l.iter().position(|l| crate::light_class(l) == 2).unwrap_or(l.len()) as u32;+ }let (q, up, e) = (&self.g.queue, &self.sc.up, &mut self.sc.tables);if d.lights && !e.lights.is_empty() {- if d.lights_moved {- e.regroup_lights();- }up.put_lights(q, &e.lights);}if d.objects {@@ -1226,6 +1469,140 @@ impl LiveCore {/// The material table to the GPU: written in place; with more materials than its section holds (materials added/// while the game runs), the section is made twice the size first and the scene's bind groups made again.+ /// The world's material functions as they are now (`World::set_shader`), each under the number it has, one the+ /// scene had not under the next: so the kernel the view runs meanwhile draws every material it knows as before,+ /// and a material of a function it has not as one without (its dispatch's default). Before the commit's+ /// materials are made (they name functions by number); the kernel with them is made after (`remake_functions`).+ fn set_functions(&mut self, world: &World) {+ let sc = &mut self.sc;+ for (name, (code, helpers)) in &world.shaders {+ let f = (name.clone(), code.clone(), helpers.clone());+ match sc.tables.retained.shaders.get(name) {+ Some(&k) => sc.shaders[k as usize] = f,+ None => {+ sc.tables.retained.shaders.insert(name.clone(), sc.shaders.len() as i32);+ sc.shaders.push(f);+ }+ }+ }+ sc.fixed_features.1 = !sc.shaders.is_empty();+ self.sc.up.kernel.features = self.kernel_features();+ }++ /// The scene's kernel with its material functions as they are now, after the commit's materials are made: where+ /// a function came or changed (`changed`), or where the functions of translucent particles' materials are+ /// others than the kernel was made with (the translucency pass's dispatch has those alone: a particle's material+ /// given another function needs another kernel). Another module, made as any variant is (`choose_kernel`).+ fn remake_functions(&mut self, changed: bool) {+ let sc = &mut self.sc;+ let used: std::collections::BTreeSet<i32> = sc.translucent_mats.iter().filter_map(|&m| sc.tables.materials.get(m as usize)).map(|m| m.tex1[3] - 1).filter(|&f| f >= 0).collect();+ if changed || used != sc.translucent_used {+ sc.up.kernel = sc.up.kernel.with_material_functions(&sc.shaders, &used);+ sc.translucent_used = used;+ }+ }++ /// Places in the texture pages what the commit's materials need of them (`Gpu::place_texture`), before the+ /// materials are made:+ /// - A texture a new or a changed material names and the pages have not got: decoded and placed, its rows in+ /// the texture table, its slot remembered (`Retained::textures`).+ /// - A texture that was replaced: its new pixels over the old where they fit their place and the slot is no+ /// other texture's, else its slots are forgotten and it is placed as another; the materials that name it are+ /// made again either way (its repeat and offset are theirs).+ fn place_textures(&mut self, world: &World, changes: &mut crate::world::Changes) -> Result<()> {+ for tid in std::mem::take(&mut changes.textures) {+ let Some(t) = world.textures.get(&tid) else { continue };+ let slots: Vec<(bool, i32)> = self.sc.tables.retained.textures.iter().filter(|(k, _)| k.0 == tid).map(|(k, s)| (k.1, *s)).collect();+ for (srgb_default, slot) in slots {+ let shared = self.sc.tables.retained.textures.iter().any(|(k, s)| *s == slot && k.0 != tid);+ if shared || !self.g.rewrite_texture(slot, &scene::Texture::of_world(t, srgb_default, &self.assets)?) {+ self.sc.tables.retained.textures.remove(&(tid, srgb_default));+ }+ }+ let known = &self.sc.tables.retained.materials;+ changes.materials.extend(world.materials.iter().filter(|(id, m)| known.contains_key(id) && crate::world::material_texture_ids(m).any(|x| x == tid)).map(|(id, _)| *id));+ }+ let (mut info, mut view) = (None, None);+ let ids: Vec<u32> = changes.new_materials.iter().chain(&changes.materials).copied().collect();+ for id in ids {+ let Some(m) = world.materials.get(&id) else { continue };+ for (tid, srgb_default) in scene::material_textures(id, m, &world.textures, &self.sc.tables.retained.shaders)? {+ if self.sc.tables.retained.textures.contains_key(&(tid, srgb_default)) {+ continue;+ }+ let t = world.textures.get(&tid).ok_or_else(|| anyhow::anyhow!("material {id}: unknown texture {tid}"))?;+ let e = self.g.place_texture(&scene::Texture::of_world(t, srgb_default, &self.assets)?)?;+ self.sc.tables.retained.textures.insert((tid, srgb_default), e.slot);+ view = e.view.or(view);+ info = e.info.or(info);+ }+ }+ self.apply_pages(info, view);+ Ok(())+ }++ /// The pages after textures were placed in them (`Gpu::place_texture`): every texture's rows (`info`, if one was+ /// placed) in the texture table, the kernel's variant that samples textures, and the bind groups again where the+ /// pages (`view`) or the table are another resource now.+ fn apply_pages(&mut self, info: Option<std::sync::Arc<Vec<[f32; 4]>>>, view: Option<wgpu::TextureView>) {+ let mut rebind = false;+ if let Some(view) = view {+ self.sc.up.bg_parts.tex_view = view;+ rebind = true;+ }+ if let Some(info) = info {+ let bytes: &[u8] = bytemuck::cast_slice(&info[..]);+ if bytes.len() as u64 > self.sc.up.heap.cap(Table::TexInfo) {+ self.sc.up.heap.grow(&self.g.device, &self.g.queue, Table::TexInfo, bytes.len() as u64 * 2);+ rebind = true;+ }+ self.sc.up.heap.write(&self.g.queue, Table::TexInfo, 0, bytes);+ // (The scene's first texture: the kernel variant that samples them.)+ self.sc.fixed_features.0 = true;+ self.sc.up.kernel.features = self.kernel_features();+ }+ if rebind {+ self.g.rebind_scene(&mut self.sc.up);+ }+ }++ /// The materials of the models the commit adds that the scene has not got (a file's own, by file and index:+ /// `Retained::asset_materials`): made as the build makes them, entries after the scene's, their textures placed+ /// in the pages. A model with material functions is the rebuild's. Whether any was made.+ fn place_models(&mut self, world: &World, changes: &crate::world::Changes) -> Result<bool> {+ let (mut info, mut view, mut made) = (None, None, false);+ for id in &changes.added {+ let Some(crate::world::Kind::Model { uri, nodes, functions, .. }) = world.objects.get(id).map(|o| &o.kind) else { continue };+ if !functions.is_empty() {+ continue;+ }+ let glb = scene::model_gltf(uri, &self.assets)?;+ let (doc, _, images) = &glb.gltf;+ for idx in glb.used_materials(nodes.as_deref()) {+ let key = (uri.clone(), idx.unwrap_or(usize::MAX));+ if self.sc.tables.retained.asset_materials.contains_key(&key) {+ continue;+ }+ let g = &self.g;+ let mut texture = |(k, srgb): (String, bool), wrap: bool, img: &mut dyn FnMut() -> Result<std::sync::Arc<image::RgbaImage>>| -> Result<i32> {+ if let Some(slot) = g.texture_slot(&scene::Texture::key_of(&k, srgb, wrap)) {+ return Ok(slot);+ }+ let e = g.place_texture(&scene::Texture::of(&k, srgb, wrap, img()?))?;+ view = e.view.or(view.take());+ info = e.info.or(info.take());+ Ok(e.slot)+ };+ let gm = scene::gltf_material(idx.and_then(|i| doc.materials().nth(i)), images, uri, &mut texture, &Default::default())?;+ self.sc.tables.retained.asset_materials.insert(key, self.sc.tables.materials.len() as u32);+ self.sc.tables.materials.push(gm);+ made = true;+ }+ }+ self.apply_pages(info, view);+ Ok(made)+ }+pub(super) fn upload_materials(&mut self) {let bytes: &[u8] = bytemuck::cast_slice(&self.sc.tables.materials);if bytes.len() as u64 > self.sc.up.heap.cap(Table::Materials) {@@ -1268,6 +1645,7 @@ impl LiveCore {/// class needs (the scene's first cutout, its first caster with glass among its sections, its first function/// on an instance); the caller rebuilds.fn remake_classes(&mut self, world: &World, build: &mut gpu::TopBuild) -> std::result::Result<(), String> {+ let more = &self.more_features;let mats: std::collections::HashSet<u32> = self.sc.tables.reclassed.iter().copied().collect();let (features, q) = (self.sc.up.kernel.features, &self.g.queue);let LoadedScene { up, tables, meshes, instances, gpu_instances, rows, .. } = &mut self.sc;@@ -1293,15 +1671,15 @@ impl LiveCore {let mat = scene::row_material(row);row[0] = scene::row_of(mat, &tables.materials)[0];if tables.materials.get(mat as usize).is_some_and(|m| m.tex1[3] != 0) && features & gpu::F_IFUNC == 0 {- return Err("the scene's first material function on an instance (kernel feature)".into());+ more.set(more.get() | gpu::F_IFUNC);}}let (bits, cast) = (scene::rows_bits(mine), scene::rows_cast(mine, casts));if bits & scene::INST_CUTOUT != 0 && features & gpu::F_MASKED == 0 {- return Err("the scene's first cutout (kernel feature)".into());+ more.set(more.get() | gpu::F_MASKED);}if bits & scene::INST_GLASS != 0 && cast && features & gpu::F_IGLASS == 0 {- return Err("the scene's first shadow caster with glass among its sections (kernel feature)".into());+ more.set(more.get() | gpu::F_IGLASS);}let Some(top) = top.as_mut() else { return Err("software traversal".into()) };// (Its rows' bits; whether its mesh deforms is its own.)@@ -1629,6 +2007,7 @@ impl LiveCore {if std::env::var("THREERT_EDIT_REBUILD").is_ok_and(|v| v == "1") {return Err("THREERT_EDIT_REBUILD=1".into());}+ let more = &self.more_features;let size = std::mem::size_of::<scene::GpuInstance>();let now = shader_time(self.time);let empty = crate::world::InstanceTable::default();@@ -1662,10 +2041,10 @@ impl LiveCore {if let Some(mat) = mat.filter(|&mat| sc.instances.get(first).is_some_and(|i| scene::row_material(&sc.rows[i.rows as usize]) != mat)) {let (gm, features) = (sc.tables.materials[mat as usize], sc.up.kernel.features);if gm.tex1[3] != 0 && features & gpu::F_IFUNC == 0 {- return Err("the scene's first material function on an instance (kernel feature)".into());+ more.set(more.get() | gpu::F_IFUNC);}if scene::mesh_class(&gm) == 1 && features & gpu::F_MASKED == 0 {- return Err("the scene's first cutout (kernel feature)".into());+ more.set(more.get() | gpu::F_MASKED);}let emits = scene::emissive(&gm);let mut w_rows = Gather::default();@@ -2256,6 +2635,7 @@ impl LiveCore {if std::env::var("THREERT_EDIT_REBUILD").is_ok_and(|v| v == "1") {return Err("THREERT_EDIT_REBUILD=1".into());}+ let more = &self.more_features;let LoadedScene { up, tables, edit, meshes, pool_tris, pool_place, instances, gpu_instances, sections, rows, procs, proc_first, moving_instances, skins, .. } = &mut self.sc;let (g, assets) = (&self.g, &self.assets);let features = up.kernel.features;@@ -2508,8 +2888,9 @@ impl LiveCore {}Kind::Model { uri, nodes, animation, functions } => {// A model already in the scene: another instance of its mesh, of each of its parts' meshes if it is- // a posed rigid one, or of a mesh of its own if it is a posed skinned one (one not in the scene- // brings materials and textures, which load with a rebuild).+ // a posed rigid one, or of a mesh of its own if it is a posed skinned one. A still one the scene+ // has not got: its mesh is made here, its materials and textures were before (`place_models`); a+ // posed one the scene has not got is the rebuild's.if !functions.is_empty() {return Err("a model with material functions (its materials load with a rebuild)".into());}@@ -2542,7 +2923,7 @@ impl LiveCore {}let mine = tables.retained.mesh_rows.get(&its_mesh).ok_or("a model's mesh without its rows")?.clone();if glass_caster(&mine) {- return Err("the scene's first shadow caster with glass among its sections (kernel feature)".into());+ more.set(more.get() | gpu::F_IGLASS);}let posed = glb.triangles(glam::Mat4::IDENTITY, nodes.as_deref(), Some(a)).map_err(|e| e.to_string())?;let n = order.len();@@ -2673,7 +3054,7 @@ impl LiveCore {}let mine = tables.retained.mesh_rows.get(&mesh).ok_or("a model's mesh without its rows")?.clone();if glass_caster(&mine) {- return Err("the scene's first shadow caster with glass among its sections (kernel feature)".into());+ more.set(more.get() | gpu::F_IGLASS);}// (A part without size, a node its clip scales to nothing: at a point, as the build has it.)let (w_n, _) = scene::placed_world(scene::RigidModel::part_world(m, node, &globals), m.w_axis.truncate());@@ -2688,7 +3069,46 @@ impl LiveCore {let entry = scene::object_row(m.transform_point3(glam::Vec3::ZERO), o.power, (hi - lo).max(glam::Vec3A::ZERO), o.custom, [1.0; 3]);(None, Placed::Parts(placed), entry)} else {- let mesh = *tables.retained.model_mesh.get(&(uri.clone(), nodes.clone())).ok_or("a model not in the scene (its materials and textures load with a rebuild)")?;+ let mesh = match tables.retained.model_mesh.get(&(uri.clone(), nodes.clone())).copied() {+ Some(k) => k,+ None => {+ // A model the scene has not got: its mesh made here as the build makes it, model-space+ // triangles by section, a material of the file (made before: `place_models`).+ let t0 = Instant::now();+ let local = glb.triangles(glam::Mat4::IDENTITY, nodes.as_deref(), None).map_err(|e| e.to_string())?;+ let mut classed: [Vec<(usize, u32)>; 4] = Default::default();+ let mut emitting: std::collections::HashSet<u32> = Default::default();+ for (k, t) in local.iter().enumerate() {+ let mat = *tables.retained.asset_materials.get(&(uri.clone(), t.material.unwrap_or(usize::MAX))).ok_or("a model's material that was not made")?;+ let gm = &tables.materials[mat as usize];+ classed[scene::mesh_class(gm) as usize].push((k, mat));+ if scene::emissive(gm) {+ emitting.insert(mat);+ }+ }+ scene::flatten_coincident(&mut classed, &emitting, &|k| local[k].p);+ if !classed[scene::FLAT].is_empty() {+ return Err("a model with triangles the build flattens at each placement".into());+ }+ if !classed[1].is_empty() && features & gpu::F_MASKED == 0 {+ more.set(more.get() | gpu::F_MASKED);+ }+ let (order, sects, mine) = scene::model_sections(&scene::kept(&classed));+ if order.is_empty() {+ return Err("a model without triangles".into());+ }+ let tris: Vec<[glam::Vec3A; 3]> = order.iter().map(|&(k, _, _)| local[k].p.map(glam::Vec3A::from)).collect();+ let attrs = order.iter().map(|&(k, section, rank)| scene::section_attr(local[k].n, local[k].uv, local[k].tangent, section, rank)).collect();+ let data = scene::MeshData { mesh: scene::own_inst_mesh(&tris, 0), tris, attrs, colors: None, sections: sects };+ split.tris += t0.elapsed().as_secs_f64() * 1e3;+ let mut cx = Meshing { g, edit: &mut *edit, grow: &grow, vertices: &mut up.vertices, words: &mut up.words, nodes: &up.bg_parts.nodes, top: &mut top, meshes: &mut *meshes, sections: &mut *sections, pool_tris: &mut *pool_tris, pool_place: &mut *pool_place, split: &mut split, w_vert: &mut w_vert, w_index: &mut w_index, w_leaf: &mut w_leaf, w_colors: &mut w_colors, vcolors };+ let k = make_mesh(&mut cx, data, false, None)?;+ new_meshes.push(k);+ tables.retained.mesh_rows.insert(k, mine);+ tables.retained.model_mesh.insert((uri.clone(), nodes.clone()), k);+ k+ }+ };let im = meshes[mesh as usize];if !top.has_mesh(mesh) {return Err("a model whose mesh is no unit (it deforms; software traversal flattens it)".into());@@ -2696,7 +3116,7 @@ impl LiveCore {// (Its rows, the mesh's own, are placed with its record below.)let mine = tables.retained.mesh_rows.get(&mesh).ok_or("a model's mesh without its rows")?.clone();if glass_caster(&mine) {- return Err("the scene's first shadow caster with glass among its sections (kernel feature)".into());+ more.set(more.get() | gpu::F_IGLASS);}*edit.users.entry(mesh).or_default() += 1;if let Some(k) = was {@@ -2733,10 +3153,10 @@ impl LiveCore {for &mat in &mats {let gm = tables.materials[mat as usize];if gm.tex1[3] != 0 && features & gpu::F_IFUNC == 0 {- return Err("the scene's first material function on an instance (kernel feature)".into());+ more.set(more.get() | gpu::F_IFUNC);}if scene::mesh_class(&gm) == 1 && features & gpu::F_MASKED == 0 {- return Err("the scene's first cutout (kernel feature)".into());+ more.set(more.get() | gpu::F_MASKED);}}// An emitting material: a mesh as any other, each instance's emitters in the light list (given@@ -2758,8 +3178,8 @@ impl LiveCore {let t0 = Instant::now();// (With its colours where an object of it reads them: this one, or one that shares the mesh.)let had = tables.retained.own_mesh.get(&key).is_some_and(|&k| meshes[k as usize].colored);- let scene::MeshData { tris: mut t, attrs: mut a, colors: mut c, sections: sects, .. } = scene::section_mesh(geo, grouped, 0, 0, colored || had);- if t.is_empty() {+ let data = scene::section_mesh(geo, grouped, 0, 0, colored || had);+ if data.tris.is_empty() {if let Some((slot, _)) = at {top.clear(slot);}@@ -2769,152 +3189,11 @@ impl LiveCore {}continue;}- // Software traversal: the mesh's tree, and its triangles (their attributes, further down their- // colours) in the tree's order, as `prepare` lays a unit's mesh out.- let tree = match &top {- gpu::Top::Hw(_) => None,- gpu::Top::Sw(_) => {- let tree = crate::units::mesh_tree(&t)?;- t = tree.order.iter().map(|&i| t[i as usize]).collect();- a = tree.order.iter().map(|&i| a[i as usize]).collect();- c = c.map(|c| tree.order.iter().map(|&i| c[i as usize]).collect());- scene::rank_in_sections(&mut a);- Some(tree)- }- };- // As `prepare` lays the pool out: the mesh's vertices, each once (indexed.rs), its triangles'- // indices from its first vertex, and for a tree its leaves: each triangle with its section- // and its index in it.- let scope = crate::indexed::shared(&t, &a);- let nv = scope.vertices.len();- let leaves: Vec<crate::indexed::Leaf> = if tree.is_some() { t.iter().zip(&a).map(|(t, x)| crate::indexed::leaf(*t, [x.uv[3].to_bits(), x.x[3].to_bits()])).collect() } else { vec![] };split.tris += t0.elapsed().as_secs_f64() * 1e3;- // The same sections as the mesh it replaces (as many triangles in each: a BLAS's geometries keep- // their sizes): rewritten where it is, its BLAS rebuilt (no room used; a geometry that moves- // every frame, three.js's dynamic draw usage). Otherwise new triangles in the room and a new- // BLAS.- if sects.len() > scene::MESH_SECTIONS {- return Err("a mesh with more than 65,536 sections".into());- }- let same = tables.retained.own_mesh.get(&key).copied().filter(|&k| meshes[k as usize].sections(sections) == sects.as_slice());- let (k, first, im) = match same {- Some(k) => {- // (Its colours stay its own while another object of it reads them.)- meshes[k as usize].colored |= colored;- // Its vertices where they were, if the run holds them; else another run, and its- // BLAS made again for as many (the objects that draw it are all placed again by- // this edit: their records and TLAS instances take what it has now).- let old = meshes[k as usize];- if nv > old.vcount as usize {- let vfirst = take_verts(edit, &grow, &mut up.vertices, nv, top.sw())?;- edit.verts.give(old.vfirst as usize, old.vcount as usize);- (meshes[k as usize].vfirst, meshes[k as usize].vcount) = (vfirst as u32, nv as u32);- if let gpu::Top::Hw(accel) = &mut top {- g.set_mesh(accel, k, edit.pool_first + old.first as usize, &meshes[k as usize], sections);- }- }- let im = meshes[k as usize];- split.deformed += 1;- // (Its tree again: the records of the objects that draw it, all placed again by- // this edit, take the root it has now.)- if let (gpu::Top::Sw(units), Some(tree)) = (&mut top, &tree) {- if let Some(old) = units.drop_tree(k) {- g.fill_tree(&up.bg_parts.nodes, old);- }- let root = units.add_tree(k, tree).ok_or("edit room: tree nodes")?;- g.write_tree(&up.bg_parts.nodes, root, tree);- }- (k, edit.pool_first + im.first as usize, im)- }- None => {- // A hole that fits, else the room's end (grown if it lacks room).- let first = match edit.tris.take(t.len()) {- Some(f) => f,- // (Software traversal's room does not grow: the rebuild makes a larger one.)- None if !top.sw() && grow.tris(&mut edit.tris, t.len(), &mut up.words, vcolors) => {- edit.grows += 1;- edit.rebind = true;- edit.tris.take(t.len()).ok_or("edit room: triangles")?- }- None => return Err(if matches!(top, gpu::Top::Sw(_)) { "edit room: triangles (software traversal's does not grow)" } else { "edit room: triangles (particles, or the device's limits)" }.into()),- };- let vfirst = take_verts(edit, &grow, &mut up.vertices, nv, top.sw())?;- let t1 = Instant::now();- // A freed mesh's slot (and its sections', where they are as many at least), else new ones.- let dead = edit.dead_meshes.pop();- let n = sects.len();- let sect_first = match dead.map(|k| meshes[k as usize]).filter(|m| m.sect_count as usize >= n) {- Some(m) => m.sect_first,- None => {- sections.resize(sections.len() + n, scene::Section { first: 0, count: 0, slot: 0 });- (sections.len() - n) as u32- }- };- sections[sect_first as usize..][..n].copy_from_slice(§s);- let im = scene::InstMesh { sect_first, sect_count: n as u32, colored, vfirst: vfirst as u32, vcount: nv as u32, ..scene::own_inst_mesh(&t, (first - edit.pool_first) as u32) };- let k = match &mut top {- gpu::Top::Hw(accel) => match dead {- Some(k) => {- g.set_mesh(accel, k, first, &im, sections);- k- }- None => g.add_mesh(accel, first, &im, sections),- },- // Its tree into the mesh trees' room (a freed mesh's slot gives its tree back first).- gpu::Top::Sw(units) => {- let k = dead.unwrap_or(meshes.len() as u32);- let tree = tree.as_ref().expect("software traversal made the tree");- if let Some(old) = units.drop_tree(k) {- g.fill_tree(&up.bg_parts.nodes, old);- }- let Some(root) = units.add_tree(k, tree) else {- edit.dead_meshes.extend(dead);- edit.tris.give(first, t.len());- return Err("edit room: tree nodes".into());- };- g.write_tree(&up.bg_parts.nodes, root, tree);- k- }- };- if k as usize == meshes.len() {- meshes.push(im);- } else {- meshes[k as usize] = im;- }- edit.managed.insert(k);- split.blas += t1.elapsed().as_secs_f64() * 1e3;- split.added += 1;- (k, first, im)- }- };- let t2 = Instant::now();- w_vert.put((im.vfirst as usize * crate::indexed::VERTEX_BYTES) as u64, bytemuck::cast_slice(&scope.vertices));- w_index.put((first * 12) as u64, bytemuck::cast_slice(&scope.indices));- // (A unit's tree's leaves; a BLAS is built from the vertices.)- if top.sw() {- w_leaf.put((first * crate::indexed::LEAF_BYTES) as u64, bytemuck::cast_slice(&leaves));- }- if vcolors {- // White where it has none: the room's slots may hold an earlier mesh's.- let c = c.filter(|_| im.colored).unwrap_or_else(|| vec![scene::WHITE; t.len()]);- w_colors.put((first * 12) as u64, bytemuck::cast_slice(&c));- }- split.upload += t2.elapsed().as_secs_f64() * 1e3;- let rel = first - edit.pool_first;- if pool_tris.len() < rel + t.len() {- pool_tris.resize(rel + t.len(), [glam::Vec3A::ZERO; 3]);- }- pool_tris[rel..rel + t.len()].copy_from_slice(&t);- // (Software traversal: where its tree left each triangle of its sections, `mesh_places`.)- if top.sw() {- if pool_place.len() < rel + t.len() {- pool_place.resize(rel + t.len(), [0; 2]);- }- for (j, x) in a.iter().enumerate() {- pool_place[rel + j] = [x.uv[3].to_bits(), x.x[3].to_bits()];- }- }- let _ = im;+ // The same sections as the mesh it replaces: that mesh, rewritten where it is.+ let same = tables.retained.own_mesh.get(&key).copied().filter(|&k| meshes[k as usize].sections(sections) == data.sections.as_slice());+ let mut cx = Meshing { g, edit: &mut *edit, grow: &grow, vertices: &mut up.vertices, words: &mut up.words, nodes: &up.bg_parts.nodes, top: &mut top, meshes: &mut *meshes, sections: &mut *sections, pool_tris: &mut *pool_tris, pool_place: &mut *pool_place, split: &mut split, w_vert: &mut w_vert, w_index: &mut w_index, w_leaf: &mut w_leaf, w_colors: &mut w_colors, vcolors };+ let k = make_mesh(&mut cx, data, colored, same)?;new_meshes.push(k);fresh.insert(key.clone(), k);tables.retained.own_mesh.insert(key, k);@@ -3011,7 +3290,7 @@ impl LiveCore {let mine = scene::section_rows(im.sections(sections), &mats, &tables.materials);// (Shadow rays pass the glass among a caster's other sections under a kernel feature.)if scene::rows_bits(&mine) & scene::INST_GLASS != 0 && scene::rows_cast(&mine, o.cast_shadow) && features & gpu::F_IGLASS == 0 {- return Err("the scene's first shadow caster with glass among its sections (kernel feature)".into());+ more.set(more.get() | gpu::F_IGLASS);}let inst = scene::Instance { mesh, world: m, object: object as u32, cast_shadow: scene::rows_cast(&mine, o.cast_shadow), name: o.name.clone(), sub: None, hidden: unseen, masked: unseen, first_emitter: 0, rows: 0, bits: scene::rows_bits(&mine), prev: 0, verts: 0 };let (lo, hi) = im.placed_bounds(m);diff --git a/renderer/src/live/frame.rs b/renderer/src/live/frame.rsindex 01f7b66..e7ab913 100644--- a/renderer/src/live/frame.rs+++ b/renderer/src/live/frame.rs@@ -202,6 +202,35 @@ pub(super) struct Profile {}impl LiveCore {+ /// The kernel this frame runs. The scene's (`up.kernel`: an edit that brings a feature or a function changes it)+ /// where what a frame asks of it is made; else the one the view has, while the scene's is made on another thread+ /// (`Gpu::warm_kernel`): the frame does not wait for a compile, and what the new kernel draws (fog, a clear+ /// coat, a function) comes when it is ready. A view's first kernel is its load's. In lockstep a frame is its+ /// world's alone, and a browser has no other thread: there the frame makes its kernel itself.+ fn choose_kernel(&mut self, guides: bool) {+ let wanted = &self.sc.up.kernel;+ let key = |k: &gpu::Kernel| (k.features, k.hash, k.approx);+ if self.kernel.as_ref().is_some_and(|k| key(k) == key(wanted)) {+ return;+ }+ // (What a frame asks: as the load makes them, and the guides and the translucency pass where it has them.)+ let mut passes: Vec<&'static str> = vec![];+ if !self.g.merged {+ passes.push("finish");+ }+ if guides {+ passes.push("surface_guides");+ }+ if wanted.features & gpu::F_MEDIA != 0 {+ passes.extend(["media_train", "media_composite"]);+ }+ let translucent = self.sc.up.translucent.is_some();+ if self.kernel.is_none() || self.fixed_dt.is_some() || cfg!(target_arch = "wasm32") || self.g.kernel_ready(wanted, &passes, translucent) {+ self.kernel = Some(wanted.clone());+ } else {+ self.g.warm_kernel(wanted, &passes, translucent);+ }+ }/// Profile slots after the cache resolve that this scene writes: particle pass + BLAS rebuild (2; stateless or GPU/// particles), translucency + volume training (2 more).pub(super) fn profile_extra(&self) -> u32 {@@ -351,16 +380,18 @@ impl LiveCore {}}self.inst_moved = false;+ self.choose_kernel(reconstruction.guides());let g = &self.g;+ let kernel = self.kernel.as_ref().unwrap_or(&self.sc.up.kernel);let t_submit = Instant::now();- let pipeline = g.pipeline(&self.sc.up.kernel, true);- let guides = reconstruction.guides().then(|| g.kernel_pass(&self.sc.up.kernel, "surface_guides"));+ let pipeline = g.pipeline(kernel, true);+ let guides = reconstruction.guides().then(|| g.kernel_pass(kernel, "surface_guides"));// (No media pass while every medium is hidden: a pool of idle fireballs costs the frame nothing.)- let media = self.sc.up.kernel.features & gpu::F_MEDIA != 0 && self.sc.up.media_hidden.borrow().iter().any(|h| !h);- let media_train = (media && self.cache.is_some()).then(|| g.kernel_pass(&self.sc.up.kernel, "media_train"));- let media_composite = media.then(|| g.kernel_pass(&self.sc.up.kernel, "media_composite"));+ let media = kernel.features & gpu::F_MEDIA != 0 && self.sc.up.media_hidden.borrow().iter().any(|h| !h);+ let media_train = (media && self.cache.is_some()).then(|| g.kernel_pass(kernel, "media_train"));+ let media_composite = media.then(|| g.kernel_pass(kernel, "media_composite"));// The pixels a sample's trace leaves at the radiance cache (pathtrace.wgsl `finish`).- let finish = self.targets.kernel.deferred.as_ref().filter(|_| self.cache.is_some()).map(|d| (g.kernel_pass(&self.sc.up.kernel, "finish"), d));+ let finish = self.targets.kernel.deferred.as_ref().filter(|_| self.cache.is_some()).map(|d| (g.kernel_pass(kernel, "finish"), d));// This frame's sub-pixel jitter (Halton 2, 3), every camera ray's and the raster visibility pass's: 8 phases at// full resolution, as many more as an output pixel has fewer traced ones (8 / scale^2: the upscaler needs each// output pixel visited), in the 12 bits a side the samples carry it in.@@ -374,7 +405,7 @@ impl LiveCore {// The light tiles (pathtrace.wgsl "Light tiles"), in a scene whose local lights are resampled (gpu::F_LISTS):// the lists the last frame built, for this frame's paths (none after a reset: its reports were another// view's), and this frame's grid offset, a pixel of 8 x 8.- let tiles_on = self.sc.up.kernel.features & gpu::F_LISTS != 0;+ let tiles_on = kernel.features & gpu::F_LISTS != 0;if self.reset || !tiles_on {self.light_tiles = None;}@@ -564,7 +595,7 @@ impl LiveCore {// translucency after the upscaler the same way), then their volume voxels trained.// (Nothing to draw while every translucent particle system is hidden in place.)let tl = self.sc.up.translucent.as_ref().filter(|_| g.translucent_particles_live(&self.sc.up)).map(|t| {- let pipes = g.translucent_pipelines(&self.sc.up.kernel, true);+ let pipes = g.translucent_pipelines(kernel, true);let target = if lp.misc2[2] > 0.0 || lp.dof[0] > 0.0 { &self.targets.buf("sb").buffer } else { &self.targets.buf("fa").buffer };// Below full resolution the particles are drawn per traced pixel, then laid over the output (`translucent_up`).let low = (iw, ih) != (w, h);diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rsindex e2b72d1..a319c7f 100644--- a/renderer/src/live/inplace_tests.rs+++ b/renderer/src/live/inplace_tests.rs@@ -807,10 +807,11 @@ fn edits_in_place_leave_what_a_build_does() {assert!(!live.commit(&mut w).unwrap() && live.cam == away && live.view.dof.is_some(), "a depth of field and an exposure: the view stays");w.set_camera_desc(6, camera(40.0, Some(3.0), manual(2.0))).unwrap();assert!(!live.commit(&mut w).unwrap() && live.cam == live.view.camera && live.cam != away, "a lens: the view takes the scene's camera");- // A commit that rebuilds (another group: what a build places) and brings another preset with it.- w.set_object(13, "more".into(), None, Kind::Group, true, false).unwrap();+ // A commit that rebuilds (a rect light with a card: its triangles are a build's to place) and brings another+ // preset with it.+ w.set_object(13, "card".into(), None, Kind::Light(serde_json::from_value(serde_json::json!({ "type": "rect", "color": [1, 1, 1], "castShadow": true, "intensity": 50, "width": 0.2, "height": 0.2, "visible": true })).unwrap()), true, false).unwrap();w.set_settings(Settings { preset: "cinematic".into(), overrides: Some(serde_json::json!({ "post": { "vignette": 0.3 } })), ..w.settings.clone() });- assert!(live.commit(&mut w).unwrap(), "another group: a rebuild");+ assert!(live.commit(&mut w).unwrap(), "a rect light's card: a rebuild");let mut fresh = open(&w).unwrap();(picture(&mut live, 1), picture(&mut fresh, 1));same_state("a rebuild with another preset", &live, &fresh);@@ -2290,9 +2291,10 @@ fn a_model_of_several_materials_placed_in_place_has_its_rows() {}/// A model with glass among its sections, in a scene where no instance of it casts a shadow: the kernel was built-/// without what has a shadow ray pass such glass, so the first instance that casts is placed by a rebuild.+/// without what has a shadow ray pass such glass. The first instance that casts is placed in place and asks for it+/// (`F_IGLASS`): the picture is a build's.#[test]-fn the_first_caster_with_glass_among_its_sections_is_a_rebuilds() {+fn the_first_caster_with_glass_among_its_sections_comes_in_place() {let presets = crate::default_presets_dir();let open = |w: &World| gpu::Gpu::new().and_then(|g| LiveCore::new(g, w, Path::new(".."), &presets, 96, 54));let model = || Kind::Model { uri: "tests/render/data/frame-pane.glb".into(), nodes: None, animation: None, functions: vec![] };@@ -2311,7 +2313,7 @@ fn the_first_caster_with_glass_among_its_sections_is_a_rebuilds() {// (Upright before the wall, its pane 1 m wide: the pane's shadow is the sun's light through it.)w.set_object(31, "caster".into(), None, model(), true, false).unwrap();w.set_transform(31, Vec3::new(0.5, 0.0, 0.5), glam::Quat::from_rotation_x(std::f32::consts::FRAC_PI_2), Vec3::splat(2.0)).unwrap();- live.commit(&mut w).unwrap();+ assert!(!live.commit(&mut w).unwrap(), "in place ({:?})", live.fallback);let mut fresh = open(&w).unwrap();forget(&mut live);let (a, b) = (picture(&mut live, 64), picture(&mut fresh, 64));@@ -2328,7 +2330,7 @@ fn the_first_caster_with_glass_among_its_sections_is_a_rebuilds() {w.set_geometry(30, Geometry { positions: vec![-1.0, -0.5, 0.0, 0.0, -0.5, 0.0, 1.0, -0.5, 0.0, -1.0, 0.5, 0.0, 0.0, 0.5, 0.0, 1.0, 0.5, 0.0], normals: [0.0, 0.0, 1.0].repeat(6), uvs: vec![0.0; 12], indices: vec![0, 1, 4, 0, 4, 3, 1, 2, 5, 1, 5, 4], groups: vec![[0, 6, 0], [6, 6, 1]], colors: vec![] }).unwrap();w.set_object(31, "pane".into(), None, Kind::Mesh { geometry: 30, material: 1, own_blas: false, materials: vec![1, 65] }, true, false).unwrap();w.set_transform(31, Vec3::new(0.0, 0.0, 0.5), glam::Quat::IDENTITY, Vec3::ONE).unwrap();- live.commit(&mut w).unwrap();+ assert!(!live.commit(&mut w).unwrap(), "in place ({:?})", live.fallback);let mut fresh = open(&w).unwrap();forget(&mut live);let (a, b) = (picture(&mut live, 64), picture(&mut fresh, 64));@@ -4119,3 +4121,419 @@ fn dynamic_resolution_rises_to_the_range_of_the_method_asked_for() {live.render(1, |_, _| {});assert_eq!(live.reconstruction(), Method::MetalFxDenoised, "{:?}", live.reconstruction_status().skipped);}++/// A world texture of `width` x `height` pixels: a checker of `a` and `b`, `cell` pixels a square.+fn checker(width: u32, height: u32, cell: u32, a: [u8; 3], b: [u8; 3]) -> crate::world::Texture {+ let rgba: Vec<u8> = (0..width * height).flat_map(|k| if (k % width / cell + k / width / cell) % 2 == 0 { [a[0], a[1], a[2], 255] } else { [b[0], b[1], b[2], 255] }).collect();+ crate::world::Texture { source: crate::world::TextureSource::Pixels { width, height, rgba: std::sync::Arc::new(rgba) }, srgb: true, wrap: true, repeat: [1.0, 1.0], offset: [0.0, 0.0] }+}++/// By world material: the keys of the textures its slots name in the pages (base, normal, roughness, metalness,+/// emissive, occlusion), None where it names none. Where in the pages a texture lies, and its number, are a view's own.+fn textures_named(c: &LiveCore) -> std::collections::BTreeMap<u32, Vec<Option<String>>> {+ let keys = c.g.pages_state().0;+ let t = &c.sc.tables;+ t.retained.materials.iter().map(|(id, &mi)| {+ let m = &t.materials[mi as usize];+ (*id, [m.tex0[0], m.tex0[1], m.tex0[2], m.tex0[3], m.tex1[0], m.tex1[1]].iter().map(|&s| (s >= 0).then(|| keys[s as usize].0.clone())).collect())+ }).collect()+}++/// Textures come and change in place, in a scene that had none: a material given a map, a new material with one, a+/// second texture of pixels the pages have (the same slot), one of those two replaced (another slot: the other+/// keeps its pixels), a texture's pixels replaced by as many (over the old ones, in their slot) and by a picture of+/// another size (another slot), a texture wider than the pages (they get a longer side and a layer more, what they+/// held copied there). After each: no rebuild, every material names the textures a build of the edited world+/// names, and the picture is that build's. A texture set again as it is changes nothing.+#[test]+fn textures_come_and_change_in_place() {+ let presets = crate::default_presets_dir();+ let open = |w: &World| gpu::Gpu::new().and_then(|g| LiveCore::new(g, w, Path::new("."), &presets, 96, 54));+ let mat = |color: f32, maps: serde_json::Value| -> crate::desc::Material {+ let mut m = serde_json::json!({ "name": "m", "color": [color, color, color], "opacity": 1, "metalness": 0, "roughness": 1, "emissive": [0, 0, 0], "emissiveIntensity": 0, "doubleSided": true });+ m.as_object_mut().unwrap().extend(maps.as_object().unwrap().clone());+ serde_json::from_value(m).unwrap()+ };+ let mut w = world();+ // (The wall and the panel with UVs over them; the panel a mesh the scene edits, with a material of its own.)+ let quad = |s: f32| Geometry { positions: vec![-s, -s, 0.0, s, -s, 0.0, s, s, 0.0, -s, s, 0.0], normals: [0.0, 0.0, 1.0].repeat(4), uvs: vec![0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0], indices: vec![0, 1, 2, 0, 2, 3], groups: vec![], colors: vec![] };+ w.set_geometry(2, quad(1.0)).unwrap();+ w.set_geometry(3, quad(0.25)).unwrap();+ w.set_material(6, mat(0.9, serde_json::json!({})));+ w.set_object(11, "panel".into(), None, Kind::Mesh { geometry: 3, material: 6, own_blas: true, materials: vec![] }, true, false).unwrap();+ let mut live = match open(&w) {+ Ok(c) => c,+ Err(e) => return eprintln!("skipped: {e}"),+ };+ w.take_changes();+ assert_eq!((live.sc.up.kernel.features & gpu::F_TEX, live.g.pages_state().0.len()), (0, 0), "a scene without a texture");+ let mut last = picture(&mut live, 24);+ let mut check = |what: &str, live: &mut LiveCore, w: &mut World| {+ assert!(!live.commit(w).unwrap(), "{what}: in place ({:?})", live.fallback);+ let mut fresh = open(w).unwrap();+ assert_eq!(textures_named(live), textures_named(&fresh), "{what}: the textures the materials name");+ assert_eq!(live.sc.up.kernel.features, fresh.sc.up.kernel.features, "{what}: the kernel's features");+ forget(live);+ let (a, b) = (picture(live, 48), picture(&mut fresh, 48));+ assert!(apart(&a, &b) < 0.5, "{what}: the picture is {:.2} steps from a build's", apart(&a, &b));+ assert!(apart(&last, &b) > 0.2, "{what}: the picture is {:.2} steps from the one before", apart(&last, &b));+ last = b;+ };+ // The wall's material given a map.+ w.set_texture(30, checker(64, 40, 8, [255, 40, 40], [40, 40, 255])).unwrap();+ w.set_material(1, mat(0.8, serde_json::json!({ "map": 30 })));+ check("a material given a map", &mut live, &mut w);+ assert_ne!(live.sc.up.kernel.features & gpu::F_TEX, 0);+ let slot = |live: &LiveCore, texture: u32| live.sc.tables.retained.textures.get(&(texture, true)).copied();+ let (keys, side, layers, places) = live.g.pages_state();+ assert_eq!((keys.len(), side, layers, slot(&live, 30)), (1, 256, 1, Some(0)), "the first texture: slot 0 of one page");+ // A new material with a map of its own, on the panel.+ w.set_texture(31, checker(100, 60, 10, [30, 220, 30], [240, 240, 30])).unwrap();+ w.set_material(8, mat(0.9, serde_json::json!({ "map": 31 })));+ w.set_object(11, "panel".into(), None, Kind::Mesh { geometry: 3, material: 8, own_blas: true, materials: vec![] }, true, false).unwrap();+ check("a new material with a map", &mut live, &mut w);+ assert_eq!((live.g.pages_state().0.len(), live.g.pages_state().3[0]), (2, places[0]), "a second texture beside the first, which stays where it is");+ // Another texture of the same pixels, on a tile of its own: the slot the pages have for them.+ w.set_texture(33, checker(100, 60, 10, [30, 220, 30], [240, 240, 30])).unwrap();+ w.set_material(9, mat(0.9, serde_json::json!({ "map": 33 })));+ w.set_object(13, "tile".into(), None, Kind::Mesh { geometry: 3, material: 9, own_blas: true, materials: vec![] }, true, false).unwrap();+ w.set_transform(13, Vec3::new(0.45, -0.5, 0.5), glam::Quat::IDENTITY, Vec3::ONE).unwrap();+ check("a texture of pixels the pages have", &mut live, &mut w);+ assert_eq!((live.g.pages_state().0.len(), slot(&live, 31), slot(&live, 33)), (2, Some(1), Some(1)), "one slot for both");+ // The first of the two given other pixels: the slot is the other's too, so it takes another.+ w.set_texture(31, checker(100, 60, 10, [230, 30, 200], [20, 20, 20])).unwrap();+ check("one of two textures in a slot replaced", &mut live, &mut w);+ assert_eq!((live.g.pages_state().0.len(), slot(&live, 31), slot(&live, 33)), (3, Some(2), Some(1)), "another slot; the other texture keeps its own");+ // The same texture again: nothing to do. Its pixels replaced by as many: over the old ones.+ w.set_texture(30, checker(64, 40, 8, [255, 40, 40], [40, 40, 255])).unwrap();+ assert!(!w.changes.any(), "a texture set again as it is changes nothing");+ w.set_texture(30, checker(64, 40, 8, [20, 230, 230], [230, 20, 230])).unwrap();+ check("a texture's pixels replaced", &mut live, &mut w);+ assert_eq!((live.g.pages_state().0.len(), slot(&live, 30)), (3, Some(0)), "written over the old ones, in their slot");+ assert_ne!(live.g.pages_state().0[0].0, keys[0].0, "the slot holds the new pixels' key");+ // A picture of another size: another slot; the material names it.+ w.set_texture(30, checker(128, 128, 16, [250, 250, 250], [10, 10, 10])).unwrap();+ check("a texture replaced by one of another size", &mut live, &mut w);+ assert_eq!((live.g.pages_state().0.len(), slot(&live, 30)), (4, Some(3)));+ let (_, side, layers, before) = live.g.pages_state();+ assert!(side == 256 && layers == 2 && before[3].layer == 1, "the first page was full: the wall's texture lies on a second ({layers} layers of {side})");+ // A texture wider than the pages, on the panel: a longer side and a layer more, what they held copied there+ // (the wall's and the tile's are drawn from the copy).+ w.set_texture(32, checker(2048, 2048, 256, [250, 120, 20], [20, 120, 250])).unwrap();+ w.set_material(8, mat(0.9, serde_json::json!({ "map": 32 })));+ check("a texture wider than the pages", &mut live, &mut w);+ let (keys, side, layers, now) = live.g.pages_state();+ assert_eq!((keys.len(), side, layers, now[4].layer, now[4].size), (5, 2048, 3, 2, (2016, 2016)), "the pages grew by a side and a layer");+ assert_eq!(now[..4], before[..], "the textures there stay where they are");+ // A material that drops its map.+ w.set_material(1, mat(0.8, serde_json::json!({})));+ check("a material without its map", &mut live, &mut w);+}++/// By model file and material of it (`Retained::asset_materials`): the keys of the textures its slots name in the+/// pages, as `textures_named` has a world's materials'.+fn model_textures_named(c: &LiveCore) -> std::collections::BTreeMap<(String, usize), Vec<Option<String>>> {+ let keys = c.g.pages_state().0;+ let t = &c.sc.tables;+ t.retained.asset_materials.iter().map(|(k, &mi)| {+ let m = &t.materials[mi as usize];+ (k.clone(), [m.tex0[0], m.tex0[1], m.tex0[2], m.tex0[3], m.tex1[0], m.tex1[1]].iter().map(|&s| (s >= 0).then(|| keys[s as usize].0.clone())).collect())+ }).collect()+}++/// A still model the scene has not got comes in place (tests/render/data/textured-quads.glb: a quad with a picture+/// and a plain one, two materials of the file): its materials are entries after the scene's, its picture is placed+/// in the pages, its mesh is made in the room; no rebuild, and the view draws what a build of the edited world+/// draws. Another of it is another instance of that mesh. With the last of them gone the mesh is given back, and the+/// model comes again in place, its materials and its picture the ones there were.+#[test]+fn a_model_the_scene_has_not_got_comes_in_place() {+ let presets = crate::default_presets_dir();+ let open_at_root = |w: &World| gpu::Gpu::new().and_then(|g| LiveCore::new(g, w, Path::new(".."), &presets, 96, 54));+ const FILE: &str = "tests/render/data/textured-quads.glb";+ let model = || Kind::Model { uri: FILE.into(), nodes: None, animation: None, functions: vec![] };+ let mut w = world();+ let mut live = match open_at_root(&w) {+ Ok(c) if c.g.hwrt => c,+ Ok(_) => return eprintln!("skipped: no hardware RT"),+ Err(e) => return eprintln!("skipped: {e}"),+ };+ w.take_changes();+ let mut last = picture(&mut live, 24);+ let (materials, meshes) = (live.sc.tables.materials.len(), live.sc.meshes.len());+ assert_eq!((live.sc.up.kernel.features & gpu::F_TEX, live.g.pages_state().0.len()), (0, 0), "a scene without a texture");+ let mut check = |what: &str, live: &mut LiveCore, w: &mut World| {+ assert!(!live.commit(w).unwrap(), "{what}: in place ({:?})", live.fallback);+ let mut fresh = open_at_root(w).unwrap();+ // (A material of a model that has gone stays in the view: it names what a build's names where a build has it.)+ let named = model_textures_named(live);+ for (k, v) in model_textures_named(&fresh) {+ assert_eq!(named.get(&k), Some(&v), "{what}: the textures the model's material {k:?} names");+ }+ forget(live);+ let (a, b) = (picture(live, 48), picture(&mut fresh, 48));+ assert!(apart(&a, &b) < 0.5, "{what}: the picture is {:.2} steps from a build's", apart(&a, &b));+ assert!(apart(&last, &b) > 0.5, "{what}: the picture is {:.2} steps from the one before", apart(&last, &b));+ last = b;+ };+ let place = |w: &mut World, id: u32, at: Vec3| {+ w.set_object(id, format!("quads{id}"), None, model(), true, false).unwrap();+ w.set_transform(id, at, glam::Quat::from_rotation_y(0.3), Vec3::ONE).unwrap();+ };+ place(&mut w, 40, Vec3::new(-0.3, 0.2, 0.7));+ check("a model the scene has not got", &mut live, &mut w);+ let key = (FILE.to_string(), None);+ let mesh = *live.sc.tables.retained.model_mesh.get(&key).expect("the model's mesh");+ assert_eq!((live.sc.tables.materials.len(), live.sc.meshes.len(), live.g.pages_state().0.len()), (materials + 2, meshes + 1, 1), "two materials, a mesh and a picture more");+ assert_ne!(live.sc.up.kernel.features & gpu::F_TEX, 0, "the kernel's variant that samples textures");+ assert_eq!(live.sc.meshes[mesh as usize].sections(&live.sc.sections).len(), 2, "a section a material of the file");+ // Another of it: an instance of that mesh; nothing else is made.+ place(&mut w, 41, Vec3::new(0.3, -0.5, 0.9));+ check("another of the model", &mut live, &mut w);+ assert_eq!((live.sc.tables.materials.len(), live.sc.meshes.len(), live.sc.edit.users.get(&mesh)), (materials + 2, meshes + 1, Some(&2)));+ // Both gone: the mesh is given back.+ w.remove(40);+ w.remove(41);+ check("the models removed", &mut live, &mut w);+ assert!(!live.sc.tables.retained.model_mesh.contains_key(&key) && !live.sc.tables.retained.mesh_rows.contains_key(&mesh), "the mesh is no model's any more");+ // It comes again: its mesh made again (in the slot the other left), its materials and its picture there still.+ place(&mut w, 42, Vec3::new(0.2, 0.1, 0.8));+ check("the model again", &mut live, &mut w);+ assert_eq!((live.sc.tables.materials.len(), live.sc.meshes.len(), live.g.pages_state().0.len()), (materials + 2, meshes + 1, 1), "nothing made twice");+ // Another model the scene has not got, one of whose materials only emits (tests/render/data/panel.glb): its+ // emitters light the scene as a build's (the lamp away: the panel is what lights it).+ w.set_visible(12, false).unwrap();+ w.set_object(43, "panel43".into(), None, Kind::Model { uri: "tests/render/data/panel.glb".into(), nodes: None, animation: None, functions: vec![] }, true, false).unwrap();+ w.set_transform(43, Vec3::new(-0.5, -0.4, 0.6), glam::Quat::from_rotation_y(0.4), Vec3::splat(0.05)).unwrap();+ check("a model that emits", &mut live, &mut w);+ list_is_its_triangles("a model that emits", &live);+}++/// A kernel variant the device has not is made on another thread while the frames go on: the frame after the edit+/// that brings a feature (a material that is glass) runs the kernel the view had, and the view takes the scene's+/// once it is made. In lockstep a frame is its world's alone: it makes its kernel itself.+#[test]+fn a_new_kernel_variant_is_made_while_the_frames_go_on() {+ let presets = crate::default_presets_dir();+ let mat = |extra: serde_json::Value| -> crate::desc::Material {+ let mut m = serde_json::json!({ "name": "m", "color": [0.5, 0.5, 0.5], "opacity": 1, "metalness": 0, "roughness": 0.2, "emissive": [0, 0, 0], "emissiveIntensity": 0, "doubleSided": true });+ m.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());+ serde_json::from_value(m).unwrap()+ };+ let mut w = world();+ let mut live = match gpu::Gpu::new().and_then(|g| LiveCore::new(g, &w, Path::new("."), &presets, 96, 54)) {+ Ok(c) => c,+ Err(e) => return eprintln!("skipped: {e}"),+ };+ w.take_changes();+ live.render(1, |_, _| {});+ let key = |k: &gpu::Kernel| (k.features, k.hash);+ let had = key(live.kernel.as_ref().expect("the view's kernel"));+ assert_eq!((had, had.0 & (gpu::F_GLASS | gpu::F_COAT)), (key(&live.sc.up.kernel), 0), "the scene's kernel, without glass or a clear coat");+ w.set_material(7, mat(serde_json::json!({ "transmission": 1 })));+ assert!(!live.commit(&mut w).unwrap(), "a new material: in place ({:?})", live.fallback);+ let wanted = key(&live.sc.up.kernel);+ assert_ne!(wanted.0 & gpu::F_GLASS, 0, "the scene's kernel has glass now");+ live.render(1, |_, _| {});+ assert_eq!(key(live.kernel.as_ref().unwrap()), had, "the frame after the edit ran the kernel the view had");+ let t = Instant::now();+ while key(live.kernel.as_ref().unwrap()) != wanted {+ assert!(t.elapsed().as_secs() < 120, "the scene's kernel was never taken");+ live.render(1, |_, _| {});+ }+ // In lockstep the next frame runs the scene's kernel, whatever it has to make for it.+ live.fixed_dt = Some(1.0 / 60.0);+ w.set_material(8, mat(serde_json::json!({ "clearcoat": 1 })));+ assert!(!live.commit(&mut w).unwrap(), "another new material: in place ({:?})", live.fallback);+ assert_ne!(live.sc.up.kernel.features & gpu::F_COAT, 0);+ live.render(1, |_, _| {});+ assert_eq!(key(live.kernel.as_ref().unwrap()), key(&live.sc.up.kernel), "in lockstep the frame ran the scene's kernel");+}++/// Material functions come and change in place, in a scene that had none: a function and a new material of it on an+/// instance (the kernel's code, `F_FUNC`, and the placement of a function's inputs by an instance, `F_IFUNC`), the+/// function's code changed, a second function whose name sorts before the first (a build numbers them by name, the+/// view in the order they came), a material that drops its function. After each: no rebuild, the kernel's features+/// are a build's, and the picture is that build's.+#[test]+fn material_functions_come_and_change_in_place() {+ let presets = crate::default_presets_dir();+ let open = |w: &World| gpu::Gpu::new().and_then(|g| LiveCore::new(g, w, Path::new("."), &presets, 96, 54));+ let mat = |function: Option<&str>| -> crate::desc::Material {+ let shader = function.map(|id| serde_json::json!({ "id": id, "params": [], "textures": [] }));+ serde_json::from_value(serde_json::json!({ "name": "m", "color": [0.8, 0.8, 0.8], "opacity": 1, "metalness": 0, "roughness": 1, "emissive": [0, 0, 0], "emissiveIntensity": 0, "doubleSided": true, "shader": shader })).unwrap()+ };+ let function = |name: &str, rgb: &str| format!("fn mf_{name}(i: MatIn, m: Material, base: MatOut) -> MatOut {{\n var o = base;\n o.base = vec3<f32>({rgb});\n return o;\n}}\n");+ let mut w = world();+ w.set_material(6, mat(None));+ w.set_object(11, "panel".into(), None, Kind::Mesh { geometry: 3, material: 6, own_blas: true, materials: vec![] }, true, false).unwrap();+ let mut live = match open(&w) {+ Ok(c) => c,+ Err(e) => return eprintln!("skipped: {e}"),+ };+ w.take_changes();+ assert_eq!(live.sc.up.kernel.features & (gpu::F_FUNC | gpu::F_IFUNC), 0, "a scene without a function");+ let mut last = picture(&mut live, 24);+ let mut check = |what: &str, live: &mut LiveCore, w: &mut World| {+ assert!(!live.commit(w).unwrap(), "{what}: in place ({:?})", live.fallback);+ let mut fresh = open(w).unwrap();+ // (An instance of a function's material: under hardware traversal and with units. A view keeps the feature+ // once it has it.)+ let unkept = !(gpu::F_IFUNC | gpu::F_FUNC);+ assert_eq!(live.sc.up.kernel.features & unkept, fresh.sc.up.kernel.features & unkept, "{what}: the kernel's features");+ assert_eq!(fresh.sc.up.kernel.features & !live.sc.up.kernel.features, 0, "{what}: the view's kernel has what a build's has");+ forget(live);+ let (a, b) = (picture(live, 48), picture(&mut fresh, 48));+ assert!(apart(&a, &b) < 0.5, "{what}: the picture is {:.2} steps from a build's", apart(&a, &b));+ assert!(apart(&last, &b) > 0.5, "{what}: the picture is {:.2} steps from the one before", apart(&last, &b));+ last = b;+ };+ // A function, and a new material of it on the wall.+ w.set_shader("zz_red", function("zz_red", "0.9, 0.05, 0.05"), String::new());+ w.set_material(7, mat(Some("zz_red")));+ w.set_object(10, "wall".into(), None, Kind::Mesh { geometry: 2, material: 7, own_blas: true, materials: vec![] }, true, false).unwrap();+ check("a function and a material of it", &mut live, &mut w);+ assert_ne!(live.sc.up.kernel.features & gpu::F_FUNC, 0, "the kernel has functions");+ let first = live.sc.up.kernel.hash;+ // The same function again: nothing. Other code: another kernel.+ w.set_shader("zz_red", function("zz_red", "0.9, 0.05, 0.05"), String::new());+ assert!(!w.changes.any(), "a function set again as it is changes nothing");+ w.set_shader("zz_red", function("zz_red", "0.05, 0.05, 0.9"), String::new());+ check("the function's code changed", &mut live, &mut w);+ assert_ne!(live.sc.up.kernel.hash, first, "another module");+ // A second function, before the first by name: the panel's material given it.+ w.set_shader("aa_green", function("aa_green", "0.05, 0.9, 0.05"), String::new());+ w.set_material(6, mat(Some("aa_green")));+ check("a second function, on a material the scene had", &mut live, &mut w);+ assert_eq!((live.sc.tables.retained.shaders.get("zz_red"), live.sc.tables.retained.shaders.get("aa_green")), (Some(&0), Some(&1)), "numbered in the order they came");+ // A material that drops its function.+ w.set_material(7, mat(None));+ check("a material without its function", &mut live, &mut w);+}++/// Lights come, change and go in place: a point light with a shadow, a spot light without, the point light without+/// its shadow (another class: the table is sorted again), a rect light without a card, the point light removed, the+/// directional light removed, every light removed; a group that comes and goes draws nothing. After each: no+/// rebuild, the view's state (the light table, the kernel's counts of it) is a build's of the edited world, and so+/// is the picture.+#[test]+fn lights_come_and_go_in_place() {+ let presets = crate::default_presets_dir();+ let open = |w: &World| gpu::Gpu::new().and_then(|g| LiveCore::new(g, w, Path::new("."), &presets, 96, 54));+ let light = |v: serde_json::Value| -> crate::desc::Light { serde_json::from_value(v).unwrap() };+ let point = |shadow: bool| light(serde_json::json!({ "type": "point", "color": [1.0, 0.6, 0.2], "castShadow": shadow, "intensity": 400.0, "radius": 0.02, "range": 0.0 }));+ let mut w = world();+ // (The lamp away: the lights light the scene.)+ w.set_visible(12, false).unwrap();+ let mut live = match open(&w) {+ Ok(c) => c,+ Err(e) => return eprintln!("skipped: {e}"),+ };+ w.take_changes();+ let last = std::cell::RefCell::new(picture(&mut live, 24));+ let check = |what: &str, live: &mut LiveCore, w: &mut World, lights: usize| {+ assert!(!live.commit(w).unwrap(), "{what}: in place ({:?})", live.fallback);+ assert_eq!((live.sc.tables.lights.len(), live.sc.base.counts[0]), (lights, lights as u32), "{what}: the table's lights and the kernel's count of them");+ let mut fresh = open(w).unwrap();+ forget(live);+ let (a, b) = (picture(live, 48), picture(&mut fresh, 48));+ same_state(what, live, &fresh);+ assert!(apart(&a, &b) < 0.5, "{what}: the picture is {:.2} steps from a build's", apart(&a, &b));+ assert!(apart(&last.borrow(), &b) > 0.1, "{what}: the picture is {:.2} steps from the one before", apart(&last.borrow(), &b));+ *last.borrow_mut() = b;+ };+ w.set_object(40, "point".into(), None, Kind::Light(point(true)), true, false).unwrap();+ w.set_transform(40, Vec3::new(-0.5, 0.3, 0.8), glam::Quat::IDENTITY, Vec3::ONE).unwrap();+ check("a point light", &mut live, &mut w, 2);+ w.set_object(41, "spot".into(), None, Kind::Light(light(serde_json::json!({ "type": "spot", "color": [0.2, 0.5, 1.0], "castShadow": false, "intensity": 900.0, "radius": 0.02, "range": 0.0, "angle": 0.5, "penumbra": 0.3 }))), true, false).unwrap();+ w.set_transform(41, Vec3::new(0.5, -0.2, 1.5), glam::Quat::IDENTITY, Vec3::ONE).unwrap();+ check("a spot light without a shadow", &mut live, &mut w, 3);+ w.set_light(40, point(false)).unwrap();+ assert!(!w.changes.structural, "a light of another class: its entry's change");+ check("the point light without its shadow", &mut live, &mut w, 3);+ w.set_object(42, "rect".into(), None, Kind::Light(light(serde_json::json!({ "type": "rect", "color": [1.0, 1.0, 1.0], "castShadow": true, "intensity": 3000.0, "width": 0.4, "height": 0.4, "visible": false }))), true, false).unwrap();+ w.set_transform(42, Vec3::new(0.0, 0.7, 1.2), glam::Quat::from_rotation_x(-0.8), Vec3::ONE).unwrap();+ check("a rect light without a card", &mut live, &mut w, 4);+ // A group that comes and goes: nothing to do.+ w.set_object(50, "group".into(), None, Kind::Group, true, false).unwrap();+ assert!(!w.changes.structural && !live.commit(&mut w).unwrap(), "a new group: nothing rebuilt");+ w.remove(50);+ assert!(!w.changes.structural && !live.commit(&mut w).unwrap(), "the group removed: nothing rebuilt");+ w.remove(40);+ check("the point light removed", &mut live, &mut w, 3);+ w.remove(20);+ check("the directional light removed", &mut live, &mut w, 2);+ w.remove(41);+ w.remove(42);+ check("every light removed", &mut live, &mut w, 0);+ // One again, in a scene without a light.+ w.set_object(43, "point".into(), None, Kind::Light(point(true)), true, false).unwrap();+ w.set_transform(43, Vec3::new(0.3, 0.3, 0.9), glam::Quat::IDENTITY, Vec3::ONE).unwrap();+ check("a light in a scene without one", &mut live, &mut w, 1);+ // As many shadow-casting local lights as the kernel resamples (the light tiles): they come with a rebuild; one+ // more and one fewer among them are in place again.+ for k in 0..gpu::RIS_EXACT as u32 {+ w.set_object(60 + k, format!("p{k}"), None, Kind::Light(point(true)), true, false).unwrap();+ w.set_transform(60 + k, Vec3::new(-0.8 + 0.2 * k as f32, -0.6, 0.7), glam::Quat::IDENTITY, Vec3::ONE).unwrap();+ }+ if gpu::light_tiles_on() {+ assert!(live.commit(&mut w).unwrap() && live.sc.up.kernel.features & gpu::F_LISTS != 0, "the light tiles come with a rebuild ({:?})", live.fallback);+ *last.borrow_mut() = picture(&mut live, 24);+ w.set_object(70, "more".into(), None, Kind::Light(point(true)), true, false).unwrap();+ w.set_transform(70, Vec3::new(0.0, 0.7, 0.8), glam::Quat::IDENTITY, Vec3::ONE).unwrap();+ check("a light among those resampled", &mut live, &mut w, gpu::RIS_EXACT + 2);+ w.remove(62);+ check("one of them removed", &mut live, &mut w, gpu::RIS_EXACT + 1);+ }+}++/// A translucent particle's material given another function, in place: the translucency pass has the functions of+/// its particles' materials alone, so the kernel is made again with the one the material has now. First a function+/// the scene had (an opaque material's: no function's code changes), then one that comes with the edit. After+/// each: no rebuild, and the picture is a build's of the edited world.+#[test]+fn a_translucent_particles_material_takes_another_function_in_place() {+ let presets = crate::default_presets_dir();+ let open = |w: &World| gpu::Gpu::new().and_then(|g| LiveCore::new(g, w, Path::new("."), &presets, 96, 54));+ let glow = |function: &str| -> crate::desc::Material {+ serde_json::from_value(serde_json::json!({ "name": "glow", "color": [0.5, 0.5, 0.5], "opacity": 0.9, "transparent": true, "metalness": 0, "roughness": 1, "emissive": [0, 0, 0], "emissiveIntensity": 0, "doubleSided": true,+ "shader": { "id": function, "params": [], "textures": [] } })).unwrap()+ };+ let function = |name: &str, rgb: &str| format!("fn mf_{name}(i: MatIn, m: Material, base: MatOut) -> MatOut {{\n var o = base;\n o.base = vec3<f32>({rgb});\n o.emissive = vec3<f32>({rgb}) * 40.0;\n return o;\n}}\n");+ let mut w = wall_world(3.0, serde_json::json!({ "name": "m", "color": [0.5, 0.5, 0.5], "opacity": 1, "metalness": 0, "roughness": 1, "emissive": [0, 0, 0], "emissiveIntensity": 0, "doubleSided": true, "shader": { "id": "fb", "params": [], "textures": [] } }));+ let sun = serde_json::from_value(serde_json::json!({ "type": "directional", "color": [1.0, 1.0, 1.0], "castShadow": true, "intensity": 1.0, "angularDiameter": 0.5 })).unwrap();+ w.set_object(20, "sun".into(), None, Kind::Light(sun), true, false).unwrap();+ w.set_shader("fa", function("fa", "0.9, 0.05, 0.05"), String::new());+ w.set_shader("fb", function("fb", "0.05, 0.9, 0.05"), String::new());+ // (A small mesh of the opaque material with `fb`, out of the particle's way: the scene has both functions.)+ w.set_object(11, "tile".into(), None, Kind::Mesh { geometry: 1, material: 3, own_blas: false, materials: vec![] }, true, false).unwrap();+ w.set_transform(11, Vec3::new(-0.8, -0.8, 0.2), glam::Quat::IDENTITY, Vec3::splat(0.1)).unwrap();+ w.set_material(5, glow("fa"));+ w.set_particle_fn("card", "fn pf_card(i: PIn, p: array<vec4<f32>, 8>) -> POut { return POut(vec3<f32>(0.0, 0.0, 0.5), vec3<f32>(0.5, 0.0, 0.0), vec3<f32>(0.0, 0.5, 0.0), true, vec4<f32>(0.0)); }".into(), String::new());+ w.set_object(30, "card".into(), None, Kind::Particles { count: 1, emitter: "card".into(), params: vec![], material: 5, emitter_area: 0.0 }, true, false).unwrap();+ let mut live = match open(&w) {+ Ok(c) if c.g.hwrt => c,+ Ok(_) => return eprintln!("skipped: no hardware RT"),+ Err(e) => return eprintln!("skipped: {e}"),+ };+ w.take_changes();+ assert!(live.sc.up.translucent.is_some(), "the particle is the translucency pass's");+ let mut last = picture(&mut live, 24);+ let mut check = |what: &str, live: &mut LiveCore, w: &mut World| {+ assert!(!live.commit(w).unwrap(), "{what}: in place ({:?})", live.fallback);+ let mut fresh = open(w).unwrap();+ forget(live);+ let (a, b) = (picture(live, 48), picture(&mut fresh, 48));+ assert!(apart(&a, &b) < 0.5, "{what}: the picture is {:.2} steps from a build's", apart(&a, &b));+ assert!(apart(&last, &b) > 0.5, "{what}: the picture is {:.2} steps from the one before", apart(&last, &b));+ last = b;+ };+ let before = live.sc.up.kernel.hash;+ w.set_material(5, glow("fb"));+ assert!(!w.changes.functions && !w.changes.structural, "a material given a function the scene has: the material's change alone");+ check("a function the scene had", &mut live, &mut w);+ assert_ne!(live.sc.up.kernel.hash, before, "another kernel: the translucency pass's functions are others");+ w.set_shader("fc", function("fc", "0.05, 0.05, 0.9"), String::new());+ w.set_material(5, glow("fc"));+ check("a function that comes with the edit", &mut live, &mut w);+}diff --git a/renderer/src/live/load.rs b/renderer/src/live/load.rsindex caefb2a..5758add 100644--- a/renderer/src/live/load.rs+++ b/renderer/src/live/load.rs@@ -55,8 +55,16 @@ pub(super) struct LoadedScene {/// (v0, e1, e2), shading attributes, corners (a triangle that is not finite: at the origin). Their vertices on/// the GPU are made from these (`upload_dynamic`).pub(super) dynamic: (usize, Vec<[f32; 4]>, Vec<scene::GpuTriAttr>, Vec<[f32; 3]>),- /// Kernel feature inputs edits cannot change: textures, material functions, traversal groups.+ /// Kernel feature inputs of the scene as a whole: whether it has textures, whether it has material functions,+ /// its traversal groups (edits cannot change the groups).pub(super) fixed_features: (bool, bool, [usize; crate::GROUPS]),+ /// The scene's material functions (name, code, helpers), each at its number (`Retained::shaders`): the build's+ /// by name, one that came while the scene runs after them (`set_functions`).+ pub(super) shaders: Vec<(String, String, String)>,+ /// The materials of translucent particles' triangles: their functions are the translucency pass's.+ pub(super) translucent_mats: Vec<u32>,+ /// The functions of those materials the scene's kernel was made with (`LiveCore::remake_functions`).+ pub(super) translucent_used: std::collections::BTreeSet<i32>,/// Where in-place geometry edits write next (`edit_geometry`); a rebuild starts it afresh.pub(super) edit: EditState,/// Power edits' emitter rebuilds on a worker (`EmitterWorker`), for scenes with many emitters.@@ -241,6 +249,11 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &Ptables.defer_powers = emit.is_some();let (mat_runs, tri_order) = (std::mem::take(&mut prep.mat_runs), std::mem::take(&mut prep.tri_order));let fixed_features = (!sc.textures.is_empty(), !sc.shaders.is_empty(), prep.groups);+ let shaders = sc.shaders.clone();+ let mut translucent_mats: Vec<u32> = sc.trans_attrs.iter().map(|a| a.uv[3].to_bits()).collect();+ translucent_mats.sort_unstable();+ translucent_mats.dedup();+ let translucent_used = translucent_mats.iter().filter_map(|&m| sc.materials.get(m as usize)).map(|m| m.tex1[3] - 1).filter(|&f| f >= 0).collect();// (The light tree is the tables' by now: its nodes from there.)let up = g.upload(&sc, &targets.accum, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, &prep.gpu_emitter_tris, &prep.emitter_runs, crate::ltree::nodes_of(tables.light_tree.as_ref()), &prep.env, &prep.env_cdf, &prep.energy, &mut timings)?;let _ = g.pipeline(&up.kernel, true); // compile the scene's kernel variant now, not in the first frame@@ -324,5 +337,5 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &Pverts: Holes::new(vertices, vertices + room.tris * 3),free_skinned: vec![],};- Ok((LoadedScene { timings, triangles, tris, tri_nodes, tri_instances, pool_tris, dynamic_verts, skins, skin_trees, pool_place, meshes, instances, sections, rows, gpu_instances, procs, proc_first, moving_instances: tables.retained.moves_instances(), instanced, instance_features, name: sc.name.clone(), up, base, tables, fixed_features, dynamic, edit, emit, mat_runs, tri_order, codes_sent: vec![] }, view, env))+ Ok((LoadedScene { timings, triangles, tris, tri_nodes, tri_instances, pool_tris, dynamic_verts, skins, skin_trees, pool_place, meshes, instances, sections, rows, gpu_instances, procs, proc_first, moving_instances: tables.retained.moves_instances(), instanced, instance_features, name: sc.name.clone(), up, base, tables, fixed_features, shaders, translucent_mats, translucent_used, dynamic, edit, emit, mat_runs, tri_order, codes_sent: vec![] }, view, env))}diff --git a/renderer/src/live/mod.rs b/renderer/src/live/mod.rsindex 5cb5b2e..f4e9b4d 100644--- a/renderer/src/live/mod.rs+++ b/renderer/src/live/mod.rs@@ -310,6 +310,14 @@ pub struct LiveCore {pub view_mode: u32,/// Lockstep frame time (s; benchmarks): motion blur and exposure adaptation use it instead of the wall clock.pub fixed_dt: Option<f32>,+ /// The kernel the frames run (`choose_kernel`): the scene's (`up.kernel`), or the one before it while the scene's+ /// is being made on another thread. None: none chosen yet (a view's first frame, the first after a rebuild).+ pub(super) kernel: Option<gpu::Kernel>,+ /// Kernel features an edit of this commit asks for that the scene's structure had not (`F_MASKED`: its first+ /// cutout on an instance; `F_IGLASS`: its first shadow caster with glass among its sections; `F_IFUNC`: its+ /// first material function on an instance). They switch code on, over data every scene has: the commit adds+ /// them to the scene's (`instance_features`).+ pub(super) more_features: std::cell::Cell<u32>,pub triangles: usize,pub scene_name: String,/// Scene time, s: what `advance_time` added up, the dt each frame script gets, so it is the game's clock (`f.time`)@@ -570,6 +578,8 @@ impl LiveCore {reconstructor};let mut core = LiveCore {+ kernel: None,+ more_features: Default::default(),reconstructor, quality: Quality::Native, frame_generation: FrameGeneration::Off, latency: Latency::Auto, rendering_control: None, pending_emitters: vec![], flipped: vec![], top_builds: 0, particle_spawns: Default::default(), grid_sources: Default::default(), g, passes, targets, sc, view, env, presets: presets.to_path_buf(), assets: assets.to_path_buf(), w, h, seq: 0, aspect: w as f32 / h as f32, cam, prev_cam: cam, frame: 0, history_len: 0.0, reset: true, bloom: ([0.0; 6], [0.0; 6]), vignette: 0.0, post: [0.0; 4], blur: (0.0, 0.0), inflight: Default::default(), gpu_ms: 0.0, gpu_frame: 0, gpu_trace_ms: 0.0, edit_ms: 0.0, instanced_ms: 0.0, build_ms: 0.0, edit_split: EditSplit::default(), rebuild_ms: 0.0, fallback: None, fallbacks: 0, bounces: 4, rays: true, view_mode: std::env::var("THREERT_VIEW_MODE").ok().and_then(|v| v.parse().ok()).unwrap_or(0), fixed_dt: None, triangles, scene_name, time: 0.0, frame_dt: 1.0 / 60.0, last_frame: Instant::now(), post_key: String::new(), render_scale: 1.0, dynamic_res: false, min_scale: MIN_SCALE, display_scale: 1.0, over_budget: (0, 0), born: Instant::now(), governed: Instant::now(), profile, timer, raster, cache, kernel_bg, tl_kernel_bg, prev_span: None, reposed: false, emitters_moved: false, emitters_reweigh: false, pose_spans: vec![], pose_reposed: false, inst_moving: vec![], inst_moved: false, prev_isz: (0, 0), light_tiles: None, lit_changed: 0, spark_lights: false, shown_spp: 1, cpu_skin_ms: 0.0, cpu_upload_ms: 0.0, gpu_blas_ms: 0.0, cpu_wait_ms: 0.0, guard_trips: guard_read.as_ref().map(|_| 0), guard_read };core.spark_lights = core.sc.tables.emitter_tris.iter().any(|e| e.nominal);core.apply_post();@@ -686,6 +696,8 @@ impl LiveCore {// What the grid programs had simulated goes with the grids that are still the same.self.g.carry_grids(&self.sc.up, &s.up);self.sc = s;+ // (Its data is its own kernel's: the load made that one.)+ self.kernel = None;self.spark_lights = self.sc.tables.emitter_tris.iter().any(|e| e.nominal);self.inst_moving.clear();self.prev_span = None;diff --git a/renderer/src/scene.rs b/renderer/src/scene.rsindex 64b0d86..ba9457b 100644--- a/renderer/src/scene.rs+++ b/renderer/src/scene.rs@@ -762,6 +762,9 @@ pub struct Retained {pub textures: HashMap<(u32, bool), i32>,/// Material function name -> index (GpuMaterial.tex1[3] - 1).pub shaders: HashMap<String, i32>,+ /// A model file's material -> `materials` index: by (the file, with its functions if it has any; the material's+ /// index in the file, usize::MAX for the file's default one).+ pub asset_materials: HashMap<(String, usize), u32>,/// Object -> where what it draws landed (`Proxy`): meshes, models, rect-light cards, instanced objects.pub proxies: HashMap<u32, Proxy>,/// Object of each `lights` entry, same order (`prepare` sorts both).@@ -1111,18 +1114,48 @@ struct TexCache {}impl TexCache {- fn add(&mut self, key: (String, bool), wrap: bool, img: impl FnOnce() -> Result<std::sync::Arc<image::RgbaImage>>) -> Result<i32> {+ fn add(&mut self, key: (String, bool), wrap: bool, mut img: impl FnMut() -> Result<std::sync::Arc<image::RgbaImage>>) -> Result<i32> {if let Some(i) = self.by_key.get(&key) {return Ok(*i);}let img = img()?;let id = self.textures.len() as i32;- self.textures.push(Texture { width: img.width(), height: img.height(), rgba: img, srgb: key.1, key: format!("{}|{}|{}", key.0, key.1, wrap), wrap });+ self.textures.push(Texture::of(&key.0, key.1, wrap, img));self.by_key.insert(key, id);Ok(id)}}+impl Texture {+ /// A texture of the pages: an image (its source's identity `key`: `texture_image`), read as sRGB or not, wrapped+ /// or clamped.+ pub fn of(key: &str, srgb: bool, wrap: bool, img: Arc<image::RgbaImage>) -> Texture {+ Texture { width: img.width(), height: img.height(), rgba: img, srgb, key: Texture::key_of(key, srgb, wrap), wrap }+ }++ /// The pages' key of the texture `of` makes.+ pub fn key_of(key: &str, srgb: bool, wrap: bool) -> String {+ format!("{key}|{srgb}|{wrap}")+ }++ /// A world's texture as a material's slot has it (`srgb_default`: whether the slot is a colour's), decoded. As+ /// the build makes it, so the pages know one they have by its key.+ pub fn of_world(t: &world::Texture, srgb_default: bool, assets: &Path) -> Result<Texture> {+ let (key, img) = texture_image(t, assets)?;+ Ok(Texture::of(&key, t.srgb && srgb_default, t.wrap, img))+ }+}++/// The textures a material's GPU form names, as `build_material` asks for them: (texture, sRGB requested).+pub fn material_textures(id: u32, m: &desc::Material, textures: &HashMap<u32, world::Texture>, shaders: &HashMap<String, i32>) -> Result<Vec<(u32, bool)>> {+ let mut out = vec![];+ build_material(id, m, textures, shaders, &mut |tid, srgb| {+ out.push((tid, srgb));+ Ok(0)+ })?;+ Ok(out)+}+/// Identity of a file version: (path, length, mtime). Assets and textures rarely change, so they are parsed //// decoded once per process.pub(crate) fn file_key(path: &Path) -> String {@@ -1502,7 +1535,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&seSome(d) => d.clone(),None => texture_image(t, assets)?,};- let slot = texcache.add((key, srgb), t.wrap, || Ok(img))?;+ let slot = texcache.add((key, srgb), t.wrap, || Ok(img.clone()))?;retained.textures.insert((tid, srgb_default), slot);Ok(slot)};@@ -1737,7 +1770,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&seSome(i) => *i,None => {let name = gm.as_ref().and_then(|g| g.name()).unwrap_or_default().to_string();- let mut gpu = gltf_material(gm, images, uri, &mut texcache, &model_images)?;+ let mut gpu = gltf_material(gm, images, uri, &mut |key, wrap, img| texcache.add(key, wrap, img), &model_images)?;// The first function whose prefix the material's name starts with, on the glTF shading.if let Some(f) = functions.iter().find(|f| name.starts_with(f.prefix.as_str())) {let mut tex = |tid: u32, srgb_default: bool| -> Result<i32> {@@ -1746,7 +1779,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&seSome(d) => d.clone(),None => texture_image(t, assets)?,};- texcache.add((tkey, t.srgb && srgb_default), t.wrap, || Ok(img))+ texcache.add((tkey, t.srgb && srgb_default), t.wrap, || Ok(img.clone()))};apply_shader(&mut gpu, &f.shader, &retained.shaders, &mut tex).with_context(|| format!("{uri}: material {name}"))?;}@@ -2252,6 +2285,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&sefor d in retained.dynamics_mut() {d.flags = tri_flags[d.first as usize..d.first as usize + d.mats.len()].to_vec();}+ retained.asset_materials = asset_materials;Ok(Scene {name: st.name.clone(),emitter_slot: false,@@ -2339,7 +2373,11 @@ pub fn aerial_params(sky: &Sky) -> [f32; 4] {}/// `converted`: the model images already in RGBA, by texture key (scene::build converts them up front, in parallel).-fn gltf_material(gm: Option<gltf::Material>, images: &[gltf::image::Data], key: &str, tc: &mut TexCache, converted: &HashMap<String, Arc<image::RgbaImage>>) -> Result<GpuMaterial> {+/// A model's material as the GPU has it. `texture((key, sRGB), wrap, image)` gives a texture's slot, and decodes the+/// image only where the texture is not there yet: the build's set (`TexCache`), or the pages of a scene that runs+/// (live/edits.rs `place_models`). `converted`: images decoded before.+#[allow(clippy::type_complexity)]+pub fn gltf_material(gm: Option<gltf::Material>, images: &[gltf::image::Data], key: &str, texture: &mut dyn FnMut((String, bool), bool, &mut dyn FnMut() -> Result<Arc<image::RgbaImage>>) -> Result<i32>, converted: &HashMap<String, Arc<image::RgbaImage>>) -> Result<GpuMaterial> {let Some(gm) = gm else {return Ok(GpuMaterial { base_color: [1.0, 1.0, 1.0, 1.0], params: [0.0, 1.0, 0.5, 1.0], tex0: [-1; 4], tex1: [-1, -1, 0, 0], uv: [1.0, 1.0, 0.0, 0.0], ..Default::default() });};@@ -2348,7 +2386,7 @@ fn gltf_material(gm: Option<gltf::Material>, images: &[gltf::image::Data], key:let src = t.source().index();let k = format!("{key}#img{src}");let pre = converted.get(&k).cloned();- tc.add((k, srgb), true, || pre.map_or_else(|| Ok(Arc::new(to_rgba(&images[src])?)), Ok))+ texture((k, srgb), true, &mut || pre.clone().map_or_else(|| Ok(Arc::new(to_rgba(&images[src])?)), Ok))};let pbr = gm.pbr_metallic_roughness();let mr = tex(pbr.metallic_roughness_texture().map(|t| t.texture()), false)?;@@ -2448,7 +2486,7 @@ pub fn dynamic_tris(w: &World, id: u32, d: &DynamicModel, assets: &Path) -> Resu/// (trace_hw.wgsl), and past what lies at the same t: in one BLAS the emitter under the decal went with it (black/// through the decal); and which of two triangles at one distance a closest hit reports is not said. Flattened, the/// two are in BLASes apart and the opaque one is met first, as the software BVH has it.-fn flatten_coincident(classed: &mut [Vec<(usize, u32)>; 4], emitting: &std::collections::HashSet<u32>, p: &dyn Fn(usize) -> [Vec3; 3]) {+pub fn flatten_coincident(classed: &mut [Vec<(usize, u32)>; 4], emitting: &std::collections::HashSet<u32>, p: &dyn Fn(usize) -> [Vec3; 3]) {let key = |k: usize| {let mut v = p(k).map(|p| [p.x.to_bits(), p.y.to_bits(), p.z.to_bits()]);v.sort_unstable();@@ -2624,7 +2662,7 @@ pub fn section_attr(n: [Vec3; 3], uv: [Vec2; 3], tangent: Option<CornerTangents>}/// The triangles of `classed` that stay in a mesh (`FLAT`'s leave it), for `model_sections`.-fn kept(classed: &[Vec<(usize, u32)>; 4]) -> Vec<(usize, u32, u32)> {+pub fn kept(classed: &[Vec<(usize, u32)>; 4]) -> Vec<(usize, u32, u32)> {classed[..FLAT].iter().enumerate().flat_map(|(class, list)| list.iter().map(move |&(k, mat)| (k, mat, class as u32))).collect()}diff --git a/renderer/src/skin.rs b/renderer/src/skin.rsindex 3a19c86..200db53 100644--- a/renderer/src/skin.rs+++ b/renderer/src/skin.rs@@ -459,6 +459,20 @@ impl Model {self.globals(pose)}+ /// The file's materials the triangles of `triangles(.., only, ..)` have, each once, in the primitives' order (None:+ /// the file's default one).+ pub fn used_materials(&self, only: Option<&[String]>) -> Vec<Option<usize>> {+ let nodes: Vec<gltf::Node> = self.gltf.0.nodes().collect();+ let mut out = vec![];+ for p in &self.prims {+ if only.is_some_and(|names| !nodes[p.node].name().is_some_and(|nm| names.iter().any(|x| x == nm))) || out.contains(&p.material) {+ continue;+ }+ out.push(p.material);+ }+ out+ }+/// A rigid model's triangles of the nodes `keep` admits, with each one's node: in world space for `pose`/// (`world` x the node's global transform), or in the node's own space (`local`: the caller places them per node)./// Same order as `triangles`. Mirrored placements keep the winding front-facing in world space, as `triangles`diff --git a/renderer/src/tables.rs b/renderer/src/tables.rsindex e91a8d7..428d7d8 100644--- a/renderer/src/tables.rs+++ b/renderer/src/tables.rs@@ -14,6 +14,8 @@ use std::collections::{HashMap, HashSet};pub struct Dirty {pub materials: bool,pub lights: bool,+ /// A light came, went or changed class: the table was listed again in a build's order (`list_lights`).+ pub lights_listed: bool,/// A local light moved, or went dark or lit: the light groups are sorted again (`Tables::regroup_lights`).pub lights_moved: bool,pub objects: bool,@@ -103,7 +105,8 @@ impl Tables {/// Applies parameter changes; Err / Ok(None) means the scene must be rebuilt instead.pub fn apply(&mut self, w: &World, c: &Changes, now: f32) -> Result<Option<Dirty>> {- if c.structural || !c.poses.is_empty() || !c.moved.is_empty() {+ // (A texture that was replaced is the live view's to place again, before this: live/edits.rs `place_textures`.)+ if c.structural || !c.poses.is_empty() || !c.moved.is_empty() || !c.textures.is_empty() {return Ok(None);}let mut d = Dirty::default();@@ -142,7 +145,11 @@ impl Tables {}}for id in &c.lights {- let o = w.objects.get(id).ok_or_else(|| anyhow!("unknown object {id}"))?;+ // (A light that is gone: its entries with it.)+ let Some(o) = w.objects.get(id) else {+ self.drop_light(*id, &mut d);+ continue;+ };if let (Some(mat), Kind::Light(desc::Light::Rect { color, intensity, visible: true, .. })) = (self.retained.proxies.get(id).and_then(|p| p.card), &o.kind) {let m = scene::card_material(*color, *intensity);if !self.can_emit(mat, &m) {@@ -153,6 +160,9 @@ impl Tables {}self.update_light(w, *id, &mut d);}+ if d.lights_listed {+ self.list_lights(w);+ }for id in &c.materials {let Some(&mi) = self.retained.materials.get(id) else { return Ok(None) };let m = w.materials.get(id).ok_or_else(|| anyhow!("unknown material {id}"))?;@@ -201,16 +211,62 @@ impl Tables {if self.retained.sun == Some(id) {return; // colour comes from the sky bake}- let (Some(idx), Some(o)) = (self.light_index.get(&id), w.objects.get(&id)) else { return };+ let Some(o) = w.objects.get(&id) else { return };let Kind::Light(l) = &o.kind else { return };- if let Some(gl) = scene::gpu_light_shown(l, w.world_matrix(id), o.power, w.shown(id)) {- // A local light somewhere else, or lit where it was dark: the groups are sorted again (`regroup_lights`).- let moved = idx.iter().any(|&i| self.lights[i].pos != gl.pos || (self.lights[i].color[..3] == [0.0; 3]) != (gl.color[..3] == [0.0; 3]));- for &i in idx {- self.lights[i] = gl;+ let Some(gl) = scene::gpu_light_shown(l, w.world_matrix(id), o.power, w.shown(id)) else { return };+ match self.light_index.get(&id) {+ Some(idx) => {+ // A local light somewhere else, or lit where it was dark: the groups are sorted again+ // (`regroup_lights`); so is the table for a light of another class (directional, local, shadowed).+ let moved = idx.iter().any(|&i| self.lights[i].pos != gl.pos || (self.lights[i].color[..3] == [0.0; 3]) != (gl.color[..3] == [0.0; 3]));+ let reclassed = idx.iter().any(|&i| crate::light_class(&self.lights[i]) != crate::light_class(&gl));+ for &i in idx {+ self.lights[i] = gl;+ }+ d.lights_moved |= (moved && gl.pos[3] != 0.0) || reclassed;+ d.lights_listed |= reclassed;}- d.lights = true;- d.lights_moved |= moved && gl.pos[3] != 0.0;+ // A light that came while the scene runs: an entry after the others, sorted in among them.+ None => {+ self.light_index.insert(id, vec![self.lights.len()]);+ self.lights.push(gl);+ self.retained.light_nodes.push(id);+ (d.lights_moved, d.lights_listed) = (true, true);+ }+ }+ d.lights = true;+ }++ /// The entries of a light that is gone, out of the table (`light_index` and the retained nodes follow).+ fn drop_light(&mut self, id: u32, d: &mut Dirty) {+ let Some(idx) = self.light_index.remove(&id) else { return };+ let keep: Vec<usize> = (0..self.lights.len()).filter(|i| !idx.contains(i)).collect();+ if self.retained.light_nodes.len() == self.lights.len() {+ self.retained.light_nodes = keep.iter().map(|&i| self.retained.light_nodes[i]).collect();+ }+ self.lights = keep.iter().map(|&i| self.lights[i]).collect();+ self.light_index.clear();+ for (i, n) in self.retained.light_nodes.iter().enumerate() {+ self.light_index.entry(*n).or_default().push(i);+ }+ (d.lights, d.lights_moved, d.lights_listed) = (true, true, true);+ }++ /// The table's lights in the order a build lists them (the world's objects' order), before they are sorted into+ /// the kernel's (`regroup_lights`, which keeps that order among lights it has no reason to part): a view where+ /// lights came, went or changed class then has the table a build of its world has.+ fn list_lights(&mut self, w: &World) {+ if self.retained.light_nodes.len() != self.lights.len() {+ return;+ }+ let at: HashMap<u32, usize> = w.ordered().into_iter().enumerate().map(|(k, id)| (id, k)).collect();+ let mut order: Vec<usize> = (0..self.lights.len()).collect();+ order.sort_by_key(|&i| at.get(&self.retained.light_nodes[i]).copied().unwrap_or(usize::MAX));+ self.lights = order.iter().map(|&i| self.lights[i]).collect();+ self.retained.light_nodes = order.iter().map(|&i| self.retained.light_nodes[i]).collect();+ self.light_index.clear();+ for (i, n) in self.retained.light_nodes.iter().enumerate() {+ self.light_index.entry(*n).or_default().push(i);}}@@ -239,9 +295,10 @@ impl Tables {/// Whether a material may emit without a rebuild: it already has emitter entries, or (`emit_in_place`) its/// triangles can get them in place, queued in `started_emitting` (ROADMAP § 6 step 3).- /// Materials created since the build (`Changes::new_materials`: no texture, no function), as entries after the- /// scene's, whatever their class: what an edit draws with one is an instance, whose rows say it. False, and- /// nothing added, if one of them cannot be made.+ /// Materials created since the build (`Changes::new_materials`: no function), as entries after the scene's,+ /// whatever their class: what an edit draws with one is an instance, whose rows say it. Their textures are the+ /// pages' by now (the live view places them first: live/edits.rs `place_textures`). False, and nothing added, if+ /// one of them cannot be made.pub fn add_materials(&mut self, w: &World, ids: &std::collections::BTreeSet<u32>) -> bool {let mut fresh = vec![];for id in ids {@@ -249,7 +306,9 @@ impl Tables {continue;}let Some(m) = w.materials.get(id) else { return false };- let Ok(gm) = scene::build_material(*id, m, &w.textures, &self.retained.shaders, &mut |_, _| Err(anyhow!("a texture"))) else { return false };+ let slots = &self.retained.textures;+ let mut tex = |tid: u32, srgb: bool| slots.get(&(tid, srgb)).copied().ok_or_else(|| anyhow!("texture {tid} is not in the pages"));+ let Ok(gm) = scene::build_material(*id, m, &w.textures, &self.retained.shaders, &mut tex) else { return false };fresh.push((*id, gm));}for (id, gm) in fresh {diff --git a/renderer/src/texpack.rs b/renderer/src/texpack.rsindex 46a34e9..ba286fd 100644--- a/renderer/src/texpack.rs+++ b/renderer/src/texpack.rs@@ -21,6 +21,104 @@ pub struct Packed {pub info: Vec<[f32; 4]>,/// Where each stream texture (`stream_key`) sits, by name: its pixels are replaced in place (`patch`).pub streams: Vec<(String, Place)>,+ /// Where every texture sits and what the pages have free: a texture is placed among them later (`Atlas::place`).+ pub atlas: Atlas,+}++/// The pages as what they hold and what they have free: every texture's place, and each layer's shelves. A texture+/// added while the scene runs takes a place here (`place`) and has its pixels written there (`patch`); nothing is+/// packed again.+#[derive(Clone, Debug, Default, PartialEq)]+pub struct Atlas {+ pub side: u32,+ /// By texture.+ pub places: Vec<Place>,+ /// By layer, top to bottom: a shelf's y, its height, and the x its next rect starts at.+ shelves: Vec<Vec<(u32, u32, u32)>>,+}++/// The size a texture of `width` x `height` has in the pages: at most `MAX_DIM` a side, and a power of two >= 512+/// gives up 2 x GUTTER texels, so that its padded rect stays a power of two and four 2048s (or sixteen 1024s) fill a+/// page exactly; anything else keeps its size and is padded.+pub fn content_size(width: u32, height: u32) -> (u32, u32) {+ let (w, h) = (width.min(MAX_DIM), height.min(MAX_DIM));+ let k = (w as f32 / width as f32).min(h as f32 / height as f32);+ let (mut w, mut h) = (((width as f32 * k) as u32).max(1), ((height as f32 * k) as u32).max(1));+ if w >= 512 && w.is_power_of_two() {+ w -= 2 * GUTTER;+ }+ if h >= 512 && h.is_power_of_two() {+ h -= 2 * GUTTER;+ }+ (w, h)+}++fn padded_size(content: (u32, u32)) -> (u32, u32) {+ (round_up(content.0 + 2 * GUTTER), round_up(content.1 + 2 * GUTTER))+}++impl Atlas {+ pub fn layers(&self) -> u32 {+ self.shelves.len() as u32+ }++ /// Two rows a texture, at the pages' side as it is now: (u0, v0, du, dv) of the content rect in page UV; (layer,+ /// wrap, width, height). (No texture: two rows of zeros, so the table is never empty.)+ pub fn info(&self) -> Vec<[f32; 4]> {+ let s = self.side as f32;+ let mut info = vec![[0.0f32; 4]; self.places.len().max(1) * 2];+ for (i, p) in self.places.iter().enumerate() {+ let (w, h) = p.size;+ info[i * 2] = [(p.x + GUTTER) as f32 / s, (p.y + GUTTER) as f32 / s, w as f32 / s, h as f32 / s];+ info[i * 2 + 1] = [p.layer as f32, p.wrap as u32 as f32, w as f32, h as f32];+ }+ info+ }++ /// A place for one more texture of `width` x `height` as its source has it: on a shelf it fits (the lowest such),+ /// else on a new shelf of a layer with room below its last, else on a new layer. The pages get a longer side+ /// where the texture is wider than they are, or where they have `max_layers` already; what they hold stays where+ /// it is, and a longer side changes every texture's rows (`info`). None: no room at the longest side and+ /// `max_layers`.+ pub fn place(&mut self, width: u32, height: u32, wrap: bool, max_layers: u32) -> Option<Place> {+ let size = content_size(width, height);+ let (w, h) = padded_size(size);+ if w.max(h) > self.side {+ self.side = w.max(h).next_power_of_two().max(256);+ }+ if self.shelves.is_empty() {+ self.shelves.push(vec![]);+ }+ loop {+ let side = self.side;+ // (The lowest shelf that takes it; the first of them.)+ let on = self+ .shelves+ .iter()+ .enumerate()+ .flat_map(|(l, shelves)| shelves.iter().enumerate().map(move |(k, s)| (l, k, *s)))+ .filter(|(_, _, s)| s.1 >= h && s.2 + w <= side)+ .min_by_key(|(_, _, s)| s.1);+ let (layer, x, y) = if let Some((l, k, s)) = on {+ self.shelves[l][k].2 += w;+ (l, s.2, s.0)+ } else if let Some((l, y)) = self.shelves.iter().enumerate().map(|(l, shelves)| (l, shelves.last().map_or(0, |s| s.0 + s.1))).find(|(_, y)| y + h <= side) {+ self.shelves[l].push((y, h, w));+ (l, 0, y)+ } else if self.layers() < max_layers {+ self.shelves.push(vec![(0, h, w)]);+ (self.shelves.len() - 1, 0, 0)+ } else if side < MAX_PAGE {+ self.side *= 2;+ continue;+ } else {+ return None;+ };+ let place = Place { layer: layer as u32, x, y, padded: (w, h), size, wrap };+ self.places.push(place);+ return Some(place);+ }+ }}/// A texture's padded rect in the pages (aligned to `ALIGN`, so its mips are its own) and its content's size.@@ -90,22 +188,13 @@ fn round_up(v: u32) -> u32 {pub fn pack(textures: &[Texture]) -> Packed {if textures.is_empty() {let img = image::RgbaImage::from_pixel(ALIGN, ALIGN, image::Rgba([255, 255, 255, 255]));- return Packed { side: ALIGN, layers: vec![mip_chain(img)], info: vec![[0.0; 4], [0.0; 4]], streams: vec![] };+ let atlas = Atlas { side: ALIGN, places: vec![], shelves: vec![vec![]] };+ return Packed { side: ALIGN, layers: vec![mip_chain(img)], info: atlas.info(), streams: vec![], atlas };}- // Power-of-two textures >= 512 give up 2 x GUTTER texels so the padded rect stays a power of two and four- // 2048s (or sixteen 1024s) fill a page exactly; anything else keeps its size and is padded.let src: Vec<std::borrow::Cow<image::RgbaImage>> = textures.par_iter().map(|t| {- let (w, h) = (t.width.min(MAX_DIM), t.height.min(MAX_DIM));- let k = (w as f32 / t.width as f32).min(h as f32 / t.height as f32);- let (mut w, mut h) = (((t.width as f32 * k) as u32).max(1), ((t.height as f32 * k) as u32).max(1));- if w >= 512 && w.is_power_of_two() {- w -= 2 * GUTTER;- }- if h >= 512 && h.is_power_of_two() {- h -= 2 * GUTTER;- }+ let (w, h) = content_size(t.width, t.height);if (w, h) == (t.width, t.height) {std::borrow::Cow::Borrowed(&*t.rgba)} else {@@ -113,7 +202,7 @@ pub fn pack(textures: &[Texture]) -> Packed {}}).collect();- let padded: Vec<(u32, u32)> = src.iter().map(|i| (round_up(i.width() + 2 * GUTTER), round_up(i.height() + 2 * GUTTER))).collect();+ let padded: Vec<(u32, u32)> = src.iter().map(|i| padded_size(i.dimensions())).collect();let mut order: Vec<usize> = (0..src.len()).collect();order.sort_by_key(|&i| std::cmp::Reverse((padded[i].1, padded[i].0)));let area: u64 = padded.iter().map(|&(w, h)| w as u64 * h as u64).sum();@@ -125,6 +214,7 @@ pub fn pack(textures: &[Texture]) -> Packed {// Shelf packing; a size that does not fit restarts on a new layer.let mut place = vec![(0u32, 0u32, 0u32); src.len()];let (mut layer, mut x, mut y, mut shelf) = (0u32, 0u32, 0u32, 0u32);+ let mut shelves: Vec<Vec<(u32, u32, u32)>> = vec![vec![]];for &i in &order {let (w, h) = padded[i];if x + w > side {@@ -137,19 +227,20 @@ pub fn pack(textures: &[Texture]) -> Packed {x = 0;y = 0;shelf = 0;+ shelves.push(vec![]);}place[i] = (layer, x, y);x += w;shelf = shelf.max(h);+ // (Its shelf: the layer's last where that is at this y, else a new one.)+ match shelves[layer as usize].last_mut() {+ Some(s) if s.0 == y => (s.1, s.2) = (s.1.max(h), x),+ _ => shelves[layer as usize].push((y, h, x)),+ }}- let mut info = vec![[0.0f32; 4]; src.len() * 2];- for (i, img) in src.iter().enumerate() {- let (l, px, py) = place[i];- let (w, h) = (img.width(), img.height());- let s = side as f32;- info[i * 2] = [(px + GUTTER) as f32 / s, (py + GUTTER) as f32 / s, w as f32 / s, h as f32 / s];- info[i * 2 + 1] = [l as f32, textures[i].wrap as u32 as f32, w as f32, h as f32];- }+ let places = (0..src.len()).map(|i| Place { layer: place[i].0, x: place[i].1, y: place[i].2, padded: padded[i], size: src[i].dimensions(), wrap: textures[i].wrap }).collect();+ let atlas = Atlas { side, places, shelves };+ let info = atlas.info();// Fill pages row-parallel: every page row gathers from the textures whose padded rect spans it.let pages: Vec<image::RgbaImage> = (0..=layer).into_par_iter()@@ -181,15 +272,8 @@ pub fn pack(textures: &[Texture]) -> Packed {image::RgbaImage::from_raw(side, side, bytemuck::cast_slice(&page).to_vec()).unwrap()}).collect();- let streams = textures- .iter()- .enumerate()- .filter_map(|(i, t)| {- let (layer, x, y) = place[i];- Some((stream_name(&t.key)?.to_string(), Place { layer, x, y, padded: padded[i], size: src[i].dimensions(), wrap: t.wrap }))- })- .collect();- Packed { side, layers: pages.into_par_iter().map(mip_chain).collect(), info, streams }+ let streams = textures.iter().enumerate().filter_map(|(i, t)| Some((stream_name(&t.key)?.to_string(), atlas.places[i]))).collect();+ Packed { side, layers: pages.into_par_iter().map(mip_chain).collect(), info, streams, atlas }}/// 2x2 box-filtered chain (sRGB-encoded texels are averaged as stored, like most engines' default mip gen).@@ -286,11 +370,16 @@ pub fn resize_triangle(img: &image::RgbaImage, nw: u32, nh: u32) -> image::RgbaI/// Identity of a texture set (pages are rebuilt only when it changes).pub fn set_key(textures: &[Texture]) -> u64 {+ set_key_of(textures.iter().map(|t| (t.key.as_str(), t.width, t.height, t.wrap)))+}++/// `set_key` of textures given as (key, width, height, wrap).+pub fn set_key_of<'a>(textures: impl Iterator<Item = (&'a str, u32, u32, bool)>) -> u64 {use std::hash::{Hash, Hasher};let mut h = std::collections::hash_map::DefaultHasher::new();- for t in textures {- t.key.hash(&mut h);- (t.width, t.height, t.wrap).hash(&mut h);+ for (key, width, height, wrap) in textures {+ key.hash(&mut h);+ (width, height, wrap).hash(&mut h);}h.finish()}@@ -349,6 +438,76 @@ mod tests {}}+ /// No two of the places overlap, each lies in its page on the 16-texel grid, and each texture's rows say its+ /// place at the pages' side.+ fn sound(what: &str, a: &Atlas) {+ let info = a.info();+ for (i, p) in a.places.iter().enumerate() {+ assert!(p.x + p.padded.0 <= a.side && p.y + p.padded.1 <= a.side && p.layer < a.layers(), "{what}: texture {i} in its page: {p:?} of {}", a.side);+ assert_eq!((p.x % ALIGN, p.y % ALIGN, p.padded.0 % ALIGN, p.padded.1 % ALIGN), (0, 0, 0, 0), "{what}: texture {i} on the grid");+ assert!(p.size.0 + 2 * GUTTER <= p.padded.0 && p.size.1 + 2 * GUTTER <= p.padded.1, "{what}: texture {i} has its gutters");+ let s = a.side as f32;+ assert_eq!(info[i * 2], [(p.x + GUTTER) as f32 / s, (p.y + GUTTER) as f32 / s, p.size.0 as f32 / s, p.size.1 as f32 / s], "{what}: texture {i}'s rect");+ assert_eq!(info[i * 2 + 1], [p.layer as f32, p.wrap as u32 as f32, p.size.0 as f32, p.size.1 as f32], "{what}: texture {i}'s layer and size");+ for (j, q) in a.places.iter().enumerate().skip(i + 1) {+ let apart = p.layer != q.layer || p.x + p.padded.0 <= q.x || q.x + q.padded.0 <= p.x || p.y + p.padded.1 <= q.y || q.y + q.padded.1 <= p.y;+ assert!(apart, "{what}: textures {i} and {j} overlap: {p:?}, {q:?}");+ }+ }+ }++ /// Textures placed after the pack take the room it left: beside the last on a shelf, on a new shelf, on a new+ /// layer; those there stay where they are. A texture wider than the pages gives them a longer side, and with as+ /// many layers as there may be a full page does too; every texture's rows are then of the new side.+ #[test]+ fn a_texture_is_placed_among_the_packed_ones() {+ let flat = |w: u32, h: u32| tex(w, h, true, |_, _| [9, 9, 9, 255]);+ let packed = pack(&[flat(300, 200), flat(100, 60), flat(200, 200)]);+ let mut a = packed.atlas.clone();+ assert_eq!((a.side, a.layers(), a.places.len()), (512, 1, 3));+ sound("packed", &a);+ assert_eq!(a.info(), packed.info, "the pack's rows are the atlas's");+ let before = a.places.clone();+ // Beside the last on a shelf (both are as high: the first), then new shelves, then more than the page has.+ let small = a.place(64, 40, false, 8).unwrap();+ assert_eq!((small.layer, small.x, small.y, small.size, small.wrap), (0, before[0].x + before[0].padded.0, before[0].y, (64, 40), false));+ let mut layers = 1;+ for k in 0..12 {+ let p = a.place(200, 120, true, 8).unwrap();+ layers = layers.max(p.layer + 1);+ sound(&format!("after {k} more"), &a);+ }+ assert!(layers > 1 && a.side == 512, "the page filled and a layer was added: {layers} layers of {}", a.side);+ assert_eq!(a.places[..3], before[..], "those packed stay where they were");+ // Wider than the pages: a longer side, the places as they were, the rows of the new side.+ let big = a.place(2048, 1024, true, 8).unwrap();+ assert_eq!((a.side, big.size, big.padded), (2048, (2016, 992), (2048, 1024)));+ assert_eq!(a.places[..3], before[..]);+ sound("a longer side", &a);+ assert_eq!(a.info()[0][0], (before[0].x + GUTTER) as f32 / 2048.0);+ // As many layers as there may be: a full page gets a longer side, not another layer.+ let mut b = pack(&[flat(224, 224)]).atlas;+ assert_eq!((b.side, b.layers()), (256, 1));+ let p = b.place(224, 224, true, 1).unwrap();+ assert_eq!((b.side, b.layers(), p.layer), (512, 1, 0));+ sound("one layer", &b);+ // The longest side and no layer more: no room.+ let mut c = Atlas { side: MAX_PAGE, places: vec![], shelves: vec![vec![]] };+ assert!((0..4).all(|_| c.place(2048, 2048, true, 1).is_some()) && c.place(16, 16, true, 1).is_none());+ assert_eq!((c.side, c.layers(), c.places.len()), (MAX_PAGE, 1, 4), "what found no room left nothing");+ // A shelf with room beside its last, but lower than the texture, is not its place.+ let mut d = pack(&[flat(100, 60)]).atlas;+ let tall = d.place(60, 150, true, 8).unwrap();+ assert!((tall.layer, tall.y) != (0, 0), "not on the shelf that is too low: {tall:?}");+ d.place(200, 60, true, 8).unwrap();+ sound("a tall one beside a low shelf", &d);+ // Pages without a texture take their first.+ let mut e = pack(&[]).atlas;+ let first = e.place(100, 60, true, 8).unwrap();+ assert_eq!((e.side, first.layer, first.x, first.y), (256, 0, 0, 0));+ sound("the first", &e);+ }+#[test]fn rects_gutters_and_mips() {// 1024 (pow2 >= 512: shrinks by 2 x GUTTER), a 100x60 clamped texture, a 300x200 wrapped one.diff --git a/renderer/src/world.rs b/renderer/src/world.rsindex 094cfdb..5dc2d94 100644--- a/renderer/src/world.rs+++ b/renderer/src/world.rs@@ -100,7 +100,7 @@ pub enum ProcSource {/// AABBs a procedural geometry may have: the hit's primitive index has 23 bits (pathtrace.wgsl `PROC_BIT`).pub const PROC_MAX_BOXES: usize = (1 << 23) - 1;-#[derive(Clone, Debug)]+#[derive(Clone, Debug, PartialEq)]pub enum TextureSource {/// Path relative to the asset root.File(String),@@ -114,7 +114,7 @@ pub enum TextureSource {Stream { name: String, width: u32, height: u32, rgba: Arc<Vec<u8>> },}-#[derive(Clone, Debug)]+#[derive(Clone, Debug, PartialEq)]pub struct Texture {pub source: TextureSource,pub srgb: bool,@@ -285,6 +285,10 @@ pub struct Changes {/// and lights without a card (their table entry goes black). A rebuild where the build left the object out.pub shown: HashSet<u32>,pub materials: HashSet<u32>,+ /// Textures that were replaced by another (`World::set_texture`): the materials that name one are made again.+ pub textures: HashSet<u32>,+ /// A material function came or changed (`World::set_shader`): the kernel's code.+ pub functions: bool,/// Objects whose light parameters changed.pub lights: HashSet<u32>,pub powers: HashSet<u32>,@@ -334,7 +338,7 @@ pub struct Changes {impl Changes {pub fn any(&self) -> bool {- self.structural || !self.shown.is_empty() || !self.new_materials.is_empty() || !self.materials.is_empty() || !self.lights.is_empty() || !self.powers.is_empty() || !self.customs.is_empty() || self.environment || self.camera || self.sun || self.view || self.settings || !self.poses.is_empty() || !self.moved.is_empty() || !self.instanced.is_empty() || self.edits()+ self.structural || !self.shown.is_empty() || !self.new_materials.is_empty() || !self.materials.is_empty() || !self.textures.is_empty() || self.functions || !self.lights.is_empty() || !self.powers.is_empty() || !self.customs.is_empty() || self.environment || self.camera || self.sun || self.view || self.settings || !self.poses.is_empty() || !self.moved.is_empty() || !self.instanced.is_empty() || self.edits()}/// Geometry edits are pending (`geometries`, `added`, `removed`).pub fn edits(&self) -> bool {@@ -419,10 +423,9 @@ impl Default for World {}}-fn same_texture_refs(a: &desc::Material, b: &desc::Material) -> bool {- let maps = |m: &desc::Material| [m.map, m.normal_map, m.roughness_map, m.metalness_map, m.ao_map, m.emissive_map, m.transmission_map];- let func = |m: &desc::Material| m.shader.as_ref().map(|s| (s.id.clone(), s.textures.clone()));- maps(a) == maps(b) && func(a) == func(b)+/// The textures a material names: its maps and its function's.+pub fn material_texture_ids(m: &desc::Material) -> impl Iterator<Item = u32> + '_ {+ [m.map, m.normal_map, m.roughness_map, m.metalness_map, m.ao_map, m.emissive_map, m.transmission_map].into_iter().flatten().chain(m.shader.iter().flat_map(|s| s.textures.iter().flatten().copied()))}fn light_class(l: &desc::Light) -> (u8, bool, bool) {@@ -505,37 +508,56 @@ impl World {Ok(())}+ /// Whether an object of kind `k` is a light that is an entry of the kernel's light table and nothing else: not a+ /// rect light with a card (its card is triangles), not the atmosphere's sun (the sky's bake has it).+ fn table_light(&self, id: u32, k: &Kind) -> bool {+ let sun = matches!(self.environment.sky, desc::Sky::Atmosphere { sun: Some(s), .. } if s == id);+ matches!(k, Kind::Light(l) if !sun && !matches!(l, desc::Light::Rect { visible: true, .. }))+ }++ /// Creates or replaces a texture. A new one is placed in the texture pages when a material first names it; one+ /// that changed (its pixels, its wrap, its repeat or offset) has its materials made again, in place+ /// (`Changes::textures`). The same texture set again changes nothing.pub fn set_texture(&mut self, id: u32, t: Texture) -> Result<()> {if let TextureSource::File(uri) = &t.source {check_uri(uri)?;}+ match self.textures.get(&id) {+ Some(old) if *old == t => return Ok(()),+ Some(_) => {+ self.changes.textures.insert(id);+ }+ None => {}+ }self.textures.insert(id, t);- mark_structural(&mut self.changes, line!());Ok(())}+ /// Creates or replaces a material function. In place (`Changes::functions`): the scene's kernel is made with it+ /// while the frames go on, and a material of it is drawn as it is without a function until then.pub fn set_shader(&mut self, name: &str, code: String, helpers: String) {if self.shaders.get(name).is_some_and(|(c, h)| *c == code && *h == helpers) {return;}self.shaders.insert(name.to_string(), (code, helpers));- mark_structural(&mut self.changes, line!());+ self.changes.functions = true;}pub fn set_material(&mut self, id: u32, m: desc::Material) {match self.materials.get(&id) {- // `transparent` moves particles between the scene and the translucency pass, `vertexColors` decides which- // triangles carry colours: a rebuild.- Some(old) if same_texture_refs(old, &m) && old.transparent == m.transparent && old.vertex_colors == m.vertex_colors => {+ // Its parameters, its textures (a texture the scene has not is placed in the pages then) and its function,+ // in place. `transparent` moves particles between the scene and the translucency pass, `vertexColors`+ // decides which triangles carry colours: a rebuild.+ Some(old) if old.transparent == m.transparent && old.vertex_colors == m.vertex_colors => {self.changes.materials.insert(id);}- // A new one of plain parameters (no texture, no function, not a particle's): in place.- None if [m.map, m.normal_map, m.roughness_map, m.metalness_map, m.ao_map, m.emissive_map, m.transmission_map].iter().all(Option::is_none) && m.shader.is_none() && !m.transparent && !m.vertex_colors => {+ // A new one that is not a particle's: in place, its textures and its function with it.+ None if !m.transparent && !m.vertex_colors => {self.changes.new_materials.insert(id);}_ => {if std::env::var("THREERT_EDIT_LOG").is_ok_and(|v| v == "1") {- eprintln!("world: structural: material {id} new with textures or a function, or changed beyond its parameters");+ eprintln!("world: structural: material {id} is a particle's or has vertex colours, new or changed");}mark_structural(&mut self.changes, line!())}@@ -594,6 +616,13 @@ impl World {self.instanced.remove(&id);}}+ // A light that is the light table's alone, new or set again as one under the same parent: its entry, in+ // place. A new group draws nothing.+ let relit = self.table_light(id, &kind) && self.objects.get(&id).is_none_or(|o| self.table_light(id, &o.kind) && o.parent == parent);+ let grouped = matches!(kind, Kind::Group) && !self.objects.contains_key(&id);+ // A camera, new or set again as one under the same parent: nothing is built from it; the view takes it if+ // it is the scene's.+ let filmed = matches!(kind, Kind::Camera(_)) && self.objects.get(&id).is_none_or(|o| matches!(o.kind, Kind::Camera(_)) && o.parent == parent);let was_parent = self.objects.get(&id).map(|o| o.parent);if was_parent != Some(parent) {if let Some(Some(p)) = was_parent {@@ -614,6 +643,11 @@ impl World {self.changes.added.insert(id);} else if rematerialed {self.changes.instanced.insert(id);+ } else if relit {+ self.changes.lights.insert(id);+ } else if grouped {+ } else if filmed {+ self.changes.camera |= self.settings.camera == Some(id);} else {if std::env::var("THREERT_EDIT_LOG").is_ok_and(|v| v == "1") {let o = &self.objects[&id];@@ -740,6 +774,8 @@ impl World {} else if sun && self.leaf(id) {// The atmosphere's sun (time of day): its light rewritten and the sky re-baked in place (live/edits.rs `move_sun`).self.changes.sun = true;+ } else if matches!(o.kind, Kind::Camera(_)) && self.leaf(id) {+ // (A camera that is not the scene's: nothing is built from it.)} else {// Fixed geometry moved: from now on it is movable. A mesh, a still model, or a group, is its instances' to move// (`Changes::started`); anything else rebuilds once, to set its triangles apart.@@ -930,9 +966,14 @@ impl World {}pub fn set_light(&mut self, id: u32, l: desc::Light) -> Result<()> {+ // Its entry in the light table, in place: another kind of light or another shadow flag too (the table is+ // sorted again). A rect light's card that comes or goes is triangles, and the atmosphere's sun is the sky's:+ // those rebuild where their class changes.+ let table = self.table_light(id, &Kind::Light(l.clone()));+ let was = self.objects.get(&id).is_some_and(|o| self.table_light(id, &o.kind));let o = self.objects.get_mut(&id).ok_or_else(|| anyhow!("unknown object {id}"))?;match &o.kind {- Kind::Light(old) if light_class(old) == light_class(&l) => {+ Kind::Light(old) if light_class(old) == light_class(&l) || (table && was) => {self.changes.lights.insert(id);}_ => mark_structural(&mut self.changes, line!()),@@ -1009,11 +1050,18 @@ impl World {// A mesh, procedural geometry, or a group of those, is removed in place, and so is a lone instanced mesh or// model (or never added, if it came in this batch; live/edits.rs `edit_geometry` rebuilds for what it cannot// take out).+ // A light of the light table alone: its entry goes, in place. A group draws nothing.let alone = |o: &Object| doomed.len() == 1 && matches!(o.kind, Kind::Instanced { procedural: false, .. } | Kind::Model { .. });- if doomed.iter().all(|d| self.objects.get(d).is_some_and(|o| edits_in_place(&o.kind) || alone(o) || (doomed.len() > 1 && matches!(o.kind, Kind::Group)))) {- for d in &doomed {+ // (So does a camera that is not the scene's.)+ let lit: Vec<bool> = doomed.iter().map(|d| self.objects.get(d).is_some_and(|o| self.table_light(*d, &o.kind))).collect();+ let spare = |d: &u32, o: &Object| matches!(o.kind, Kind::Camera(_)) && self.settings.camera != Some(*d);+ if doomed.iter().zip(&lit).all(|(d, lit)| self.objects.get(d).is_some_and(|o| edits_in_place(&o.kind) || alone(o) || matches!(o.kind, Kind::Group) || *lit || spare(d, o))) {+ for (d, lit) in doomed.iter().zip(&lit) {self.instanced.remove(d);- if self.objects.remove(d).is_some_and(|o| !matches!(o.kind, Kind::Group)) && !self.changes.added.remove(d) {+ if *lit {+ self.objects.remove(d);+ self.changes.lights.insert(*d);+ } else if self.objects.remove(d).is_some_and(|o| !matches!(o.kind, Kind::Group | Kind::Camera(_))) && !self.changes.added.remove(d) {self.changes.removed.insert(*d);}// What else this batch changed of it goes with it (a pose, a move, its visibility: there is nothing@@ -1491,8 +1539,16 @@ mod tests {assert!(!c.structural && c.any() && c.new_materials.contains(&2), "a new material of plain parameters: in place");let mut textured = mat();textured.map = Some(9);- w.set_material(3, textured);- assert!(w.take_changes().structural, "one with a texture: a rebuild");+ w.set_material(3, textured.clone());+ let c = w.take_changes();+ assert!(!c.structural && c.new_materials.contains(&3), "one with a texture: in place too (the texture is placed in the pages)");+ // A new one that is a particle's (`transparent`), or has vertex colours: a rebuild.+ for (k, what) in ["transparent", "vertex colours"].iter().enumerate() {+ let mut m = mat();+ (m.transparent, m.vertex_colors) = (k == 0, k == 1);+ w.set_material(20 + k as u32, m);+ assert!(w.take_changes().structural, "a new material with {what}: a rebuild");+ }// (The engine's `object` call gives a mesh a body will drive its own BLAS.)w.set_object(2, "box".into(), None, mesh(2, true), true, false).unwrap();w.set_driven(2).unwrap();@@ -1582,7 +1638,34 @@ mod tests {w.set_object(16, "lamp".into(), Some(15), Kind::Light(serde_json::from_value(serde_json::json!({ "type": "point", "color": [1, 1, 1], "castShadow": true, "intensity": 1, "range": 0, "radius": 0.01 })).unwrap()), true, false).unwrap();w.take_changes();w.remove(15);- assert!(w.take_changes().structural, "a group with a light");+ let c = w.take_changes();+ assert!(!c.structural && c.lights.contains(&16) && c.removed.is_empty(), "a group with a light: the light's entry goes, in place");+ // A light alone, and a group alone: in place too. A light set again as one: its entry's change.+ let lamp = |shadow: bool| Kind::Light(serde_json::from_value(serde_json::json!({ "type": "point", "color": [1, 1, 1], "castShadow": shadow, "intensity": 1, "range": 0, "radius": 0.01 })).unwrap());+ w.set_object(17, "lamp".into(), None, lamp(true), true, false).unwrap();+ let c = w.take_changes();+ assert!(!c.structural && c.lights.contains(&17), "a new light: its entry, in place");+ w.set_object(17, "lamp".into(), None, lamp(false), true, false).unwrap();+ assert!(!w.changes.structural && w.take_changes().lights.contains(&17), "the light set again without its shadow");+ w.set_object(18, "set".into(), None, Kind::Group, true, false).unwrap();+ assert!(!w.take_changes().structural, "a new group draws nothing");+ w.remove(18);+ w.remove(17);+ let c = w.take_changes();+ assert!(!c.structural && c.lights.contains(&17), "a group and a light removed");+ // A camera that is not the scene's: created, moved and removed, nothing rebuilt.+ let lens = || Kind::Camera(serde_json::from_value(serde_json::json!({ "fov": 50.0, "near": 0.1, "far": 100.0, "exposure": { "mode": "manual", "ev100": 0.0 } })).unwrap());+ w.set_object(19, "spare".into(), None, lens(), true, false).unwrap();+ w.set_transform(19, Vec3::X, Quat::IDENTITY, Vec3::ONE).unwrap();+ w.remove(19);+ let c = w.take_changes();+ assert!(!c.structural && !c.camera && c.removed.is_empty() && c.promoted.is_empty(), "a camera that is not the scene's");+ // Not in place: something else among them (a rect light with a card is triangles).+ w.set_object(15, "set".into(), None, Kind::Group, true, false).unwrap();+ w.set_object(16, "card".into(), Some(15), Kind::Light(serde_json::from_value(serde_json::json!({ "type": "rect", "color": [1, 1, 1], "castShadow": true, "intensity": 1, "width": 1, "height": 1, "visible": true })).unwrap()), true, false).unwrap();+ assert!(w.take_changes().structural, "a rect light with a card: a rebuild");+ w.remove(15);+ assert!(w.take_changes().structural, "a group with a rect light's card");// Under a still group in a movable subtree (`movable` walks the ancestors, as the build does).w.set_object(8, "rig".into(), None, Kind::Group, true, true).unwrap();w.set_object(9, "still".into(), Some(8), Kind::Group, true, false).unwrap();@@ -1715,9 +1798,46 @@ mod tests {let c = w.take_changes();assert!(!c.structural && c.materials.contains(&1), "{what}: the material's change");}- m.map = Some(7);+ // Its textures too: a map that comes, another, none again.+ for (map, what) in [(Some(7), "a map"), (Some(8), "another map"), (None, "no map again")] {+ m.map = map;+ w.set_material(1, m.clone());+ let c = w.take_changes();+ assert!(!c.structural && c.materials.contains(&1), "{what}: the material's change");+ }+ // A texture: a new one is nothing until a material names it, the same again is nothing, another under its+ // number is that texture's change.+ let texture = |v: u8| Texture { source: TextureSource::Pixels { width: 1, height: 1, rgba: Arc::new(vec![v; 4]) }, srgb: true, wrap: true, repeat: [1.0, 1.0], offset: [0.0, 0.0] };+ w.set_texture(7, texture(1)).unwrap();+ w.set_texture(7, texture(1)).unwrap();+ assert!(!w.take_changes().any(), "a new texture, and the same again: no change");+ w.set_texture(7, texture(2)).unwrap();+ let c = w.take_changes();+ assert!(!c.structural && c.textures.contains(&7) && c.any(), "other pixels: the texture's change");+ w.set_texture(7, Texture { repeat: [2.0, 1.0], ..texture(2) }).unwrap();+ assert!(w.take_changes().textures.contains(&7), "another repeat: the texture's change");+ // A material function: new, the same again (nothing), other code; a material given one.+ w.set_shader("f", "fn mf_f() {}".into(), String::new());+ let c = w.take_changes();+ assert!(!c.structural && c.functions && c.any(), "a new function: the kernel's code, in place");+ w.set_shader("f", "fn mf_f() {}".into(), String::new());+ assert!(!w.take_changes().any(), "the same function again: no change");+ w.set_shader("f", "fn mf_f() { }".into(), String::new());+ assert!(w.take_changes().functions, "other code: the function's change");+ m.shader = Some(desc::ShaderRef { id: "f".into(), params: vec![], textures: vec![] });+ w.set_material(1, m.clone());+ let c = w.take_changes();+ assert!(!c.structural && c.materials.contains(&1), "a material given a function: the material's change");+ m.shader = None;+ w.set_material(1, m.clone());+ w.take_changes();+ // `transparent` moves particles between the scene and the translucency pass: a rebuild.+ m.transparent = true;+ w.set_material(1, m.clone());+ assert!(w.take_changes().structural, "a material that turns transparent: a rebuild");+ m.transparent = false;w.set_material(1, m);- assert!(w.take_changes().structural, "texture slots are structural");+ w.take_changes();w.set_object(5, "placed".into(), None, Kind::Mesh { geometry: 1, material: 1, own_blas: false, materials: vec![] }, true, false).unwrap();w.set_transform(5, Vec3::Y, Quat::IDENTITY, Vec3::ONE).unwrap();assert!(w.take_changes().promoted.is_empty(), "placing a new object is not a move");diff --git a/tests/render/data/textured-quads.glb b/tests/render/data/textured-quads.glbnew file mode 100644index 0000000..8670583Binary files /dev/null and b/tests/render/data/textured-quads.glb differ