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.

A light's card, a coincident pair and a model without size are instances (#272)

Yujia167a374744d6
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index addf1e7..382028d 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -2908,6 +2908,22 @@ 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.
+**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
+ material its row's, and it moves as its instance, under software traversal too. An emitter's entry in the light
+ list says whether it is a card's (it lights one side), where the kernel read the triangle's material. A card
+ of another size is the build's: it was taken in place, and only its material changed.
+- A triangle on exactly another's vertices (a cutout on an emitter, glass on what is under it) alone leaves its
+ mesh, for the model's second mesh, with an instance beside the first: a BLAS apart, as the flattened pair was.
+ A posed rigid model with such a part is hidden and removed in place now. A movable still model with one moves
+ 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
+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
that nothing set: `THREERT_EDIT_BLAS` (an edit mesh's BLAS is built fast), `THREERT_LIGHT_GROUPS` (measured:
+4.6 ms of trace without the groups), `THREERT_RIGID_NODES` (measured: 4 to 10 % of GPU time with every node
diff --git a/docs/RUNTIME.md b/docs/RUNTIME.md
index 27db92e..5db33be 100644
--- a/docs/RUNTIME.md
+++ b/docs/RUNTIME.md
@@ -843,7 +843,8 @@ at the end. `THREERT_EDIT_LOG=1` says where a rebuild was decided, and a frame's
- **Groups and cameras.** A new group, and a camera that is not the scene's, draw nothing.
Still a rebuild: particle systems that come or go, and their functions and programs; a geometry function; a posed model the scene has not got, and any new model under software traversal (its room does
-not grow); a material that becomes a particle's or gets vertex colours; a rect light's card; as many shadow-casting
+not grow); a material that becomes a particle's or gets vertex colours; a rect light's card that comes, goes or takes
+another size (its colour is in place, and a movable one's move); as many shadow-casting
local lights as bring the light tiles or take them away; the scene's first instance, procedural object, instance
colours or vertex colours (the kernel's data is laid out for them); the atmosphere's sun shown or hidden.
@@ -1618,7 +1619,7 @@ 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 (a light's card, a flattened scene's)
+- **Rows** (`Stream::Triangles`, four words). A triangle no instance places (what the build still flattens)
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
diff --git a/renderer/shaders/pathtrace.wgsl b/renderer/shaders/pathtrace.wgsl
index 1bb9084..19ad074 100644
--- a/renderer/shaders/pathtrace.wgsl
+++ b/renderer/shaders/pathtrace.wgsl
@@ -201,8 +201,8 @@ fn glass_energy_at(i: u32) -> vec4<f32> { return table_f(P.table_first[2].z + i)
// no placement (what moves it is copied again: emitter_fill.wgsl); `tri`: its triangle in the triangles' table
// (attributes: `emitter_attrs`), `inst`: the instance that places it (NO_INST: none), `code`: the light tree's path
// code (0: not one of the tree's), EMITTER_MOVES if it moves; `part`: as a hit's (`Hit.part`): its section of its
-// instance's mesh, or its own row. Four vec4s, a cache line.
-struct EmitterTri { v0: vec3<f32>, tri: u32, e1: vec3<f32>, inst: u32, e2: vec3<f32>, code: u32, part: u32 };
+// instance's mesh, or its own row; `flags`: EMITTER_CARD. Four vec4s, a cache line.
+struct EmitterTri { v0: vec3<f32>, tri: u32, e1: vec3<f32>, inst: u32, e2: vec3<f32>, code: u32, part: u32, flags: u32 };
const EMITTER_TRI_VEC4: u32 = 4u;
const EMITTER_MOVES: u32 = 0x80000000u;
fn emitter_tri_at(i: u32) -> EmitterTri {
@@ -210,7 +210,8 @@ fn emitter_tri_at(i: u32) -> EmitterTri {
let r0 = tables[b];
let r1 = tables[b + 1u];
let r2 = tables[b + 2u];
- return EmitterTri(bitcast<vec3<f32>>(r0.xyz), r0.w, bitcast<vec3<f32>>(r1.xyz), r1.w, bitcast<vec3<f32>>(r2.xyz), r2.w, tables[b + 3u].x);
+ let r3 = tables[b + 3u];
+ return EmitterTri(bitcast<vec3<f32>>(r0.xyz), r0.w, bitcast<vec3<f32>>(r1.xyz), r1.w, bitcast<vec3<f32>>(r2.xyz), r2.w, r3.x, r3.y);
}
// The seven tables read at every hit or light, through `material_at`, `light_at`, `emitter_at`, `tex_info_at`,
// `object_at`, `instance_at` and `medium_at` in every layout.
@@ -322,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 (a light's card, a scene's that is flattened), four words:
+// The row of a triangle no instance places (what the build flattens), 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> {
@@ -330,12 +331,9 @@ fn tri_row(row: u32) -> vec4<u32> {
return vec4<u32>(words[k], words[k + 1u], words[k + 2u], words[k + 3u]);
}
fn tri_flags(row: u32) -> u32 { return words[P.word_first[1].y + row * 4u + 2u]; }
-// Whether an emitter is a rect light's card, which lights one side. (A card is in world space: its row has its
-// material. No mesh is drawn with a card's.)
-fn emitter_is_card(em: EmitterTri) -> bool {
- if (has(F_INST) && em.inst != NO_INST) { return false; }
- return material_at(tri_row(em.part).x).tex1.z == MAT_EMITTER_CARD;
-}
+// Whether an emitter is a rect light's card, which lights one side: its entry says (lib.rs `EMITTER_CARD`).
+const EMITTER_CARD: u32 = 1u;
+fn emitter_is_card(em: EmitterTri) -> bool { return (em.flags & EMITTER_CARD) != 0u; }
// A triangle read whole: its first corner and its edges, and its attributes as a hit has them: normals and UVs a
// corner; `uv.w`: its section (an instance's: `part`) or its material; `x`: -, its object (an instance's: where its
// attributes are placed, `inst_x`), -, its emitter entry + 1. `vi`: where its three vertices are in `vertices`
diff --git a/renderer/src/indexed.rs b/renderer/src/indexed.rs
index 55dd8a7..e3b8b7a 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 (a light's card, a flattened scene's): its material, its
+/// The row of a triangle no instance places (what the build flattens): 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/lib.rs b/renderer/src/lib.rs
index fb89230..e29ae11 100644
--- a/renderer/src/lib.rs
+++ b/renderer/src/lib.rs
@@ -113,7 +113,7 @@ pub fn emitter_tri(k: usize, tri_verts: &[[f32; 4]], a: &scene::GpuTriAttr, mate
}
let c = v(0) + (e1 + e2) / 3.0;
let moves = tri_verts[k * 3][3].to_bits() & scene::TRI_DYNAMIC != 0;
- Some(EmitterTri { tri: k as u32, mat, obj: a.x[1].to_bits(), area, c: c.to_array(), moves, nominal: false, in_tree: false, inst: NO_INST, part: 0 })
+ Some(EmitterTri { tri: k as u32, mat, obj: a.x[1].to_bits(), area, c: c.to_array(), moves, nominal: false, in_tree: false, inst: NO_INST, part: 0, card: is_card(m) })
}
/// An emissive triangle of the emitter CDF: triangle (traversal order), material, object, area.
@@ -138,6 +138,12 @@ pub struct EmitterTri {
/// Its section of that instance's mesh (0 without one): a mesh's triangle does not say which section it is of,
/// so a light sample is told here, as a ray is by its hit.
pub part: u32,
+ /// A rect light's card (its material: `scene::MAT_EMITTER_CARD`): it lights its front side alone.
+ pub card: bool,
+}
+
+fn is_card(m: &scene::GpuMaterial) -> bool {
+ m.tex1[2] == scene::MAT_EMITTER_CARD
}
/// No instance (pathtrace.wgsl `NO_INST`).
@@ -145,13 +151,15 @@ pub const NO_INST: u32 = u32::MAX;
/// `GpuEmitterTri::code`: the emitter moves (`EmitterTri::moves`). Path codes are below it.
pub const EMITTER_MOVES: u32 = 1 << 31;
+/// `GpuEmitterTri::flags`: a rect light's card (`EmitterTri::card`).
+pub const EMITTER_CARD: u32 = 1;
const _: () = assert!((ltree::PATH_BITS + 2) << ltree::PATH_BITS <= EMITTER_MOVES);
/// An emitter's triangle as the kernel's light sampling reads it (pathtrace.wgsl `EmitterTri`; `Table::EmitterTris`,
/// entry i for `emitter_tris[i]`): in world space, the light list's own copy, so a sample reads no placement. v0, e1,
/// e2 in world space; its triangle in the triangles' table (attributes); the instance that places it (`NO_INST`: the
/// triangle is in world space there too); where its weight is (`emitter_codes`) with `EMITTER_MOVES`; its section of
-/// that instance's mesh. 64 bytes.
+/// that instance's mesh; `EMITTER_CARD`. 64 bytes.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
pub struct GpuEmitterTri {
@@ -162,7 +170,8 @@ pub struct GpuEmitterTri {
pub e2: [f32; 3],
pub code: u32,
pub part: u32,
- pub spare: [u32; 3],
+ pub flags: u32,
+ pub spare: [u32; 2],
}
impl GpuEmitterTri {
@@ -171,7 +180,7 @@ impl GpuEmitterTri {
let v = |r: usize| [rows[r][0], rows[r][1], rows[r][2]];
// (As a hit has it: with an instance its section, without one its row, which is its triangle's.)
let part = if e.inst == NO_INST { e.tri } else { e.part };
- GpuEmitterTri { v0: v(0), tri: e.tri, e1: v(1), inst: e.inst, e2: v(2), code: code | if e.moves { EMITTER_MOVES } else { 0 }, part, spare: [0; 3] }
+ GpuEmitterTri { v0: v(0), tri: e.tri, e1: v(1), inst: e.inst, e2: v(2), code: code | if e.moves { EMITTER_MOVES } else { 0 }, part, flags: if e.card { EMITTER_CARD } else { 0 }, spare: [0; 2] }
}
/// As `new`, from its vertices.
@@ -197,13 +206,13 @@ impl GpuEmitterTri {
/// object's copy not shown) keep their mesh's own area: its object has no power, so they weigh nothing, and the light
/// tree has them (`switchable_power`) for when the copy is shown.
pub fn instance_emitters(inst: &scene::Instance, record: u32, tris: &[[glam::Vec3A; 3]], first: u32, numbered: &dyn Fn(usize) -> Option<(usize, u32, u32)>, count: usize, materials: &[scene::GpuMaterial], moves: bool, nominal: Option<f32>) -> Vec<(EmitterTri, [glam::Vec3A; 3])> {
- let dead = EmitterTri { tri: first, mat: 0, obj: inst.object, area: 0.0, c: [0.0; 3], moves, nominal: false, in_tree: false, inst: record, part: 0 };
+ let dead = EmitterTri { tri: first, mat: 0, obj: inst.object, area: 0.0, c: [0.0; 3], moves, nominal: false, in_tree: false, inst: record, part: 0, card: false };
let mut out = vec![(dead, [glam::Vec3A::ZERO; 3]); count];
for (k, t) in tris.iter().enumerate() {
let Some((slot, mat, part)) = numbered(k) else { continue };
let (area, c, w) = placed_emitter(inst, t, mat, materials);
// (A particle system's: weighed by its nominal area, whatever size its pass gives it.)
- out[slot] = (EmitterTri { tri: first + k as u32, mat, area: nominal.unwrap_or(area), c, part, nominal: nominal.is_some(), ..dead }, w);
+ out[slot] = (EmitterTri { tri: first + k as u32, mat, area: nominal.unwrap_or(area), c, part, nominal: nominal.is_some(), card: materials.get(mat as usize).is_some_and(is_card), ..dead }, w);
}
out
}
@@ -1638,7 +1647,7 @@ mod light_lod_tests {
// the one a load with all of them on builds: the plain build's, its powers summed bottom-up.
let mats = [scene::GpuMaterial { emissive: [1.0, 1.0, 1.0, 0.0], ..Default::default() }];
let tris: Vec<EmitterTri> = (0..600u32)
- .map(|i| EmitterTri { tri: i, mat: 0, obj: (i % 6 != 0) as u32, area: 0.5, c: [2.0 * i as f32 + 1.0 / 3.0, 1.0 / 3.0, 0.0], moves: false, nominal: false, in_tree: false, inst: NO_INST, part: 0 })
+ .map(|i| EmitterTri { tri: i, mat: 0, obj: (i % 6 != 0) as u32, area: 0.5, c: [2.0 * i as f32 + 1.0 / 3.0, 1.0 / 3.0, 0.0], moves: false, nominal: false, in_tree: false, inst: NO_INST, part: 0, card: false })
.collect();
let verts: Vec<[f32; 4]> = (0..600).flat_map(|i| [[2.0 * i as f32, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0]]).collect();
let (off, on) = ([[0.0, 0.0, 0.0, 1.0], [0.0; 4]], [[0.0, 0.0, 0.0, 1.0]; 2]);
@@ -1671,7 +1680,7 @@ mod light_lod_tests {
let mut unit = || (rnd() >> 8) as f32 / (1 << 24) as f32;
let mats: Vec<scene::GpuMaterial> = (0..4).map(|k| scene::GpuMaterial { emissive: [k as f32 * 3.0, k as f32, 0.5 * k as f32, 0.0], ..Default::default() }).collect();
let tris: Vec<EmitterTri> = (0..3000)
- .map(|i| EmitterTri { tri: i, mat: if i % 9 == 0 { 0 } else { 1 + i % 3 }, obj: 0, area: 10f32.powf(-6.0 * unit()), c: [300.0 * unit(), 5.0, 100.0 * unit()], moves: i % 50 == 0, nominal: false, in_tree: false, inst: NO_INST, part: 0 })
+ .map(|i| EmitterTri { tri: i, mat: if i % 9 == 0 { 0 } else { 1 + i % 3 }, obj: 0, area: 10f32.powf(-6.0 * unit()), c: [300.0 * unit(), 5.0, 100.0 * unit()], moves: i % 50 == 0, nominal: false, in_tree: false, inst: NO_INST, part: 0, card: false })
.collect();
let (t, total, _) = emitter_cdf(&tris, &emitter_order(&tris, None), &mats, &[], 3, [20.0, 0.0, 30.0, 10.0], EmitterCull::default());
let n = tris.len() as u32;
@@ -1792,9 +1801,9 @@ mod units_tests {
use crate::world::{Geometry, Kind, World};
use glam::{Mat4, Quat};
- /// A world with a ground and a light's card (the card's two triangles are the only still ones: a mesh is a unit
- /// under software traversal), meshes turned and scaled, one that casts no shadow, one hidden, and an instanced mesh
- /// of five instances of which four are drawn.
+ /// A world with a ground and a light's card (an instance each, as every mesh: units under software traversal, and
+ /// no still triangle), meshes turned and scaled, one that casts no shadow, one hidden, and an instanced mesh of
+ /// five instances of which four are drawn.
fn world(ground: bool) -> World {
let mut w = World::default();
w.set_material(1, serde_json::from_value(serde_json::json!({ "name": "m", "color": [0.5, 0.5, 0.5], "opacity": 1, "metalness": 0, "roughness": 1, "emissive": [0, 0, 0], "emissiveIntensity": 0, "doubleSided": true })).unwrap());
@@ -1883,6 +1892,11 @@ mod units_tests {
let (q, n, uv, tangent) = x.triangle(k, base(k));
let v = |r: usize| [p.tri_verts[k * 3 + r][0], p.tri_verts[k * 3 + r][1], p.tri_verts[k * 3 + r][2]];
let edge = |c: usize| [q[c][0] - q[0][0], q[c][1] - q[0][1], q[c][2] - q[0][2]];
+ // (The triangle of a still tree over nothing, after the pool: without area either way.)
+ if sc.units.is_some() && sc.tris.is_empty() && k + 1 == sc.attrs.len() {
+ assert_eq!((edge(1), edge(2), v(1), v(2)), ([0.0; 3], [0.0; 3], [0.0; 3], [0.0; 3]), "{what}: the still tree's own triangle has no area");
+ continue;
+ }
assert_eq!((bits(&q[0]), bits(&edge(1)), bits(&edge(2))), (bits(&v(0)), bits(&v(1)), bits(&v(2))), "{what}: triangle {k}'s first corner and its edges");
let skinned_without_normals = n.iter().flatten().all(|c| *c == 0.0);
if !skinned_without_normals {
@@ -2057,12 +2071,13 @@ mod units_tests {
};
let (su, pu) = build(true);
let (sf, pf) = build(false);
- let ground = usize::from(w.objects.contains_key(&10));
- assert_eq!(su.tris.len(), 2 * ground, "still triangles: the card's only");
+ // (The ground and the light's card come together: `world`.)
+ let ground = 2 * usize::from(w.objects.contains_key(&10));
+ assert_eq!(su.tris.len(), 0, "no still triangle: the card is an instance too");
let u = su.units.as_ref().expect("the scene has units");
assert!(sf.units.is_none() && sf.instances.is_empty(), "flattened: no instance is left");
- // Ten instances and the ground: four meshes shown, one hidden (an instance no ray sees), five of the instanced
- // mesh of which one is hidden: eight units in the top tree, and the ground.
+ // Ten instances, the ground and the card: four meshes shown, one hidden (an instance no ray sees), five of the
+ // instanced mesh of which one is hidden: eight units in the top tree, the ground and the card.
assert_eq!((su.instances.len(), u.count as usize), (10 + ground, 8 + ground), "{:?}", su.instances.iter().map(|i| (i.name.clone(), i.hidden)).collect::<Vec<_>>());
assert!(gpu::instance_features(&su) & gpu::F_UNITS != 0 && gpu::instance_features(&sf) & gpu::F_UNITS == 0);
assert_eq!((pu.params.motion[2].to_bits(), pu.params.motion[3].to_bits() as usize), (u.layout.top_first, 8 + ground));
diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rs
index a9ae806..19d4a5c 100644
--- a/renderer/src/live/edits.rs
+++ b/renderer/src/live/edits.rs
@@ -693,9 +693,9 @@ pub(super) fn rows_for(edit: &mut EditState, grow: &Grow, words: &mut Heap<Strea
}
/// Whether an object's instance is all of it, so that an edit can hide, move or take out the object by it: a mesh's,
-/// or a still model's whose mesh has nothing flattened at each placement beside.
+/// or a still model's whose mesh has no second mesh beside it (`scene::InstMesh::over`).
pub(super) fn whole(i: &scene::InstanceRef, instances: &[scene::Instance], meshes: &[scene::InstMesh]) -> bool {
- i.mesh.own() || (matches!(i.mesh, scene::MeshKind::Model) && instances.get(i.instance as usize).is_some_and(|x| meshes.get(x.mesh as usize).is_some_and(|m| m.rest_count == 0)))
+ i.mesh.own() || (matches!(i.mesh, scene::MeshKind::Model) && instances.get(i.instance as usize).is_some_and(|x| meshes.get(x.mesh as usize).is_some_and(|m| m.over == scene::NO_OVER)))
}
/// An object removed or hidden in place is no longer drawn: hidden where its record's value is (`LiveCore::pick`
@@ -1401,7 +1401,7 @@ impl LiveCore {
// A posed rigid model: every part's instance. Shown, it is placed where it stands and posed as it is
// now (`repose_rigid`, this commit: a move while it was hidden placed nothing).
crate::world::Kind::Model { .. } => {
- let Some(records) = self.sc.tables.retained.rigid(k).filter(|r| r.rest.mats.is_empty()).map(|r| r.records()) else { return false };
+ let Some(records) = self.sc.tables.retained.rigid(k).map(|r| r.records()) else { return false };
let unseen = !world.shown(k);
if records.iter().all(|&r| self.sc.instances.get(r as usize).is_some_and(|i| i.hidden == unseen)) {
continue;
@@ -1445,7 +1445,7 @@ impl LiveCore {
for &(node, i) in placed {
let inst = &mut self.sc.instances[i as usize];
// (A placement without size, as scene code hides by scaling to 0: at a point, where no ray sees it.)
- let (w, gone) = scene::placed_world(world.world_matrix(node), inst.world.w_axis.truncate());
+ let (w, gone) = scene::placed_world(scene::drawn_world(world, node), inst.world.w_axis.truncate());
// (Software traversal: an instance of a mesh that deforms is no unit; its triangles are among the still
// scene's, in the world, and a rebuild moves them.)
if !top.has_mesh(inst.mesh) {
@@ -1795,7 +1795,7 @@ impl LiveCore {
let area = 0.5 * (b - a).cross(c - a).length();
if area > 0.0 {
let centre = (a + b + c) / 3.0;
- let e = crate::EmitterTri { tri: k, mat, obj, area, c: centre.to_array(), moves: false, nominal: false, in_tree: false, inst: crate::NO_INST, part: 0 };
+ let e = crate::EmitterTri { tri: k, mat, obj, area, c: centre.to_array(), moves: false, nominal: false, in_tree: false, inst: crate::NO_INST, part: 0, card: sc.tables.materials[mat as usize].tex1[2] == scene::MAT_EMITTER_CARD };
new.push((sc.tables.emitter_tris.len() as u32, crate::GpuEmitterTri::of(&e, [a, b, c], 0)));
sc.tables.emitter_tris.push(e);
}
@@ -2268,17 +2268,16 @@ impl LiveCore {
/// Posed rigid models (`scene::RigidModel`): each moving node's instance takes object x node transform from the clip
/// (previous rows kept for motion vectors), the instance of the nodes left alone the object's where the object
- /// moved (its emitters moving ones from its first move, `emitters_start_moving`), and their flattened triangles
- /// are re-transformed in place; the commit builds the dynamic BLASes (if they have such triangles) and what is
+ /// moved (its emitters moving ones from its first move, `emitters_start_moving`); the commit builds what is
/// above the instances (the TLAS, or software traversal's top tree over its units). A hidden model's parts are
/// placed as a shown one's, unseen. False when it cannot (software traversal without units, a part that is no
- /// unit, or flattened triangles there; a pose that names other nodes; a model changed): the caller rebuilds.
+ /// unit; a pose that names other nodes; a model changed): the caller rebuilds.
pub(super) fn repose_rigid(&mut self, world: &World, ids: &[u32], build: &mut gpu::TopBuild) -> Result<bool> {
// (Nothing is changed unless all of it can be.)
{
let Some(top) = gpu::Top::of(&mut self.sc.up.accel, &mut self.sc.up.units) else { return Ok(false) };
let (retained, instances) = (&self.sc.tables.retained, &self.sc.instances);
- let placed = |id: &u32| retained.rigid(*id).is_some_and(|r| r.rest.finals.len() == r.rest.mats.len() && r.records().iter().all(|&i| instances.get(i as usize).is_some_and(|x| top.has_mesh(x.mesh))));
+ let placed = |id: &u32| retained.rigid(*id).is_some_and(|r| r.records().iter().all(|&i| instances.get(i as usize).is_some_and(|x| top.has_mesh(x.mesh))));
// (A pose that names other nodes is other parts.)
let same_parts = |id: &u32| match world.objects.get(id).map(|o| &o.kind) {
Some(crate::world::Kind::Model { animation, .. }) => retained.rigid(*id).is_some_and(|r| animation.as_ref().map_or(String::new(), scene::rigid_pose_key) == r.pose),
@@ -2291,7 +2290,6 @@ impl LiveCore {
let mut placements: Vec<(u32, glam::Mat4)> = vec![];
// (Object, where it stands now, and the instance of its nodes left alone if this is its first move.)
let mut worlds: Vec<(u32, glam::Mat4, Option<u32>)> = vec![];
- let (mut lo, mut hi) = (usize::MAX, 0usize);
for id in ids {
let Some(o) = world.objects.get(id) else { return Ok(false) };
let crate::world::Kind::Model { uri, animation, .. } = &o.kind else { return Ok(false) };
@@ -2300,27 +2298,16 @@ impl LiveCore {
let r = self.sc.tables.retained.rigid(*id).expect("a rigid model (`commit`)");
// (The nodes its clip leaves alone move with the object alone.)
let moved = m != r.world;
- placements.extend(r.instances.iter().map(|&(node, i)| (i, m * globals[node])));
+ placements.extend(r.instances.iter().map(|&(node, i)| (i, scene::RigidModel::part_world(m, node, &globals))));
if moved {
placements.extend(r.still.map(|i| (i, m)));
worlds.push((*id, m, r.still.filter(|_| !r.still_moves)));
}
- let d = &r.rest;
- let (first, verts, attrs, blas) = &mut self.sc.dynamic;
- for (j, (node, p, n, uv, tg)) in r.rest_local.iter().enumerate() {
- let (pw, nw, uvw, tw) = scene::placed_tri(scene::RigidModel::part_world(m, *node, &globals), p, n, uv, *tg);
- let a = scene::tri_attr(nw, uvw, tw, d.mats[j]);
- let k = d.finals[j] as usize - *first;
- let (e1, e2) = (pw[1] - pw[0], pw[2] - pw[0]);
- verts[k * 3..k * 3 + 3].copy_from_slice(&[[pw[0].x, pw[0].y, pw[0].z, f32::from_bits(d.flags[j])], [e1.x, e1.y, e1.z, 0.0], [e2.x, e2.y, e2.z, 0.0]]);
- attrs[k] = scene::GpuTriAttr { x: [a.x[0], f32::from_bits(d.object), a.x[2], attrs[k].x[3]], ..a };
- blas[k * 3..k * 3 + 3].copy_from_slice(&scene::blas_tri(pw.map(|v| v.to_array())));
- self.sc.tris[(d.first + j as u32) as usize] = pw.map(glam::Vec3A::from);
- (lo, hi) = (lo.min(k), hi.max(k + 1));
- }
let pivot = m.transform_point3(glam::Vec3::ZERO);
- let o = &mut self.sc.tables.objects[d.object as usize * self.sc.tables.stride];
- (o[0], o[1], o[2]) = (pivot.x, pivot.y, pivot.z);
+ if let Some(object) = self.sc.tables.retained.proxies.get(id).and_then(|p| p.object) {
+ let o = &mut self.sc.tables.objects[object as usize * self.sc.tables.stride];
+ (o[0], o[1], o[2]) = (pivot.x, pivot.y, pivot.z);
+ }
}
for (id, m, first_move) in worlds {
if let Some(scene::Draw::Rigid(r)) = self.sc.tables.retained.proxies.get_mut(&id).map(|p| &mut p.draw) {
@@ -2352,9 +2339,6 @@ impl LiveCore {
self.inst_moving.push(i);
}
}
- if lo < hi {
- self.emitters_moved = true;
- }
// A model's node instances are contiguous: one write.
if ilo < ihi {
self.sc.up.heap.write(&self.g.queue, Table::Instances, ilo as u64 * size, bytemuck::cast_slice(&self.sc.gpu_instances[ilo..ihi]));
@@ -2362,16 +2346,7 @@ impl LiveCore {
self.fill_moved(placements.iter().map(|&(i, _)| i));
self.inst_moved = true;
self.sc.up.heap.write(&self.g.queue, Table::Objects, 0, bytemuck::cast_slice(&self.sc.tables.objects));
- if lo < hi {
- // Motion vectors of the flattened triangles: the previous frame's vertices, as `repose` keeps them.
- let both = self.prev_span.map_or((lo, hi), |(a, b)| (a.min(lo), b.max(hi)));
- self.keep_prev(both);
- self.prev_span = Some((lo, hi));
- self.reposed = true;
- self.upload_dynamic(lo, hi);
- }
build.instances = true;
- build.dynamic |= lo < hi;
Ok(true)
}
@@ -2792,11 +2767,8 @@ impl LiveCore {
continue;
}
// A posed rigid model: its parts' instances out, as an instance is; what an edit placed goes back to the
- // room. (One with triangles flattened beside them is the build's to take out.)
+ // room.
if let Some(r) = tables.retained.rigid(*id) {
- if !r.rest.mats.is_empty() {
- return Err("an object the build placed otherwise (a model in parts, something it flattened) removed".into());
- }
for rec in r.records() {
let rec = rec as usize;
top.clear(inst_base + rec);
@@ -2825,8 +2797,8 @@ impl LiveCore {
// triangles and its skinning job stay until the next rebuild, as the build's do.)
let its_own = |i: &scene::InstanceRef| whole(i, instances, meshes) || (matches!(i.mesh, scene::MeshKind::Skinned(_)) && instances.get(i.instance as usize).is_some_and(|x| top.has_mesh(x.mesh)));
let at = slot_of(*id, edit, tables).or_else(|| tables.retained.instance(*id).filter(|i| its_own(i)).map(|i| (inst_base + i.instance as usize, i.instance as usize)));
- // Drawn, and not at a record an edit can clear (a model with triangles flattened beside its instance,
- // anything the build flattened): a rebuild takes it out.
+ // Drawn, and not at a record an edit can clear (a model of two instances, anything the build flattened): a
+ // rebuild takes it out.
if at.is_none() && tables.retained.proxies.contains_key(id) {
return Err("an object the build placed otherwise (a model in parts, something it flattened) removed".into());
}
@@ -3170,9 +3142,8 @@ impl LiveCore {
emitting.insert(mat);
}
}
- scene::flatten_coincident(&mut classed, &emitting, &|k| local[k].p);
- if !classed[scene::FLAT].is_empty() {
- return Err("a model with triangles the build flattens at each placement".into());
+ if !scene::split_coincident(&mut classed, &emitting, &|k| local[k].p).is_empty() {
+ return Err("a model with a second mesh (triangles on another's vertices): the build's".into());
}
if !classed[1].is_empty() && features & gpu::F_MASKED == 0 {
more.set(more.get() | gpu::F_MASKED);
@@ -3446,8 +3417,6 @@ impl LiveCore {
_ => String::new(),
};
let mut rigid = scene::RigidModel { world: world.world_matrix(id), pose, ..Default::default() };
- // (Its row of the object table: where a new pose or a move writes its pivot.)
- rigid.rest.object = object as u32;
for (j, (node, mut inst, mut mine)) in parts.into_iter().enumerate() {
place(record + j, &mut inst, &mut mine, node != scene::STILL_NODES)?;
if node == scene::STILL_NODES {
diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rs
index fb1fd17..e2f647c 100644
--- a/renderer/src/live/inplace_tests.rs
+++ b/renderer/src/live/inplace_tests.rs
@@ -260,13 +260,6 @@ fn mesh_is_the_cpus(what: &str, c: &LiveCore, id: u32) {
assert_eq!(got.p, want, "{what}: the mesh's corners through its indices");
}
-/// The world-space triangles that move, on the GPU through their indices, are the CPU's (`LoadedScene::dynamic`).
-fn moving_triangles_are_the_cpus(what: &str, c: &LiveCore) {
- let (first, rows, _, corners) = &c.sc.dynamic;
- let got = triangles_on_gpu(c, *first as u64, rows.len() as u64 / 3, 0, None);
- assert_eq!(got.p, corners.iter().flatten().copied().collect::<Vec<f32>>(), "{what}: the moving triangles' corners through their indices");
-}
-
/// Mean absolute difference of two pictures, in 8-bit steps.
fn apart(a: &[u8], b: &[u8]) -> f64 {
assert_eq!(a.len(), b.len());
@@ -482,6 +475,32 @@ fn an_emitting_particle_lights_both_its_sides_beside_a_lights_card() {
assert!(b > 20.0 && (a / b - 1.0).abs() < 0.05, "the wall beside the particle: {a:.1} of 255 with its back to the wall, {b:.1} with its face");
}
+/// A rect light's card lights its front side alone: a wall it faces is lit, and with its back to the wall the wall is
+/// dark (the light list's entry says that an emitter is a card's: `EMITTER_CARD`). Under either traversal.
+#[test]
+fn a_card_lights_its_front_side_alone() {
+ 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 scene = |turned: bool| {
+ let mut w = wall_world(3.0, serde_json::json!({ "name": "none", "color": [0, 0, 0], "opacity": 1, "metalness": 0, "roughness": 1, "emissive": [0, 0, 0], "emissiveIntensity": 0, "doubleSided": true }));
+ let card = serde_json::from_value(serde_json::json!({ "type": "rect", "color": [1, 1, 1], "castShadow": true, "intensity": 5, "width": 0.4, "height": 0.4, "range": 0 })).unwrap();
+ w.set_object(21, "card".into(), None, Kind::Light(card), true, false).unwrap();
+ // (Half a metre before the wall; a rect light shines down its own -Z: at the wall, or turned, at the camera.)
+ w.set_transform(21, Vec3::new(0.0, 0.0, 0.5), glam::Quat::from_rotation_y(if turned { std::f32::consts::PI } else { 0.0 }), Vec3::ONE).unwrap();
+ w
+ };
+ let (mut facing, mut turned) = match (open(&scene(false)), open(&scene(true))) {
+ (Ok(a), Ok(b)) => (a, b),
+ (Err(e), _) | (_, Err(e)) => return eprintln!("skipped: {e}"),
+ };
+ let e = &facing.sc.tables.emitter_tris;
+ assert!(e.len() == 2 && e.iter().all(|e| e.card && e.inst != crate::NO_INST), "the light list: the card's two triangles, its instance's");
+ // (The wall beside the card, as the camera sees it.)
+ let region = [26, 18, 36, 36];
+ let (a, b) = (region_mean(&picture(&mut facing, 64), region), region_mean(&picture(&mut turned, 64), region));
+ assert!(a > 20.0 && b < a * 0.1, "the wall beside the card: {a:.1} of 255 with the card's face to it, {b:.1} with its back");
+}
+
/// A mesh changed in place to triangles of more vertices (a crease: its two triangles share no corner any more) takes
/// another run of vertices, and the mesh that lies after it keeps its own; changed back, it stays where it is. Each
/// is read back through its indices, and the picture is a build's.
@@ -537,12 +556,11 @@ fn a_mesh_changed_in_place_to_more_vertices_takes_another_run() {
against_a_build("flat again", &mut live, &w);
}
-/// Two movable rect lights' cards (world-space triangles that move, one card after the other; a still card's
-/// vertices lie before theirs): each moved alone is written where it lies, the other's vertices as they were; the
-/// motion vectors at its pixels are its step back (its previous positions are its own); the picture is a build's.
-/// (Hardware traversal: under software traversal a world-space triangle that moves is a rebuild's.)
+/// Two movable rect lights' cards beside a still one (instances of the card mesh): each moved alone has its instance
+/// where its light is, the others' as they were; the motion vectors at its pixels are its step back; the picture is
+/// a build's.
#[test]
-fn a_moved_card_beside_another_is_written_where_it_lies() {
+fn a_moved_card_beside_another_is_placed_where_its_light_is() {
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 turn = glam::Quat::from_rotation_y(3.3);
@@ -554,22 +572,42 @@ fn a_moved_card_beside_another_is_written_where_it_lies() {
w.set_transform(id + 100, at[k], turn, Vec3::ONE).unwrap();
}
let mut live = match open(&w) {
- Ok(c) if c.g.hwrt => c,
- Ok(_) => return eprintln!("skipped: no hardware RT"),
+ Ok(c) => c,
Err(e) => return eprintln!("skipped: {e}"),
};
w.take_changes();
- assert!(live.sc.dynamic.1.len() == 12 && live.sc.dynamic_verts.0 > 0, "two cards that move, four triangles, after vertices that do not");
- moving_triangles_are_the_cpus("as loaded", &live);
+ // Each card's instance: its transform, and its record's on the GPU.
+ let cards = |live: &LiveCore| -> Vec<(glam::Mat4, scene::GpuInstance)> {
+ (120..123u32)
+ .map(|id| {
+ let i = live.sc.tables.retained.instance(id).expect("a card is an instance").instance as usize;
+ let size = std::mem::size_of::<scene::GpuInstance>() as u64;
+ let r: Vec<scene::GpuInstance> = read_back(live, &live.sc.up.heap.buffer, live.sc.up.heap.at(Table::Instances) + i as u64 * size, size);
+ assert_eq!(r[0].m, live.sc.gpu_instances[i].m, "card {id}: its record on the GPU is the CPU's");
+ (live.sc.instances[i].world, r[0])
+ })
+ .collect()
+ };
+ let placed = |m: glam::Mat4, to: Vec3| m.abs_diff_eq(scene::card_world(glam::Mat4::from_rotation_translation(turn, to), 0.4, 0.3), 1e-6);
+ assert!(live.sc.dynamic.1.is_empty() && live.sc.tris.is_empty(), "a card is no world-space triangle");
+ let first = cards(&live);
+ assert!((0..3).all(|k| placed(first[k].0, at[k])), "as loaded: each card where its light is");
+ assert!(first.iter().all(|c| c.1.m == c.1.p), "as loaded: nothing has moved");
picture(&mut live, 2);
for (k, to) in [(2, Vec3::new(0.5, 0.5, 1.4)), (1, Vec3::new(-0.4, 0.3, 1.0)), (2, Vec3::new(0.9, 0.9, 1.1))] {
- let (what, before, step) = (format!("card {k} moved"), live.sc.dynamic.3.clone(), at[k] - to);
+ let (what, before, step) = (format!("card {k} moved"), cards(&live), at[k] - to);
at[k] = to;
w.set_transform(120 + k as u32, to, turn, Vec3::ONE).unwrap();
assert!(!live.commit(&mut w).unwrap(), "{what}: in place ({:?})", live.fallback);
- let moved = (0..4).filter(|&t| live.sc.dynamic.3[t * 3..t * 3 + 3] != before[t * 3..t * 3 + 3]).collect::<Vec<_>>();
- assert!(moved == [0, 1] || moved == [2, 3], "{what}: its two triangles alone ({moved:?})");
- moving_triangles_are_the_cpus(&what, &live);
+ let now = cards(&live);
+ for j in 0..3 {
+ if j == k {
+ assert!(placed(now[j].0, to), "{what}: its instance is where its light is");
+ assert_eq!(now[j].1.p, before[j].1.m, "{what}: its record keeps where it was");
+ } else {
+ assert_eq!(now[j].0, before[j].0, "{what}: card {j} stays");
+ }
+ }
// The frame after: where the card is seen, the way back to where it was.
live.render(1, |_, _| {});
let m = &live.targets.kernel.motion;
@@ -3096,11 +3134,11 @@ fn a_model_with_emitters_is_placed_again_in_place() {
lit_as_a_build("another posed rigid model placed after one was removed", &mut live, &mut open(&w).unwrap());
}
-/// A posed rigid model with triangles flattened beside its parts (tests/render/data/panel-decal.glb: a cutout on
-/// exactly an emitter's vertices leaves the mesh with it) is hidden, and removed, by a rebuild: an instance's mask
-/// hides no world-space triangle. The picture is a build's.
+/// A posed rigid model with a part's second mesh (tests/render/data/panel-decal.glb: a cutout on exactly an
+/// emitter's vertices is a mesh apart, an instance beside the part's) is hidden, and removed, as its instances are:
+/// in place. The picture is a build's.
#[test]
-fn a_posed_rigid_model_with_flattened_triangles_is_hidden_and_removed_by_a_rebuild() {
+fn a_posed_rigid_model_with_a_second_mesh_is_hidden_and_removed_in_place() {
let presets = crate::default_presets_dir();
let open = |w: &World| gpu::Gpu::new().and_then(|g| LiveCore::new(g, w, Path::new(".."), &presets, 96, 54));
let model = || Kind::Model { uri: "tests/render/data/panel-decal.glb".into(), nodes: None, animation: Some(crate::desc::Animation { clip: "slide".into(), time: 0.25, r#loop: true, nodes: Default::default() }), functions: vec![] };
@@ -3124,20 +3162,23 @@ fn a_posed_rigid_model_with_flattened_triangles_is_hidden_and_removed_by_a_rebui
Err(e) => return eprintln!("skipped: {e}"),
};
w.take_changes();
- assert!(!live.sc.tables.retained.rigid(32).expect("a posed rigid model").rest.mats.is_empty(), "the model has triangles flattened beside its part");
+ {
+ let r = live.sc.tables.retained.rigid(32).expect("a posed rigid model");
+ assert!(live.sc.tris.is_empty() && r.records().iter().any(|&i| live.sc.meshes.iter().any(|m| m.over == live.sc.instances[i as usize].mesh)), "one of its instances is of a part's second mesh");
+ }
let before = picture(&mut live, 48);
w.set_visible(32, false).unwrap();
- assert!(live.commit(&mut w).unwrap(), "hidden: a rebuild");
- let hidden = pictured("a posed rigid model with flattened triangles hidden", &mut live, &w);
+ assert!(!live.commit(&mut w).unwrap(), "hidden: in place ({:?})", live.fallback);
+ let hidden = pictured("a posed rigid model with a second mesh hidden", &mut live, &w);
assert!(apart(&before, &hidden) > 0.5, "it is gone from the picture ({:.2} steps)", apart(&before, &hidden));
let mut w = scene();
let mut live = open(&w).unwrap();
w.take_changes();
w.remove(32);
- assert!(live.commit(&mut w).unwrap(), "removed: a rebuild");
- let removed = pictured("a posed rigid model with flattened triangles removed", &mut live, &w);
+ assert!(!live.commit(&mut w).unwrap(), "removed: in place ({:?})", live.fallback);
+ let removed = pictured("a posed rigid model with a second mesh removed", &mut live, &w);
assert!(apart(&hidden, &removed) < 0.5, "as when it was hidden ({:.2} steps)", apart(&hidden, &removed));
- // Placed again: what is flattened beside its part is a build's to make.
+ // Placed again: a model with a second mesh is a build's to make.
let mut w = scene();
// (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();
@@ -3148,7 +3189,7 @@ fn a_posed_rigid_model_with_flattened_triangles_is_hidden_and_removed_by_a_rebui
w.set_object(33, "again".into(), None, model(), true, false).unwrap();
w.set_transform(33, Vec3::new(0.6, -0.4, 0.8), glam::Quat::IDENTITY, Vec3::splat(0.08)).unwrap();
assert!(live.commit(&mut w).unwrap(), "placed again: a rebuild");
- let two = pictured("a posed rigid model with flattened triangles placed again", &mut live, &w);
+ let two = pictured("a posed rigid model with a second mesh placed again", &mut live, &w);
assert!(apart(&one, &two) > 0.5, "the second is in the picture ({:.2} steps)", apart(&one, &two));
}
@@ -3320,7 +3361,7 @@ fn a_posed_skinned_model_is_added_in_place() {
let prev_size = live.sc.up.prev_vertices.size();
{
let i = &live.sc.instances[live.sc.tables.retained.skinned[of(&live, 31)].instance as usize];
- assert!(live.sc.dynamic.1.len() == 6 && i.prev == i.verts - live.sc.dynamic_verts.0 && i.prev >= 6, "a mesh's previous positions lie after the card's six vertices'");
+ assert!(i.prev == i.verts - live.sc.dynamic_verts.0, "a mesh's previous positions are counted from the first vertex that moves");
}
// One of a model the scene has, in a pose of its own.
@@ -3348,9 +3389,6 @@ fn a_posed_skinned_model_is_added_in_place() {
check("posed on", &live, 32, &bend(0.8), &bend(0.3));
check("the built one posed on", &live, 30, &bend(0.8), &bend(0.0));
check("the other built one posed on", &live, 31, &bend(0.8), &bend(0.0));
- // (The card did not move: its previous vertices are its own, whatever the meshes' did.)
- let card = 6 * crate::indexed::VERTEX_BYTES as u64;
- assert_eq!(read(&live, &live.sc.up.prev_vertices, 0, card), read(&live, &live.sc.up.vertices, live.sc.dynamic_verts.0 as u64 * crate::indexed::VERTEX_BYTES as u64, card), "the card's previous vertices are its vertices");
let motion = |c: &mut LiveCore| -> Vec<f32> {
(c.fixed_dt, c.frame, c.reset) = (Some(1.0 / 60.0), 16, true);
c.render(1, |_, _| {});
@@ -3650,7 +3688,7 @@ fn the_skinning_pass_writes_what_the_cpu_skin_writes() {
w.set_object(id, format!("m{id}"), None, Kind::Model { uri: format!("tests/render/data/{uri}.glb"), nodes: None, animation: Some(bend(0.0)), functions: vec![] }, true, false).unwrap();
w.set_transform(id, Vec3::new(x, -0.6, 0.8), glam::Quat::from_rotation_y(0.3), Vec3::splat(1.1)).unwrap();
}
- // (A rect light's card, far below: world-space triangles, which come before the meshes' in the GPU's order.)
+ // (A rect light's card, far below: an instance of a mesh that does not deform.)
let card = serde_json::from_value(serde_json::json!({ "type": "rect", "color": [1, 1, 1], "castShadow": true, "intensity": 1, "width": 0.2, "height": 0.2, "range": 0 })).unwrap();
w.set_object(21, "card".into(), None, Kind::Light(card), true, false).unwrap();
w.set_transform(21, Vec3::new(0.0, -60.0, 0.0), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
@@ -3660,7 +3698,7 @@ fn the_skinning_pass_writes_what_the_cpu_skin_writes() {
};
w.take_changes();
let hw = live.g.hwrt;
- assert!(live.sc.edit.pool_first > 0, "a mesh's first triangle on the GPU is not its first in the pool");
+ assert!(live.sc.meshes.iter().any(|m| m.deforms && m.first > 0), "a deforming mesh that is not the pool's first");
{
let g = live.sc.tables.retained.skinned.iter().find(|g| g.uri.ends_with("skin-blend.glb")).expect("the model's mesh");
assert!(g.order.iter().enumerate().any(|(at, &(k, _, _))| at as u32 != k), "the mesh has the model's triangles in another order (by material)");
diff --git a/renderer/src/ltree.rs b/renderer/src/ltree.rs
index 5e00d58..d75f5c6 100644
--- a/renderer/src/ltree.rs
+++ b/renderer/src/ltree.rs
@@ -433,7 +433,7 @@ mod tests {
use super::*;
fn tri(i: u32, x: f32) -> (EmitterTri, [[f32; 4]; 3]) {
- (EmitterTri { tri: i, mat: 0, obj: 0, area: 0.5, c: [x + 1.0 / 3.0, 1.0 / 3.0, 0.0], moves: false, nominal: false, in_tree: false, inst: crate::NO_INST, part: 0 }, [[x, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0]])
+ (EmitterTri { tri: i, mat: 0, obj: 0, area: 0.5, c: [x + 1.0 / 3.0, 1.0 / 3.0, 0.0], moves: false, nominal: false, in_tree: false, inst: crate::NO_INST, part: 0, card: false }, [[x, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0]])
}
/// Garbage in: emitters whose triangles are not finite, that coincide, or carry weights near f32's limit make a
diff --git a/renderer/src/scene.rs b/renderer/src/scene.rs
index a2c33bf..3842dca 100644
--- a/renderer/src/scene.rs
+++ b/renderer/src/scene.rs
@@ -58,9 +58,9 @@ pub fn copy_row(mut row: ObjectRow, dark: bool) -> ObjectRow {
pub struct InstMesh {
pub first: u32,
pub count: u32,
- /// Triangles each placement flattens instead (`flatten_coincident`'s pairs), in the build's rest arrays.
- pub rest_first: u32,
- pub rest_count: u32,
+ /// A model's second mesh, of the triangles that lie on another's vertices (`split_coincident`), or `NO_OVER`:
+ /// every placement of the model has an instance of each.
+ pub over: u32,
/// Model-space bounds (object bounds of its instances, picking).
pub lo: Vec3A,
pub hi: Vec3A,
@@ -77,6 +77,9 @@ pub struct InstMesh {
pub vcount: u32,
}
+/// No second mesh (`InstMesh::over`).
+pub const NO_OVER: u32 = u32::MAX;
+
/// A run of a mesh's triangles that an object draws with one of its materials: a geometry group, or the whole of a
/// geometry drawn with one material. A geometry of the mesh's BLAS; an instance has a row for each (`Instance::rows`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -801,11 +804,11 @@ pub struct Retained {
/// Whether the scene said a mesh's geometry will be edited or driven (`own_blas`, `driven`): it gets room for
/// edits in place (gpu.rs `EditRoom`).
pub edits_meshes: bool,
- /// Static models' instanced meshes by (uri, nodes), those with nothing flattened per placement: a model added in
- /// place is another instance of one (live/edits.rs `edit_geometry`).
+ /// Static models' instanced meshes by (uri, nodes), those without a second mesh (`InstMesh::over`): a model added
+ /// in place is another instance of one (live/edits.rs `edit_geometry`).
pub model_mesh: HashMap<(String, Option<Vec<String>>), u32>,
/// Posed rigid models' parts by (uri, `rigid_pose_key`), each its node (`STILL_NODES`) and its mesh, where every
- /// part is a mesh with nothing flattened beside: one added in place is an instance of each.
+ /// part is a mesh without a second one: one added in place is an instance of each.
pub rigid_meshes: HashMap<(String, String), Vec<(usize, u32)>>,
/// A model's mesh's rows as every instance of it has them (the file's materials, `model_sections`; where a
/// section's triangles and emitters are is each instance's to fill).
@@ -862,6 +865,8 @@ pub enum MeshKind {
Skinned(u32),
/// A geometry's mesh, shared by the objects of the geometry (`Retained::own_mesh`).
Own,
+ /// The rect lights' card (`card_mesh`).
+ Card,
}
impl MeshKind {
@@ -932,7 +937,6 @@ impl Retained {
pub fn dynamics_mut(&mut self) -> impl Iterator<Item = &mut DynamicModel> {
self.proxies.values_mut().filter_map(|p| match &mut p.draw {
Draw::Dynamic(d) => Some(d),
- Draw::Rigid(r) => Some(&mut r.rest),
_ => None,
})
}
@@ -955,11 +959,12 @@ pub struct InstancedPlace {
/// moves and the pose does not name merged into one mesh in the model's space, placed by the object's transform;
/// each other node a mesh in the node's space, placed at object x node transform, so a new pose, of whichever clip,
/// moves instances only (a part's emitters are its
-/// instance's in the light list, filled again when it moves). What `flatten_coincident` takes out of a part's mesh
-/// is flattened: `rest`, re-transformed in place from `rest_local`.
+/// instance's in the light list, filled again when it moves). What `split_coincident` takes out of a part's mesh
+/// is the part's second mesh, an instance beside the part's (with its node, in `instances`).
#[derive(Clone, Default)]
pub struct RigidModel {
- /// (glTF node, instance index): the nodes a pose may move.
+ /// (glTF node, instance index): the nodes a pose may move; and a part's second mesh's (its node `STILL_NODES`
+ /// where the part is the nodes left alone: `part_world`).
pub instances: Vec<(usize, u32)>,
/// The instance of the nodes it leaves alone, if any is drawn. It moves with the object alone; its emitters are
/// still ones until the object first moves (`still_moves`: live/edits.rs `repose_rigid`).
@@ -968,10 +973,6 @@ pub struct RigidModel {
/// The object's transform its parts were last placed by, as `World::world_matrix` gives it (an update compares
/// with it to tell a move from a new pose).
pub world: Mat4,
- pub rest: DynamicModel,
- /// Per `rest` triangle: its node (`STILL_NODES`: the model's own space) and its triangle there (positions,
- /// normals, uvs, tangent).
- pub rest_local: Vec<(usize, [Vec3; 3], [Vec3; 3], [Vec2; 3], Option<CornerTangents>)>,
/// `rigid_pose_key` of the pose its parts were made for: a pose with another is other parts (a build's to make).
pub pose: String,
}
@@ -1003,18 +1004,17 @@ impl RigidModel {
}
/// A part of a rigid model as the build makes it once for the placements of the model with a clip: its node
-/// (`STILL_NODES`), its mesh (None: nothing of it stays in a mesh), and what `flatten_coincident` took out, in the
-/// part's space with its material.
+/// (`STILL_NODES`) and its mesh (None: it has no triangle); the mesh has what `split_coincident` took out
+/// (`InstMesh::over`).
struct RigidPart {
node: usize,
mesh: Option<u32>,
- rest: Vec<([Vec3; 3], [Vec3; 3], [Vec2; 3], Option<CornerTangents>, u32)>,
}
/// 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 meshes without triangles flattened per placement.
+/// one of them took another pose, and that was a rebuild). Only a model none of whose triangles emits.
#[derive(Clone, Debug)]
pub struct Skinned {
pub mesh: u32,
@@ -1159,7 +1159,7 @@ pub struct GpuParticleSystem {
pub collide: world::ParticleCollide,
}
-/// A dynamic object's triangles (posed model, or movable mesh / model / rect-light card): their range in build order,
+/// A dynamic object's triangles (a posed model's, or a movable mesh's or model's the build flattened): their range in build order,
/// and per triangle the material and flags.
#[derive(Clone, Default)]
pub struct DynamicModel {
@@ -1647,9 +1647,6 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
// 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 mut pool_attrs: Vec<GpuTriAttr> = vec![];
- // Model-space triangles of instanced meshes that each placement flattens (`flatten_coincident`'s pairs).
- let mut rest_tris: Vec<[Vec3A; 3]> = vec![];
- let mut rest_attrs: Vec<GpuTriAttr> = vec![];
let mut meshes: Vec<InstMesh> = vec![];
let mut instances: Vec<Instance> = vec![];
let (mut sections, mut rows): (Vec<Section>, Vec<Row>) = (vec![], vec![]);
@@ -1675,6 +1672,8 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
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![];
+ // 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.
let tinted = w.instanced.iter().any(|(id, t)| t.colors.is_some() && w.shown(*id) && matches!(w.objects.get(id).map(|o| &o.kind), Some(Kind::Instanced { .. })));
let stride = object_stride(tinted);
@@ -1864,9 +1863,8 @@ 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's triangles are dynamic (re-skinned in place). A movable one is an instance whose
- // transform moves (hardware RT), unless it has triangles flattened per placement: then they are dynamic
- // too (re-transformed in place).
+ // A posed model the build flattens has dynamic triangles (re-skinned in place). 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;
@@ -1905,52 +1903,35 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
emitting.insert(mat);
}
}
- flatten_coincident(&mut classed, &emitting, &|k| local[k].p);
- let mesh = classed[..FLAT].iter().any(|l| !l.is_empty()).then(|| {
- let first_pool = pool_tris.len() as u32;
- let (order, sects, mine) = model_sections(&kept(&classed));
- for &(k, section, rank) in &order {
- let t = &local[k];
- pool_tris.push([t.p[0].into(), t.p[1].into(), t.p[2].into()]);
- pool_attrs.push(section_attr(t.n, t.uv, t.tangent, section, rank));
- }
- meshes.push(InstMesh { sect_first: sections.len() as u32, sect_count: sects.len() as u32, ..own_inst_mesh(&pool_tris[first_pool as usize..], first_pool) });
- sections.extend(sects);
- retained.mesh_rows.insert(meshes.len() as u32 - 1, mine);
- meshes.len() as u32 - 1
- });
- let rest = classed[FLAT].iter().map(|&(k, mat)| (local[k].p, local[k].n, local[k].uv, local[k].tangent, mat)).collect();
- parts.push(RigidPart { node: *node, mesh, rest });
- }
- if std::env::var("THREERT_INSTANCING").is_ok_and(|v| v == "log") {
- let (merged, rest) = (lists.iter().filter(|l| l.0 == STILL_NODES).map(|l| l.1.len()).sum::<usize>(), parts.iter().map(|p| p.rest.len()).sum::<usize>());
- eprintln!("rigid: {uri} ({}): {merged} triangles of the nodes left alone in one mesh, {} nodes apart, {rest} triangles flattened a placement", a.clip, lists.iter().filter(|l| l.0 != STILL_NODES).count());
+ let over = split_coincident(&mut classed, &emitting, &|k| local[k].p);
+ let mesh = model_meshes(local, &classed, &over, &mut Pool { tris: &mut pool_tris, attrs: &mut pool_attrs, meshes: &mut meshes, sections: &mut sections, instances: &mut instances, rows: &mut rows }, &mut retained.mesh_rows);
+ parts.push(RigidPart { node: *node, mesh });
}
// (What an edit can place again: every part a mesh whole in the pool, the file's own materials.)
- if functions.is_empty() && parts.iter().all(|p| p.mesh.is_some() && p.rest.is_empty()) {
+ if functions.is_empty() && parts.iter().all(|p| p.mesh.is_some_and(|k| meshes[k as usize].over == NO_OVER)) {
retained.rigid_meshes.insert((uri.clone(), rigid_pose_key(a)), parts.iter().filter_map(|p| Some((p.node, p.mesh?))).collect());
}
rigid_parts.insert(pkey.clone(), std::rc::Rc::new(parts));
}
let parts = rigid_parts[&pkey].clone();
- let base_flags = if n.cast_shadow { 0 } else { TRI_NO_SHADOW };
let oi = (objects.len() / stride) as u32;
let (mut olo, mut ohi) = (Vec3A::splat(f32::MAX), Vec3A::splat(f32::MIN));
// (Where the object stands as an update finds it, `World::world_matrix`: the same product as `m`,
// multiplied in another order, so not always the same bits.)
let mut rigid = RigidModel { world: w.world_matrix(*id), pose: rigid_pose_key(a), ..Default::default() };
- rigid.rest.first = tris.len() as u32;
- rigid.rest.object = oi;
for part in parts.iter() {
// (A part placed without size, a node its clip scales to nothing: at a point; `repose_rigid`
// keeps it from the rays.)
let (w_n, _) = placed_world(RigidModel::part_world(m, part.node, &globals), m.w_axis.truncate());
- if let Some(mesh) = part.mesh {
+ // (Its mesh, and the mesh of what lies over it: an instance each, the second with the part's
+ // node among the instances a pose places.)
+ let over = part.mesh.map(|k| meshes[k as usize].over).filter(|&k| k != NO_OVER);
+ for (mesh, second) in part.mesh.map(|k| (k, false)).into_iter().chain(over.map(|k| (k, true))) {
let (lo, hi) = meshes[mesh as usize].placed_bounds(w_n);
(olo, ohi) = (olo.min(lo.into()), ohi.max(hi.into()));
let mine = retained.mesh_rows[&mesh].clone();
let i = instances.len() as u32;
- if part.node == STILL_NODES {
+ if part.node == STILL_NODES && !second {
rigid.still = Some(i);
} else {
rigid.instances.push((part.node, i));
@@ -1958,28 +1939,10 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
instances.push(Instance { mesh, world: w_n, 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 });
rows.extend(mine);
}
- for (p, nn, uv, tg, mat) in &part.rest {
- let (p, nn, uv, tg) = placed_tri(w_n, p, nn, uv, *tg);
- push_tri(&mut tris, &mut tri_flags, &mut attrs, p, nn, uv, tg, *mat, base_flags | TRI_DYNAMIC);
- rigid.rest.mats.push(*mat);
- }
- rigid.rest_local.extend(part.rest.iter().map(|&(p, nn, uv, tg, _)| (part.node, p, nn, uv, tg)));
- }
- for t in &tris[first as usize..] {
- for v in t {
- olo = olo.min(*v);
- ohi = ohi.max(*v);
- }
}
let pivot = m.transform_point3(Vec3::ZERO);
let size = (ohi - olo).max(Vec3A::ZERO);
objects.extend_from_slice(&object_row(pivot, n.power, size, n.custom, [1.0; 3])[..stride]);
- for a in &mut attrs[first as usize..] {
- a.x[1] = f32::from_bits(oi);
- }
- if tris.len() as u32 > first {
- tri_nodes.push((n.name.clone(), first, tris.len() as u32));
- }
*retained.proxy(*id) = Proxy { object: Some(oi), card: None, draw: Draw::Rigid(rigid) };
continue;
}
@@ -2045,7 +2008,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
continue;
}
}
- if instancing && !posed && m.determinant() != 0.0 {
+ if instancing && !posed {
let key = mesh_key.clone();
let mesh = match mesh_of.get(&key) {
Some(k) => *k,
@@ -2062,72 +2025,46 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
emitting.insert(mat);
}
}
- flatten_coincident(&mut classed, &emitting, &|k| local[k].p);
- let k = classed[..FLAT].iter().any(|l| !l.is_empty()).then(|| {
- let (first, rest_first) = (pool_tris.len() as u32, rest_tris.len() as u32);
- let (mut lo, mut hi) = (Vec3A::splat(f32::MAX), Vec3A::splat(f32::MIN));
- for t in &local {
- for v in t.p {
- lo = lo.min(v.into());
- hi = hi.max(v.into());
- }
- }
- let (order, sects, mine) = model_sections(&kept(&classed));
- for &(k, section, rank) in &order {
- let t = &local[k];
- pool_tris.push([t.p[0].into(), t.p[1].into(), t.p[2].into()]);
- pool_attrs.push(section_attr(t.n, t.uv, t.tangent, section, rank));
+ let over = split_coincident(&mut classed, &emitting, &|k| local[k].p);
+ let k = model_meshes(&local, &classed, &over, &mut Pool { tris: &mut pool_tris, attrs: &mut pool_attrs, meshes: &mut meshes, sections: &mut sections, instances: &mut instances, rows: &mut rows }, &mut retained.mesh_rows);
+ // (The mesh's bounds are the model's: its object's, and what picking goes by.)
+ if let Some(k) = k {
+ let im = &mut meshes[k as usize];
+ for v in local.iter().flat_map(|t| t.p) {
+ (im.lo, im.hi) = (im.lo.min(v.into()), im.hi.max(v.into()));
}
- // (What leaves the mesh keeps its material on the triangle: each placement flattens it.)
- for &(k, mat) in &classed[FLAT] {
- let t = &local[k];
- rest_tris.push([t.p[0].into(), t.p[1].into(), t.p[2].into()]);
- rest_attrs.push(tri_attr(t.n, t.uv, t.tangent, mat));
- }
- meshes.push(InstMesh { rest_first, rest_count: classed[FLAT].len() as u32, lo, hi, sect_first: sections.len() as u32, sect_count: sects.len() as u32, ..own_inst_mesh(&pool_tris[first as usize..], first) });
- sections.extend(sects);
- retained.mesh_rows.insert(meshes.len() as u32 - 1, mine);
- meshes.len() as u32 - 1
- });
+ }
if std::env::var("THREERT_INSTANCING").is_ok_and(|v| v == "log") {
- eprintln!("instancing: {uri} {nodes:?}: {} opaque, {} cutout, {} glass instanced; {} flattened per placement", classed[0].len(), classed[1].len(), classed[2].len(), classed[FLAT].len());
+ 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].rest_count == 0) {
+ if let Some(k) = k.filter(|&k| meshes[k as usize].over == NO_OVER) {
retained.model_mesh.insert(key.clone(), k);
}
mesh_of.insert(key, k);
k
}
};
- if let Some(mesh) = mesh.filter(|&k| !movable || meshes[k as usize].rest_count == 0) {
- // Object entry from the placed mesh bounds (the box of the transformed model-space box).
+ if let Some(mesh) = mesh {
+ // Object entry from the placed mesh bounds (the box of the transformed model-space box). A
+ // model placed without size is an instance no ray sees (`placed_world`), as a mesh is.
let im = meshes[mesh as usize];
- let (lo, hi) = im.placed_bounds(m);
let pivot = m.transform_point3(Vec3::ZERO);
- let size = hi - lo;
+ let (world, gone) = placed_world(m, pivot);
+ let (lo, hi) = im.placed_bounds(world);
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 }, hi - lo, n.custom, [1.0; 3])[..stride]);
retained.proxy(*id).object = Some(oi);
- let mine = retained.mesh_rows[&mesh].clone();
- let inst = 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 };
- rows.extend(mine);
- // Its glass / function triangles as ordinary world-space ones (same object).
- for k in im.rest_first..im.rest_first + im.rest_count {
- let (t, a, _) = inst.flat(&rest_tris[k as usize], &rest_attrs[k as usize], None);
- tris.push(t);
- tri_flags.push(flags);
- attrs.push(a);
- }
- if tris.len() as u32 > first {
- tri_nodes.push((n.name.clone(), first, tris.len() as u32));
- }
- // (Its proxy has the instance where the instance is all of it: one with triangles flattened at
- // its placement beside is the build's to change, `Draw::Fixed`.)
- if im.rest_count == 0 {
+ // (Its proxy has the instance where the instance is all of it: a model with a second mesh is
+ // two instances, the build's to change, `Draw::Fixed`.)
+ if im.over == NO_OVER {
retained.proxy(*id).draw = Draw::Instance(InstanceRef { instance: instances.len() as u32, mesh: MeshKind::Model, moves: movable });
}
- instances.push(inst);
+ for mesh in [mesh, im.over].into_iter().filter(|&k| k != NO_OVER) {
+ let mine = retained.mesh_rows[&mesh].clone();
+ 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);
+ }
continue;
}
}
@@ -2147,17 +2084,21 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
retained.light_nodes.push(*id);
}
(Light::Rect { color, intensity, width, height, .. }, None) if shown => {
- // Visible one-sided emissive quad (importance sampled as an emitter).
+ // Its card, a one-sided emissive quad the lights are sampled by as any emitter: an instance of
+ // the scene's card mesh, sized by its transform (`card_world`), its material its row's. It
+ // casts no shadow. A move is the instance's.
let mat = materials.len() as u32;
materials.push(card_material(*color, *intensity));
- retained.proxy(*id).card = Some(mat);
- let movable = w.movable(*id);
- for (v, dir) in card_tris(m, *width, *height) {
- push_tri(&mut tris, &mut tri_flags, &mut attrs, v, [dir; 3], [Vec2::ZERO; 3], None, mat, if movable { TRI_NO_SHADOW | TRI_DYNAMIC } else { TRI_NO_SHADOW });
- }
- if movable {
- retained.proxy(*id).draw = Draw::Dynamic(DynamicModel { first, mats: vec![mat; 2], ..Default::default() });
- }
+ let mesh = *card.get_or_insert_with(|| card_mesh(&mut Pool { tris: &mut pool_tris, attrs: &mut pool_attrs, meshes: &mut meshes, sections: &mut sections, instances: &mut instances, rows: &mut rows }));
+ let pivot = m.transform_point3(Vec3::ZERO);
+ let (world, gone) = placed_world(card_world(m, *width, *height), pivot);
+ let (lo, hi) = meshes[mesh as usize].placed_bounds(world);
+ let oi = (objects.len() / stride) as u32;
+ objects.extend_from_slice(&object_row(pivot, if gone { 0.0 } else { n.power }, hi - lo, n.custom, [1.0; 3])[..stride]);
+ *retained.proxy(*id) = Proxy { object: Some(oi), card: Some(mat), draw: Draw::Instance(InstanceRef { instance: instances.len() as u32, mesh: MeshKind::Card, moves: w.movable(*id) }) };
+ let mine = [row_of(mat, &materials)];
+ instances.push(Instance { mesh, world, object: oi, cast_shadow: false, 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);
}
_ => {}
},
@@ -2450,17 +2391,35 @@ fn to_rgba(img: &gltf::image::Data) -> Result<image::RgbaImage> {
image::RgbaImage::from_raw(w, h, rgba).ok_or_else(|| anyhow!("bad image"))
}
-/// Triangles of scene-code geometry (three.js conventions: UV v up, flipped to the renderer's v down) under `world`.
-/// A visible rect light's one-sided emissive quad (two triangles, winding so the geometric normal faces the light's
-/// direction), slightly in front of the light.
-fn card_tris(m: Mat4, width: f32, height: f32) -> [([Vec3; 3], Vec3); 2] {
- let pos = m.transform_point3(Vec3::ZERO);
- let dir = m.transform_vector3(Vec3::NEG_Z).normalize();
- let ux = m.transform_vector3(Vec3::X).normalize() * (width * 0.5);
- let uy = m.transform_vector3(Vec3::Y).normalize() * (height * 0.5);
- let c = pos + dir * 0.001;
- let p = [c - ux - uy, c + ux - uy, c + ux + uy, c - ux + uy];
- [([p[0], p[2], p[1]], dir), ([p[0], p[3], p[2]], dir)]
+/// The visible rect lights' card, a mesh of the pool: a unit quad in a light's own space, 1 mm in front of the light
+/// (which shines down -Z), its two triangles wound so that their geometric normal is the light's direction; one
+/// section. An instance a light sizes it (`card_world`), and the instance's row has the light's material.
+fn card_mesh(pool: &mut Pool) -> u32 {
+ let p = [Vec3A::new(-0.5, -0.5, -0.001), Vec3A::new(0.5, -0.5, -0.001), Vec3A::new(0.5, 0.5, -0.001), Vec3A::new(-0.5, 0.5, -0.001)];
+ let first = pool.tris.len() as u32;
+ for (k, t) in [[p[0], p[2], p[1]], [p[0], p[3], p[2]]].into_iter().enumerate() {
+ pool.tris.push(t);
+ pool.attrs.push(section_attr([Vec3::NEG_Z; 3], [Vec2::ZERO; 3], None, 0, k as u32));
+ }
+ pool.meshes.push(InstMesh { sect_first: pool.sections.len() as u32, sect_count: 1, ..own_inst_mesh(&pool.tris[first as usize..], first) });
+ pool.sections.push(Section { first: 0, count: 2, slot: 0 });
+ pool.meshes.len() as u32 - 1
+}
+
+/// Where a rect light at `m`, `width` by `height`, has its card: the light's axes, each of its own length (a light's
+/// scale does not size it), the card's width and height along the first two.
+pub fn card_world(m: Mat4, width: f32, height: f32) -> Mat4 {
+ let axis = |v: Vec3| m.transform_vector3(v).normalize();
+ Mat4::from_cols((axis(Vec3::X) * width).extend(0.0), (axis(Vec3::Y) * height).extend(0.0), axis(Vec3::Z).extend(0.0), m.transform_point3(Vec3::ZERO).extend(1.0))
+}
+
+/// The transform of the instance that draws object `node`: the object's, or for a rect light its card's.
+pub fn drawn_world(w: &World, node: u32) -> Mat4 {
+ let m = w.world_matrix(node);
+ match w.objects.get(&node).map(|o| &o.kind) {
+ Some(Kind::Light(Light::Rect { width, height, visible: true, .. })) => card_world(m, *width, *height),
+ _ => m,
+ }
}
/// A dynamic object's triangles at its current transform / pose, with their shading attributes (materials as built):
@@ -2487,36 +2446,67 @@ pub fn dynamic_tris(w: &World, id: u32, d: &DynamicModel, assets: &Path) -> Resu
}
Some(tris.iter().zip(&d.mats).map(|(t, &mat)| (t.p, tri_attr(t.n, t.uv, t.tangent, mat))).collect())
}
- Kind::Light(Light::Rect { width, height, visible: true, .. }) => {
- Some(card_tris(m, *width, *height).iter().zip(&d.mats).map(|((v, dir), &mat)| (*v, tri_attr([*dir; 3], [Vec2::ZERO; 3], None, mat))).collect())
- }
_ => None,
})
}
-/// A model's triangles by class (`classed`: opaque, cutout, glass, and `FLAT`: what leaves the mesh; each a triangle's
-/// index and material). Triangles on exactly the same vertices leave the mesh together in two cases: one that emits (a
-/// material of `emitting`) with a cutout over it (Zero Day: masked decals over emissive quads of the same shape), and
-/// glass with whatever lies under it. A cutout hit that its alpha lets through steps the ray on past it
-/// (trace_hw.wgsl), and past what lies at the same t: in one BLAS the emitter under the decal went with it (black
-/// through the decal); and which of two triangles at one distance a closest hit reports is not said. Flattened, the
-/// two are in BLASes apart and the opaque one is met first, as the software BVH has it.
-pub fn flatten_coincident(classed: &mut [Vec<(usize, u32)>; 4], emitting: &std::collections::HashSet<u32>, p: &dyn Fn(usize) -> [Vec3; 3]) {
+/// A model's triangles by class (`classed`: opaque, cutout, glass; each a triangle's index and material): those that
+/// lie on exactly another's vertices leave the mesh, in two cases: a cutout on a triangle that emits (a material of
+/// `emitting`; Zero Day: masked decals over emissive quads of the same shape), and glass on an opaque triangle or
+/// a cutout. A cutout hit that its alpha lets through steps the ray on past it (trace_hw.wgsl), and past what lies at
+/// the same t: in one BLAS the emitter under the decal went with it (black through the decal); and which of two
+/// triangles at one distance a closest hit reports is not said. Returns what leaves, each with its class: the
+/// model's second mesh (`InstMesh::over`), a BLAS apart.
+pub fn split_coincident(classed: &mut [Vec<(usize, u32)>; 4], emitting: &std::collections::HashSet<u32>, p: &dyn Fn(usize) -> [Vec3; 3]) -> Vec<(usize, u32, u32)> {
let key = |k: usize| {
let mut v = p(k).map(|p| [p.x.to_bits(), p.y.to_bits(), p.z.to_bits()]);
v.sort_unstable();
v
};
- let keys = |list: &[(usize, u32)]| -> std::collections::HashSet<[[u32; 3]; 3]> { list.iter().map(|&(k, _)| key(k)).collect() };
- let (cutouts, glass) = (keys(&classed[1]), keys(&classed[2]));
- let mut flat = keys(&classed[FLAT]);
- flat.extend(classed[0].iter().filter(|(_, mat)| emitting.contains(mat)).map(|&(k, _)| key(k)).filter(|v| cutouts.contains(v)));
- flat.extend(classed[..2].iter().flatten().map(|&(k, _)| key(k)).filter(|v| glass.contains(v)));
- for c in 0..FLAT {
- let (stay, go): (Vec<_>, Vec<_>) = classed[c].iter().partition(|&&(k, _)| !flat.contains(&key(k)));
- classed[c] = stay;
- classed[FLAT].extend(go);
+ 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();
+ let mut over = vec![];
+ for (class, on) in [(1, &emitters), (2, &under)] {
+ 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)));
}
+ over
+}
+
+/// A model's triangles `list` (each one's index in `local`, its material and its class) as a mesh of the pool, laid
+/// out by section (`model_sections`); its rows, the file's materials, go to `mesh_rows`.
+fn model_mesh(local: &[crate::skin::ModelTri], list: &[(usize, u32, u32)], pool: &mut Pool, mesh_rows: &mut HashMap<u32, Vec<Row>>) -> u32 {
+ let first = pool.tris.len() as u32;
+ let (order, sects, mine) = model_sections(list);
+ for &(k, section, rank) in &order {
+ let t = &local[k];
+ pool.tris.push([t.p[0].into(), t.p[1].into(), t.p[2].into()]);
+ pool.attrs.push(section_attr(t.n, t.uv, t.tangent, section, rank));
+ }
+ pool.meshes.push(InstMesh { sect_first: pool.sections.len() as u32, sect_count: sects.len() as u32, ..own_inst_mesh(&pool.tris[first as usize..], first) });
+ pool.sections.extend(sects);
+ let k = pool.meshes.len() as u32 - 1;
+ mesh_rows.insert(k, mine);
+ k
+}
+
+/// A model's meshes (`model_mesh`) of its triangles by class after `split_coincident` took `over` out: the mesh, with
+/// the second one if anything left (`InstMesh::over`). None: the model has no triangle.
+fn model_meshes(local: &[crate::skin::ModelTri], classed: &[Vec<(usize, u32)>; 4], over: &[(usize, u32, u32)], pool: &mut Pool, mesh_rows: &mut HashMap<u32, Vec<Row>>) -> Option<u32> {
+ // (Nothing under what lies over: that is the mesh.)
+ let (main, over) = match kept(classed) {
+ main if main.is_empty() => (over.to_vec(), vec![]),
+ main => (main, over.to_vec()),
+ };
+ (!main.is_empty()).then(|| {
+ let k = model_mesh(local, &main, pool, mesh_rows);
+ if !over.is_empty() {
+ pool.meshes[k as usize].over = model_mesh(local, &over, pool, mesh_rows);
+ }
+ k
+ })
}
/// Whether a material created since the build can be drawn in place (tables.rs `add_materials`): 0 only when it is
@@ -2704,8 +2694,7 @@ pub fn mesh_class(g: &GpuMaterial) -> u32 {
}
}
-/// `classed`'s last list: what leaves a mesh and is flattened at each placement (`flatten_coincident`'s pairs; the
-/// emitters of a mesh that deforms).
+/// `classed`'s last list: the emitters of a mesh that deforms, which leave it (the model is flattened then).
pub const FLAT: usize = 3;
/// The build's arrays a mesh of the pool and its instance are added to.
@@ -2753,7 +2742,7 @@ pub fn own_inst_mesh(tris: &[[Vec3A; 3]], first: u32) -> InstMesh {
}
}
let count = tris.len() as u32;
- InstMesh { first, count, rest_first: 0, rest_count: 0, lo, hi, deforms: false, sect_first: 0, sect_count: 0, colored: false, vfirst: 0, vcount: 0 }
+ InstMesh { first, count, over: NO_OVER, lo, hi, deforms: false, sect_first: 0, sect_count: 0, colored: false, vfirst: 0, vcount: 0 }
}
/// The GPU material of each triangle of a mesh with several (`Kind::Mesh::materials`, here GPU indices) by its
@@ -3032,6 +3021,47 @@ mod instance_tests {
assert_eq!(sc.instances.iter().map(|i| i.gpu(0).n[1][3].to_bits()).collect::<Vec<_>>(), [INST_MIRRORED, 0, 0, 0], "and its record says so");
}
+ /// A visible rect light's card is an instance of one card mesh: the lights share the mesh, each instance has its
+ /// light's size and place, its material in its row, and casts no shadow; its two triangles stand 1 mm in front of
+ /// the light, facing where it shines, and are its emitters, marked as a card's. A light without size has an
+ /// instance no ray sees. No world-space triangle. No GPU.
+ #[test]
+ fn a_rect_lights_card_is_an_instance_of_the_card_mesh() {
+ let mut w = World::default();
+ let rect = |width: f32, height: f32| Kind::Light(serde_json::from_value(serde_json::json!({ "type": "rect", "color": [1, 0.5, 0.25], "castShadow": true, "intensity": 3, "width": width, "height": height, "range": 0 })).unwrap());
+ w.set_object(1, "a".into(), None, rect(2.0, 1.0), true, false).unwrap();
+ // (Turned to shine along +X, and scaled: a light's scale does not size its card.)
+ w.set_transform(1, Vec3::new(1.0, 2.0, 3.0), glam::Quat::from_rotation_y(-std::f32::consts::FRAC_PI_2), Vec3::new(5.0, 7.0, 9.0)).unwrap();
+ w.set_object(2, "b".into(), None, rect(0.5, 0.5), true, true).unwrap();
+ w.set_object(3, "none".into(), None, rect(0.0, 1.0), true, false).unwrap();
+ 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 mut sc = build(&w, Path::new("."), &crate::default_presets_dir(), None).unwrap();
+ assert_eq!((sc.tris.len(), sc.meshes.len(), sc.instances.len(), sc.lights.len()), (0, 1, 3, 0), "one mesh, an instance a card, no table light");
+ let m = sc.meshes[0];
+ assert_eq!((m.count, m.sect_count, m.deforms), (2, 1, false));
+ let inst = |id: u32| sc.instances[sc.retained.instance(id).expect("a card is an instance").instance as usize].clone();
+ let (a, b, none) = (inst(1), inst(2), inst(3));
+ assert_eq!([a.mesh, b.mesh, none.mesh], [0; 3], "the cards share the mesh");
+ assert_eq!([(a.cast_shadow, a.hidden), (b.cast_shadow, b.hidden), (none.cast_shadow, none.hidden && none.masked)], [(false, false), (false, false), (false, true)], "no card casts a shadow; one without size is unseen");
+ assert_eq!([sc.retained.instance(1).unwrap().moves, sc.retained.instance(2).unwrap().moves], [false, true], "a movable light's card moves as its instance");
+ // The first card in the world: 2 m along the light's X (the world's Z here), 1 m up, 1 mm in front (+X).
+ let corners: Vec<Vec3> = sc.pool_tris[m.first as usize..(m.first + m.count) as usize].iter().flatten().map(|p| a.world.transform_point3((*p).into())).collect();
+ let (lo, hi) = corners.iter().fold((Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)), |(lo, hi), p| (lo.min(*p), hi.max(*p)));
+ assert!(lo.abs_diff_eq(Vec3::new(1.001, 1.5, 2.0), 1e-5) && hi.abs_diff_eq(Vec3::new(1.001, 2.5, 4.0), 1e-5), "{lo} to {hi}");
+ for t in corners.chunks(3) {
+ assert!((t[1] - t[0]).cross(t[2] - t[0]).normalize().abs_diff_eq(Vec3::X, 1e-5), "a triangle faces where the light shines");
+ }
+ // Each row has its card's own material, which emits; the emitters are the instances'.
+ let mats: Vec<u32> = [&a, &b].iter().map(|i| row_material(&sc.rows[i.rows as usize])).collect();
+ assert!(mats[0] != mats[1] && mats.iter().all(|&k| sc.materials[k as usize].tex1[2] == MAT_EMITTER_CARD) && sc.retained.proxies[&1].card == Some(mats[0]));
+ let p = crate::prepare_as(true, false, &mut sc, &mut vec![]);
+ // (A card no ray sees keeps its place in the list, as every hidden instance: its object has no power.)
+ assert_eq!(p.emitter_tris.len(), 6, "two triangles a card");
+ assert!(p.emitter_tris.iter().all(|e| e.card && e.inst != crate::NO_INST) && p.gpu_emitter_tris.iter().all(|e| e.flags == crate::EMITTER_CARD));
+ }
+
/// An instanced object whose material only emits is placed as any other: one shared mesh, which has the emitters,
/// an instance a copy; a hidden copy's entry has no power. `prepare` gives every copy, the hidden too, its run of
/// the light list, of emitters that move: a hidden copy's at its mesh's own area and no weight.
@@ -3064,8 +3094,7 @@ mod instance_tests {
/// A model placed mirrored (a negative scale) is an instance as one placed straight is, of the same mesh: a model
/// that stays and a rigid model's moving node (tests/render/data/panel-decal.glb). The meshes do not depend on
- /// the placement's hand; the instances' records say that they mirror; what the build flattens of them keeps
- /// facing as its normals do.
+ /// the placement's hand; the instances' records say that they mirror, a second mesh's instance too.
#[test]
fn a_mirrored_model_is_an_instance_of_the_same_mesh() {
let scene = |x: f32| {
@@ -3082,21 +3111,15 @@ mod instance_tests {
build(&w, Path::new(".."), &crate::default_presets_dir(), None).unwrap()
};
let (straight, mirrored) = (scene(1.0), scene(-1.0));
- let meshes = |sc: &Scene| sc.meshes.iter().map(|m| (m.first, m.count, m.sect_count, m.rest_count)).collect::<Vec<_>>();
+ let meshes = |sc: &Scene| sc.meshes.iter().map(|m| (m.first, m.count, m.sect_count, m.over)).collect::<Vec<_>>();
assert_eq!(meshes(&mirrored), meshes(&straight));
assert_eq!(mirrored.pool_tris, straight.pool_tris, "the meshes' triangles are the model's own, whatever places them");
assert_eq!((mirrored.instances.len(), mirrored.tris.len()), (straight.instances.len(), straight.tris.len()));
assert_eq!((&mirrored.sections, &mirrored.rows), (&straight.sections, &straight.rows), "and their sections and rows");
assert!(straight.instances.len() >= 2 && straight.instances.iter().all(|i| i.gpu(0).n[1][3].to_bits() & INST_MIRRORED == 0));
assert!(mirrored.instances.iter().all(|i| i.gpu(0).n[1][3].to_bits() & INST_MIRRORED != 0), "every instance of a mirrored model mirrors");
- // What is flattened of them (the cutout on an emitter with its emitter: a still model's, a moving node's) faces
- // as its normals do, mirrored too.
- for (sc, what) in [(&straight, "straight"), (&mirrored, "mirrored")] {
- assert!(!sc.tris.is_empty());
- for (t, a) in sc.tris.iter().zip(&sc.attrs) {
- assert!((t[1] - t[0]).cross(t[2] - t[0]).dot(Vec3A::new(a.n0[0], a.n0[1], a.n0[2])) > 0.0, "{what}: a flattened triangle faces away from its normals");
- }
- }
+ // (The cutout on an emitter: a mesh apart, a still model's and a moving node's, an instance each.)
+ assert!(straight.tris.is_empty() && straight.meshes.iter().filter(|m| m.over != NO_OVER).count() == 2 && straight.instances.len() == 4);
}
/// A mesh of a geometry drawn by its groups lies by section, a group after another: a triangle in no group is not
@@ -3178,7 +3201,7 @@ mod instance_tests {
w.set_transform(id, Vec3::new(id as f32 * 5.0, 0.0, 0.0), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
}
let mut sc = build(&w, Path::new(".."), &crate::default_presets_dir(), None).unwrap();
- assert_eq!(sc.meshes.iter().map(|m| (m.count, m.sect_count, m.rest_count)).collect::<Vec<_>>(), [(6, 3, 0)]);
+ assert_eq!(sc.meshes.iter().map(|m| (m.count, m.sect_count, m.over)).collect::<Vec<_>>(), [(6, 3, NO_OVER)]);
assert_eq!((sc.instances.len(), sc.tris.len()), (2, 0));
assert_eq!(sc.meshes[0].parts(&sc.sections), [(0, 2), (2, 2), (4, 2)], "a geometry a section");
assert_eq!(sc.pool_attrs.iter().map(|a| (a.uv[3].to_bits(), a.x[3].to_bits())).collect::<Vec<_>>(), [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)], "a triangle's section and its index in it");
@@ -3204,31 +3227,63 @@ mod instance_tests {
assert_eq!(rows, [[7, 0, NO_EMITTER, 0], [8 | ROW_CUTOUT, 0, NO_EMITTER, 0], [9 | ROW_GLASS, 0, NO_EMITTER, 0]]);
}
- /// A cutout on exactly an emitter's vertices leaves the mesh with it (`flatten_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): each mesh keeps the grey quad alone.
+ /// A model placed without size (scene code hides by scaling to 0) is an instance no ray sees, of the model's
+ /// mesh, as one with a size is: nothing of it is a world-space triangle, and its object has no power.
+ #[test]
+ fn a_model_without_size_is_an_instance_no_ray_sees() {
+ 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, Vec3::ONE), (2, Vec3::ZERO), (3, Vec3::new(1.0, 0.0, 1.0))] {
+ w.set_object(id, format!("model{id}"), None, Kind::Model { uri: "tests/render/data/frame-pane.glb".into(), nodes: None, animation: None, functions: vec![] }, true, false).unwrap();
+ w.set_transform(id, Vec3::new(id as f32 * 5.0, 0.0, 0.0), glam::Quat::IDENTITY, scale).unwrap();
+ }
+ let sc = build(&w, Path::new(".."), &crate::default_presets_dir(), None).unwrap();
+ assert_eq!((sc.tris.len(), sc.meshes.len(), sc.instances.len()), (0, 1, 3), "one mesh, an instance a placement");
+ assert_eq!(sc.instances.iter().map(|i| (i.hidden, i.masked)).collect::<Vec<_>>(), [(false, false), (true, true), (true, true)]);
+ assert!(sc.instances.iter().all(|i| i.world.is_finite() && glam::Mat3::from_mat4(i.world).determinant() != 0.0), "each stands somewhere");
+ 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), power(3)], [1.0, 0.0, 0.0], "an unseen model's object has no power");
+ assert!(matches!(sc.retained.proxies[&2].draw, Draw::Instance(_)), "it comes back as its instance does");
+ }
+
+ /// 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
+ /// cutout is a mesh apart with an instance beside the first's, and nothing is a world-space triangle.
#[test]
- fn a_cutout_on_an_emitter_is_flattened_with_it() {
+ fn a_cutout_on_an_emitter_is_the_models_second_mesh() {
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 model = |animation| Kind::Model { uri: "tests/render/data/panel-decal.glb".into(), nodes: None, animation, functions: vec![] };
w.set_object(1, "still".into(), None, model(None), true, false).unwrap();
+ w.set_transform(1, Vec3::new(3.0, 1.0, -2.0), glam::Quat::from_rotation_y(0.5), Vec3::splat(1.5)).unwrap();
w.set_object(2, "posed".into(), None, model(Some(desc::Animation { clip: "slide".into(), time: 0.25, r#loop: true, nodes: Default::default() })), true, false).unwrap();
let sc = build(&w, Path::new(".."), &crate::default_presets_dir(), None).unwrap();
- let mesh = |name: &str| {
- let i = sc.instances.iter().find(|i| i.name == name).unwrap();
- let m = &sc.meshes[i.mesh as usize];
- (m.count, m.rest_count, rows_emitters(m.sections(&sc.sections), &sc.rows[i.rows as usize..][..m.sect_count as usize], &sc.materials))
+ assert_eq!(sc.tris.len(), 0, "no world-space triangle");
+ // An object's instances: (triangles of the mesh, whether it has a second mesh, the instance's emitters, its rows' classes).
+ let of = |name: &str| {
+ sc.instances
+ .iter()
+ .filter(|i| i.name == name)
+ .map(|i| {
+ let m = &sc.meshes[i.mesh as usize];
+ let rows = &sc.rows[i.rows as usize..][..m.sect_count as usize];
+ (m.count, m.over != NO_OVER, rows_emitters(m.sections(&sc.sections), rows, &sc.materials), rows.iter().map(|r| r[0] & (ROW_CUTOUT | ROW_GLASS)).collect::<Vec<_>>())
+ })
+ .collect::<Vec<_>>()
};
- assert_eq!((mesh("still"), mesh("posed")), ((2, 4, 0), (2, 0, 0)), "(triangles in the mesh, flattened a placement, emitters of the instance)");
- let count = |f: &dyn Fn(usize) -> bool| (0..sc.tris.len()).filter(|&k| f(k)).count();
- let emits = |k: usize| sc.materials[sc.attrs[k].uv[3].to_bits() as usize].emissive[..3].iter().any(|e| *e > 0.0);
- let flattened = (sc.tris.len(), count(&emits), count(&|k| sc.tri_flags[k] & TRI_MASKED != 0), count(&|k| sc.tri_flags[k] & TRI_DYNAMIC != 0));
- assert_eq!(flattened, (8, 4, 4, 4), "flattened: (triangles, emitting, cutout, the moving node's)");
+ assert_eq!(of("still"), [(4, true, 2, vec![0, 0]), (2, false, 0, vec![ROW_CUTOUT])], "the model's mesh (the grey quad and the emitter), then the cutout's");
+ let still: Vec<&Instance> = sc.instances.iter().filter(|i| i.name == "still").collect();
+ assert!(still[0].world == still[1].world && still[0].world != Mat4::IDENTITY && still[0].object == still[1].object && sc.meshes[still[0].mesh as usize].over == still[1].mesh, "the second instance is of the mesh's second, at the same place, of the same object");
+ assert!(matches!(sc.retained.proxies[&1].draw, Draw::Fixed), "a model of two instances is the build's to change");
+ // The posed model's moving node: the same two meshes of its own, both instances the pose's to place.
+ assert_eq!(of("posed"), of("still"));
let Draw::Rigid(r) = &sc.retained.proxies[&2].draw else { panic!("the posed model is rigid") };
- assert_eq!((r.instances.len(), r.rest.mats.len()), (1, 4));
+ assert!(r.still.is_none() && r.instances.len() == 2 && r.instances[0].0 == r.instances[1].0, "{:?}", r.instances);
}
/// A posed rigid model is its parts (tests/render/data/panel-slider.glb: a node its clip leaves alone, a grey quad
@@ -3247,7 +3302,7 @@ mod instance_tests {
w.set_transform(id, Vec3::new(id as f32 * 20.0, 0.0, 0.0), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
}
let mut sc = build(&w, Path::new(".."), &crate::default_presets_dir(), None).unwrap();
- assert_eq!(sc.meshes.iter().map(|m| (m.count, m.sect_count, m.rest_count)).collect::<Vec<_>>(), [(4, 2, 0), (2, 1, 0)], "the part left alone (two materials), the moved node");
+ assert_eq!(sc.meshes.iter().map(|m| (m.count, m.sect_count, m.over)).collect::<Vec<_>>(), [(4, 2, NO_OVER), (2, 1, NO_OVER)], "the part left alone (two materials), the moved node");
assert_eq!((sc.meshes[0].lo.x, sc.meshes[0].hi.x, sc.meshes[1].lo.x, sc.meshes[1].hi.x), (1.0, 9.0, -1.0, 1.0), "the part left alone in the model's space (its node 5 m along x), the moved node in its own");
assert_eq!((sc.instances.len(), sc.tris.len()), (4, 0), "two instances a placement, nothing flattened");
let rigid = |sc: &Scene, id: u32| match &sc.retained.proxies[&id].draw {
diff --git a/renderer/src/world.rs b/renderer/src/world.rs
index 0c16885..67dc0d2 100644
--- a/renderer/src/world.rs
+++ b/renderer/src/world.rs
@@ -432,6 +432,14 @@ pub fn material_texture_ids(m: &desc::Material) -> impl Iterator<Item = u32> + '
[m.map, m.normal_map, m.roughness_map, m.metalness_map, m.ao_map, m.emissive_map, m.transmission_map].into_iter().flatten().chain(m.shader.iter().flat_map(|s| s.textures.iter().flatten().copied()))
}
+/// The size of a rect light's card, if it has one (`visible`).
+fn card_size(l: &desc::Light) -> Option<(u32, u32)> {
+ match l {
+ desc::Light::Rect { width, height, visible: true, .. } => Some((width.to_bits(), height.to_bits())),
+ _ => None,
+ }
+}
+
fn light_class(l: &desc::Light) -> (u8, bool, bool) {
match l {
desc::Light::Directional { cast_shadow, .. } => (0, *cast_shadow, false),
@@ -984,7 +992,8 @@ impl World {
let was = self.objects.get(&id).is_some_and(|o| self.table_light(id, &o.kind));
let o = self.objects.get_mut(&id).ok_or_else(|| anyhow!("unknown object {id}"))?;
match &o.kind {
- Kind::Light(old) if light_class(old) == light_class(&l) || (table && was) => {
+ // (A card of another size is another instance transform: the build's.)
+ Kind::Light(old) if (light_class(old) == light_class(&l) || (table && was)) && card_size(old) == card_size(&l) => {
self.changes.lights.insert(id);
}
_ => mark_structural(&mut self.changes, line!()),
@@ -1493,6 +1502,17 @@ mod tests {
}
w.set_visible(1, false).unwrap();
assert!(w.hidden_built(1) && !w.hidden_built(2), "a hidden volume keeps its place in the build; a light always has one");
+ // A card's colour is its material's, in place; its size is its instance's transform, the build's. A rect light
+ // without a card is its table entry whatever changes.
+ let rect = |w: f32, color: f32, visible: bool| serde_json::from_value::<desc::Light>(serde_json::json!({ "type": "rect", "color": [color, 1, 1], "castShadow": true, "intensity": 100, "width": w, "height": 1, "range": 0, "visible": visible })).unwrap();
+ w.set_light(3, rect(1.0, 0.5, true)).unwrap();
+ let c = w.take_changes();
+ assert!(!c.structural && c.lights.contains(&3), "a card of another colour: in place");
+ w.set_light(3, rect(2.0, 0.5, true)).unwrap();
+ assert!(w.take_changes().structural, "a card of another size: the build's");
+ w.set_light(4, rect(2.0, 0.5, false)).unwrap();
+ let c = w.take_changes();
+ assert!(!c.structural && c.lights.contains(&4), "a rect light without a card, of another size: in place");
w.set_visible(3, false).unwrap();
assert!(w.take_changes().structural, "a rect light's card is geometry");
// (A group, as a mesh: the renderer hides its meshes' instances, or says it cannot.)