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.

The build flattens nothing: a skinned model keeps its emitters, THREERT_INSTANCING goes (#273)

Yujia2146e6331620
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 3e01e45..a5acdf2 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -2920,6 +2920,21 @@ Mutations: 26. 25 failed a test there was; one, a texture put on a shelf too low
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.
+**The build flattens nothing (2026-11-25, after them).** The last two things it flattened:
+- A posed skinned model with triangles that emit was flattened whole and skinned on the CPU. It is a skinned
+ instance as any other, and the triangles are its instance's emitters: at a new pose the light list's copies are
+ taken again on the GPU from the skinned vertices, the CPU places the emitting triangles alone (the light tree's
+ moving subtree is refit by them) and their weights follow the pose's areas. One placed without size is an
+ instance no ray sees. A cutout on exactly an emitter's vertices is left out of a skinned model's mesh: it is
+ one mesh, where the cutout's holes would take the emitter with them, and what is drawn is the emitter, as where
+ the two are meshes apart.
+- `THREERT_INSTANCING=0`, the flattened reference of the instancing step, is gone with the build's arms it alone
+ reached (a mesh's, an instanced object's copies', a model's). `tools/check-instancing.ts` holds software
+ traversal to hardware traversal's render now.
+
+World-space triangles are left under software traversal alone, where an instance is no unit (lib.rs
+`flatten_instances`, `flatten_deforming`); what read them under hardware traversal is not deleted yet.
+
**A light's card, a coincident pair and a model without size are instances (2026-11-25, after it).** Three of the
things the build still flattened into world-space triangles:
- A visible rect light's card is an instance of one card mesh, a unit quad: its size is its transform's, its
@@ -2932,8 +2947,8 @@ things the build still flattened into world-space triangles:
by a rebuild (it was re-transformed on the CPU).
- A model placed without size is an instance no ray sees, as a mesh is.
-Flattened still: a posed skinned model with triangles that emit, and a scene under `THREERT_INSTANCING=0`; under
-software traversal, what has no unit. Which of a pair is drawn is as it was: a scene with the pair near and far
+Flattened still then: a posed skinned model with triangles that emit, and a scene under `THREERT_INSTANCING=0`;
+under software traversal, what has no unit. Which of a pair is drawn is as it was: a scene with the pair near and far
renders to main's picture, byte for byte, under both traversals.
**Five A/B switches and the uniform tables are removed (2026-11-25).** Switches whose question was answered, or
diff --git a/docs/RUNTIME.md b/docs/RUNTIME.md
index 4cd7da9..46a6a07 100644
--- a/docs/RUNTIME.md
+++ b/docs/RUNTIME.md
@@ -1626,7 +1626,8 @@ Vertices and indices, one layout for hardware and software traversal (`renderer/
the section has the material and where the section's triangles and emitters start; its instance's record has
its object and whether its mesh deforms (`INST_DEFORMS`). A light sample is told its emitter's section by the
light list's record (64 bytes). The record a pixel is left to `finish` by has 16 bits for it (`MESH_SECTIONS`).
-- **Rows** (`Stream::Triangles`, four words). A triangle no instance places (what the build still flattens)
+- **Rows** (`Stream::Triangles`, four words). A triangle no instance places (software traversal's, where an
+ instance is no unit: the build places every triangle by an instance)
has one: its material, its object, its flags, its emitter + 1. They are all the GPU holds: the world-space
triangles'.
- **Software traversal's leaves** (`leaves`, binding 2; `indexed::Leaf`). A tree keeps its triangles itself, as an
@@ -1645,8 +1646,7 @@ Vertices and indices, one layout for hardware and software traversal (`renderer/
triangle's index in the mesh / 2 past it (kernel feature `F_PART`). A system the lights are sampled by has an
emitter a triangle among its instance's, weighed by half the particle's nominal area and taken again from the
vertices every frame. A translucent system's instance is hidden from the scene's TLAS and is an instance of
- the translucency pass's own. The same whatever `THREERT_INSTANCING` says; under software traversal the passes
- do not run.
+ the translucency pass's own. Under software traversal the passes do not run.
- **Tangents.** A vertex's own: the tangent at a hit is its triangle's three vertices' there, the hand its first
vertex's, placed by its instance (`hit_tangent`; read only where a frame is asked, by a normal map or a
function). A model's file gives them; a primitive of a file that has UVs and no tangents has them made where it
diff --git a/renderer/shaders/pathtrace.wgsl b/renderer/shaders/pathtrace.wgsl
index 19ad074..5c38a41 100644
--- a/renderer/shaders/pathtrace.wgsl
+++ b/renderer/shaders/pathtrace.wgsl
@@ -323,7 +323,7 @@ fn tri_indices(ti: u32) -> vec3<u32> {
let k = P.word_first[1].x + ti * 3u;
return vec3<u32>(words[k], words[k + 1u], words[k + 2u]);
}
-// The row of a triangle no instance places (what the build flattens), four words:
+// The row of a triangle no instance places (software traversal's, of an instance that is no unit), four words:
// its material, its object, its flags (TRI_*), its emitter entry + 1. A mesh's triangle has none: which section of
// its mesh it is in is its hit's to say (`Hit.part`), and the rest is its instance's.
fn tri_row(row: u32) -> vec4<u32> {
diff --git a/renderer/src/indexed.rs b/renderer/src/indexed.rs
index 77af74d..af2e72f 100644
--- a/renderer/src/indexed.rs
+++ b/renderer/src/indexed.rs
@@ -14,7 +14,7 @@ use std::hash::Hash;
pub type Vertex = [[f32; 4]; 3];
pub const VERTEX_BYTES: usize = std::mem::size_of::<Vertex>();
-/// The row of a triangle no instance places (what the build flattens): its material, its
+/// The row of a triangle no instance places (software traversal's, of an instance that is no unit): its material, its
/// object, its flags (`scene::TRI_*`), its emitter entry + 1. A mesh's triangle needs none on the GPU: a ray's hit
/// says which section of its mesh it is in, and the rest is its instance's. (The build has one for every triangle,
/// a mesh's with its section and its index there: `Indexed::rows`.)
diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rs
index 2cd7bb1..072311c 100644
--- a/renderer/src/live/edits.rs
+++ b/renderer/src/live/edits.rs
@@ -1276,14 +1276,15 @@ impl LiveCore {
}
/// An instance that came back, or went unseen: its emitters' areas and centres as it stands now (an unseen one's
- /// are its mesh's own: `placed_emitter`), for their weights.
- fn weigh_run(&mut self, r: u32) {
+ /// are its mesh's own: `placed_emitter`), for their weights. `all`: those without area too (a mesh that deforms:
+ /// a pose may leave a triangle none, and the next give it some again).
+ fn weigh_run(&mut self, r: u32, all: bool) {
let LoadedScene { tables, instances, pool_tris, edit, .. } = &mut self.sc;
let Some(inst) = instances.get(r as usize) else { return };
let run = emitter_run(&tables.emitter_tris, instances, r);
for j in run.clone() {
let e = tables.emitter_tris[j];
- if e.area > 0.0 {
+ if all || e.area > 0.0 {
let (area, c, _) = crate::placed_emitter(inst, &pool_tris[e.tri as usize - edit.pool_first], e.mat, &tables.materials);
(tables.emitter_tris[j].area, tables.emitter_tris[j].c) = (area, c);
}
@@ -1392,7 +1393,7 @@ impl LiveCore {
top.moved(top.inst_base() + r, w, Some((inst.cast_shadow, unseen)));
build.instances = true;
changes.powers.insert(k);
- self.weigh_run(r as u32);
+ self.weigh_run(r as u32, false);
// (A skinned model shown is skinned as it is posed now: its mesh kept the pose it was hidden in.)
if skinned && !unseen {
changes.poses.insert(k);
@@ -1415,7 +1416,7 @@ impl LiveCore {
build.instances = true;
changes.powers.insert(k);
for r in records {
- self.weigh_run(r);
+ self.weigh_run(r, false);
}
if !unseen {
changes.poses.insert(k);
@@ -1482,7 +1483,7 @@ impl LiveCore {
self.sc.up.heap.write(q, Table::Objects, 0, bytemuck::cast_slice(&self.sc.tables.objects));
for k in 0..self.flipped.len() {
if let Some(r) = self.sc.tables.retained.instance(self.flipped[k]).map(|i| i.instance) {
- self.weigh_run(r);
+ self.weigh_run(r, false);
}
}
self.fill_moved(placed.iter().map(|&(_, i)| i));
@@ -2454,9 +2455,36 @@ impl LiveCore {
})
.collect();
self.keep_prev_spans(&posed.iter().chain(&self.pose_spans).copied().collect::<Vec<_>>());
+ // Their triangles that emit, placed by the new poses here too: the light tree's moving subtree is refit by
+ // them (`move_emitters`). The light list's own copies are taken again on the GPU, from the vertices the pass
+ // writes (`fill_moved`).
+ let mut lit: Vec<(u32, Vec<(usize, [glam::Vec3A; 3])>)> = vec![];
+ for (g, rows) in &work {
+ let sk = &self.sc.tables.retained.skinned[*g as usize];
+ let run = emitter_run(&self.sc.tables.emitter_tris, &self.sc.instances, sk.instance);
+ if run.is_empty() {
+ continue;
+ }
+ let m = self.sc.meshes[sk.mesh as usize];
+ let Some((vertices, index)) = self.sc.skins.get(sk.source as usize).filter(|s| s.1.len() == m.count as usize) else { return Ok(false) };
+ let first = self.sc.edit.pool_first + m.first as usize;
+ let placed = |e: &crate::EmitterTri| {
+ let k = (e.tri as usize).checked_sub(first)?;
+ Some((m.first as usize + k, (*index.get(k)?).map(|v| glam::Vec3A::from(crate::skin::skin_corner(&vertices[v as usize], rows).0))))
+ };
+ lit.push((sk.instance, self.sc.tables.emitter_tris[run].iter().filter_map(placed).collect()));
+ }
if !self.g.skin(&self.sc.up, &work) {
return Ok(false);
}
+ for &(at, t) in lit.iter().flat_map(|l| &l.1) {
+ self.sc.pool_tris[at] = t;
+ }
+ self.fill_moved(lit.iter().map(|l| l.0));
+ // (And their weights, by the areas the pose gives them.)
+ for l in &lit {
+ self.weigh_run(l.0, true);
+ }
self.pose_spans = posed;
self.pose_reposed = true;
for (g, a) in jobs {
@@ -2972,8 +3000,8 @@ impl LiveCore {
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());
+ if features & gpu::F_INST == 0 || m.determinant() == 0.0 {
+ return Err("a model without size, or the scene's first instance".into());
}
// (Shadow rays pass the glass among a caster's other sections under a kernel feature: a scene where
// no instance of the model cast a shadow was built without it.)
@@ -3240,9 +3268,9 @@ impl LiveCore {
if features & gpu::F_INST == 0 {
return Err("the scene's first instanced mesh (kernel feature)".into());
}
- // An instanced object placed without size, or instancing off (the build flattens).
- if (capacity.is_some() && m.determinant() == 0.0) || std::env::var("THREERT_INSTANCING").is_ok_and(|v| v == "0") {
- return Err("an instanced object without size, or instancing off".into());
+ // An instanced object placed without size.
+ if capacity.is_some() && m.determinant() == 0.0 {
+ return Err("an instanced object without size".into());
}
let mats = ids.iter().map(|k| tables.retained.materials.get(k).copied().ok_or("unknown material")).collect::<std::result::Result<Vec<u32>, _>>()?;
let mat = mats[0];
diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rs
index c762354..b03224e 100644
--- a/renderer/src/live/inplace_tests.rs
+++ b/renderer/src/live/inplace_tests.rs
@@ -3238,6 +3238,67 @@ fn posed_skinned_models_are_meshes_of_their_own() {
assert!(apart(&both, &one) > 0.5, "its pose is in the picture ({:.2} steps)", apart(&both, &one));
}
+/// A posed skinned model with triangles that emit (tests/render/data/arm-glow.glb) is posed in place, and its emitters
+/// follow: the light list's copies are its skinned triangles, the CPU's triangles of them the pose's, their weights
+/// and the picture a build's at the new pose; also through a pose that leaves some of them no area. Under either
+/// traversal.
+#[test]
+fn a_posed_skinned_models_emitters_follow_its_pose() {
+ 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 bend = |time| Some(crate::desc::Animation { clip: "bend".into(), time, r#loop: true, nodes: Default::default() });
+ let mut w = world();
+ w.set_object(30, "arm".into(), None, Kind::Model { uri: "tests/render/data/arm-glow.glb".into(), nodes: None, animation: bend(0.0), functions: vec![] }, true, false).unwrap();
+ w.set_transform(30, Vec3::new(-0.3, -0.9, 0.8), glam::Quat::from_rotation_y(0.3), Vec3::splat(2.0)).unwrap();
+ let mut live = match open(&w) {
+ Ok(c) => c,
+ Err(e) => return eprintln!("skipped: {e}"),
+ };
+ w.take_changes();
+ let sk = live.sc.tables.retained.skinned.iter().find(|s| s.object == 30).expect("a posed skinned model").clone();
+ let its = |c: &LiveCore| c.sc.tables.emitter_tris.iter().filter(|e| e.inst == sk.instance && e.area > 0.0).copied().collect::<Vec<_>>();
+ assert!(live.sc.tris.is_empty() && !its(&live).is_empty() && its(&live).iter().all(|e| e.moves), "its emitters are its instance's, moving ones");
+ list_is_its_triangles("as loaded", &live);
+ // (The codes the load uploaded are on record: the first write of the weights sends those that change, not all.)
+ {
+ let t = &live.sc.tables;
+ let order = crate::emitter_order(&t.emitter_tris, t.light_tree.as_ref());
+ assert_eq!(live.sc.codes_sent, crate::emitter_codes(&t.emitter_tris, &order, t.light_tree.as_ref()), "as loaded: the light list's codes as the GPU has them");
+ }
+ let loaded = picture(&mut live, 48);
+ for time in [0.8, 0.3] {
+ let what = format!("posed at {time}");
+ w.set_animation(30, bend(time)).unwrap();
+ assert!(!live.commit(&mut w).unwrap(), "{what}: in place ({:?})", live.fallback);
+ list_is_its_triangles(&what, &live);
+ // (The CPU's triangles of the emitters: the model skinned at the pose.)
+ let cpu = skinned_on_cpu(&live, &sk, &bend(time).unwrap()).p;
+ let m = live.sc.meshes[sk.mesh as usize];
+ for e in its(&live) {
+ let k = e.tri as usize - live.sc.edit.pool_first - m.first as usize;
+ let got: Vec<f32> = live.sc.pool_tris[m.first as usize + k].iter().flat_map(|v| v.to_array()).collect();
+ assert!(got.iter().zip(&cpu[k * 9..k * 9 + 9]).all(|(a, b)| (a - b).abs() < 1e-5), "{what}: the CPU has triangle {k} at {got:?}, the pose {:?}", &cpu[k * 9..k * 9 + 9]);
+ }
+ lit_as_a_build(&what, &mut live, &mut open(&w).unwrap());
+ }
+ let last = picture(&mut live, 48);
+ assert!(apart(&loaded, &last) > 0.5, "the pose is in the picture ({:.2} steps)", apart(&loaded, &last));
+ // A pose that leaves some of its emitters no area (the file's other clip scales the joint they follow to nothing),
+ // then one that gives it back: they weigh nothing, then what a build has them weigh again.
+ let clip = |name: &str, time| Some(crate::desc::Animation { clip: name.into(), time, r#loop: true, nodes: Default::default() });
+ let all = its(&live).len();
+ w.set_animation(30, clip("vanish", 0.0)).unwrap();
+ assert!(!live.commit(&mut w).unwrap(), "its joint scaled to nothing: in place ({:?})", live.fallback);
+ let left = its(&live).len();
+ assert!(left < all, "some of its {all} emitters have no area ({left} have)");
+ lit_as_a_build("its joint scaled to nothing", &mut live, &mut open(&w).unwrap());
+ w.set_animation(30, clip("bend", 0.3)).unwrap();
+ assert!(!live.commit(&mut w).unwrap(), "its joint back: in place ({:?})", live.fallback);
+ assert_eq!(its(&live).len(), all, "its emitters have their area again");
+ list_is_its_triangles("its joint back", &live);
+ lit_as_a_build("its joint back", &mut live, &mut open(&w).unwrap());
+}
+
/// A posed skinned model is hidden and shown in place: hidden, no ray sees its instance and a new pose skins
/// nothing; shown, it is skinned as it is posed then, where it stands. The picture is a build's each time, under
/// either traversal.
diff --git a/renderer/src/live/load.rs b/renderer/src/live/load.rs
index 1fe8bb9..89f9239 100644
--- a/renderer/src/live/load.rs
+++ b/renderer/src/live/load.rs
@@ -12,7 +12,8 @@ pub(super) struct LoadedScene {
pub(super) tri_nodes: Vec<(String, u32, u32)>,
/// Flattened instances of instanced objects: (first, end, instance index), for picking.
pub(super) tri_instances: Vec<(u32, u32, u32)>,
- /// (A mesh the GPU skins has its build's pose here: `LiveCore::mesh_tris` has it as it is now.)
+ /// (A mesh the GPU skins has its build's pose here, but for its triangles that emit, which a new pose places:
+ /// `repose_skinned`. `LiveCore::mesh_tris` has the mesh as it is now.)
pub(super) pool_tris: Vec<[glam::Vec3A; 3]>,
/// The vertices that move, the first and how many (`indexed::Indexed::dynamic`); by skin source, the model's
/// vertices its meshes are skinned from and their triangles' indices (`Indexed::skins`).
@@ -73,8 +74,8 @@ pub(super) struct LoadedScene {
/// and the flattened triangles' build indices in traversal order (positions in `tris`).
pub(super) mat_runs: std::collections::HashMap<u32, Vec<[u32; 3]>>,
pub(super) tri_order: Vec<u32>,
- /// The light list's path codes as the last `write_emitters` wrote them (`GpuEmitterTri::code`, by emitter): it
- /// writes only those that changed since. Empty after a load or a rebuild (the next write sends them all).
+ /// The light list's path codes as the GPU has them (`GpuEmitterTri::code`, by emitter): the upload's, then what
+ /// `write_emitters` wrote, which writes only those that changed since.
pub(super) codes_sent: Vec<u32>,
}
@@ -254,6 +255,8 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &P
let translucent_mats = sc.translucent_mats();
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.)
+ // (The codes the upload writes with the list: `write_emitters` sends those that change after.)
+ let codes_sent: Vec<u32> = prep.gpu_emitter_tris.iter().map(|t| t.code).collect();
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
if !g.merged {
@@ -334,5 +337,5 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &P
verts: 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(), instance_features, name: sc.name.clone(), up, base, tables, fixed_features, shaders, translucent_mats, translucent_used, volume_fns, 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(), instance_features, name: sc.name.clone(), up, base, tables, fixed_features, shaders, translucent_mats, translucent_used, volume_fns, dynamic, edit, emit, mat_runs, tri_order, codes_sent }, view, env))
}
diff --git a/renderer/src/live/mod.rs b/renderer/src/live/mod.rs
index 6a2e535..673d688 100644
--- a/renderer/src/live/mod.rs
+++ b/renderer/src/live/mod.rs
@@ -1035,7 +1035,8 @@ impl LiveCore {
if !posed.contains_key(&mesh) {
let tris = scene::model_gltf(&pg.uri, &self.assets).and_then(|model| model.triangles(glam::Mat4::IDENTITY, pg.nodes.as_deref(), Some(&pg.animation)));
match tris {
- Ok(t) if t.len() == pg.order.len() => posed.insert(mesh, pg.order.iter().map(|&(k, _, _)| t[k as usize].p.map(glam::Vec3A::from)).collect()),
+ // (The mesh's triangles are the model's, less what the build left out of it.)
+ Ok(t) if pg.order.iter().all(|&(k, _, _)| (k as usize) < t.len()) => posed.insert(mesh, pg.order.iter().map(|&(k, _, _)| t[k as usize].p.map(glam::Vec3A::from)).collect()),
_ => return pool,
};
}
diff --git a/renderer/src/scene.rs b/renderer/src/scene.rs
index 1861723..505b0a3 100644
--- a/renderer/src/scene.rs
+++ b/renderer/src/scene.rs
@@ -1014,7 +1014,7 @@ struct RigidPart {
/// A posed skinned model's mesh: the model's triangles in its own space, a mesh a model. The skinning pass skins it at
/// each new pose (gpu.rs `skin`: the CPU sends the pose's matrices) and its BLAS is built again; the model moves as
/// its instance (hardware RT). Never shared: two models in one pose are two meshes (a mesh shared came apart when
-/// one of them took another pose, and that was a rebuild). Only a model none of whose triangles emits.
+/// one of them took another pose, and that was a rebuild).
#[derive(Clone, Debug)]
pub struct Skinned {
pub mesh: u32,
@@ -1650,7 +1650,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
materials.push(gm);
}
- let mut tris: Vec<[Vec3A; 3]> = vec![];
+ let tris: Vec<[Vec3A; 3]> = vec![];
let mut tri_flags: Vec<u32> = vec![];
let mut attrs: Vec<GpuTriAttr> = vec![];
let mut lights: Vec<GpuLight> = vec![];
@@ -1671,13 +1671,8 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
let mut grids: Vec<GridBuild> = vec![];
let grid_programs: Vec<(String, String, String)> = w.grid_programs.iter().map(|(k, (c, h))| (k.clone(), c.clone(), h.clone())).collect();
let mut objects: Vec<[f32; 4]> = vec![];
- // Static glTF models drawn more than once share their triangles (model space, one BLAS): opaque, shadow-casting
- // per node. THREERT_INSTANCING=0 flattens everything.
- let instancing = std::env::var("THREERT_INSTANCING").map_or(true, |v| v != "0");
let mut pool_tris: Vec<[Vec3A; 3]> = vec![];
- let (mut vcolors, mut pool_vcolors): (Vec<[u32; 3]>, Vec<[u32; 3]>) = (vec![], vec![]);
- // Whether a mesh's triangles carry its geometry's vertex colours: any of its materials asks for them.
- let colored = |g: &world::Geometry, mats: &mut dyn Iterator<Item = &u32>| !g.colors.is_empty() && mats.filter(|k| w.materials.get(k).is_some_and(|m| m.vertex_colors)).count() > 0;
+ let (vcolors, mut pool_vcolors): (Vec<[u32; 3]>, Vec<[u32; 3]>) = (vec![], vec![]);
let mut pool_attrs: Vec<GpuTriAttr> = vec![];
let mut meshes: Vec<InstMesh> = vec![];
let mut instances: Vec<Instance> = vec![];
@@ -1703,7 +1698,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
let mut skin_rest: Vec<Vec<skin::PaletteRows>> = vec![];
let mut skin_source_of: HashMap<(String, Option<Vec<String>>, Vec<bool>), (u32, Arc<Vec<(u32, u32, u32)>>)> = HashMap::new();
// Flattened instances' triangle ranges.
- let mut tri_instances: Vec<(u32, u32, u32)> = vec![];
+ let tri_instances: Vec<(u32, u32, u32)> = vec![];
// The rect lights' card mesh, once a scene has a card (`card_mesh`).
let mut card: Option<u32> = None;
// Instance colours anywhere: object entries of 4 vec4s, and the kernel's F_TINT.
@@ -1714,9 +1709,8 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
let m = worlds[id];
let first = tris.len() as u32;
let shown = w.shown(*id);
- let flags = if n.cast_shadow { 0 } else { TRI_NO_SHADOW };
match &n.kind {
- Kind::Mesh { geometry, material, own_blas, materials: mesh_mats } if instancing => {
+ Kind::Mesh { geometry, material, own_blas, materials: mesh_mats } => {
// A mesh is an instance of its geometry's mesh: the triangles in model space in the pool, one BLAS,
// shared by the objects of the geometry whatever their materials, which are the instance's rows
// (`section_mesh`, `Row`: a cutout, glass, one that emits). A move is the instance's transform
@@ -1765,8 +1759,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
// copies' records and entries contiguous (live/edits.rs `update_instanced` rewrites them in place).
// With a material that emits each copy has its emitters in the light list (`rows_emitters`), a
// hidden copy's at no weight (its object has no power). A copy may mirror
- // the mesh (`INST_MIRRORED`). Without instancing each copy is its own triangles, and changing the
- // instances rebuilds.
+ // the mesh (`INST_MIRRORED`).
let empty = world::InstanceTable::default();
let t = w.instanced.get(id).unwrap_or(&empty);
let placed: Vec<(Mat4, bool)> = (0..*capacity as usize).map(|i| instance_world(m, t, i)).collect();
@@ -1787,77 +1780,34 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
let material = mats.first().ok_or_else(|| anyhow!("object {}: an instanced mesh needs a material", n.name))?;
let mat = *retained.materials.get(material).ok_or_else(|| anyhow!("object {}: unknown material {material}", n.name))?;
let emits = emissive(&materials[mat as usize]);
- let vc = colored(g, &mut std::iter::once(material));
- if instancing {
- // (The geometry whole, with the object's first material: the mesh an object of one material has.)
- let key = (*geometry, false);
- let mesh = match retained.own_mesh.get(&key) {
- Some(&k) => Some(k),
- None => {
- let d = section_mesh(g, false, pool_tris.len() as u32, sections.len() as u32, colored_meshes.contains(&key));
- (!d.tris.is_empty()).then(|| {
- meshes.push(d.mesh);
- sections.extend(d.sections);
- put_colors(&mut pool_vcolors, pool_tris.len(), d.colors);
- pool_tris.extend(d.tris);
- pool_attrs.extend(d.attrs);
- let k = meshes.len() as u32 - 1;
- retained.own_mesh.insert(key, k);
- k
- })
- }
- };
- if let Some(mesh) = mesh {
- let object = (objects.len() / stride) as u32;
- retained.proxy(*id).draw = Draw::Instanced(InstancedPlace { first: instances.len() as u32, capacity: *capacity, object, mesh: Some(mesh), drawn: t.count });
- let mine = section_rows(meshes[mesh as usize].sections(&sections), std::slice::from_ref(&mat), &materials);
- for (i, &(wm, hidden)) in placed.iter().enumerate() {
- let (lo, hi) = meshes[mesh as usize].placed_bounds(wm);
- objects.extend_from_slice(&copy_row(entry(i, wm, Vec3::from(hi - lo)), emits && hidden)[..stride]);
- instances.push(Instance { mesh, world: wm, object: object + i as u32, cast_shadow: rows_cast(&mine, n.cast_shadow), name: n.name.clone(), sub: Some(i as u32), hidden, masked: false, first_emitter: 0, rows: rows.len() as u32, bits: rows_bits(&mine), prev: 0, verts: 0 });
- rows.extend(mine.iter().copied());
- }
- }
- continue;
- }
- // Flattened: nothing kept to change it by (`Draw::Fixed`; an entry a copy, as the instances have).
- retained.proxy(*id);
- for (i, &(wm, hidden)) in placed.iter().enumerate() {
- if hidden {
- continue;
- }
- let start = tris.len();
- put_colors(&mut vcolors, start, vc.then(|| tri_colors(g, wm.determinant() < 0.0, None)));
- append_arrays(g, wm, mat, flags, None, &mut tris, &mut tri_flags, &mut attrs);
- let (mut lo, mut hi) = (Vec3A::splat(f32::MAX), Vec3A::splat(f32::MIN));
- for v in tris[start..].iter().flatten() {
- lo = lo.min(*v);
- hi = hi.max(*v);
+ // (The geometry whole, with the object's first material: the mesh an object of one material has.)
+ let key = (*geometry, false);
+ let mesh = match retained.own_mesh.get(&key) {
+ Some(&k) => Some(k),
+ None => {
+ let d = section_mesh(g, false, pool_tris.len() as u32, sections.len() as u32, colored_meshes.contains(&key));
+ (!d.tris.is_empty()).then(|| {
+ meshes.push(d.mesh);
+ sections.extend(d.sections);
+ put_colors(&mut pool_vcolors, pool_tris.len(), d.colors);
+ pool_tris.extend(d.tris);
+ pool_attrs.extend(d.attrs);
+ let k = meshes.len() as u32 - 1;
+ retained.own_mesh.insert(key, k);
+ k
+ })
}
- let oi = (objects.len() / stride) as u32;
- objects.extend_from_slice(&entry(i, wm, Vec3::from((hi - lo).max(Vec3A::ZERO)))[..stride]);
- for a in &mut attrs[start..] {
- a.x[1] = f32::from_bits(oi);
+ };
+ if let Some(mesh) = mesh {
+ let object = (objects.len() / stride) as u32;
+ retained.proxy(*id).draw = Draw::Instanced(InstancedPlace { first: instances.len() as u32, capacity: *capacity, object, mesh: Some(mesh), drawn: t.count });
+ let mine = section_rows(meshes[mesh as usize].sections(&sections), std::slice::from_ref(&mat), &materials);
+ for (i, &(wm, hidden)) in placed.iter().enumerate() {
+ let (lo, hi) = meshes[mesh as usize].placed_bounds(wm);
+ objects.extend_from_slice(&copy_row(entry(i, wm, Vec3::from(hi - lo)), emits && hidden)[..stride]);
+ instances.push(Instance { mesh, world: wm, object: object + i as u32, cast_shadow: rows_cast(&mine, n.cast_shadow), name: n.name.clone(), sub: Some(i as u32), hidden, masked: false, first_emitter: 0, rows: rows.len() as u32, bits: rows_bits(&mine), prev: 0, verts: 0 });
+ rows.extend(mine.iter().copied());
}
- tri_nodes.push((n.name.clone(), start as u32, tris.len() as u32));
- tri_instances.push((start as u32, tris.len() as u32, i as u32));
- }
- }
- Kind::Mesh { geometry, material, materials: mesh_mats, .. } if shown => {
- let g = w.geometries.get(geometry).ok_or_else(|| anyhow!("object {}: unknown geometry {geometry}", n.name))?;
- let mat = *retained.materials.get(material).ok_or_else(|| anyhow!("object {}: unknown material {material}", n.name))?;
- // Several materials: each geometry group's triangles with its own (three.js's material array).
- let gpu_mats = mesh_mats.iter().map(|k| retained.materials.get(k).copied().ok_or_else(|| anyhow!("object {}: unknown material {k}", n.name))).collect::<Result<Vec<u32>>>()?;
- let per_tri = group_materials(g, &gpu_mats);
- let movable = w.movable(*id);
- // Coloured where the triangle's own material asks (each group's; without groups, the mesh's).
- let wants = |k: &u32| w.materials.get(k).is_some_and(|m| m.vertex_colors);
- let vc_tri = group_materials(g, &mesh_mats.iter().map(|k| u32::from(wants(k))).collect::<Vec<_>>());
- let vc = !g.colors.is_empty() && match &vc_tri { Some(v) => v.iter().any(|f| *f == Some(1)), None => wants(material) };
- put_colors(&mut vcolors, tris.len(), vc.then(|| tri_colors(g, m.determinant() < 0.0, vc_tri.as_deref())));
- append_arrays(g, m, mat, if movable { flags | TRI_DYNAMIC } else { flags }, per_tri.as_deref(), &mut tris, &mut tri_flags, &mut attrs);
- if movable {
- retained.proxy(*id).draw = Draw::Dynamic(DynamicModel { first, mats: attrs[first as usize..].iter().map(|a| a.uv[3].to_bits()).collect(), ..Default::default() });
}
}
Kind::Model { uri, nodes, animation, functions } if shown => {
@@ -1895,16 +1845,14 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
};
Ok((i, mesh_class(&materials[i as usize]), emissive(&materials[i as usize])))
};
- // A posed model the build flattens has dynamic triangles (re-skinned in place). A movable one is an
- // instance whose transform moves.
+ // (A posed model is posed in place: its parts' instances, or its mesh by the skinning pass. A movable one
+ // is an instance whose transform moves.)
let posed = animation.is_some() && glb.animated();
let movable = w.movable(*id);
- let dynamic = posed || movable;
- let flags = if dynamic { flags | TRI_DYNAMIC } else { flags };
// Posed rigid model: its parts as instances (`RigidModel`: the nodes its clip leaves alone merged into
// one mesh, each node it moves a mesh); a movable one too (each update re-places its instances from
// the object's transform).
- if instancing && posed && nodes.is_none() && glb.rigid() {
+ if posed && nodes.is_none() && glb.rigid() {
let a = animation.as_ref().unwrap();
let globals = glb.node_globals(Some(a))?;
let pkey = (key.clone(), rigid_pose_key(a));
@@ -1979,17 +1927,30 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
continue;
}
// A posed skinned model is an instance of a mesh of its own, in its own space, which the skinning pass
- // skins at each new pose (`Skinned`). One with emitting triangles is not yet: skinned alone, below.
- if instancing && posed && m.determinant() != 0.0 && !(nodes.is_none() && glb.rigid()) {
+ // skins at each new pose (`Skinned`). Its triangles that emit are its instance's emitters, as any
+ // mesh's: the light list takes them again from the skinned vertices at each pose (live/edits.rs
+ // `repose_skinned`). Placed without size it is an instance no ray sees (`placed_world`).
+ if posed && !(nodes.is_none() && glb.rigid()) {
let a = animation.as_ref().unwrap();
let local = glb.triangles(Mat4::IDENTITY, nodes.as_deref(), Some(a))?;
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() {
- // (A mesh that deforms does not keep its emitters: the light list does not follow a pose yet.)
let (mat, class, emits) = resolve(t.material.and_then(|i| doc.materials().nth(i)))?;
- classed[if emits { FLAT } else { class as usize }].push((k, mat));
+ classed[class as usize].push((k, mat));
+ if emits {
+ emitting.insert(mat);
+ }
}
- if classed[FLAT].is_empty() && !local.is_empty() {
+ // A cutout on exactly an emitter's vertices is left out: a skinned model is one mesh, where the
+ // cutout's holes would take the emitter with them (`split_coincident`). What is drawn is the
+ // emitter, as where the two are meshes apart. (Glass on what lies under it stays, as it was.)
+ for (k, mat, class) in split_coincident(&mut classed, &emitting, &|k| local[k].p) {
+ if class == 2 {
+ classed[2].push((k, mat));
+ }
+ }
+ if !local.is_empty() {
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))?;
@@ -2024,13 +1985,14 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
let mesh = meshes.len() as u32 - 1;
sections.extend(sects);
retained.mesh_rows.insert(mesh, mine.clone());
- let (lo, hi) = meshes[mesh as usize].placed_bounds(m);
let pivot = m.transform_point3(Vec3::ZERO);
+ let (world, gone) = placed_world(m, pivot);
+ let (lo, hi) = meshes[mesh as usize].placed_bounds(world);
let size = hi - lo;
let oi = (objects.len() / stride) as u32;
- objects.extend_from_slice(&object_row(pivot, n.power, size, n.custom, [1.0; 3])[..stride]);
+ objects.extend_from_slice(&object_row(pivot, if gone { 0.0 } else { n.power }, size, n.custom, [1.0; 3])[..stride]);
let i = instances.len() as u32;
- instances.push(Instance { mesh, world: m, object: oi, cast_shadow: rows_cast(&mine, n.cast_shadow), name: n.name.clone(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: rows.len() as u32, bits: rows_bits(&mine), prev: 0, verts: 0 });
+ instances.push(Instance { mesh, world, object: oi, cast_shadow: rows_cast(&mine, n.cast_shadow), name: n.name.clone(), sub: None, hidden: gone, masked: gone, first_emitter: 0, rows: rows.len() as u32, bits: rows_bits(&mine), prev: 0, verts: 0 });
rows.extend(mine);
retained.skinned.push(Skinned { mesh, uri: uri.clone(), nodes: nodes.clone(), animation: a.clone(), order: tri_order, object: *id, instance: i, source, palette_len: glb.palette_len() as u32, mirrors });
*retained.proxy(*id) = Proxy { object: Some(oi), card: None, draw: Draw::Instance(InstanceRef { instance: i, mesh: MeshKind::Skinned(retained.skinned.len() as u32 - 1), moves: true }) };
@@ -2040,7 +2002,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
continue;
}
}
- if instancing && !posed {
+ if !posed {
let key = mesh_key.clone();
let mesh = match mesh_of.get(&key) {
Some(k) => *k,
@@ -2066,9 +2028,6 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
(im.lo, im.hi) = (im.lo.min(v.into()), im.hi.max(v.into()));
}
}
- if std::env::var("THREERT_INSTANCING").is_ok_and(|v| v == "log") {
- eprintln!("instancing: {uri} {nodes:?}: {} opaque, {} cutout, {} glass in the mesh; {} in a second mesh", classed[0].len(), classed[1].len(), classed[2].len(), over.len());
- }
// (What an edit can place another instance of: a mesh whole in the pool.)
if let Some(k) = k.filter(|&k| meshes[k as usize].over == NO_OVER) {
retained.model_mesh.insert(key.clone(), k);
@@ -2100,15 +2059,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
continue;
}
}
- let mut mats = vec![];
- for t in glb.triangles(m, nodes.as_deref(), animation.as_ref())? {
- let mat = resolve(t.material.and_then(|i| doc.materials().nth(i)))?.0;
- push_tri(&mut tris, &mut tri_flags, &mut attrs, t.p, t.n, t.uv, t.tangent, mat, flags);
- mats.push(mat);
- }
- if dynamic {
- retained.proxy(*id).draw = Draw::Dynamic(DynamicModel { first, mats, ..Default::default() });
- }
+ // (A model without a triangle draws nothing.)
}
Kind::Light(l) => match (l, gpu_light_shown(l, m, n.power, shown)) {
(_, Some(gl)) => {
@@ -2167,7 +2118,6 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
// instance of it; each particle its own object (pivot, bounds and per-particle data for material
// functions). The quads are collapsed at the node until the particle pass writes their vertices where
// the particles are (the instance places nothing), and the mesh's BLAS is built again after the pass.
- // (Whatever THREERT_INSTANCING says: a system has no flattened form.)
let mat = *retained.materials.get(material).ok_or_else(|| anyhow!("object {}: unknown material {material}", n.name))?;
let func = particle_fns.iter().position(|(k, _, _)| k == emitter).ok_or_else(|| anyhow!("object {}: unknown particle function {emitter}", n.name))? as u32;
let pivot = m.transform_point3(Vec3::ZERO);
@@ -2730,7 +2680,7 @@ pub fn mesh_class(g: &GpuMaterial) -> u32 {
}
}
-/// `classed`'s last list: the emitters of a mesh that deforms, which leave it (the model is flattened then).
+/// How many classes a model's triangles are of (`classed`'s lists before this one).
pub const FLAT: usize = 3;
/// The build's arrays a mesh of the pool and its instance are added to.
@@ -3284,6 +3234,67 @@ mod instance_tests {
assert!(matches!(sc.retained.proxies[&2].draw, Draw::Instance(_)), "it comes back as its instance does");
}
+ /// A posed skinned model's triangles that emit stay in its mesh (tests/render/data/arm-glow.glb: arm.glb with its
+ /// light half emitting, and a clip, `vanish`, that scales its tip joint from nothing to its size): the model is an instance of a mesh that deforms, and they are its instance's emitters,
+ /// moving ones, each its mesh's triangle as the instance places it. Nothing is a world-space triangle. One placed
+ /// without size is an instance no ray sees. No GPU.
+ #[test]
+ fn a_posed_skinned_models_emitters_are_its_instances() {
+ let mut w = World::default();
+ let cam = serde_json::from_value(serde_json::json!({ "fov": 50, "near": 0.1, "far": 100, "exposure": { "mode": "manual", "ev100": 0 } })).unwrap();
+ w.set_object(9, "camera".into(), None, Kind::Camera(cam), true, false).unwrap();
+ w.set_settings(world::Settings { camera: Some(9), ..Default::default() });
+ for (id, scale) in [(1, 1.5), (2, 0.0)] {
+ let animation = Some(desc::Animation { clip: "bend".into(), time: 0.25, r#loop: true, nodes: Default::default() });
+ w.set_object(id, format!("arm{id}"), None, Kind::Model { uri: "tests/render/data/arm-glow.glb".into(), nodes: None, animation, functions: vec![] }, true, false).unwrap();
+ w.set_transform(id, Vec3::new(id as f32 * 3.0, 0.5, -1.0), glam::Quat::from_rotation_y(0.4), Vec3::splat(scale)).unwrap();
+ }
+ let mut sc = build(&w, Path::new(".."), &crate::default_presets_dir(), None).unwrap();
+ assert_eq!((sc.tris.len(), sc.instances.len(), sc.retained.skinned.len()), (0, 2, 2), "an instance a model, of a mesh of its own");
+ assert!(sc.meshes.iter().all(|m| m.deforms) && sc.instances.iter().map(|i| (i.hidden, i.masked)).collect::<Vec<_>>() == [(false, false), (true, true)]);
+ let power = |id: u32| sc.objects[sc.retained.proxies[&id].object.unwrap() as usize * object_stride(sc.tinted)][3];
+ assert_eq!([power(1), power(2)], [1.0, 0.0], "the unseen one's object has no power");
+ let a = sc.instances[0].clone();
+ let m = sc.meshes[a.mesh as usize];
+ let glow = rows_emitters(m.sections(&sc.sections), &sc.rows[a.rows as usize..][..m.sect_count as usize], &sc.materials);
+ assert!(glow > 0 && glow < m.count, "its emitting half: {glow} of {} triangles", m.count);
+ let p = crate::prepare_as(true, false, &mut sc, &mut vec![]);
+ let pool_first = sc.attrs.len() - sc.pool_tris.len();
+ let mine: Vec<usize> = (0..p.emitter_tris.len()).filter(|&i| p.emitter_tris[i].inst == 0).collect();
+ assert_eq!(mine.len() as u32, glow, "its instance's emitters");
+ for i in mine {
+ let e = &p.emitter_tris[i];
+ assert!(e.moves && !e.card && e.area > 0.0, "emitter {i}: one that moves");
+ let want = sc.pool_tris[e.tri as usize - pool_first].map(|v| a.world.transform_point3(v.into()));
+ let got = p.gpu_emitter_tris[i].vertices().map(Vec3::from);
+ assert!((0..3).all(|c| got[c].abs_diff_eq(want[c], 1e-5)), "emitter {i}: its mesh's triangle where the instance places it");
+ }
+ }
+
+ /// A posed skinned model's cutout on exactly an emitter's vertices is left out of its mesh (tests/render/data/
+ /// arm-glow-decal.glb: arm-glow.glb with a masked primitive on its emitting one's vertices): the mesh, its rows
+ /// and its emitters are the model's without the cutout. No GPU.
+ #[test]
+ fn a_skinned_models_cutout_on_an_emitter_is_left_out() {
+ let scene = |uri: &str| {
+ let mut w = World::default();
+ let cam = serde_json::from_value(serde_json::json!({ "fov": 50, "near": 0.1, "far": 100, "exposure": { "mode": "manual", "ev100": 0 } })).unwrap();
+ w.set_object(9, "camera".into(), None, Kind::Camera(cam), true, false).unwrap();
+ w.set_settings(world::Settings { camera: Some(9), ..Default::default() });
+ let animation = Some(desc::Animation { clip: "bend".into(), time: 0.25, r#loop: true, nodes: Default::default() });
+ w.set_object(1, "arm".into(), None, Kind::Model { uri: format!("tests/render/data/{uri}"), nodes: None, animation, functions: vec![] }, true, false).unwrap();
+ build(&w, Path::new(".."), &crate::default_presets_dir(), None).unwrap()
+ };
+ let (with, without) = (scene("arm-glow-decal.glb"), scene("arm-glow.glb"));
+ assert_eq!((with.tris.len(), with.meshes.len(), with.instances.len()), (0, 1, 1));
+ assert_eq!(with.pool_tris, without.pool_tris, "the mesh's triangles: the model's without the cutout's");
+ let classes = |sc: &Scene| sc.rows.iter().map(|r| r[0] & (ROW_CUTOUT | ROW_GLASS)).collect::<Vec<_>>();
+ assert_eq!((classes(&with), with.sections.clone()), (classes(&without), without.sections.clone()), "no section is a cutout's");
+ assert!(classes(&with).iter().all(|c| *c == 0));
+ let emitters = |sc: &Scene| rows_emitters(sc.meshes[0].sections(&sc.sections), &sc.rows, &sc.materials);
+ assert_eq!((emitters(&with), emitters(&without)), (2, 2));
+ }
+
/// A cutout on exactly an emitter's vertices leaves the mesh for the model's second one (`split_coincident`), in a
/// model that stays and in a rigid model's moving node (tests/render/data/panel-decal.glb: panel.glb, a grey quad
/// and an emitting one, with a masked quad on the emitting one's vertices): the emitter stays in its mesh, the
diff --git a/renderer/web/src/lib.rs b/renderer/web/src/lib.rs
index 162093f..9acf0ea 100644
--- a/renderer/web/src/lib.rs
+++ b/renderer/web/src/lib.rs
@@ -95,6 +95,12 @@ pub fn read_asset(path: &str, _offset: Option<f64>, _length: Option<f64>) -> Res
Err(JsValue::from_str(&format!("readAsset {path}: the native renderer reads assets; a page fetches them")))
}
+/// `preloadModel`: native only (a page has no thread that reads a model ahead): false, nothing is read.
+#[wasm_bindgen(js_name = preloadModel)]
+pub fn preload_model(_uri: &str, _node_sets: Option<String>) -> bool {
+ false
+}
+
#[wasm_bindgen(js_name = physicsPoses)]
pub fn physics_poses() -> Vec<f32> {
engine(|e| api::physics_poses(&e.physics).to_vec())
diff --git a/renderer/web/www/engine.ts b/renderer/web/www/engine.ts
index bd8f4ea..3d6ab57 100644
--- a/renderer/web/www/engine.ts
+++ b/renderer/web/www/engine.ts
@@ -23,6 +23,7 @@ export interface EngineExports {
voxelGone(): string;
voxelFrame(dt: number): string;
readAsset(path: string, offset?: number, length?: number): Uint8Array;
+ preloadModel(uri: string, nodeSets?: string): boolean;
geometry(id: number, p: Float32Array, n: Float32Array, uv: Float32Array, idx: Uint32Array, groups?: Uint32Array | null, colors?: Float32Array | null): void;
texture(id: number, d: string, data?: Uint8Array | null): void;
shader(name: string, code: string, helpers: string): void;
@@ -90,6 +91,7 @@ export function webEngine(w: EngineExports): WebEngine {
voxelGone: () => w.voxelGone(),
voxelFrame: (dt) => w.voxelFrame(dt),
readAsset: (path, offset, length) => w.readAsset(path, offset, length).buffer as ArrayBuffer,
+ preloadModel: (uri, nodeSets) => w.preloadModel(uri, nodeSets),
geometry: (id, p, n, uv, idx, groups, colors) => w.geometry(id, p, n, uv, idx, groups, colors),
texture: (id, d, data) => w.texture(id, json(d), data),
shader: (name, code, helpers) => w.shader(name, code, helpers),
diff --git a/tests/render/data/arm-glow-decal.glb b/tests/render/data/arm-glow-decal.glb
new file mode 100644
index 0000000..9aca648
Binary files /dev/null and b/tests/render/data/arm-glow-decal.glb differ
diff --git a/tests/render/data/arm-glow.glb b/tests/render/data/arm-glow.glb
new file mode 100644
index 0000000..00da611
Binary files /dev/null and b/tests/render/data/arm-glow.glb differ
diff --git a/tools/check-instancing.ts b/tools/check-instancing.ts
index ab7c5d0..23ee56f 100644
--- a/tools/check-instancing.ts
+++ b/tools/check-instancing.ts
@@ -1,8 +1,7 @@
// Instancing consistency check: the same scene of instanced cutout props (tests/checks/instanced-cutouts.ts) rendered
-// three ways. The flattened render (THREERT_INSTANCING=0: world-space triangles, as before instancing) is the reference;
-// hardware instancing and software traversal (which flattens the instances itself) must match it. Mean dE and p99 dE
-// catch whole surfaces gone wrong: cutouts rendered solid (software traversal losing the cutout flag), holes thinned
-// or filled by the alpha test sampling the wrong mip on scaled placements.
+// under hardware traversal, the reference, and under software traversal, which must match it. Mean dE and p99 dE
+// catch whole surfaces gone wrong: cutouts rendered solid (a traversal losing the cutout flag), holes thinned or
+// filled by the alpha test sampling the wrong mip on scaled placements.
//
// node tools/check-instancing.ts [--assets DIR] [--spp 64] [--bin path] (exit 1 above the limits)
import { execFileSync } from "node:child_process";
@@ -69,11 +68,10 @@ function fenceGLB(): Uint8Array {
writeFileSync(join(out, "fence.glb"), fenceGLB());
const bundle = (await bundleGame(join(repoRoot, "tests/checks/instanced-cutouts.ts"), join(out, "instanced-cutouts.js"))).out;
-/** Limits against the flattened render: hardware paths differ by sampling noise only; software traversal also by its
- * own traversal order (paths decorrelate), not by surfaces. */
+/** Limits against the hardware render: software traversal differs by its own traversal order (paths decorrelate), not
+ * by surfaces. */
const runs = [
- { name: "flattened", env: { THREERT_INSTANCING: "0" } },
- { name: "instanced", env: {}, limit: { mean: 0.15, p99: 3 } },
+ { name: "hardware", env: {} },
{ name: "software", env: { THREERT_HWRT: "0" }, limit: { mean: 0.6, p99: 6 } },
];
let failed = 0;
@@ -84,10 +82,10 @@ for (const r of runs) {
console.log(`${r.name}: reference (${stats.triangles} triangles)`);
continue;
}
- const m = JSON.parse(execFileSync(bin, ["compare", join(out, "flattened.png"), png]).toString().trim().split("\n").pop()!);
+ const m = JSON.parse(execFileSync(bin, ["compare", join(out, "hardware.png"), png]).toString().trim().split("\n").pop()!);
const bad = m.mean_delta_e > r.limit.mean || m.p99_delta_e > r.limit.p99;
if (bad) failed++;
- console.log(`${bad ? "FAIL" : "ok "} ${r.name} vs flattened: dE ${m.mean_delta_e} (≤ ${r.limit.mean}), p99 ${m.p99_delta_e} (≤ ${r.limit.p99}), SSIM ${m.ssim}`);
+ console.log(`${bad ? "FAIL" : "ok "} ${r.name} vs hardware: dE ${m.mean_delta_e} (≤ ${r.limit.mean}), p99 ${m.p99_delta_e} (≤ ${r.limit.p99}), SSIM ${m.ssim}`);
}
-console.log(`${out}/{flattened,instanced,software}.png`);
+console.log(`${out}/{hardware,software}.png`);
if (failed) process.exit(1);