Skip to content

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.

Streaming models in place: models with material functions the kernel has, preloadModel, faster vertex sharing (#276)

Evan (Yifeng) Wang3038e08ca5cf
diff --git a/docs/RUNTIME.md b/docs/RUNTIME.md
index 5db33be..4cd7da9 100644
--- a/docs/RUNTIME.md
+++ b/docs/RUNTIME.md
@@ -866,11 +866,18 @@ reads files under the asset root as it goes and adds what they hold without rebu
- **The binding syncs what changed.** Objects added under a parent or taken from one since the last sync are bound or
dropped with their subtrees; the graph is walked whole only at the first sync. A world removes a childless object
without looking for its children (`World::remove` keeps a count of each object's children).
-- **In place:** a new mesh (any geometry) with materials the scene has; a model whose file the scene has (another
- copy); moving or showing an object the build placed as an instance; new materials without textures that neither
- emit nor are glass.
-- **Rebuilds:** a new group (place the meshes themselves under groups the scene made); a material with textures or a
- function that the scene has not seen (make every material at setup, and put each on a mesh, out of sight if need
+- **`preloadModel(uri, nodeSets?)`** (`@threert/scene`; `__engine.preloadModel`): parses a GLB under the asset root on
+ a worker thread (its buffers, images and tangents into the process's parse cache) and reads the triangles of each
+ node set given (the `nodes` of the still `GLTFModel`s of it to come). A model of it added a few frames later goes in
+ without that work in its frame's commit: TokyoRT's far tiles, ~80 k triangles and 13 models each, from 30-90 ms of
+ commit to ~10.
+- **In place:** a new mesh (any geometry) with materials the scene has; a still model, of a file the scene has or not,
+ without material functions or with functions the scene's kernel has (its materials are made in place as a build
+ makes them); moving or showing an object the build placed as an instance; new materials without textures that
+ neither emit nor are glass.
+- **Rebuilds:** a new group (place the meshes themselves under groups the scene made); a posed model with material
+ functions, or a model with a function the scene's kernel has not; a material with textures or a function that the
+ scene has not seen (make every material at setup, and put each on a mesh, out of sight if need
be); showing an object that was hidden when the scene was built or rebuilt (move it out of sight instead of hiding
it); a model of nodes the file lacks (it draws nothing and has no instance to hide).
- **Emitters cost the commit**: each commit that adds or removes emitting triangles writes the emitter CDF and the
diff --git a/packages/scene/src/engine.ts b/packages/scene/src/engine.ts
index e434b0f..bef2bfe 100644
--- a/packages/scene/src/engine.ts
+++ b/packages/scene/src/engine.ts
@@ -201,6 +201,8 @@ export interface Engine extends RenderingBinding {
/** `colors`: the vertex colours (three.js's `color` attribute), linear RGB per vertex. */
/** A file under the asset root, whole or a range (native only; a page's throws): `readAsset` below. */
readAsset?(path: string, offset?: number, length?: number): ArrayBuffer;
+ /** A model file parsed on a worker thread ahead of its use (native only): `preloadModel` below. */
+ preloadModel?(uri: string, nodeSets?: string): boolean;
geometry(id: number, positions: Float32Array, normals: Float32Array, uvs: Float32Array, indices: Uint32Array, groups?: Uint32Array | null, colors?: Float32Array | null): void;
texture(id: number, desc: TextureDesc, data: Uint8Array | null): void;
shader(name: string, code: string, helpers: string): void;
@@ -1686,6 +1688,17 @@ export function readAsset(path: string, offset?: number, length?: number): Array
return offset === undefined ? e.readAsset(path) : e.readAsset(path, offset, length ?? 0);
}
+/**
+ * Parses a model file (a GLB under the asset root) on a worker thread now, and reads the triangles of each of
+ * `nodeSets` (the `nodes` of the still `GLTFModel`s of it to come; null: the whole file), so that those models added
+ * later go in without that work in their frame (native renderer only; elsewhere, or for a path outside the root,
+ * false and nothing done). What a game streams models in by: its next ones preloaded a few frames ahead.
+ */
+export function preloadModel(uri: string, nodeSets: (string[] | null)[] = []): boolean {
+ const e = (globalThis as { __engine?: Partial<Pick<Engine, "preloadModel">> }).__engine;
+ return e?.preloadModel?.(uri, JSON.stringify(nodeSets)) ?? false;
+}
+
export function cameraDesc(c: PerspectiveCamera): CameraDesc {
return { fov: c.fov, near: c.near, far: c.far, exposure: { ...c.exposure }, ...(c.dof ? { dof: { ...c.dof } } : {}) };
}
diff --git a/renderer/src/indexed.rs b/renderer/src/indexed.rs
index e3b8b7a..77af74d 100644
--- a/renderer/src/indexed.rs
+++ b/renderer/src/indexed.rs
@@ -51,9 +51,43 @@ fn corner(a: &GpuTriAttr, c: usize) -> ([f32; 3], [f32; 2], [f32; 4]) {
/// `n` triangles as shared vertices. `vertex(k, c)`: corner c of triangle k: what tells it from every other vertex,
/// and its record. Two corners are one vertex where their keys are equal.
+/// A hasher for keys of plain words (vertices' bits, triangles' corners), several times SipHash's speed: FxHash's mix
+/// (rustc's). No map keyed with it is iterated, and its keys come from the scene, not from an adversary.
+#[derive(Default, Clone, Copy)]
+pub struct FastHash(u64);
+impl FastHash {
+ #[inline]
+ fn add(&mut self, x: u64) {
+ self.0 = (self.0.rotate_left(5) ^ x).wrapping_mul(0x51_7c_c1_b7_27_22_0a_95);
+ }
+}
+impl std::hash::Hasher for FastHash {
+ fn finish(&self) -> u64 {
+ self.0
+ }
+ fn write(&mut self, bytes: &[u8]) {
+ for c in bytes.chunks(8) {
+ let mut w = [0u8; 8];
+ w[..c.len()].copy_from_slice(c);
+ self.add(u64::from_le_bytes(w));
+ }
+ }
+ fn write_u32(&mut self, x: u32) {
+ self.add(x as u64);
+ }
+ fn write_u64(&mut self, x: u64) {
+ self.add(x);
+ }
+ fn write_usize(&mut self, x: usize) {
+ self.add(x as u64);
+ }
+}
+pub type FastMap<K, V> = HashMap<K, V, std::hash::BuildHasherDefault<FastHash>>;
+pub type FastSet<K> = std::collections::HashSet<K, std::hash::BuildHasherDefault<FastHash>>;
+
fn share<K: Hash + Eq>(n: usize, vertex: impl Fn(usize, usize) -> (K, Vertex)) -> Scope {
let mut s = Scope { indices: Vec::with_capacity(n), ..Default::default() };
- let mut seen: HashMap<K, u32> = HashMap::with_capacity(n);
+ let mut seen: FastMap<K, u32> = FastMap::with_capacity_and_hasher(n, Default::default());
// (A triangle with a corner that is not finite: three times one vertex at the origin, a triangle without size,
// which no ray meets. The BLASes are built from these positions.)
let mut nowhere = None;
diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rs
index 19d4a5c..2cd7bb1 100644
--- a/renderer/src/live/edits.rs
+++ b/renderer/src/live/edits.rs
@@ -1656,15 +1656,21 @@ impl LiveCore {
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() {
+ let Some(crate::world::Kind::Model { uri, nodes, functions, animation }) = world.objects.get(id).map(|o| &o.kind) else { continue };
+ // (A model with material functions: its own copies of the file's materials, the functions' on those that
+ // name them, as the build makes them; only a still one whose functions the scene's kernel has: the rest is
+ // the rebuild's, as `edit_geometry` says.)
+ let shaders = &self.sc.tables.retained.shaders;
+ if !functions.is_empty() && (animation.is_some() || functions.iter().any(|f| !shaders.contains_key(f.shader.id.as_str()))) {
continue;
}
+ let shaders = shaders.clone();
+ let key = scene::model_key(uri, functions);
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) {
+ let mkey = (key.clone(), idx.unwrap_or(usize::MAX));
+ if self.sc.tables.retained.asset_materials.contains_key(&mkey) {
continue;
}
let g = &self.g;
@@ -1677,8 +1683,21 @@ impl LiveCore {
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);
+ let gltf_mat = idx.and_then(|i| doc.materials().nth(i));
+ let name = gltf_mat.as_ref().and_then(|m| m.name()).unwrap_or_default().to_string();
+ let mut gm = scene::gltf_material(gltf_mat, images, uri, &mut texture, &Default::default())?;
+ // The first function whose prefix the material's name starts with, on the glTF shading (its textures
+ // the world's, as the build places them).
+ if let Some(f) = functions.iter().find(|f| name.starts_with(f.prefix.as_str())) {
+ let assets = &self.assets;
+ scene::apply_shader(&mut gm, &f.shader, &shaders, &mut |tid, srgb_default| {
+ let t = world.textures.get(&tid).ok_or_else(|| anyhow::anyhow!("unknown texture {tid}"))?;
+ let (tkey, img) = scene::texture_image(t, assets)?;
+ texture((tkey, t.srgb && srgb_default), t.wrap, &mut || Ok(img.clone()))
+ })
+ .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);
made = true;
}
@@ -2947,9 +2966,12 @@ impl LiveCore {
// 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());
+ // (With material functions: a still one whose functions the scene's kernel has, its materials made
+ // by `place_models`, its mesh kept under the file with its functions, as the build keeps them.)
+ if !functions.is_empty() && (animation.is_some() || functions.iter().any(|f| !tables.retained.shaders.contains_key(f.shader.id.as_str()))) {
+ return Err("a model with material functions the scene has not got, or posed (its materials load with a rebuild)".into());
}
+ let key = scene::model_key(uri, functions);
if features & gpu::F_INST == 0 || m.determinant() == 0.0 || std::env::var("THREERT_INSTANCING").is_ok_and(|v| v == "0") {
return Err("a model the build would flatten (no size, instancing off, or the scene's first instance)".into());
}
@@ -3125,17 +3147,36 @@ 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 = match tables.retained.model_mesh.get(&(uri.clone(), nodes.clone())).copied() {
+ let mesh = match tables.retained.model_mesh.get(&(key.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())?;
+ // (read ahead on a worker if the game preloaded them: `preloadModel`)
+ let local = match scene::take_prepared(uri, nodes) {
+ Some(t) => t,
+ None => {
+ if std::env::var("THREERT_EDIT_LOG").is_ok_and(|v| v == "1") {
+ eprintln!("edit: {uri} {nodes:?}: triangles read now (not preloaded)");
+ }
+ 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();
+ // (each of the file's materials looked up once: the key is the file with its functions)
+ let mut mat_of: std::collections::HashMap<usize, 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 idx = t.material.unwrap_or(usize::MAX);
+ let mat = match mat_of.get(&idx) {
+ Some(&m) => m,
+ None => {
+ let m = *tables.retained.asset_materials.get(&(key.clone(), idx)).ok_or("a model's material that was not made")?;
+ mat_of.insert(idx, m);
+ m
+ }
+ };
let gm = &tables.materials[mat as usize];
classed[scene::mesh_class(gm) as usize].push((k, mat));
if scene::emissive(gm) {
@@ -3160,7 +3201,7 @@ impl LiveCore {
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);
+ tables.retained.model_mesh.insert((key.clone(), nodes.clone()), k);
k
}
};
diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rs
index e2f647c..c762354 100644
--- a/renderer/src/live/inplace_tests.rs
+++ b/renderer/src/live/inplace_tests.rs
@@ -4825,3 +4825,53 @@ fn density_grids_come_and_change_in_place() {
check("every volume removed", &mut live, &mut w, &[]);
assert_eq!((live.g.grids_state(&live.sc.up).0, live.sc.up.kernel.features & (gpu::F_MEDIA | gpu::F_GRID)), (vec![], 0), "no grid: the kernel without its media code");
}
+
+/// Models with material functions the scene's kernel has come in place (a streamed city's far tiles: each tile's
+/// ground, buildings and windows a model with the city's functions): another of a model the scene has, and one of a
+/// file it has not got, its materials made as a build makes them (its own copies, the function on those its prefix
+/// names), and one with a function that comes in the same commit. Each time no rebuild, and the picture is a build's.
+#[test]
+fn models_with_functions_the_scene_has_come_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 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 tinted = |uri: &str, id: &str| Kind::Model {
+ uri: uri.into(),
+ nodes: None,
+ animation: None,
+ functions: vec![crate::desc::ModelFunction { prefix: String::new(), shader: crate::desc::ShaderRef { id: id.into(), params: vec![], textures: vec![] } }],
+ };
+ let mut w = world();
+ w.set_shader("zz_red", function("zz_red", "0.9, 0.05, 0.05"), String::new());
+ w.set_object(30, "first".into(), None, tinted("tests/render/data/panel.glb", "zz_red"), true, false).unwrap();
+ w.set_transform(30, Vec3::new(-0.5, 0.3, 0.8), glam::Quat::IDENTITY, Vec3::splat(0.5)).unwrap();
+ // (A mesh the scene says it edits: room for what is placed.)
+ w.set_object(28, "own".into(), None, Kind::Mesh { geometry: 3, material: 1, own_blas: true, materials: vec![] }, true, false).unwrap();
+ w.set_transform(28, Vec3::new(0.9, -0.1, 0.4), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ let mut live = match open(&w) {
+ Ok(c) => c,
+ Err(e) => return eprintln!("skipped: {e}"),
+ };
+ w.take_changes();
+ 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;
+ };
+ w.set_object(31, "again".into(), None, tinted("tests/render/data/panel.glb", "zz_red"), true, false).unwrap();
+ w.set_transform(31, Vec3::new(0.5, -0.3, 0.9), glam::Quat::from_rotation_y(0.3), Vec3::splat(0.5)).unwrap();
+ check("another of the model with its function", &mut live, &mut w);
+ w.set_object(32, "other file".into(), None, tinted("tests/render/data/quad.glb", "zz_red"), true, false).unwrap();
+ w.set_transform(32, Vec3::new(0.3, -0.3, 1.0), glam::Quat::IDENTITY, Vec3::splat(1.2)).unwrap();
+ check("a file the scene has not got, with the function", &mut live, &mut w);
+ // (a function that comes with the model: the kernel has it by the time the model's materials are made)
+ w.set_shader("aa_green", function("aa_green", "0.05, 0.9, 0.05"), String::new());
+ w.set_object(33, "new function".into(), None, tinted("tests/render/data/panel.glb", "aa_green"), true, false).unwrap();
+ w.set_transform(33, Vec3::new(-0.2, -0.5, 1.1), glam::Quat::IDENTITY, Vec3::splat(0.5)).unwrap();
+ check("a model with a function that came in the same commit", &mut live, &mut w);
+}
diff --git a/renderer/src/scene.rs b/renderer/src/scene.rs
index 3842dca..1861723 100644
--- a/renderer/src/scene.rs
+++ b/renderer/src/scene.rs
@@ -1273,7 +1273,7 @@ fn bytes_key(kind: &str, bytes: &[u8]) -> String {
}
/// Decoded texture image + its cache identity (files: path version; generated: the bytes' content).
-fn texture_image(t: &world::Texture, assets: &Path) -> Result<(String, Arc<image::RgbaImage>)> {
+pub fn texture_image(t: &world::Texture, assets: &Path) -> Result<(String, Arc<image::RgbaImage>)> {
match &t.source {
world::TextureSource::File(uri) => {
let path = crate::files::asset_path(assets, uri);
@@ -1298,6 +1298,31 @@ fn texture_image(t: &world::Texture, assets: &Path) -> Result<(String, Arc<image
}
/// A model file (cached per file version).
+/// Still models' triangles read ahead (`prepare_triangles`, a game's `preloadModel` with the node sets it will add):
+/// by (uri, nodes), taken by the first model added in place that wants them (live/edits.rs).
+#[allow(clippy::type_complexity)]
+static PREPARED: std::sync::Mutex<Option<HashMap<(String, Option<Vec<String>>), Vec<skin::ModelTri>>>> = std::sync::Mutex::new(None);
+
+/// The model's triangles for `nodes` (all of them: None), read now (a worker thread's job) for a model of them added
+/// later in place: that commit then only sorts them by material and places them.
+pub fn prepare_triangles(uri: &str, assets: &Path, nodes: Option<Vec<String>>) -> Result<()> {
+ let glb = model_gltf(uri, assets)?;
+ let t = glb.triangles(Mat4::IDENTITY, nodes.as_deref(), None)?;
+ let mut c = PREPARED.lock().unwrap();
+ let c = c.get_or_insert_with(HashMap::new);
+ // (bounded: what was read and never added goes)
+ if c.len() > 4096 {
+ c.clear();
+ }
+ c.insert((uri.to_string(), nodes), t);
+ Ok(())
+}
+
+/// Triangles `prepare_triangles` read for (uri, nodes), if it has: taken.
+pub fn take_prepared(uri: &str, nodes: &Option<Vec<String>>) -> Option<Vec<skin::ModelTri>> {
+ PREPARED.lock().unwrap().as_mut()?.remove(&(uri.to_string(), nodes.clone()))
+}
+
pub fn model_gltf(uri: &str, assets: &Path) -> Result<Arc<skin::Model>> {
let path = crate::files::asset_path(assets, uri);
cached_gltf(&file_key(&path), || skin::Model::new(import_gltf(&path).with_context(|| format!("asset {uri}"))?))
@@ -1346,6 +1371,13 @@ pub fn build_material(id: u32, m: &desc::Material, textures: &HashMap<u32, world
/// A material function's binding on a GPU material: the function, its 32 parameters and its textures (`tex(texture,
/// sRGB requested)`).
+/// What a model's materials and meshes are kept under (`Retained::asset_materials`, `model_mesh`): its file, with its
+/// material functions if it has any (its materials are its own copies of the file's then, and placements share a mesh
+/// only with the same functions).
+pub fn model_key(uri: &str, functions: &[desc::ModelFunction]) -> String {
+ if functions.is_empty() { uri.to_string() } else { format!("{uri}\u{0}{functions:?}") }
+}
+
pub fn apply_shader(gm: &mut GpuMaterial, sh: &desc::ShaderRef, shaders: &HashMap<String, i32>, tex: &mut dyn FnMut(u32, bool) -> Result<i32>) -> Result<()> {
let f = *shaders.get(sh.id.as_str()).ok_or_else(|| anyhow!("unknown material function {}", sh.id))?;
gm.tex1[3] = f + 1;
@@ -1832,7 +1864,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
let glb = model_gltf(uri, assets)?;
let (doc, _, images) = &glb.gltf;
// (A model with material functions has its own copies of the file's materials.)
- let key = if functions.is_empty() { uri.clone() } else { format!("{uri}\u{0}{functions:?}") };
+ let key = model_key(uri, functions);
// (Its meshes too: placements share a mesh only with the same functions.)
let mesh_key = (key.clone(), nodes.clone());
// A material of the file: its index, its class in a mesh (`mesh_class`), whether it only emits.
@@ -1961,7 +1993,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
let (order, sects, mine) = model_sections(&kept(&classed));
// (The model's corners in its mesh's order: one copy for every placement of the model.)
let mirrors = glb.mirrored(Some(a))?;
- let file = if functions.is_empty() { uri.clone() } else { format!("{uri}\u{0}{functions:?}") };
+ let file = model_key(uri, functions);
let skey = (file, nodes.clone(), mirrors.clone());
let (source, tri_order) = match skin_source_of.get(&skey) {
Some(s) => s.clone(),
@@ -2463,11 +2495,15 @@ pub fn split_coincident(classed: &mut [Vec<(usize, u32)>; 4], emitting: &std::co
v.sort_unstable();
v
};
- type Keys = std::collections::HashSet<[[u32; 3]; 3]>;
- let emitters: Keys = classed[0].iter().filter(|(_, mat)| emitting.contains(mat)).map(|&(k, _)| key(k)).collect();
- let under: Keys = classed[..2].iter().flatten().map(|&(k, _)| key(k)).collect();
+ type Keys = crate::indexed::FastSet<[[u32; 3]; 3]>;
+ // (each class's keys made only where it has triangles to check: most models have no cutout and no glass)
+ let emitters: Keys = if classed[1].is_empty() { Keys::default() } else { classed[0].iter().filter(|(_, mat)| emitting.contains(mat)).map(|&(k, _)| key(k)).collect() };
+ let under: Keys = if classed[2].is_empty() { Keys::default() } else { classed[..2].iter().flatten().map(|&(k, _)| key(k)).collect() };
let mut over = vec![];
for (class, on) in [(1, &emitters), (2, &under)] {
+ if on.is_empty() {
+ continue;
+ }
let (stay, go): (Vec<_>, Vec<_>) = classed[class].iter().partition(|&&(k, _)| !on.contains(&key(k)));
classed[class] = stay;
over.extend(go.into_iter().map(|(k, mat)| (k, mat, class as u32)));
diff --git a/renderer/src/script.rs b/renderer/src/script.rs
index d7141a6..464e873 100644
--- a/renderer/src/script.rs
+++ b/renderer/src/script.rs
@@ -395,6 +395,33 @@ fn install_engine<'js>(ctx: &Ctx<'js>, world: &Rc<RefCell<World>>, voxels: &Rc<R
let bytes = read_asset(&path, range).map_err(|e| fail(&ctx, e))?;
rquickjs::ArrayBuffer::new(ctx, bytes)
})?)?;
+ // preloadModel(uri, nodeSets?): the model file parsed on a worker thread into the process's parse cache (its
+ // buffers, images and tangents), and the triangles of each node set (JSON: [["a", "b"], ...]; null: the whole
+ // model) read, so a still GLTFModel of them added later in place does neither in that frame's commit (a streamed
+ // city's far tiles: ~30-90 ms each). False for a path outside the asset root or node sets that are no such list.
+ e.set("preloadModel", Function::new(ctx.clone(), move |uri: String, sets: rquickjs::function::Opt<String>| -> bool {
+ let p = std::path::Path::new(&uri);
+ if !p.is_relative() || p.components().any(|c| matches!(c, std::path::Component::ParentDir)) {
+ return false;
+ }
+ let sets: Vec<Option<Vec<String>>> = match sets.0 {
+ Some(j) => match serde_json::from_str(&j) {
+ Ok(v) => v,
+ Err(_) => return false,
+ },
+ None => vec![],
+ };
+ let root = ASSET_ROOT.read().unwrap().clone().unwrap_or_else(|| std::path::PathBuf::from("."));
+ rayon::spawn(move || {
+ if crate::scene::model_gltf(&uri, &root).is_err() {
+ return;
+ }
+ for nodes in sets {
+ let _ = crate::scene::prepare_triangles(&uri, &root, nodes);
+ }
+ });
+ true
+ })?)?;
let w = world.clone();
// (…, groups?, colors?): the optional arguments as the rest (rquickjs takes seven parameters at most).
e.set("geometry", Function::new(ctx.clone(), move |ctx: Ctx<'js>, id: u32, p: TypedArray<f32>, n: TypedArray<f32>, uv: TypedArray<f32>, idx: TypedArray<u32>, rest: rquickjs::function::Rest<Value<'js>>| -> rquickjs::Result<()> {