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
Texture slots and model materials freed when nothing names them (#285)
Evan (Yifeng) Wang18c0e00c8adc
diff --git a/docs/RUNTIME.md b/docs/RUNTIME.mdindex 7098c07..9829f49 100644--- a/docs/RUNTIME.md+++ b/docs/RUNTIME.md@@ -849,8 +849,21 @@ at the end. `THREERT_EDIT_LOG=1` says where a rebuild was decided, and a frame'smaterial 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`). Pageswithout 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.+ New pixels of the same size go over the old ones, unless another texture has the same slot.+- **Textures and materials freed.** The world counts the models of each file (`World::models`). When a file's last+ model leaves, the commit retires the file's materials: their entries name nothing and the next file's materials+ take them (`Retained::free_materials`). Every texture slot that no material of the table names is then freed+ (`LiveCore::retire_models`, `Gpu::free_textures`). Its slot and its room in the pages go to the next texture placed:+ - the smallest free rect that holds it, the rest of the rect cut off (`texpack::Atlas::free`, `place`);+ - a layer's free room is made again from what it holds, so it does not depend on the order textures came and went:+ free columns at a shelf's end go back to the shelf, and empty last shelves go.++ This happens before the commit places what it adds, so a GLB place that replaces another takes the entries, the+ slot and the room the other left, and places that come and go do not grow the pages. Textures a world material+ names stay, as long as the material is in the world. Checked: `texpack` tests (2,000 places of 256–2,048 texels,+ ten at a time, with the pages as the first 200 left them; 10,000 rounds of arbitrary sizes after the first 1,000+ without growth) and `models_that_come_and_go_do_not_grow_the_pages` (twelve GLB files one after another: the same+ two entries, the same slot, the same pages, the picture a build's).- **Materials.** A new one, its maps and its function with it; a material given other maps, another function ornone. (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 nextdiff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rsindex a9bd9c0..7ea1317 100644--- a/renderer/src/gpu.rs+++ b/renderer/src/gpu.rs@@ -2427,18 +2427,18 @@ impl Gpu {/// 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.)+ /// on the GPU. A slot and a rect that a freed texture left (`free_textures`) are taken first.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) {+ if let Some(slot) = pages.keys.iter().position(|k| !k.0.is_empty() && k.0 == t.key) {return Ok(PagesEdit { slot: slot as i32, info: None, view: None });}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"))?;+ let (slot, 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) {@@ -2460,15 +2460,49 @@ impl Gpu {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));+ let k = (t.key.clone(), t.width, t.height, t.wrap);+ if slot < pages.keys.len() {+ pages.keys[slot] = k;+ } else {+ pages.keys.push(k);+ }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 })+ Ok(PagesEdit { slot: slot as i32, info: Some(pages.info.clone()), view })+ }++ /// Frees the textures in `slots` (no material names them any more): their slots and rects are the next placed+ /// textures' (`texpack::Atlas::free`), their rows zeros. The texture table's rows as they are now, if any was+ /// freed. A stream's texture is never freed (its name keeps it).+ pub fn free_textures(&self, slots: &[i32]) -> Option<std::sync::Arc<Vec<[f32; 4]>>> {+ let mut cache = self.pages.lock().unwrap();+ let pages = cache.as_mut()?;+ let mut freed = false;+ for &slot in slots {+ let s = slot as usize;+ if slot < 0 || !pages.atlas.holds(s) || crate::texpack::stream_name(&pages.keys[s].0).is_some() {+ continue;+ }+ pages.atlas.free(s);+ pages.keys[s] = (String::new(), 0, 0, false);+ freed = true;+ }+ if !freed {+ return None;+ }+ pages.key = crate::texpack::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());+ Some(pages.info.clone())+ }++ /// The slots that hold a texture now.+ pub fn texture_slots(&self) -> Vec<i32> {+ self.pages.lock().unwrap().as_ref().map_or_else(Vec::new, |p| (0..p.atlas.places.len()).filter(|&s| p.atlas.holds(s)).map(|s| s as i32).collect())}/// 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)+ self.pages.lock().unwrap().as_ref()?.keys.iter().position(|k| !k.0.is_empty() && 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@@ -2477,7 +2511,7 @@ impl Gpu {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 };+ let Some(place) = pages.atlas.places.get(slot as usize).copied().filter(|_| pages.atlas.holds(slot as usize)) 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;}diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rsindex 0e71545..7b98cb9 100644--- a/renderer/src/live/edits.rs+++ b/renderer/src/live/edits.rs@@ -798,6 +798,9 @@ impl LiveCore {}}}+ // Files no model is left of: their materials retired, the textures no material names any more freed, before+ // what this commit adds takes room (the place that replaces another takes its entries and its slots).+ let retired = !changes.structural && self.retire_models(world, &changes);// 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()) {@@ -1077,7 +1080,7 @@ impl LiveCore {}return Ok(true);};- if d.materials {+ if d.materials || retired {self.upload_materials();}if d.materials || changes.functions {@@ -1645,6 +1648,48 @@ impl LiveCore {Ok(())}+ /// The materials of the files whose last model left the world in this commit (`Changes::gone_models`, none of+ /// them back since): out of `asset_materials`, their entries named no texture and given to the next file's+ /// materials (`Retained::free_materials`; nothing draws with them: their models' instances are gone). Then every+ /// texture slot no material of the table names is freed (`Gpu::free_textures`): its slot and its place in the+ /// pages are the next texture's, so places that come and go do not grow the pages. True when a material changed.+ fn retire_models(&mut self, world: &World, changes: &crate::world::Changes) -> bool {+ let gone: Vec<&String> = changes.gone_models.iter().filter(|k| !world.models.contains_key(*k)).collect();+ if gone.is_empty() {+ return false;+ }+ let t = &mut self.sc.tables;+ let retired: Vec<((String, usize), u32)> = t.retained.asset_materials.iter().filter(|(k, _)| gone.contains(&&k.0)).map(|(k, i)| (k.clone(), *i)).collect();+ if retired.is_empty() {+ return false;+ }+ for (k, i) in retired {+ t.retained.asset_materials.remove(&k);+ if let Some(m) = t.materials.get_mut(i as usize) {+ m.tex0 = [-1; 4];+ (m.tex1[0], m.tex1[1]) = (-1, -1);+ m.uv[2] = 0.0;+ m.mt = [-1; 8];+ }+ t.retained.free_materials.push(i);+ }+ // The slots the table's materials name (`GpuMaterial`: tex0, tex1's first two, the transmission map + 1 in+ // uv.z, the function's slots).+ let mut named = std::collections::HashSet::new();+ for m in &t.materials {+ named.extend(m.tex0.iter().chain(&m.tex1[..2]).chain(&m.mt).copied().filter(|&s| s >= 0));+ if m.uv[2] >= 1.0 {+ named.insert(m.uv[2] as i32 - 1);+ }+ }+ let unnamed: Vec<i32> = self.g.texture_slots().into_iter().filter(|s| !named.contains(s)).collect();+ if let Some(info) = self.g.free_textures(&unnamed) {+ self.sc.tables.retained.textures.retain(|_, s| !unnamed.contains(s));+ self.apply_pages(Some(info), None);+ }+ true+ }+/// 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.@@ -1717,8 +1762,19 @@ impl LiveCore {}).map_err(|e| e.context(format!("{uri}: material {name}")))?;}- self.sc.tables.retained.asset_materials.insert(mkey, self.sc.tables.materials.len() as u32);- self.sc.tables.materials.push(gm);+ // (An entry a retired file left, or a new one.)+ let tables = &mut self.sc.tables;+ let at = match tables.retained.free_materials.pop() {+ Some(i) => {+ tables.materials[i as usize] = gm;+ i+ }+ None => {+ tables.materials.push(gm);+ tables.materials.len() as u32 - 1+ }+ };+ tables.retained.asset_materials.insert(mkey, at);made = true;}}diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rsindex 477ee9f..0c72b9c 100644--- a/renderer/src/live/inplace_tests.rs+++ b/renderer/src/live/inplace_tests.rs@@ -4351,8 +4351,9 @@ fn model_textures_named(c: &LiveCore) -> std::collections::BTreeMap<(String, usi/// 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.+/// draws. Another of it is another instance of that mesh. With the last of them gone the mesh is given back, its+/// materials retired and its picture freed (`retire_models`), and the model comes again in place, its materials in+/// the entries it left and its picture in the slot it left.#[test]fn a_model_the_scene_has_not_got_comes_in_place() {let presets = crate::default_presets_dir();@@ -4403,7 +4404,10 @@ fn a_model_the_scene_has_not_got_comes_in_place() {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.+ assert_eq!(live.sc.tables.retained.free_materials.len(), 2, "its two materials retired");+ assert!(live.g.texture_slots().is_empty(), "its picture freed: no material names it");+ // It comes again: its mesh made again (in the slot the other left), its materials in the entries they left, its+ // picture in its slot.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");@@ -4416,6 +4420,59 @@ fn a_model_the_scene_has_not_got_comes_in_place() {list_is_its_triangles("a model that emits", &live);}+/// Places that come and go (EarthRT's GLB places: a model of a file comes, the next replaces it): with each file's+/// last model gone its materials are retired and its pictures freed (`retire_models`), so twelve files one after+/// another take the same material entries, the same texture slot and the same room in the pages, which do not grow.+/// The files are copies of tests/render/data/textured-quads.glb under other names (a picture's key is its file's).+/// After them the view draws what a build of the world draws.+#[test]+fn models_that_come_and_go_do_not_grow_the_pages() {+ 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));+ let dir = Path::new("../out/test-places");+ std::fs::create_dir_all(dir).unwrap();+ let files: Vec<String> = (0..12)+ .map(|i| {+ let uri = format!("out/test-places/quads-{i}.glb");+ std::fs::copy("../tests/render/data/textured-quads.glb", Path::new("..").join(&uri)).unwrap();+ uri+ })+ .collect();+ 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 base = live.sc.tables.materials.len();+ let mut first = None;+ for (i, uri) in files.iter().enumerate() {+ if i > 0 {+ w.remove(100 + i as u32 - 1);+ }+ w.set_object(100 + i as u32, format!("place{i}"), None, Kind::Model { uri: uri.clone(), nodes: None, animation: None, functions: vec![] }, true, false).unwrap();+ w.set_transform(100 + i as u32, Vec3::new(-0.3, 0.2, 0.7), glam::Quat::from_rotation_y(0.3), Vec3::ONE).unwrap();+ assert!(!live.commit(&mut w).unwrap(), "place {i}: in place ({:?})", live.fallback);+ let (keys, side, layers, _) = live.g.pages_state();+ let now = (live.sc.tables.materials.len(), live.g.texture_slots(), keys.len(), side, layers);+ assert!(keys.iter().any(|k| k.0.contains(&format!("quads-{i}.glb"))), "place {i}: its picture is in the pages: {keys:?}");+ match &first {+ None => first = Some(now),+ Some(f) => assert_eq!(&now, f, "place {i}: the materials, the slots and the pages as the first place left them"),+ }+ }+ assert_eq!(first.unwrap().0, base + 2, "two material entries in all");+ let mut fresh = open_at_root(&w).unwrap();+ forget(&mut live);+ let (a, b) = (picture(&mut live, 48), picture(&mut fresh, 48));+ assert!(apart(&a, &b) < 0.5, "the picture is {:.2} steps from a build's", apart(&a, &b));+ // The last one gone: nothing names a texture.+ w.remove(100 + files.len() as u32 - 1);+ assert!(!live.commit(&mut w).unwrap());+ assert!(live.g.texture_slots().is_empty() && live.sc.tables.retained.asset_materials.is_empty());+}+/// 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.@@ -4998,3 +5055,26 @@ fn a_planets_altitude_is_not_another_sky() {assert!(!altitude_moved(400_000.0, 381_000.0) && altitude_moved(400_000.0, 379_000.0));assert!(!altitude_moved(2.0, 200.0) && altitude_moved(2.0, 260.0) && altitude_moved(260.0, 2.0));}++/// The world counts the models of each file (`World::models`): a file's last model gone, by removal or by becoming+/// something else, is `Changes::gone_models`; one that comes back in the same batch is counted again.+#[test]+fn the_world_counts_a_files_models() {+ let mut w = world();+ let model = |uri: &str| Kind::Model { uri: uri.into(), nodes: None, animation: None, functions: vec![] };+ w.set_object(40, "a".into(), None, model("a.glb"), true, false).unwrap();+ w.set_object(41, "a2".into(), None, model("a.glb"), true, false).unwrap();+ w.set_object(42, "b".into(), None, model("b.glb"), true, false).unwrap();+ assert_eq!((w.models.get("a.glb"), w.models.get("b.glb")), (Some(&2), Some(&1)));+ w.take_changes();+ w.remove(40);+ assert!(w.take_changes().gone_models.is_empty(), "one of a.glb is left");+ w.remove(41);+ w.set_object(42, "b".into(), None, model("c.glb"), true, false).unwrap();+ let c = w.take_changes();+ assert_eq!(c.gone_models, ["a.glb".to_string(), "b.glb".to_string()].into(), "the last of a.glb removed, b.glb's turned into c.glb");+ assert!(!w.models.contains_key("a.glb") && !w.models.contains_key("b.glb") && w.models.get("c.glb") == Some(&1));+ w.remove(42);+ w.set_object(43, "c".into(), None, model("c.glb"), true, false).unwrap();+ assert!(w.take_changes().gone_models.contains("c.glb") && w.models.get("c.glb") == Some(&1), "gone and back: counted again (the view keeps its materials)");+}diff --git a/renderer/src/scene.rs b/renderer/src/scene.rsindex 7bb23a8..20eb1cc 100644--- a/renderer/src/scene.rs+++ b/renderer/src/scene.rs@@ -699,6 +699,9 @@ pub struct Retained {/// 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>,+ /// `materials` entries of files no model is left of (live/edits.rs `retire_models`): the next file's materials+ /// take them.+ pub free_materials: Vec<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).diff --git a/renderer/src/texpack.rs b/renderer/src/texpack.rsindex ba286fd..9656d9d 100644--- a/renderer/src/texpack.rs+++ b/renderer/src/texpack.rs@@ -35,6 +35,11 @@ pub struct Atlas {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)>>,+ /// Slots whose texture was freed (`free`): the next texture placed takes the lowest.+ free_slots: Vec<usize>,+ /// Rects freed textures left, by layer: (layer, x, y, width, height), aligned to ALIGN. A texture placed takes the+ /// smallest that holds it, the rest of it split in two (to its right, below it: a guillotine cut).+ free_rects: Vec<(u32, u32, 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@@ -68,6 +73,10 @@ impl Atlas {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() {+ // (A freed slot: zeros, as no texture.)+ if self.free_slots.contains(&i) {+ continue;+ }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];@@ -80,9 +89,19 @@ impl Atlas {/// 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> {+ pub fn place(&mut self, width: u32, height: u32, wrap: bool, max_layers: u32) -> Option<(usize, Place)> {let size = content_size(width, height);let (w, h) = padded_size(size);+ // A rect a freed texture left, the smallest that holds it.+ if let Some(i) = (0..self.free_rects.len()).filter(|&i| self.free_rects[i].3 >= w && self.free_rects[i].4 >= h).min_by_key(|&i| self.free_rects[i].3 as u64 * self.free_rects[i].4 as u64) {+ let (layer, x, y, fw, fh) = self.free_rects.swap_remove(i);+ for r in [(layer, x + w, y, fw - w, h), (layer, x, y + h, fw, fh - h)] {+ if r.3 > 0 && r.4 > 0 {+ self.free_rects.push(r);+ }+ }+ return Some(self.take_slot(Place { layer, x, y, padded: (w, h), size, wrap }));+ }if w.max(h) > self.side {self.side = w.max(h).next_power_of_two().max(256);}@@ -114,11 +133,102 @@ impl Atlas {} else {return None;};- let place = Place { layer: layer as u32, x, y, padded: (w, h), size, wrap };- self.places.push(place);- return Some(place);+ return Some(self.take_slot(Place { layer: layer as u32, x, y, padded: (w, h), size, wrap }));+ }+ }++ /// A slot for `place`: a freed one (the lowest), or a new one.+ fn take_slot(&mut self, place: Place) -> (usize, Place) {+ let slot = match self.free_slots.iter().enumerate().min_by_key(|(_, s)| **s).map(|(i, _)| i) {+ Some(i) => {+ let s = self.free_slots.swap_remove(i);+ self.places[s] = place;+ s+ }+ None => {+ self.places.push(place);+ self.places.len() - 1+ }+ };+ (slot, place)+ }++ /// Frees the texture in `slot`: its slot and its rect are the next textures' (`place`). Its texels stay in the+ /// pages until another's are written there. False for a slot that holds none.+ pub fn free(&mut self, slot: usize) -> bool {+ if slot >= self.places.len() || self.free_slots.contains(&slot) {+ return false;+ }+ let p = self.places[slot];+ self.free_slots.push(slot);+ self.rebuild_free(p.layer);+ true+ }++ /// A layer's free room made again from what it holds, so that it does not depend on the order textures came and+ /// went: on a grid of ALIGN texels, the shelves' room less the textures held there. Free columns at the end of a+ /// shelf go back to it (its next x moves back) and a layer's last empty shelves go, room a texture of any size can+ /// take again; what is left is cut into rects row by row, each as wide and then as tall as it can be.+ fn rebuild_free(&mut self, layer: u32) {+ let n = (self.side / ALIGN) as usize;+ let cell = |v: u32| (v / ALIGN) as usize;+ // 1: free, 0: held or outside the shelves.+ let mut free = vec![0u8; n * n];+ let Some(shelves) = self.shelves.get_mut(layer as usize) else { return };+ for s in shelves.iter() {+ for y in cell(s.0)..cell(s.0 + s.1).min(n) {+ free[y * n..y * n + cell(s.2).min(n)].fill(1);+ }+ }+ for (i, p) in self.places.iter().enumerate() {+ if p.layer != layer || self.free_slots.contains(&i) {+ continue;+ }+ for y in cell(p.y)..cell(p.y + p.padded.1).min(n) {+ free[y * n + cell(p.x)..y * n + cell(p.x + p.padded.0).min(n)].fill(0);+ }+ }+ for s in shelves.iter_mut() {+ let rows = cell(s.0)..cell(s.0 + s.1).min(n);+ while s.2 > 0 && rows.clone().all(|y| free[y * n + cell(s.2) - 1] == 1) {+ s.2 -= ALIGN;+ for y in rows.clone() {+ free[y * n + cell(s.2)] = 0;+ }+ }+ }+ while shelves.last().is_some_and(|s| s.2 == 0) {+ shelves.pop();+ }+ self.free_rects.retain(|r| r.0 != layer);+ for y in 0..n {+ let mut x = 0;+ while x < n {+ if free[y * n + x] == 0 {+ x += 1;+ continue;+ }+ let mut w = 0;+ while x + w < n && free[y * n + x + w] == 1 {+ w += 1;+ }+ let mut h = 1;+ while y + h < n && free[(y + h) * n + x..(y + h) * n + x + w].iter().all(|&c| c == 1) {+ h += 1;+ }+ for yy in y..y + h {+ free[yy * n + x..yy * n + x + w].fill(0);+ }+ self.free_rects.push((layer, x as u32 * ALIGN, y as u32 * ALIGN, w as u32 * ALIGN, h as u32 * ALIGN));+ x += w;+ }}}++ /// Whether `slot` holds a texture.+ pub fn holds(&self, slot: usize) -> bool {+ slot < self.places.len() && !self.free_slots.contains(&slot)+ }}/// A texture's padded rect in the pages (aligned to `ALIGN`, so its mips are its own) and its content's size.@@ -188,7 +298,7 @@ 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]));- let atlas = Atlas { side: ALIGN, places: vec![], shelves: vec![vec![]] };+ let atlas = Atlas { side: ALIGN, places: vec![], shelves: vec![vec![]], ..Default::default() };return Packed { side: ALIGN, layers: vec![mip_chain(img)], info: atlas.info(), streams: vec![], atlas };}let src: Vec<std::borrow::Cow<image::RgbaImage>> = textures@@ -239,7 +349,7 @@ pub fn pack(textures: &[Texture]) -> Packed {}}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 atlas = Atlas { side, places, shelves, ..Default::default() };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)@@ -443,13 +553,17 @@ mod tests {fn sound(what: &str, a: &Atlas) {let info = a.info();for (i, p) in a.places.iter().enumerate() {+ if !a.holds(i) {+ assert_eq!((info[i * 2], info[i * 2 + 1]), ([0.0; 4], [0.0; 4]), "{what}: freed slot {i} has no rows");+ continue;+ }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) {+ for (j, q) in a.places.iter().enumerate().skip(i + 1).filter(|(j, _)| a.holds(*j)) {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:?}");}@@ -469,18 +583,18 @@ mod tests {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();+ let small = a.place(64, 40, false, 8).unwrap().1;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();+ let p = a.place(200, 120, true, 8).unwrap().1;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();+ let big = a.place(2048, 1024, true, 8).unwrap().1;assert_eq!((a.side, big.size, big.padded), (2048, (2016, 992), (2048, 1024)));assert_eq!(a.places[..3], before[..]);sound("a longer side", &a);@@ -488,26 +602,93 @@ mod tests {// 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();+ let p = b.place(224, 224, true, 1).unwrap().1;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![]] };+ let mut c = Atlas { side: MAX_PAGE, places: vec![], shelves: vec![vec![]], ..Default::default() };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();+ let tall = d.place(60, 150, true, 8).unwrap().1;assert!((tall.layer, tall.y) != (0, 0), "not on the shelf that is too low: {tall:?}");- d.place(200, 60, true, 8).unwrap();+ d.place(200, 60, true, 8).unwrap().1;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();+ let first = e.place(100, 60, true, 8).unwrap().1;assert_eq!((e.side, first.layer, first.x, first.y), (256, 0, 0, 0));sound("the first", &e);}+ /// Freed textures give their slots and rects to the next: the lowest slot first, the smallest rect that holds+ /// the texture, the rest of it to the next; the pages grow only when the freed room is not enough. Textures come+ /// and go a thousand times without the pages growing.+ #[test]+ fn freed_textures_give_their_room_to_the_next() {+ let flat = |w: u32, h: u32| tex(w, h, true, |_, _| [9, 9, 9, 255]);+ let mut a = pack(&[flat(300, 200), flat(100, 60), flat(200, 200)]).atlas;+ let before = a.places.clone();+ assert!(a.free(1) && !a.free(1) && !a.free(7) && !a.holds(1));+ sound("one freed", &a);+ // A smaller one: slot 1 again, in the room it left (the pages as they were).+ let (side, layers) = (a.side, a.layers());+ let (slot, p) = a.place(40, 20, false, 8).unwrap();+ assert_eq!((slot, p.layer, a.side, a.layers()), (1, 0, side, layers));+ sound("a smaller one in it", &a);+ let (slot, _) = a.place(16, 16, false, 8).unwrap();+ assert_eq!((slot, a.side, a.layers()), (3, side, layers), "a new slot: none is free");+ sound("another", &a);+ // Larger than the room freed: a place of its own.+ a.free(0);+ let (slot, big) = a.place(600, 600, true, 8).unwrap();+ assert_eq!(slot, 0);+ assert!(big.layer > 0 || a.side > side, "{big:?}");+ sound("a larger one", &a);+ // GLB places that come and go (textures of 256-2048 a side, as models have them, ten at a time): the pages+ // stay as large as the most there were at once needs.+ let mut g = pack(&[]).atlas;+ let sizes = [(1024, 1024), (2048, 2048), (512, 512), (1024, 1024), (256, 256), (2048, 1024), (512, 512), (1024, 512)];+ let mut live: std::collections::VecDeque<usize> = Default::default();+ let mut most = (0, 0);+ for k in 0..2000usize {+ let (w, h) = sizes[(k * 7 + k / 3) % sizes.len()];+ live.push_back(g.place(w, h, true, 64).unwrap().0);+ if live.len() > 10 {+ g.free(live.pop_front().unwrap());+ }+ if k == 200 {+ most = (g.side, g.layers());+ }+ if k % 199 == 0 {+ sound(&format!("place {k}"), &g);+ }+ }+ assert!(g.side == most.0 && g.layers() <= most.1 + 1, "the pages grew: {} layers of {} (after 200 places: {} of {})", g.layers(), g.side, most.1, most.0);+ assert!(g.places.len() <= 11, "slots are taken again: {}", g.places.len());+ // Any sizes, freed as soon as placed: the freed room is taken again, so the pages stop growing (what the+ // pieces of a cut cannot hold takes new room for a while; ten thousand rounds after the first thousand add+ // nothing).+ let mut after = (0, 0);+ for k in 0..11000u32 {+ let (w, h) = (64 + (k * 37) % 400, 64 + (k * 53) % 300);+ let (s1, _) = a.place(w, h, true, 64).unwrap();+ let (s2, _) = a.place(h, w, true, 64).unwrap();+ if k % 997 == 0 {+ sound(&format!("round {k}"), &a);+ }+ a.free(s1);+ a.free(s2);+ if k == 999 {+ after = (a.side, a.layers());+ }+ }+ sound("after them", &a);+ assert!(a.places.len() <= 6, "slots are taken again: {}", a.places.len());+ assert_eq!((a.side, a.layers()), after, "the pages grew after the first thousand rounds");+ }+#[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 a20a0ea..2cc609f 100644--- a/renderer/src/world.rs+++ b/renderer/src/world.rs@@ -304,6 +304,9 @@ pub struct Changes {pub sun: bool,/// Another sky (its kind or its parameters): baked and put in place (live/edits.rs `apply_sky`). With `environment`.pub sky: bool,+ /// Files whose last model left the world in this batch (`World::models`): the live view retires their materials+ /// and frees the textures nothing names any more (live/edits.rs `retire_models`), unless one came back.+ pub gone_models: HashSet<String>,/// A planet's viewer altitude, the sky otherwise the same (`desc::Sky::Atmosphere::altitude`): re-baked in place/// past a step (live/edits.rs `move_altitude`). With `environment`.pub altitude: bool,@@ -365,6 +368,10 @@ pub struct World {/// How many objects each object is the parent of (`remove` skips the scan for children of a childless one: a/// streamed city removes thousands of objects a frame among tens of thousands). Kept by `set_object` and `remove`.kids: HashMap<u32, u32>,+ /// How many objects are models of each file (`scene::model_key`: the file and its material functions). Kept by+ /// `set_object` and `remove`; a key's last model gone is `Changes::gone_models`, whose materials the live view+ /// retires (live/edits.rs `retire_models`).+ pub models: HashMap<String, u32>,pub geometries: HashMap<u32, Arc<Geometry>>,pub textures: HashMap<u32, Texture>,pub materials: HashMap<u32, desc::Material>,@@ -406,6 +413,7 @@ impl Default for World {World {objects: BTreeMap::new(),kids: HashMap::new(),+ models: HashMap::new(),geometries: HashMap::new(),textures: HashMap::new(),materials: HashMap::new(),@@ -651,10 +659,13 @@ impl World {*self.kids.entry(p).or_default() += 1;}}- let o = match self.objects.remove(&id) {+ let o = match self.take_object(id) {Some(o) => Object { name, parent, kind, cast_shadow, movable: movable || o.movable, ..o },None => Object { name, parent, kind, position: Vec3::ZERO, rotation: Quat::IDENTITY, scale: Vec3::ONE, visible: true, cast_shadow, power: 1.0, custom: [0.0; 4], movable, driven: false, sway: None, sway_rot: Quat::IDENTITY },};+ if let Kind::Model { uri, functions, .. } = &o.kind {+ *self.models.entry(crate::scene::model_key(uri, functions)).or_default() += 1;+ }self.objects.insert(id, o);if fresh {self.changes.added.insert(id);@@ -1051,6 +1062,22 @@ impl World {self.geometries.remove(&id).is_some() | self.proc_geometries.remove(&id).is_some()}+ /// Takes object `id` out of `objects`, counting it out of `models` (a file's last model: `Changes::gone_models`).+ fn take_object(&mut self, id: u32) -> Option<Object> {+ let o = self.objects.remove(&id)?;+ if let Kind::Model { uri, functions, .. } = &o.kind {+ let key = crate::scene::model_key(uri, functions);+ if let Some(n) = self.models.get_mut(&key) {+ *n = n.saturating_sub(1);+ if *n == 0 {+ self.models.remove(&key);+ self.changes.gone_models.insert(key);+ }+ }+ }+ Some(o)+ }+pub fn remove(&mut self, id: u32) -> Vec<u32> {let mut doomed = vec![id];let mut k = 0;@@ -1084,12 +1111,12 @@ impl World {for (d, lit) in doomed.iter().zip(&lit) {self.instanced.remove(d);if *lit {- self.objects.remove(d);+ self.take_object(*d);self.changes.lights.insert(*d);} else if self.objects.get(d).is_some_and(mist) {- self.objects.remove(d);+ self.take_object(*d);self.changes.media = true;- } else if self.objects.remove(d).is_some_and(|o| !matches!(o.kind, Kind::Group | Kind::Camera(_))) && !self.changes.added.remove(d) {+ } else if self.take_object(*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@@ -1106,7 +1133,7 @@ impl World {}for &d in &doomed {self.instanced.remove(&d);- if self.objects.remove(&d).is_some() {+ if self.take_object(d).is_some() {mark_structural(&mut self.changes, line!());}}