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 mesh is its geometry's alone: sections, and an instance's rows for their materials (#170)

Yujia8651b268d069
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 22467d2..3ab0e05 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -2730,6 +2730,29 @@ geometric normal through a function on a mirrored mesh, vertex colours on one (e
traversal); the flattening of an instance against the build's flattening, mirrored too; a mirrored model's build; a
copy mirrored in place; an emitting instanced object added, changed and removed in place against a build.
+**A mesh is its geometry's alone (2026-11-19, the material on the instance, first part).** A mesh was shared by the
+objects of one geometry and the same materials, a triangle holding its material: two objects of a geometry with
+different materials held its triangles and its BLAS twice. Now a scene mesh's and an instanced object's mesh is
+keyed by its geometry (`Retained::own_mesh`, `scene::section_mesh`). Its triangles lie by section, a geometry group
+or the whole geometry, each a geometry of the BLAS, all flagged opaque, and hold their section and their index in
+it. An instance has a row a section in the words' heap (`scene::Row`, heap.rs `Stream::Rows`; its record has their
+first): the material with its class, the section's first triangle, its first emitter. The kernel reads a hit's
+material, whether it is a cutout or glass, and its emitter through the row (`material_of`, `row_word`; kernel
+feature `F_ROWS`); the trace's test of a hit reads no attribute and no material. Whether an instance casts a shadow,
+has a cutout or glass, emits: its rows say (`rows_cast`, `rows_bits`, `rows_emitters`). Glass among an instance's
+other sections is stepped through by a shadow ray, as a cutout that lets it pass is; an instance that is all glass
+is out of its way by its mask, as before. Vertex colours are the geometry's, and a material says whether it reads
+them, where they were baked white for one that did not. Software traversal: a unit's cutouts and glass by its rows,
+asked only of a unit that has some.
+Models keep their layout until the next part (materials on triangles, a BLAS geometry a class). Edits place what
+they placed (one section; a row a record of the room). A material that starts emitting gives the instances with a
+row of it their emitters, and writes no attribute. Still a rebuild: a several-material mesh edited, a material that
+turns glass or cutout, vertex colours asked of a mesh made without them.
+Tests: a geometry's sections and an instance's rows; six objects of one geometry with six materials (one reads its
+vertex colours, cutouts, glass, an emitter) against a geometry an object, at the build, one placed in place, two
+given another material; a pane and its frame as one mesh against a mesh each, under a sky sampled as a light; the
+light list's emitters found through the rows.
+
**Meshes are edited in place (2026-11-18, scene step E, second part).** With every mesh an instance, what the
scene does to one is a change of its instance, not a rebuild. Hidden or shown (itself, or a group above it): the
instance's mask; a hidden mesh is built as an instance no ray sees, its row without power (`Instance::masked`,
diff --git a/renderer/shaders/pathtrace.wgsl b/renderer/shaders/pathtrace.wgsl
index 682cd06..8233ee4 100644
--- a/renderer/shaders/pathtrace.wgsl
+++ b/renderer/shaders/pathtrace.wgsl
@@ -71,6 +71,7 @@ fn approx(a: u32) -> bool { return (APPROX & a) != 0u; }
// Features the scene uses (gpu::F_*): the rest is compiled out, so plain scenes pay nothing for them.
override FEAT: u32 = 0xffffffffu;
const F_MASKED: u32 = 1u;
+const F_ROWS: u32 = 2u; // an instance has rows (`row_word`): a section's material is its row's
const F_FOG: u32 = 64u;
const F_VOLUME: u32 = 128u;
const F_TEX: u32 = 256u;
@@ -90,7 +91,7 @@ const F_BACKGROUND: u32 = 2097152u; // scene.background (`sky_mis`)
const F_VCOLOR: u32 = 4194304u; // vertex colours (`vcolor`)
const F_GRID: u32 = 33554432u; // density grids (`vgrid`)
const F_IFUNC: u32 = 268435456u; // a material function on an instanced mesh: `mat_in_at` places the triangle by its instance
-const F_IGLASS: u32 = 536870912u; // glass among other triangles in an instanced mesh: shadow rays cull its geometry (trace_hw.wgsl), a unit's glass triangles by their flag
+const F_IGLASS: u32 = 536870912u; // glass among an instance's other triangles: shadow rays pass it by its row, or cull a model's glass geometry (trace_hw.wgsl); a unit's glass triangles by their flag
const F_LISTS: u32 = 134217728u; // light tiles (`lt_list_start`): a scene whose shadow-casting local lights are resampled
fn has(f: u32) -> bool { return (FEAT & f) != 0u; }
@@ -125,7 +126,7 @@ struct Params {
ltile2: vec4<u32>, // the traced size they were built at, -, -
lt_cam: array<vec4<f32>, 4>, // the camera they were built under: position (w = tan(fov/2)), forward (w = aspect), right, up
table_first: array<vec4<u32>, 3>, // each table's first vec4 in `tables` (heap.rs `Table`): light tree (0), materials, lights, light groups; emitters, tex_info, objects, instances; media, energy LUT, glass energy, emitter triangles
- word_first: vec4<u32>, // each stream's first word in `words` (heap.rs `Stream`): environment CDF (0), procedural data, vertex colours, -
+ word_first: vec4<u32>, // each stream's first word in `words` (heap.rs `Stream`): environment CDF (0), procedural data, vertex colours, the instances' rows
live_first: array<vec4<u32>, 2>, // the merged layout: each of group 1's vec4 sections' first vec4 in `ML.vecs` (heap.rs `Live`): cache values (0), refl, motion, direct; lists, -, -, -
live_len: vec4<u32>, // and the vec4s of refl, motion, direct, lists
};
@@ -150,7 +151,8 @@ struct Light { pos: vec4<f32>, dir: vec4<f32>, color: vec4<f32>, ext: vec4<f32>,
@group(0) @binding(9) var env_tex: texture_2d<f32>;
// The scene's flat arrays, sections of one buffer of 32-bit words (heap.rs `Stream`), each from the word
// `P.word_first` names: the environment's CDF (floats: [0, H) the rows' marginal CDF, then H rows of W conditional
-// entries; `env_cdf_at`), the procedural data (`pword`, `gdata`), the vertex colours (`vcolor_word`).
+// entries; `env_cdf_at`), the procedural data (`pword`, `gdata`), the vertex colours (`vcolor_word`), the instances'
+// rows (`row_word`).
@group(0) @binding(5) var<storage, read> words: array<u32>;
// (The CDF is the buffer's first section: from word 0, no offset to read.)
fn env_cdf_at(i: u32) -> f32 { return bitcast<f32>(words[i]); }
@@ -293,11 +295,33 @@ fn inst_normal(r: Instance, n: vec4<f32>) -> vec4<f32> {
fn inst_x(info: vec4<u32>, x: vec4<f32>) -> vec4<f32> {
return vec4<f32>(x.x + bitcast<f32>(info.z), bitcast<f32>(info.y), x.z, x.w);
}
+// An instance's rows (scene.rs `Row`): four words a section of its mesh, from the record's info.w on. The material
+// with its class bits, the section's first triangle, its first emitter (NO_EMITTER: it does not emit). A record's
+// n1.w says whether it has rows (INST_ROWS: its mesh is its geometry's alone, and a triangle's attributes hold its
+// section in uv.w and its index in the section in x.w), and whether a row of it is a cutout's or glass.
+const INST_ROWS: u32 = 8u;
+const INST_CUTOUT: u32 = 16u;
+const INST_GLASS: u32 = 32u;
+const ROW_MATERIAL: u32 = 0xffffffu;
+const ROW_CUTOUT: u32 = 0x1000000u;
+const ROW_GLASS: u32 = 0x2000000u;
+const NO_EMITTER: u32 = 0xffffffffu;
+fn has_rows(r: Instance) -> bool { return has(F_ROWS) && (bitcast<u32>(r.n1.w) & INST_ROWS) != 0u; }
+fn row_word(first: u32, section: u32, k: u32) -> u32 { return words[P.word_first.w + (first + section) * 4u + k]; }
+
// The material of a triangle, given its attributes and the instance that places it (NO_INST: none). Every read of a
-// hit's material goes through here: where the material is kept is this function's alone.
+// hit's material goes through here: where the material is kept is this function's alone. On the triangle; with rows,
+// in the row of the triangle's section.
fn material_of(a: TriAttr, inst: u32) -> u32 {
- return bitcast<u32>(a.uv.w);
+ let m = triangle_material(a);
+ if (has(F_ROWS) && inst != NO_INST) {
+ let r = instance_at(inst);
+ if (has_rows(r)) { return row_word(r.info.w, m, 0u) & ROW_MATERIAL; }
+ }
+ return m;
}
+// The material a triangle itself holds: one that no instance with rows places.
+fn triangle_material(a: TriAttr) -> u32 { return bitcast<u32>(a.uv.w); }
// A model-space triangle's shading attributes placed by instance r (scene::instance_attr).
fn inst_attr(r: Instance, a: TriAttr) -> TriAttr {
@@ -889,7 +913,7 @@ fn glass_at(h: Hit, d: vec3<f32>, t: f32) -> GlassAt {
if (tr <= 0.0) { return g; }
g.tint = m.base_color.rgb;
if (has(F_TINT)) { g.tint *= obj_tint(object_of(a)); }
- if (has(F_VCOLOR)) { g.tint *= vcolor(h.tri, h.u, h.v); }
+ if (has(F_VCOLOR) && m.uv.w > 0.0) { g.tint *= vcolor(h.tri, h.u, h.v); }
if (has(F_TEX) && (m.tex0.x >= 0 || m.uv.z > 0.5)) {
let uv = mesh_uv(a, m, h.u, h.v);
var lod = mesh_lod(a, m) + log2(max(t * 2.0 * P.cam_pos.w / lod_height(), 1e-7)) - LOD_BIAS;
@@ -1267,7 +1291,7 @@ fn surface(o: vec3<f32>, d: vec3<f32>, h: Hit, width: f32) -> Surface {
s.card = m.tex1.z == MAT_EMITTER_CARD;
var base = m.base_color.rgb;
if (has(F_TINT)) { base *= obj_tint(object_of(a)); }
- if (has(F_VCOLOR)) { base *= vcolor(i, h.u, h.v); }
+ if (has(F_VCOLOR) && m.uv.w > 0.0) { base *= vcolor(i, h.u, h.v); }
var rough = m.params.y;
var metal = m.params.x;
var spec = m.params.z;
@@ -1866,10 +1890,23 @@ fn emitter_attrs(em: EmitterTri) -> TriAttr {
fn emit_mis(hit: Hit, d: vec3<f32>, pdf: f32) -> f32 {
if (is_proc(hit) || P.counts.y == 0u) { return 1.0; }
// The hit triangle's emitter: its attributes' x.w is the entry + 1 (0: it is not light-sampled), counted from its
- // instance's first entry (the record's n2.w) when an instance places it.
- var entry = bitcast<u32>(attrs[hit.tri].x.w);
+ // instance's first entry (the record's n2.w) when an instance places it. With rows: x.w is the triangle's index
+ // in its section, counted from the section's first entry (its row's).
+ let a = attrs[hit.tri];
+ var entry = bitcast<u32>(a.x.w);
+ var rows = false;
+ if (has(F_INST) && hit.inst != NO_INST) {
+ let r = instance_at(hit.inst);
+ rows = has_rows(r);
+ if (rows) {
+ let first = row_word(r.info.w, bitcast<u32>(a.uv.w), 2u);
+ if (first == NO_EMITTER) { return 1.0; }
+ entry += first + 1u;
+ } else if (entry != 0u) {
+ entry += bitcast<u32>(r.n2.w);
+ }
+ }
if (entry == 0u) { return 1.0; }
- if (has(F_INST) && hit.inst != NO_INST) { entry += bitcast<u32>(instance_at(hit.inst).n2.w); }
let em = emitter_tri_at(entry - 1u);
let cr = cross(em.e1, em.e2);
let area = 0.5 * length(cr);
diff --git a/renderer/shaders/records.wgsl b/renderer/shaders/records.wgsl
index 8471bd5..0470feb 100644
--- a/renderer/shaders/records.wgsl
+++ b/renderer/shaders/records.wgsl
@@ -4,7 +4,8 @@
// A triangle's shading attributes (scene.rs GpuTriAttr): normals (w: uv parts), uv parts (w: material index, bits),
// tangent (w: bitangent sign), x: (texel density, object (bits), a particle's area, its emitter entry + 1 (bits; 0: it
-// is not light-sampled)).
+// is not light-sampled)). A triangle of a mesh with sections: uv.w its section, x.w its index in it (its instance's
+// row has the material and where the section's emitters start: pathtrace.wgsl `material_of`, `row_word`).
struct TriAttr { n0: vec4<f32>, n1: vec4<f32>, n2: vec4<f32>, uv: vec4<f32>, t: vec4<f32>, x: vec4<f32> };
// A sample the kernel leaves in `accum`. Live: color = diffuse lighting at the first hit (w: first-hit distance, 0 =
diff --git a/renderer/shaders/trace_hw.wgsl b/renderer/shaders/trace_hw.wgsl
index a4cccae..d2df7e2 100644
--- a/renderer/shaders/trace_hw.wgsl
+++ b/renderer/shaders/trace_hw.wgsl
@@ -1,5 +1,6 @@
// Hardware ray tracing (wgpu ray query). Up to four instances (see Prepared::groups): shadow casters mask 1, the rest
-// mask 2 (glass among them; an instanced mesh's glass is a geometry of its BLAS that a shadow ray culls); opaque groups
+// mask 2 (glass among them; a model's mesh's glass is a geometry of its BLAS that a shadow ray culls, an instance's
+// glass among its other sections is stepped through by its row); opaque groups
// never report candidates, alpha-cutout groups are confirmed by `alpha_pass`.
// instance_custom_data holds the instance's first global triangle index, or in scenes where a group starts beyond
// 2^24 triangles (F_HUGE: custom data has 24 bits) its traversal group, whose first triangle is in P.group_first.
@@ -10,8 +11,9 @@
if (rays_off) { return Hit(tmax_in, 0xffffffffu, 0.0, 0.0, NO_INST); }
let mask = select(0xffu, 1u, mode == TRACE_SHADOW);
let any = mode != TRACE_CLOSEST;
- // (A scene without cutouts: one query. A feature bit: the kernel has this or what follows, not both.)
- if (!has(F_MASKED)) { return trace_opaque(o, d, tmax_in, mask, any); }
+ // (A scene without cutouts: one query. A feature bit: the kernel has this or what follows, not both. Glass among an
+ // instance's other sections is stepped through as a cutout is: `passes`.)
+ if (!has(F_MASKED) && !(has(F_IGLASS) && has(F_ROWS))) { return trace_opaque(o, d, tmax_in, mask, any); }
// Whether a cutout stops this ray as any triangle does: A_CUTOUT_PATHS, A_CUTOUT_EMITTERS (TRACE_ANY_OPAQUE)
// (pathtrace.wgsl `cutouts_opaque`, `emitter_tr`).
@if(!cutout_lite) let solid = cutouts_opaque() || mode == TRACE_ANY_OPAQUE;
@@ -38,15 +40,22 @@
// origin.
var first = any;
var t0 = 0.0;
+ var hole = false;
for (var k = 0u; k < steps + u32(any); k++) {
let h = trace_opaque(o + d * t0, d, tmax_in - t0, mask, first);
if (h.tri == 0xffffffffu) {
- // (A shadow ray comes here in order only past a cutout that let it through: `shadow_hole`.)
- if (any && !first) { shadow_hole = true; }
+ // (A shadow ray comes here in order only past a cutout that let it through, `shadow_hole`, or past glass.)
+ if (any && !first && hole) { shadow_hole = true; }
return Hit(tmax_in, 0xffffffffu, 0.0, 0.0, NO_INST);
}
let t = t0 + h.t;
- if (solid || is_proc(h) || !cutout(h.tri, h.inst) || alpha_pass(h.tri, h.inst, h.u, h.v, t)) { return Hit(t, h.tri, h.u, h.v, h.inst); }
+ // A shadow ray passes the glass among an instance's sections (its row says so; an instance that is all glass is
+ // out of its way by its mask).
+ let passes = has(F_IGLASS) && has(F_ROWS) && mask == 1u && hit_row != NO_ROW && (hit_row & ROW_GLASS) != 0u;
+ if (!passes) {
+ if (!has(F_MASKED) || solid || is_proc(h) || !cutout_hit(h) || alpha_pass(h.tri, h.inst, h.u, h.v, t)) { return Hit(t, h.tri, h.u, h.v, h.inst); }
+ hole = true;
+ }
if (first) { first = false; } else { t0 = t + 1e-4 * max(1.0, t); }
}
if (any) { return Hit(t0, 0u, 0.0, 0.0, NO_INST); }
@@ -55,11 +64,13 @@
// The closest (or with `any`, the first found) hit, every triangle opaque.
@if(hwrt) fn trace_opaque(o: vec3<f32>, d: vec3<f32>, tmax_in: f32, mask: u32, any: bool) -> Hit {
+ hit_row = NO_ROW;
@if(strict) if (ray_bad(o, d, tmax_in)) { return Hit(tmax_in, 0xffffffffu, 0.0, 0.0, NO_INST); }
var rq: ray_query;
- // A shadow ray (mask 1) where an instanced mesh mixes glass with other triangles (F_IGLASS): it culls the geometry
+ // A shadow ray (mask 1) where a model's mesh mixes glass with other triangles (F_IGLASS): it culls the geometry
// that is not flagged opaque, the glass parts alone (gpu.rs), instead of forcing every geometry opaque. A mesh that
- // is all glass is out of its way by the instance's mask. (Measured on Metal with every geometry opaque: the same
+ // is all glass is out of its way by the instance's mask. (A mesh with sections has every geometry flagged opaque:
+ // `trace` steps through its glass.) (Measured on Metal with every geometry opaque: the same
// pictures, at most 0.5 % of a frame's GPU time.)
let opacity = select(RAY_FLAG_FORCE_OPAQUE, RAY_FLAG_CULL_NO_OPAQUE, has(F_IGLASS) && mask == 1u);
let flags = select(opacity, opacity | RAY_FLAG_TERMINATE_ON_FIRST_HIT, any);
@@ -98,10 +109,15 @@
return Hit(it.t, ti, it.barycentrics.x, it.barycentrics.y, hit_inst(it.instance_custom_data));
}
-// An alpha-cutout triangle: its material has an alpha test (as the build flags TRI_MASKED; model instances' pool
-// triangles carry no flags).
-@if(hwrt) fn cutout(ti: u32, inst: u32) -> bool {
- return material_at(material_of(attrs[ti], inst)).uv2.w > 0.0;
+// The first word of the row of the hit `trace_opaque` last found (its material and class bits), NO_ROW where its
+// instance has no rows: the trace's tests of a hit read no attribute and no material then.
+@if(hwrt) var<private> hit_row: u32;
+@if(hwrt) const NO_ROW: u32 = 0xffffffffu;
+// Whether that hit is an alpha-cutout's: its row says, or without a row its triangle's material has an alpha test (as
+// the build flags TRI_MASKED; a model instance's pool triangles carry no flags, and its record is not asked again).
+@if(hwrt) fn cutout_hit(h: Hit) -> bool {
+ if (has(F_ROWS) && hit_row != NO_ROW) { return (hit_row & ROW_CUTOUT) != 0u; }
+ return material_at(triangle_material(attrs[h.tri])).uv2.w > 0.0;
}
// The model-instance record a hit's custom data names (F_INST), or NO_INST for a traversal group.
@@ -118,6 +134,14 @@
// (Its mesh's geometries: where the second and the third start, scene.rs `InstMesh::part_offsets`; a third
// only with glass.)
let rec = instance_at(custom & (INSTANCE_BIT - 1u));
+ // (With rows: a geometry is a section, and its row has where its triangles start; the first section starts
+ // where the mesh does. The row's class is read where the trace tests a hit by it.)
+ if (has_rows(rec)) {
+ if (has(F_MASKED) || has(F_IGLASS)) { hit_row = row_word(rec.info.w, geometry, 0u); }
+ var first = rec.info.x;
+ if (geometry != 0u) { first = row_word(rec.info.w, geometry, 1u); }
+ return first + prim;
+ }
var at = select(0u, rec.info.w, geometry == 1u);
if (has(F_IGLASS) && geometry == 2u) { at = bitcast<u32>(rec.n0.w); }
return rec.info.x + at + prim;
diff --git a/renderer/shaders/trace_units.wgsl b/renderer/shaders/trace_units.wgsl
index ca52b5a..ab7a8be 100644
--- a/renderer/shaders/trace_units.wgsl
+++ b/renderer/shaders/trace_units.wgsl
@@ -37,6 +37,13 @@ const UNIT_SHADOW: u32 = 1u;
const UNIT_SHIFTED: u32 = 2u;
@if(units) var<private> stack: array<u32, 64>;
+// The flags of a triangle of a unit with rows (from `first` on), which its vertices do not carry: its section's row
+// says whether it is a cutout's (TRI_MASKED) or glass (TRI_NO_SHADOW). Asked of the units that have such a section.
+@if(units) fn row_flags(first: u32, ti: u32) -> u32 {
+ let x = row_word(first, bitcast<u32>(attrs[ti].uv.w), 0u);
+ return select(0u, TRI_MASKED, (x & ROW_CUTOUT) != 0u) | select(0u, TRI_NO_SHADOW, (x & ROW_GLASS) != 0u);
+}
+
@if(units) fn trace_units(o: vec3<f32>, d: vec3<f32>, inv_d: vec3<f32>, hit_in: Hit, mode: u32) -> Hit {
var hit = hit_in;
if (bitcast<u32>(P.motion.w) == 0u) { return hit; }
@@ -52,6 +59,9 @@ const UNIT_SHIFTED: u32 = 2u;
var off = top;
var first = 0u;
var base = 0u;
+ // The unit's bits and its rows' first (a unit with rows has its cutouts and its glass by them: `row_flags`).
+ var ubits = 0u;
+ var urows = 0u;
loop {
let n = nodes[node];
if (n.count == 0u) {
@@ -90,6 +100,8 @@ const UNIT_SHIFTED: u32 = 2u;
}
off = bitcast<u32>(u.n0.w);
first = u.info.x;
+ ubits = bitcast<u32>(u.n1.w);
+ urows = u.info.w;
base = sp;
node = off;
continue;
@@ -99,7 +111,8 @@ const UNIT_SHIFTED: u32 = 2u;
let ti = first + n.left_or_first + k;
let x = intersect_tri(ro, rd, ti, hit.t);
if (x.x < hit.t) {
- let flags = bitcast<u32>(tri_verts[ti * 3u].w);
+ var flags = bitcast<u32>(tri_verts[ti * 3u].w);
+ if (has(F_ROWS) && (ubits & (INST_CUTOUT | INST_GLASS)) != 0u) { flags |= row_flags(urows, ti); }
if (has(F_IGLASS) && mode == TRACE_SHADOW && (flags & TRI_NO_SHADOW) != 0u) { continue; }
if (has(F_MASKED) && (flags & TRI_MASKED) != 0u && !cutouts_opaque() && mode != TRACE_ANY_OPAQUE && !alpha_pass(ti, rec, x.y, x.z, x.x)) { shadow_hole = true; continue; }
hit = Hit(x.x, ti, x.y, x.z, rec);
diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rs
index a3d72bc..0fcb52e 100644
--- a/renderer/src/gpu.rs
+++ b/renderer/src/gpu.rs
@@ -163,7 +163,8 @@ pub struct Params {
}
/// Room the live view's in-place geometry edits grow into (live/edits.rs `edit_geometry`), past the scene's own data:
-/// triangles (verts, attrs, BLAS vertices), kernel records and TLAS instances, object-table entries, procedural words.
+/// triangles (verts, attrs, BLAS vertices), kernel records and TLAS instances (and a row a record: what an edit
+/// places has one section), object-table entries, procedural words.
/// Only scenes with editable geometry (procedural meshes, `own_blas` meshes) under hardware RT get any: a quarter of
/// what they have, at least a minimum; `THREERT_EDIT_RESERVE` scales it (0: none). Past it an edit rebuilds the scene.
#[derive(Clone, Copy, Default, Debug)]
@@ -1630,6 +1631,8 @@ pub const A_LIVE: u32 = 31;
// Kernel features (`override FEAT` in pathtrace.wgsl).
pub const F_MASKED: u32 = 1;
+/// An instance has rows (scene.rs `Row`): its mesh is its geometry's alone, a section's material is its row's.
+pub const F_ROWS: u32 = 2;
pub const F_FOG: u32 = 64;
pub const F_VOLUME: u32 = 128;
pub const F_TEX: u32 = 256;
@@ -1677,10 +1680,11 @@ pub const F_LISTS: u32 = 1 << 27;
/// every call otherwise, taken or not (Kabukicho's 64,224 emitters with a function, none on an instance: frame GPU
/// +2.7 %).
pub const F_IFUNC: u32 = 1 << 28;
-/// Glass among other triangles in an instanced mesh: its BLAS geometry is not flagged opaque, and a shadow ray culls
-/// such geometry instead of forcing opacity (trace_hw.wgsl; software traversal skips a unit's glass triangles by
-/// their flag). Compiled out where no instanced mesh mixes the two: an instance of a mesh that is all glass is out of
-/// a shadow ray's way by its mask (`scene::InstMesh::casts`).
+/// Glass among an instance's other triangles. With rows: a shadow ray steps through a hit whose row says glass
+/// (trace_hw.wgsl). A model's mesh: its glass geometry is not flagged opaque, and a shadow ray culls such geometry
+/// instead of forcing opacity. (Software traversal skips a unit's glass triangles by their flag, a row's or their
+/// own.) Compiled out where no instance mixes the two: one that is all glass is out of a shadow ray's way by its mask
+/// (`scene::rows_cast`, `scene::InstMesh::casts`).
pub const F_IGLASS: u32 = 1 << 29;
/// Whether a scene with more such lights has the light tiles (`F_LISTS`): `THREERT_LIGHT_TILES=1|0`, else everywhere
/// but Android. On Adreno 740 they took OpenStrikeRT's Foundry from 31 to 48 ms a frame (249 x 140, one bounce):
@@ -1755,10 +1759,18 @@ pub fn instance_features(scene: &Scene) -> u32 {
if scene.gpu_instances.is_empty() {
return media | particles;
}
- let function = |a: &crate::scene::GpuTriAttr| scene.materials.get(a.uv[3].to_bits() as usize).is_some_and(|m| m.tex1[3] != 0);
- let ifunc = if scene.pool_attrs.iter().any(function) { F_IFUNC } else { 0 };
- let iglass = if scene.meshes.iter().any(|m| m.glass > 0 && m.glass < m.count) { F_IGLASS } else { 0 };
- media | particles | ifunc | iglass | F_INST | if scene.meshes.iter().any(|m| m.opaque + m.glass < m.count) { F_MASKED } else { 0 } | if scene.units.is_some() { F_UNITS } else { 0 }
+ // (A model's mesh has its materials on its triangles and its classes in its counts; a mesh with sections has
+ // them in its instances' rows.)
+ let function = |mat: u32| scene.materials.get(mat as usize).is_some_and(|m| m.tex1[3] != 0);
+ let on_triangles = scene.meshes.iter().filter(|m| m.sect_count == 0).flat_map(|m| &scene.pool_attrs[m.first as usize..(m.first + m.count) as usize]).any(|a| function(a.uv[3].to_bits()));
+ let rows = |i: &crate::scene::Instance| &scene.rows[i.rows as usize..][..scene.meshes[i.mesh as usize].sect_count as usize];
+ let any_row = |bit: u32| scene.instances.iter().any(|i| rows(i).iter().any(|r| r[0] & bit != 0));
+ let mixed_glass = scene.instances.iter().any(|i| i.bits & crate::scene::INST_GLASS != 0 && i.cast_shadow);
+ let ifunc = if on_triangles || scene.rows.iter().any(|r| function(crate::scene::row_material(r))) { F_IFUNC } else { 0 };
+ let iglass = if mixed_glass || scene.meshes.iter().any(|m| m.glass > 0 && m.glass < m.count) { F_IGLASS } else { 0 };
+ let masked = any_row(crate::scene::ROW_CUTOUT) || scene.meshes.iter().any(|m| m.opaque + m.glass < m.count);
+ let with_rows = if scene.instances.iter().any(|i| i.bits & crate::scene::INST_ROWS != 0) { F_ROWS } else { 0 };
+ media | particles | ifunc | iglass | with_rows | F_INST | if masked { F_MASKED } else { 0 } | if scene.units.is_some() { F_UNITS } else { 0 }
}
/// `features` from the parts parameter edits change (the materials; `environment`: `environment_features`), and the
@@ -1790,7 +1802,7 @@ pub fn features_of(ms: &[crate::scene::GpuMaterial], environment: u32, textures:
}
if let Some(mask) = std::env::var("THREERT_FEATURES").ok().and_then(|v| v.parse::<u32>().ok()) {
- f &= mask | F_HUGE | F_INST | F_PROC | F_TINT; // not optional: they say what the instances' custom data / the object table holds
+ f &= mask | F_HUGE | F_INST | F_PROC | F_TINT | F_ROWS; // not optional: they say what the instances' custom data / the object table / the records hold
}
// Features compiled in although the scene does not use them (the perf smoke's cost of a contract compiled in but off).
if let Some(on) = std::env::var("THREERT_FEATURES_ON").ok().and_then(|v| v.parse::<u32>().ok()) {
@@ -2265,7 +2277,7 @@ impl Gpu {
// What the triangles hold on the GPU besides their BLASes: vertices (a, e1, e2), attributes, the software BVH's nodes
// (ROADMAP § 6 step 2's table: a meshed representation against voxel data).
timings.push(("tri_data_mb".into(), (std::mem::size_of_val(tri_verts) + std::mem::size_of_val(&scene.attrs[..]) + nodes.len()) as f64 / (1 << 20) as f64));
- let (words, region_words, proc_room) = self.upload_words(scene, env_cdf, room.proc_words, room.tris, timings)?;
+ let (words, region_words, proc_room) = self.upload_words(scene, env_cdf, room.proc_words, room.tris, room.records, timings)?;
let room = EditRoom { proc_words: proc_room, ..room };
// Density grids: field A of each in the atlas (stacked along z), their data; for a grid with a program, its
// other textures (A', B, B'), its two half steps and its sources.
@@ -2416,7 +2428,7 @@ impl Gpu {
// INSTANCE_BIT | record; shadow casters mask 1).
// Per mesh: (first triangle, count, opaque) geometries: the opaque part, the cutout part, the glass part
// (`InstMesh::parts`).
- let mesh_parts: Vec<Vec<(u32, u32, bool)>> = scene.meshes.iter().map(|m| m.parts().into_iter().map(|(at, count, opaque)| (m.first + at, count, opaque)).collect()).collect();
+ let mesh_parts: Vec<Vec<(u32, u32, bool)>> = scene.meshes.iter().map(|m| m.parts(&scene.sections).into_iter().map(|(at, count, opaque)| (m.first + at, count, opaque)).collect()).collect();
let mesh_sizes: Vec<Vec<wgpu::BlasTriangleGeometrySizeDescriptor>> = mesh_parts
.iter()
.map(|parts| {
@@ -2731,13 +2743,15 @@ impl Gpu {
/// (`room_words` after the region, as much of it as the binding limit leaves; `room_tris` triangles' colours).
/// Written straight into the new buffer's mapping; the blobs are copied on the GPU from the last upload when its
/// geometries are the same. Returns the heap, the region's words in use and the room it got.
- fn upload_words(&self, scene: &Scene, env_cdf: &[f32], room_words: usize, room_tris: usize, timings: &mut Vec<(String, f64)>) -> Result<(Heap<Stream>, usize, usize)> {
+ fn upload_words(&self, scene: &Scene, env_cdf: &[f32], room_words: usize, room_tris: usize, room_rows: usize, timings: &mut Vec<(String, f64)>) -> Result<(Heap<Stream>, usize, usize)> {
let t = Instant::now();
let l = scene.proc_layout.as_ref();
let (head, blob_words) = l.map_or((0, 0), |l| (l.head.len(), l.blob_words));
let colors: &[u8] = bytemuck::cast_slice(&scene.gpu_vcolors);
let color_bytes = if colors.is_empty() { 0 } else { colors.len() + room_tris * 12 };
- let sizes = |room: usize| [(env_cdf.len() * 4) as u64, ((head + blob_words + room) * 4) as u64, color_bytes as u64];
+ let rows: &[u8] = bytemuck::cast_slice(&scene.rows);
+ let row_bytes = if rows.is_empty() && room_rows == 0 { 0 } else { rows.len() + room_rows * 16 };
+ let sizes = |room: usize| [(env_cdf.len() * 4) as u64, ((head + blob_words + room) * 4) as u64, color_bytes as u64, row_bytes as u64];
let (used, limit) = (Heap::<Stream>::size_for(&sizes(0)), self.device.limits().max_storage_buffer_binding_size as u64);
if used > limit {
return Err(anyhow!("procedural geometry: {} MB of data, more than this device binds in one buffer ({} MB)", used >> 20, limit >> 20));
@@ -2758,6 +2772,7 @@ impl Gpu {
heap.write(&self.queue, Stream::EnvCdf, 0, bytemuck::cast_slice(env_cdf));
heap.write(&self.queue, Stream::Procs, 0, bytemuck::cast_slice(&l.head));
heap.write(&self.queue, Stream::VertexColors, 0, colors);
+ heap.write(&self.queue, Stream::Rows, 0, rows);
let mut e = self.device.create_command_encoder(&Default::default());
e.copy_buffer_to_buffer(&c.buf, c.offset, &heap.buffer, heap.at(Stream::Procs) + blob_at, c.bytes);
self.queue.submit([e.finish()]);
@@ -2766,6 +2781,7 @@ impl Gpu {
_ => Heap::filled(&self.device, &sizes, |put| {
put(Stream::EnvCdf, 0, bytemuck::cast_slice(env_cdf));
put(Stream::VertexColors, 0, colors);
+ put(Stream::Rows, 0, rows);
let Some(l) = l else { return };
put(Stream::Procs, 0, bytemuck::cast_slice(&l.head));
for (blob, off) in &l.blobs {
@@ -3237,15 +3253,15 @@ impl Gpu {
}
/// Mesh `k` (one an edit no longer draws) made again over `count` triangles from `first`: a new BLAS in its slot.
- pub fn set_mesh(&self, accel: &mut Accel, k: u32, first: usize, mesh: &crate::scene::InstMesh) {
- let (blas, geo) = self.mesh_blas_for(accel, first, mesh);
+ pub fn set_mesh(&self, accel: &mut Accel, k: u32, first: usize, mesh: &crate::scene::InstMesh, sections: &[crate::scene::Section]) {
+ let (blas, geo) = self.mesh_blas_for(accel, first, mesh, sections);
accel.meshes[k as usize] = blas;
accel.mesh_geo[k as usize] = geo;
}
- fn mesh_blas_for(&self, accel: &Accel, first: usize, mesh: &crate::scene::InstMesh) -> (wgpu::Blas, (Vec<(u32, u32, bool)>, Vec<wgpu::BlasTriangleGeometrySizeDescriptor>)) {
+ fn mesh_blas_for(&self, accel: &Accel, first: usize, mesh: &crate::scene::InstMesh, sections: &[crate::scene::Section]) -> (wgpu::Blas, (Vec<(u32, u32, bool)>, Vec<wgpu::BlasTriangleGeometrySizeDescriptor>)) {
let rel = (first - accel.pool_first) as u32;
- let parts: Vec<(u32, u32, bool)> = mesh.parts().into_iter().map(|(at, count, opaque)| (rel + at, count, opaque)).collect();
+ let parts: Vec<(u32, u32, bool)> = mesh.parts(sections).into_iter().map(|(at, count, opaque)| (rel + at, count, opaque)).collect();
let sizes: Vec<wgpu::BlasTriangleGeometrySizeDescriptor> = parts
.iter()
.map(|&(_, c, opaque)| wgpu::BlasTriangleGeometrySizeDescriptor {
@@ -3263,10 +3279,10 @@ impl Gpu {
/// A new instanced mesh over `count` triangles from GPU-order index `first` (in the edit room; live/edits.rs
/// `edit_geometry`), its first `opaque` ones opaque: its BLAS, which the commit's build builds (`TopBuild::meshes`). Returns its index.
- pub fn add_mesh(&self, accel: &mut Accel, first: usize, mesh: &crate::scene::InstMesh) -> u32 {
+ pub fn add_mesh(&self, accel: &mut Accel, first: usize, mesh: &crate::scene::InstMesh, sections: &[crate::scene::Section]) -> u32 {
// Built fast rather than traced fast (edits come every frame under destruction; the batches of pieces are rebuilt
// every frame); THREERT_EDIT_BLAS=trace for the A/B (`mesh_blas_for`).
- let (blas, geo) = self.mesh_blas_for(accel, first, mesh);
+ let (blas, geo) = self.mesh_blas_for(accel, first, mesh, sections);
accel.meshes.push(blas);
accel.mesh_geo.push(geo);
accel.meshes.len() as u32 - 1
@@ -3670,6 +3686,7 @@ mod tests {
("F_GLASS", F_GLASS), ("F_COAT", F_COAT), ("F_HUGE", F_HUGE), ("F_INST", F_INST), ("F_MEDIA", F_MEDIA), ("F_PEMIT", F_PEMIT),
("F_HMEDIA", F_HMEDIA), ("F_PROC", F_PROC), ("F_TINT", F_TINT), ("F_UNLIT", F_UNLIT), ("F_BACKGROUND", F_BACKGROUND),
("F_VCOLOR", F_VCOLOR), ("F_AERIAL", F_AERIAL), ("F_GRID", F_GRID), ("F_LISTS", F_LISTS), ("F_IFUNC", F_IFUNC), ("F_IGLASS", F_IGLASS),
+ ("F_ROWS", F_ROWS),
];
let mut seen = 0u32;
for (name, bit) in all {
diff --git a/renderer/src/heap.rs b/renderer/src/heap.rs
index a2c84d5..6c9cd00 100644
--- a/renderer/src/heap.rs
+++ b/renderer/src/heap.rs
@@ -72,10 +72,12 @@ pub enum Stream {
Procs,
/// Vertex colours: three sRGB8 words a triangle, in the triangles' GPU order.
VertexColors,
+ /// The instances' rows (scene.rs `Row`): four words a section of an instance's mesh.
+ Rows,
}
impl Section for Stream {
- const COUNT: usize = 3;
+ const COUNT: usize = 4;
const UNIT: u64 = 4;
const LABEL: &'static str = "words";
fn index(self) -> usize {
diff --git a/renderer/src/lib.rs b/renderer/src/lib.rs
index dbc0b8c..c3594ea 100644
--- a/renderer/src/lib.rs
+++ b/renderer/src/lib.rs
@@ -179,7 +179,8 @@ impl GpuEmitterTri {
}
}
-/// The emitters of an instance of a mesh that emits (`scene::InstMesh::emitters`, `count` of them): one a numbered
+/// The emitters of an instance that has some (`count` of them: `scene::rows_emitters`, or a model's mesh's
+/// `InstMesh::emitters`): one a numbered
/// triangle, in the numbers' order, each with its triangle as the instance places it. `tris`: the mesh's, in model
/// space; `first`: its first triangle in the triangles' table; `numbered(k)`: triangle k's number and material, if
/// it emits; `record`: the instance's. A triangle of no area: no weight (area 0). A hidden instance's (an instanced
@@ -592,19 +593,32 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut
let pool_first = tri_verts.len() / 3;
// Deforming meshes come first (scene build): flagged dynamic, their previous vertices kept for motion vectors.
let deforming = scene::deforming_pool(&sc.meshes);
+ // (A mesh with sections has no material on its triangles: its instances' rows say which are cutouts or glass.)
+ let mut on_triangle = vec![true; sc.pool_tris.len()];
+ for m in sc.meshes.iter().filter(|m| m.sect_count > 0) {
+ on_triangle[m.first as usize..(m.first + m.count) as usize].fill(false);
+ }
for (k, (t, a)) in sc.pool_tris.iter().zip(&sc.pool_attrs).enumerate() {
let [a0, b, c] = *t;
let (e1, e2): (Vec3A, Vec3A) = (b - a0, c - a0);
// (A unit's triangles are in its tree's order, cutouts and glass among the rest: each carries its own flag, as
// the still scene's do. Hardware traversal has them apart, in geometries of their own.)
- let material = sc.materials.get(a.uv[3].to_bits() as usize).filter(|_| trees.is_some());
+ let material = sc.materials.get(a.uv[3].to_bits() as usize).filter(|_| trees.is_some() && on_triangle[k]);
let (cutout, glass) = (material.is_some_and(|m| m.uv2[3] > 0.0), material.is_some_and(|m| m.layer[0] > 0.0));
tri_verts.push([a0.x, a0.y, a0.z, f32::from_bits(if k < deforming { scene::TRI_DYNAMIC } else { 0 } | if cutout { scene::TRI_MASKED } else { 0 } | if glass { scene::TRI_NO_SHADOW } else { 0 })]);
tri_verts.push([e1.x, e1.y, e1.z, 0.0]);
tri_verts.push([e2.x, e2.y, e2.z, 0.0]);
attrs.push(*a);
}
- sc.gpu_instances = sc.instances.iter().map(|i| { let m = sc.meshes[i.mesh as usize]; i.gpu(pool_first as u32 + m.first, m.part_offsets()) }).collect();
+ sc.gpu_instances = sc.instances.iter().map(|i| { let m = sc.meshes[i.mesh as usize]; i.gpu(pool_first as u32 + m.first, i.parts(&m)) }).collect();
+ // A row's section starts here in the triangles' table (hardware traversal: a hit's geometry is its section, its
+ // primitive counts from there).
+ for i in &sc.instances {
+ let m = sc.meshes[i.mesh as usize];
+ for (s, row) in m.sections(&sc.sections).iter().zip(&mut sc.rows[i.rows as usize..]) {
+ row[1] = pool_first as u32 + m.first + s.first;
+ }
+ }
// A scene whose triangles are all units': the still tree is then the leaf of one triangle, triangle 0 (bvh.rs
// `EMPTY`), which no ray meets while triangle 0 is the zeros of an empty buffer. Here triangle 0 is the pool's
// first, a mesh's in its model space, and the still walk would meet it standing in the world. The leaf gets a
@@ -699,9 +713,9 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut
timings.push(("bvh_ms".into(), t.elapsed().as_secs_f64() * 1000.0));
// The light list (an emitter's weight = area x luminance of the emissive factor x object power): the flattened
- // triangles that emit, then, an instance at a time, those of a mesh that emits (`InstMesh::emitters`): a run of
- // the list an instance, its first in its record, its triangles' numbers counted from it. Each with its triangle in
- // world space.
+ // triangles that emit, then, an instance at a time, those of its triangles that emit: a run of the list an
+ // instance, its first in its record, its triangles' numbers counted from it (a model's mesh), or from where its
+ // section's start, which the section's row has (a mesh with sections). Each with its triangle in world space.
let mut emitter_tris: Vec<EmitterTri> = vec![];
let mut gpu_emitter_tris: Vec<GpuEmitterTri> = vec![];
for k in 0..pool_first {
@@ -720,17 +734,30 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut
let moving = sc.retained.moving_records();
for r in 0..sc.instances.len() {
let m = sc.meshes[sc.instances[r].mesh as usize];
- if m.emitters == 0 {
+ // (With sections: the emitters of its sections whose material emits, a section after another; each one's row
+ // has where they start.)
+ let (sections, at) = (m.sections(&sc.sections), sc.instances[r].rows as usize);
+ let rows = sc.rows.get(at..at + sections.len()).unwrap_or(&[]).to_vec();
+ let starts = scene::section_emitters(sections, &rows, &sc.materials);
+ let count = if sections.is_empty() { m.emitters } else { scene::rows_emitters(sections, &rows, &sc.materials) };
+ if count == 0 {
continue;
}
- sc.instances[r].first_emitter = emitter_tris.len() as u32;
+ let first = emitter_tris.len() as u32;
+ sc.instances[r].first_emitter = first;
if let Some(g) = sc.gpu_instances.get_mut(r) {
- g.n[2][3] = f32::from_bits(emitter_tris.len() as u32);
+ g.n[2][3] = f32::from_bits(first);
+ }
+ for (k, start) in starts.iter().enumerate() {
+ sc.rows[at + k][2] = start.map_or(scene::NO_EMITTER, |s| first + s);
}
let (a, b) = (m.first as usize, (m.first + m.count) as usize);
let attrs = &sc.attrs[pool_first + a..pool_first + b];
- let numbered = |k: usize| (attrs[k].x[3].to_bits() as usize).checked_sub(1).map(|n| (n, attrs[k].uv[3].to_bits()));
- for (e, w) in instance_emitters(&sc.instances[r], r as u32, &sc.pool_tris[a..b], (pool_first + a) as u32, &numbered, m.emitters as usize, &sc.materials, moving.contains(&(r as u32)) || sc.instances[r].masked) {
+ let numbered = |k: usize| match sections.is_empty() {
+ true => (attrs[k].x[3].to_bits() as usize).checked_sub(1).map(|n| (n, attrs[k].uv[3].to_bits())),
+ false => scene::section_slot(&attrs[k], &rows, &starts),
+ };
+ for (e, w) in instance_emitters(&sc.instances[r], r as u32, &sc.pool_tris[a..b], (pool_first + a) as u32, &numbered, count as usize, &sc.materials, moving.contains(&(r as u32)) || sc.instances[r].masked) {
gpu_emitter_tris.push(GpuEmitterTri::of(&e, w, 0));
emitter_tris.push(e);
}
@@ -742,13 +769,17 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut
// triangle has: each instance of such a mesh gets its emitters in place too (live/edits.rs
// `add_material_emitters`).
let mut mat_runs: std::collections::HashMap<u32, Vec<[u32; 3]>> = std::collections::HashMap::new();
- let mut fixed_mats: std::collections::HashSet<u32> = sc.pool_attrs.iter().map(|a| a.uv[3].to_bits()).collect();
- let own: std::collections::HashSet<u32> = sc.retained.own_mesh.values().copied().collect();
+ // (A model's mesh has its materials on its triangles; a mesh with sections has them in its instances' rows, and
+ // an instanced object's copies are not a mesh's instance here.)
let (mut mesh_mats, mut others): (std::collections::HashSet<u32>, std::collections::HashSet<u32>) = Default::default();
- for (k, m) in sc.meshes.iter().enumerate() {
- let mats = sc.attrs[pool_first + m.first as usize..pool_first + (m.first + m.count) as usize].iter().map(|a| a.uv[3].to_bits());
- if own.contains(&(k as u32)) { mesh_mats.extend(mats) } else { others.extend(mats) }
+ for m in sc.meshes.iter().filter(|m| m.sect_count == 0) {
+ others.extend(sc.attrs[pool_first + m.first as usize..pool_first + (m.first + m.count) as usize].iter().map(|a| a.uv[3].to_bits()));
+ }
+ for i in &sc.instances {
+ let mats = sc.rows[i.rows as usize..][..sc.meshes[i.mesh as usize].sect_count as usize].iter().map(scene::row_material);
+ if i.sub.is_none() { mesh_mats.extend(mats) } else { others.extend(mats) }
}
+ let mut fixed_mats: std::collections::HashSet<u32> = mesh_mats.union(&others).copied().collect();
for (k, a) in sc.attrs[..pool_first].iter().enumerate() {
let (mat, obj) = (a.uv[3].to_bits(), a.x[1].to_bits());
if tri_verts[k * 3][3].to_bits() & scene::TRI_DYNAMIC != 0 {
@@ -914,7 +945,10 @@ fn unit_trees(sc: &mut scene::Scene) -> Option<Vec<Option<units::MeshTree>>> {
let r = m.first as usize..(m.first + m.count) as usize;
let tris: Vec<_> = t.order.iter().map(|&i| sc.pool_tris[r.start + i as usize]).collect();
sc.pool_tris[r.clone()].copy_from_slice(&tris);
- let attrs: Vec<_> = t.order.iter().map(|&i| sc.pool_attrs[r.start + i as usize]).collect();
+ let mut attrs: Vec<_> = t.order.iter().map(|&i| sc.pool_attrs[r.start + i as usize]).collect();
+ if m.sect_count > 0 {
+ scene::rank_in_sections(&mut attrs);
+ }
sc.pool_attrs[r.clone()].copy_from_slice(&attrs);
if !sc.pool_vcolors.is_empty() {
let colors: Vec<_> = t.order.iter().map(|&i| sc.pool_vcolors[r.start + i as usize]).collect();
@@ -936,12 +970,13 @@ fn flatten_deforming(sc: &mut scene::Scene) {
}
let first = sc.tris.len() as u32;
for k in m.first..m.first + m.count {
- let (t, a, c) = inst.flat(&sc.pool_tris[k as usize], &sc.pool_attrs[k as usize], sc.pool_vcolors.get(k as usize).copied());
+ let own = inst.resolved(&sc.pool_attrs[k as usize], sc.rows.get(inst.rows as usize..).unwrap_or(&[]));
+ let (t, a, c) = inst.flat(&sc.pool_tris[k as usize], &own, sc.pool_vcolors.get(k as usize).copied());
if let Some(c) = c {
scene::put_colors(&mut sc.vcolors, sc.tris.len(), Some(vec![c]));
}
sc.tris.push(t);
- sc.tri_flags.push(scene::instance_tri_flags(&inst, &sc.pool_attrs[k as usize], &sc.materials));
+ sc.tri_flags.push(scene::instance_tri_flags(&inst, &own, &sc.materials));
sc.attrs.push(a);
}
sc.tri_nodes.push((inst.name.clone(), first, sc.tris.len() as u32));
@@ -959,12 +994,13 @@ fn flatten_instances(sc: &mut scene::Scene) {
let m = sc.meshes[inst.mesh as usize];
let first = sc.tris.len() as u32;
for k in m.first..m.first + m.count {
- let (t, a, c) = inst.flat(&sc.pool_tris[k as usize], &sc.pool_attrs[k as usize], sc.pool_vcolors.get(k as usize).copied());
+ let own = inst.resolved(&sc.pool_attrs[k as usize], sc.rows.get(inst.rows as usize..).unwrap_or(&[]));
+ let (t, a, c) = inst.flat(&sc.pool_tris[k as usize], &own, sc.pool_vcolors.get(k as usize).copied());
if let Some(c) = c {
scene::put_colors(&mut sc.vcolors, sc.tris.len(), Some(vec![c]));
}
sc.tris.push(t);
- sc.tri_flags.push(scene::instance_tri_flags(&inst, &sc.pool_attrs[k as usize], &sc.materials));
+ sc.tri_flags.push(scene::instance_tri_flags(&inst, &own, &sc.materials));
sc.attrs.push(a);
}
// A second range for the node when a part of its mesh was flattened at build: node_tris joins them.
@@ -976,6 +1012,8 @@ fn flatten_instances(sc: &mut scene::Scene) {
sc.pool_tris.clear();
sc.pool_attrs.clear();
sc.meshes.clear();
+ sc.sections.clear();
+ sc.rows.clear();
}
/// Traversal group: shadow casting x alpha cutout, static (0..4) or dynamic (4..8: posed models, own BLASes).
@@ -1658,12 +1696,13 @@ mod units_tests {
assert_eq!(pu.nodes.len(), u.layout.top_first as usize + u.layout.top_cap as usize);
let kernel = |p: &Prepared, sc: &scene::Scene| {
let (top, units) = (p.params.motion[2].to_bits(), p.params.motion[3].to_bits());
- (p.nodes.clone(), p.tri_verts.clone(), sc.gpu_instances.clone(), top, units)
+ (p.nodes.clone(), p.tri_verts.clone(), sc.gpu_instances.clone(), top, units, sc.attrs.iter().map(|a| a.uv[3].to_bits()).collect::<Vec<u32>>(), sc.rows.clone())
};
let (ku, kf) = (kernel(&pu, &su), kernel(&pf, &sf));
- let walk = |k: &(Vec<bvh::GpuNode>, Vec<[f32; 4]>, Vec<scene::GpuInstance>, u32, u32), o: Vec3A, d: Vec3A, mode: u32| {
+ #[allow(clippy::type_complexity)]
+ let walk = |k: &(Vec<bvh::GpuNode>, Vec<[f32; 4]>, Vec<scene::GpuInstance>, u32, u32, Vec<u32>, Vec<scene::Row>), o: Vec3A, d: Vec3A, mode: u32| {
let instances = if k.2.is_empty() { vec![scene::GpuInstance::default()] } else { k.2.clone() };
- let kernel = Kernel { nodes: &k.0, tri_verts: &k.1, instances: &instances, top: k.3, units: k.4, steps: Default::default(), budget: 1 << 20, deepest: Default::default(), reads: Default::default() };
+ let kernel = Kernel { nodes: &k.0, tri_verts: &k.1, instances: &instances, sections: &k.5, rows: &k.6, top: k.3, units: k.4, steps: Default::default(), budget: 1 << 20, deepest: Default::default(), reads: Default::default() };
kernel.trace(o, d, INF, mode).unwrap_or_else(|e| panic!("ray {o} {d}, mode {mode}: the kernel {e}"))
};
let mut s = 12345u64;
diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rs
index ab17d16..a7df821 100644
--- a/renderer/src/live/edits.rs
+++ b/renderer/src/live/edits.rs
@@ -107,6 +107,8 @@ pub(super) struct EditState {
pub(super) uniform_said: bool,
/// (triangles, records, objects, words, TLAS instances) the scene itself has: the room starts there.
pub(super) base: (usize, usize, usize, usize, usize),
+ /// The rows the scene itself has: the room's follow, one a record of the room (`row_at`).
+ pub(super) row_base: usize,
/// The first pool triangle (instanced meshes' triangles are counted from it).
pub(super) pool_first: usize,
/// Procedural blobs in the region by hash: their first word (the build's and those edits wrote).
@@ -118,6 +120,12 @@ impl EditState {
pub(super) fn in_room(&self, record: usize) -> bool {
record >= self.base.1
}
+
+ /// The row of what an edit places at `record` (one section: one row): the room's own for a record of the room,
+ /// else the first of the rows the build gave the instance there.
+ pub(super) fn row_at(&self, instances: &[scene::Instance], record: usize) -> usize {
+ if self.in_room(record) { self.row_base + record - self.base.1 } else { instances.get(record).map_or(0, |i| i.rows as usize) }
+ }
}
/// Ranges of one kind of the edit room: free holes (start -> length; first fit, neighbours merged) below `end`, the
@@ -246,15 +254,18 @@ impl Grow<'_> {
true
}
- /// Kernel records and the TLAS (a record's instance is `inst_base` + it).
- pub(super) fn records(&self, h: &mut Holes, extra: usize, heap: &mut Heap<Table>, accel: &mut gpu::Accel) -> bool {
+ /// Kernel records and the TLAS (a record's instance is `inst_base` + it), and the room's rows, one a record
+ /// (`row_base`: the scene's own before them).
+ pub(super) fn records(&self, h: &mut Holes, extra: usize, heap: &mut Heap<Table>, accel: &mut gpu::Accel, words: &mut Heap<Stream>, row_base: usize) -> bool {
if !self.ok {
return false;
}
let cap = Self::cap(h, extra);
- if !self.table(heap, Table::Instances, (cap * std::mem::size_of::<scene::GpuInstance>()) as u64) {
+ let row_bytes = ((row_base + cap - h.base) * 16) as u64;
+ if !self.fits(&[words.size_with(Stream::Rows, row_bytes)]) || !self.table(heap, Table::Instances, (cap * std::mem::size_of::<scene::GpuInstance>()) as u64) {
return false;
}
+ words.grow(&self.g.device, &self.g.queue, Stream::Rows, row_bytes);
self.g.grow_tlas(accel, accel.inst_base + cap);
h.cap = cap;
true
@@ -791,7 +802,7 @@ impl LiveCore {
if !sub.iter().all(held) {
return false;
}
- let LoadedScene { tables, instances, gpu_instances, pool_tris, edit, .. } = &mut self.sc;
+ let LoadedScene { tables, instances, gpu_instances, pool_tris, meshes, rows, up, edit, .. } = &mut self.sc;
for k in sub {
let Some(scene::Draw::Instance(i)) = tables.retained.proxies.get_mut(&k).map(|p| &mut p.draw) else { continue };
if std::mem::replace(&mut i.moves, true) {
@@ -802,7 +813,7 @@ impl LiveCore {
if old.is_empty() || tables.emitter_tris[old.clone()].iter().all(|e| e.moves) {
continue;
}
- let first = tables.emitter_tris.len() as u32;
+ let (was, first) = (old.start as u32, tables.emitter_tris.len() as u32);
let inst = &mut instances[r as usize];
// (Where this commit's move places it: `move_instances`, next.)
let (to, _) = scene::placed_world(world.world_matrix(k), inst.world.w_axis.truncate());
@@ -817,6 +828,14 @@ impl LiveCore {
if let Some(rec) = gpu_instances.get_mut(r as usize) {
rec.n[2][3] = f32::from_bits(first);
}
+ // (Its rows say where its sections' emitters start: where the run is now.)
+ let at = inst.rows as usize..inst.rows as usize + meshes[inst.mesh as usize].sect_count as usize;
+ for row in rows[at.clone()].iter_mut().filter(|row| row[2] != scene::NO_EMITTER) {
+ row[2] = row[2] - was + first;
+ }
+ if !at.is_empty() {
+ up.words.write(&self.g.queue, Stream::Rows, (at.start * 16) as u64, bytemuck::cast_slice(&rows[at]));
+ }
self.emitters_reweigh = true;
}
true
@@ -979,62 +998,71 @@ impl LiveCore {
}
}
}
- // The meshes with a triangle of one of them (`Tables::mesh_mats`): the mesh's emitting triangles are numbered
- // again as they lie (`scene::number_emitters`: the build's numbering, with the materials as they are now), and
- // each of its instances gets its emitters as a new run at the list's end, its first in the instance's record;
- // the run it had, of fewer, stays at no weight.
+ // The meshes' instances with a row of one of them (`Tables::mesh_mats`): each gets its emitters as a new run
+ // at the list's end, the sections that emit now one after another, where each starts in its row and the
+ // run's first in the instance's record; the run it had, of fewer, stays at no weight.
if !started.is_empty() && !sc.meshes.is_empty() {
- let LoadedScene { tables, instances, gpu_instances, meshes, pool_tris, edit, up, .. } = sc;
+ let LoadedScene { tables, instances, gpu_instances, meshes, pool_tris, sections, rows, edit, up, .. } = sc;
let moving = tables.retained.moving_records();
- let mut done = std::collections::HashSet::new();
+ // Each mesh's triangles as the pool has them: their section and their index in it (`rank_in_sections`).
+ let mut places: std::collections::HashMap<u32, Vec<(u32, u32)>> = Default::default();
for (id, o) in &world.objects {
let crate::world::Kind::Mesh { geometry, material, materials: mesh_mats, .. } = &o.kind else { continue };
let gpu_of = |k: &u32| tables.retained.materials.get(k).copied();
if !std::iter::once(material).chain(mesh_mats).any(|k| gpu_of(k).is_some_and(|m| started.contains(&m))) {
continue;
}
- let Some(k) = tables.retained.instance(*id).filter(|i| i.mesh.own()).and_then(|i| instances.get(i.instance as usize)).map(|i| i.mesh) else { continue };
- if !done.insert(k) {
+ let Some(r) = tables.retained.instance(*id).filter(|i| i.mesh.own()).map(|i| i.instance as usize) else { continue };
+ // (A record no object draws any more has none; one hidden by its object's visibility has.)
+ let Some(inst) = instances.get(r).filter(|i| !i.hidden || i.masked).cloned() else { continue };
+ let (k, im) = (inst.mesh, meshes[inst.mesh as usize]);
+ let sects = im.sections(sections);
+ if sects.is_empty() {
continue;
}
- let gpu_mats: Option<Vec<u32>> = mesh_mats.iter().map(gpu_of).collect();
- let (Some(g), Some(mat), Some(gpu_mats)) = (world.geometries.get(geometry), gpu_of(material), gpu_mats) else { continue };
- let (t, mut a, _, _) = scene::own_mesh(g, mat, scene::group_materials(g, &gpu_mats).as_deref(), &tables.materials, 0);
- // (Software traversal: a unit's triangles lie in its tree's order.)
- if !hwrt {
- let Ok(tree) = crate::units::mesh_tree(&t) else { continue };
- a = tree.order.iter().map(|&i| a[i as usize]).collect();
+ if !places.contains_key(&k) {
+ let Some(g) = world.geometries.get(geometry) else { continue };
+ let mut d = scene::section_mesh(g, scene::by_groups(g, mesh_mats.len()), 0, 0, false);
+ // (Software traversal: a unit's triangles lie in its tree's order.)
+ if !hwrt {
+ let Ok(tree) = crate::units::mesh_tree(&d.tris) else { continue };
+ d.attrs = tree.order.iter().map(|&i| d.attrs[i as usize]).collect();
+ scene::rank_in_sections(&mut d.attrs);
+ }
+ if d.attrs.len() != im.count as usize {
+ debug_assert!(false, "mesh {k}: {} triangles made again, {} in the pool", d.attrs.len(), im.count);
+ continue;
+ }
+ places.insert(k, d.attrs.iter().map(|a| (a.uv[3].to_bits(), a.x[3].to_bits())).collect());
+ }
+ let place = &places[&k];
+ let at = inst.rows as usize;
+ let mine = rows[at..at + sects.len()].to_vec();
+ let starts = scene::section_emitters(sects, &mine, &tables.materials);
+ let n = scene::rows_emitters(sects, &mine, &tables.materials);
+ let old = emitter_run(&tables.emitter_tris, instances, r as u32);
+ for e in &mut tables.emitter_tris[old] {
+ e.area = 0.0;
}
- let im = meshes[k as usize];
- if a.len() != im.count as usize {
- debug_assert!(false, "mesh {k}: {} triangles made again, {} in the pool", a.len(), im.count);
- continue;
+ let first = tables.emitter_tris.len() as u32;
+ instances[r].first_emitter = first;
+ if let Some(rec) = gpu_instances.get_mut(r) {
+ rec.n[2][3] = f32::from_bits(first);
+ up.heap.write(q, Table::Instances, (r * std::mem::size_of::<scene::GpuInstance>()) as u64, bytemuck::bytes_of(rec));
}
- let n = scene::number_emitters(&mut a, &tables.materials);
- meshes[k as usize].emitters = n;
+ for (s, start) in starts.iter().enumerate() {
+ rows[at + s][2] = start.map_or(scene::NO_EMITTER, |x| first + x);
+ }
+ up.words.write(q, Stream::Rows, (at * 16) as u64, bytemuck::cast_slice(&rows[at..at + sects.len()]));
+ let numbered = |j: usize| {
+ let (s, i) = place[j];
+ starts.get(s as usize).copied().flatten().map(|x| ((x + i) as usize, scene::row_material(&mine[s as usize])))
+ };
let first_tri = edit.pool_first + im.first as usize;
- q.write_buffer(&up.attrs, (first_tri * std::mem::size_of::<scene::GpuTriAttr>()) as u64, bytemuck::cast_slice(&a));
- let numbered = |j: usize| (a[j].x[3].to_bits() as usize).checked_sub(1).map(|slot| (slot, a[j].uv[3].to_bits()));
- for r in 0..instances.len() {
- // (A record no object draws any more has none; one hidden by its object's visibility has.)
- if instances[r].mesh != k || (instances[r].hidden && !instances[r].masked) {
- continue;
- }
- let old = emitter_run(&tables.emitter_tris, instances, r as u32);
- for e in &mut tables.emitter_tris[old] {
- e.area = 0.0;
- }
- let first = tables.emitter_tris.len() as u32;
- instances[r].first_emitter = first;
- if let Some(rec) = gpu_instances.get_mut(r) {
- rec.n[2][3] = f32::from_bits(first);
- up.heap.write(q, Table::Instances, (r * std::mem::size_of::<scene::GpuInstance>()) as u64, bytemuck::bytes_of(rec));
- }
- let (b0, b1) = (im.first as usize, (im.first + im.count) as usize);
- for (e, w) in crate::instance_emitters(&instances[r], r as u32, &pool_tris[b0..b1], first_tri as u32, &numbered, n as usize, &tables.materials, moving.contains(&(r as u32))) {
- new.push((tables.emitter_tris.len() as u32, crate::GpuEmitterTri::of(&e, w, 0)));
- tables.emitter_tris.push(e);
- }
+ let (b0, b1) = (im.first as usize, (im.first + im.count) as usize);
+ for (e, w) in crate::instance_emitters(&instances[r], r as u32, &pool_tris[b0..b1], first_tri as u32, &numbered, n as usize, &tables.materials, moving.contains(&(r as u32))) {
+ new.push((tables.emitter_tris.len() as u32, crate::GpuEmitterTri::of(&e, w, 0)));
+ tables.emitter_tris.push(e);
}
}
}
@@ -1289,8 +1317,9 @@ impl LiveCore {
}
(inst.world, inst.hidden) = (wm, hidden);
let im = sc.meshes[inst.mesh as usize];
- emits = im.emitters > 0;
- casts = im.casts(n.cast_shadow);
+ let mine = &sc.rows[inst.rows as usize..][..im.sect_count as usize];
+ emits = scene::rows_emitters(im.sections(&sc.sections), mine, &sc.tables.materials) > 0;
+ casts = scene::rows_cast(mine, n.cast_shadow);
let (lo, hi) = im.placed_bounds(wm);
let row = scene::object_row(wm.transform_point3(glam::Vec3::ZERO), n.power, hi - lo, t.custom(i, n.custom), t.color(i));
if emits {
@@ -1773,7 +1802,7 @@ impl LiveCore {
if std::env::var("THREERT_EDIT_REBUILD").is_ok_and(|v| v == "1") {
return Err("THREERT_EDIT_REBUILD=1".into());
}
- let LoadedScene { up, tables, edit, meshes, pool_tris, instances, gpu_instances, procs, proc_first, moving_instances, .. } = &mut self.sc;
+ let LoadedScene { up, tables, edit, meshes, pool_tris, instances, gpu_instances, sections, rows, procs, proc_first, moving_instances, .. } = &mut self.sc;
let (g, assets) = (&self.g, &self.assets);
let features = up.kernel.features;
let grow = Grow { g: &self.g, ok: up.particles.is_none() && up.gpu_particles.is_none() };
@@ -1874,7 +1903,8 @@ impl LiveCore {
let mut w_colors = Gather::default();
let vcolors = up.vcolors;
// (geometry, material) -> the mesh built in this batch (objects sharing a replaced geometry share it again).
- let mut fresh: std::collections::HashMap<(u32, Vec<u32>), u32> = Default::default();
+ let mut fresh: std::collections::HashMap<(u32, bool), u32> = Default::default();
+ let mut w_rows = Gather::default();
let mask = |shadow: bool| if shadow { 1 } else { 2 };
for id in todo {
let Some(o) = world.objects.get(&id) else { continue };
@@ -1989,7 +2019,7 @@ impl LiveCore {
if let Some(k) = was {
drop_mesh_user(k, edit, tables, meshes);
}
- let inst = scene::Instance { mesh, world: m, object: object as u32, cast_shadow: im.casts(o.cast_shadow), name: o.name.clone(), sub: None, hidden: false, masked: false, first_emitter: 0 };
+ let inst = scene::Instance { mesh, world: m, object: object as u32, cast_shadow: im.casts(o.cast_shadow), name: o.name.clone(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: 0 };
let gpu = top.record(inst.gpu((edit.pool_first as u32) + im.first, im.part_offsets()), mesh, inst.cast_shadow);
let (lo, hi) = im.placed_bounds(m);
let entry = scene::object_row(m.transform_point3(glam::Vec3::ZERO), o.power, hi - lo, o.custom, [1.0; 3]);
@@ -2003,7 +2033,7 @@ impl LiveCore {
_ => unreachable!(),
};
let (geometry, material) = (&geometry, &material);
- if features & gpu::F_INST == 0 {
+ if features & gpu::F_INST == 0 || features & gpu::F_ROWS == 0 {
return Err("the scene's first instanced mesh (kernel feature)".into());
}
// A placement without size (a build places it, unseen at a point), or instancing off (it flattens).
@@ -2034,14 +2064,18 @@ impl LiveCore {
if colored && !vcolors {
return Err("the scene's first vertex colours (kernel feature)".into());
}
- let key = (*geometry, vec![mat]);
+ // (The geometry whole, with one material: the mesh every such object of the geometry shares; its
+ // material is this instance's row.)
+ let key = (*geometry, false);
let kept = (!ch.geometries.contains(geometry)).then(|| tables.retained.own_mesh.get(&key).copied()).flatten();
let mesh = match fresh.get(&key).copied().or(kept) {
+ // (A mesh made without its geometry's colours, for objects that read none.)
+ Some(k) if colored && !meshes[k as usize].colored => return Err("vertex colours on a mesh made without them".into()),
Some(k) => k,
None => {
let geo = world.geometries.get(geometry).ok_or("unknown geometry")?;
let t0 = Instant::now();
- let (mut t, mut a) = scene::own_mesh_tris(geo, mat);
+ let scene::MeshData { tris: mut t, attrs: mut a, .. } = scene::section_mesh(geo, false, 0, 0, false);
if t.is_empty() {
if let Some((slot, _)) = at {
top.clear(slot);
@@ -2060,15 +2094,12 @@ impl LiveCore {
let tree = crate::units::mesh_tree(&t)?;
t = tree.order.iter().map(|&i| t[i as usize]).collect();
a = tree.order.iter().map(|&i| a[i as usize]).collect();
+ scene::rank_in_sections(&mut a);
Some(tree)
}
};
- // (A mesh that emits: its triangles numbered as they lie, for its instances' emitters.)
- if emits {
- scene::number_emitters(&mut a, &tables.materials);
- }
- // (A unit's cutout triangles carry their flag; hardware traversal has them in a geometry apart.)
- let flags = f32::from_bits(if tree.is_none() { 0 } else { [0, scene::TRI_MASKED, scene::TRI_NO_SHADOW][class as usize] });
+ // (No flag on the triangles: a unit's cutouts and glass are its rows'.)
+ let flags = 0.0f32;
// As `prepare` lays the pool out: (a, flags), e1, e2; attributes; the BLAS's vertices.
let verts: Vec<[f32; 4]> = t.iter().flat_map(|&[a, b, c]| [[a.x, a.y, a.z, flags], [b.x - a.x, b.y - a.y, b.z - a.z, 0.0], [c.x - a.x, c.y - a.y, c.z - a.z, 0.0]]).collect();
let blas_verts: Vec<[f32; 3]> = t.iter().flat_map(|&[a, b, c]| [[a.x, a.y, a.z], [b.x, b.y, b.z], [c.x, c.y, c.z]]).collect();
@@ -2079,6 +2110,8 @@ impl LiveCore {
let same = tables.retained.own_mesh.get(&key).copied().filter(|&k| meshes[k as usize].count as usize == t.len() );
let (k, first, im) = match same {
Some(k) => {
+ // (Its colours stay its own while another object of it reads them.)
+ meshes[k as usize].colored |= colored;
let im = meshes[k as usize];
split.deformed += 1;
// (Its tree again: the records of the objects that draw it, all placed again by
@@ -2104,18 +2137,25 @@ impl LiveCore {
}
None => return Err(if matches!(top, gpu::Top::Sw(_)) { "edit room: triangles (software traversal's does not grow)" } else { "edit room: triangles (particles, or the device's limits)" }.into()),
};
- let mut im = scene::own_inst_mesh(&t, (first - edit.pool_first) as u32, class);
- im.emitters = if emits { t.len() as u32 } else { 0 };
let t1 = Instant::now();
- // A freed mesh's slot, else a new one.
+ // A freed mesh's slot (and its section's), else a new one.
let dead = edit.dead_meshes.pop();
+ let sect_first = match dead.map(|k| meshes[k as usize]).filter(|m| m.sect_count > 0) {
+ Some(m) => m.sect_first,
+ None => {
+ sections.push(scene::Section { first: 0, count: 0, slot: 0 });
+ sections.len() as u32 - 1
+ }
+ };
+ sections[sect_first as usize] = scene::Section { first: 0, count: t.len() as u32, slot: 0 };
+ let im = scene::InstMesh { sect_first, sect_count: 1, colored, ..scene::own_inst_mesh(&t, (first - edit.pool_first) as u32, 0) };
let k = match &mut top {
gpu::Top::Hw(accel) => match dead {
Some(k) => {
- g.set_mesh(accel, k, first, &im);
+ g.set_mesh(accel, k, first, &im, sections);
k
}
- None => g.add_mesh(accel, first, &im),
+ None => g.add_mesh(accel, first, &im, sections),
},
// Its tree into the mesh trees' room (a freed mesh's slot gives its tree back first).
gpu::Top::Sw(units) => {
@@ -2152,6 +2192,7 @@ impl LiveCore {
}
if vcolors {
// White where it has none: the room's slots may hold an earlier mesh's.
+ let colored = im.colored;
let mut c = if colored { scene::tri_colors(geo, false, None) } else { vec![scene::WHITE; t.len()] };
if let (Some(tree), true) = (&tree, colored) {
c = tree.order.iter().map(|&i| c[i as usize]).collect();
@@ -2190,7 +2231,7 @@ impl LiveCore {
edit.objects.give(object, 1);
let r0 = match edit.records.take(cap) {
Some(r) => r,
- None if match &mut top { gpu::Top::Hw(accel) => grow.records(&mut edit.records, cap, &mut up.heap, accel), gpu::Top::Sw(_) => false } => {
+ None if match &mut top { gpu::Top::Hw(accel) => grow.records(&mut edit.records, cap, &mut up.heap, accel, &mut up.words, edit.row_base), gpu::Top::Sw(_) => false } => {
edit.grows += 1;
edit.rebind = true;
edit.records.take(cap).ok_or("edit room: records")?
@@ -2208,7 +2249,7 @@ impl LiveCore {
};
let (st, size) = (tables.stride, std::mem::size_of::<scene::GpuInstance>());
if instances.len() < r0 + cap {
- let filler = scene::Instance { mesh, world: glam::Mat4::IDENTITY, object: 0, cast_shadow: false, name: String::new(), sub: None, hidden: true, masked: false, first_emitter: 0 };
+ let filler = scene::Instance { mesh, world: glam::Mat4::IDENTITY, object: 0, cast_shadow: false, name: String::new(), sub: None, hidden: true, masked: false, first_emitter: 0, rows: 0, bits: 0 };
instances.resize(r0 + cap, filler);
}
if gpu_instances.len() < r0 + cap {
@@ -2218,14 +2259,18 @@ impl LiveCore {
tables.objects.resize((o0 + cap) * st, [0.0; 4]);
}
for (i, &(wm, hidden)) in placed.iter().enumerate() {
- let mut inst = scene::Instance { mesh, world: wm, object: (o0 + i) as u32, cast_shadow: im.casts(o.cast_shadow), name: o.name.clone(), sub: Some(i as u32), hidden, masked: false, first_emitter: 0 };
- // A copy of a mesh that emits: its emitters, a run at the light list's end; moving ones
+ // (Its row: the room's, as its record is.)
+ let row_at = edit.row_at(instances, r0 + i);
+ let mut row = scene::row_of(mat, &tables.materials);
+ row[1] = edit.pool_first as u32 + im.first;
+ let mut inst = scene::Instance { mesh, world: wm, object: (o0 + i) as u32, cast_shadow: scene::rows_cast(&[row], o.cast_shadow), name: o.name.clone(), sub: Some(i as u32), hidden, masked: false, first_emitter: 0, rows: row_at as u32, bits: scene::rows_bits(&[row]) };
+ // A copy whose material emits: its emitters, a run at the light list's end; moving ones
// (`update_instanced` changes the copies in place), a hidden copy's at no weight.
- if im.emitters > 0 {
+ if emits {
let first = tables.emitter_tris.len();
- inst.first_emitter = first as u32;
+ (inst.first_emitter, row[2]) = (first as u32, first as u32);
let (a, b) = (im.first as usize, (im.first + im.count) as usize);
- let made = crate::instance_emitters(&inst, (r0 + i) as u32, &pool_tris[a..b], (edit.pool_first + a) as u32, &|k| Some((k, mat)), im.emitters as usize, &tables.materials, true);
+ let made = crate::instance_emitters(&inst, (r0 + i) as u32, &pool_tris[a..b], (edit.pool_first + a) as u32, &|k| Some((k, mat)), im.count as usize, &tables.materials, true);
for (j, (e, w)) in made.into_iter().enumerate() {
new_emitters.push(((first + j) as u32, crate::GpuEmitterTri::of(&e, w, 0)));
tables.emitter_tris.push(e);
@@ -2233,12 +2278,17 @@ impl LiveCore {
tables.emissive.insert(mat);
emitters_changed = true;
}
- let rec = top.record(inst.gpu((edit.pool_first as u32) + im.first, im.part_offsets()), mesh, inst.cast_shadow);
+ w_rows.put((row_at * 16) as u64, bytemuck::bytes_of(&row));
+ if rows.len() <= row_at {
+ rows.resize(row_at + 1, [0; 4]);
+ }
+ rows[row_at] = row;
+ let rec = top.record(inst.gpu((edit.pool_first as u32) + im.first, inst.parts(&im)), mesh, inst.cast_shadow);
w_records.put(((r0 + i) * size) as u64, bytemuck::bytes_of(&rec));
gpu_instances[r0 + i] = rec;
top.place(inst_base + r0 + i, mesh, wm, gpu::INSTANCE_BIT | (r0 + i) as u32, inst.cast_shadow, hidden);
let (lo, hi) = im.placed_bounds(wm);
- let entry = scene::copy_row(scene::object_row(wm.transform_point3(glam::Vec3::ZERO), o.power, hi - lo, t.custom(i, o.custom), t.color(i)), im.emitters > 0 && hidden);
+ let entry = scene::copy_row(scene::object_row(wm.transform_point3(glam::Vec3::ZERO), o.power, hi - lo, t.custom(i, o.custom), t.color(i)), emits && hidden);
w_objects.put(((o0 + i) * st * 16) as u64, bytemuck::cast_slice(&entry[..st]));
tables.objects[(o0 + i) * st..(o0 + i + 1) * st].copy_from_slice(&entry[..st]);
instances[r0 + i] = inst;
@@ -2246,8 +2296,11 @@ impl LiveCore {
*tables.retained.proxy(id) = scene::Proxy { object: None, card: None, draw: scene::Draw::Instanced(scene::InstancedPlace { first: r0 as u32, capacity: cap as u32, object: o0 as u32, mesh: Some(mesh), drawn: t.count }) };
continue;
}
- let inst = scene::Instance { mesh, world: m, object: object as u32, cast_shadow: im.casts(o.cast_shadow), name: o.name.clone(), sub: None, hidden: false, masked: false, first_emitter: 0 };
- let gpu = top.record(inst.gpu((edit.pool_first as u32) + im.first, im.part_offsets()), mesh, inst.cast_shadow);
+ // (Its row, which says its material, is placed with its record below; its bits and whether it
+ // casts are the row's.)
+ let row = [scene::row_of(mat, &tables.materials)];
+ let inst = scene::Instance { mesh, world: m, object: object as u32, cast_shadow: scene::rows_cast(&row, o.cast_shadow), name: o.name.clone(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: scene::rows_bits(&row) };
+ let gpu = top.record(inst.gpu((edit.pool_first as u32) + im.first, inst.parts(&im)), mesh, inst.cast_shadow);
let (lo, hi) = im.placed_bounds(m);
let entry = scene::object_row(m.transform_point3(glam::Vec3::ZERO), o.power, hi - lo, o.custom, [1.0; 3]);
(at.map(|(_, r)| r), gpu, Placed::Mesh(inst), entry)
@@ -2260,7 +2313,7 @@ impl LiveCore {
_ => {
let r = match edit.records.take(1) {
Some(r) => r,
- None if match &mut top { gpu::Top::Hw(accel) => grow.records(&mut edit.records, 1, &mut up.heap, accel), gpu::Top::Sw(_) => false } => {
+ None if match &mut top { gpu::Top::Hw(accel) => grow.records(&mut edit.records, 1, &mut up.heap, accel, &mut up.words, edit.row_base), gpu::Top::Sw(_) => false } => {
edit.grows += 1;
edit.rebind = true;
edit.records.take(1).ok_or("edit room: records")?
@@ -2276,13 +2329,19 @@ impl LiveCore {
let (mut gpu, mut blas) = (gpu, blas);
if let (Placed::Mesh(inst), Kind::Mesh { material, .. }) = (&mut blas, &o.kind) {
let im = meshes[inst.mesh as usize];
- if let (true, Some(&mat)) = (im.emitters > 0, tables.retained.materials.get(material)) {
+ let mat = *tables.retained.materials.get(material).ok_or("unknown material")?;
+ // Its row (one section: the geometry whole), where its record's is.
+ let row_at = edit.row_at(instances, record);
+ let mut row = scene::row_of(mat, &tables.materials);
+ row[1] = edit.pool_first as u32 + im.first;
+ (inst.rows, gpu.info[3]) = (row_at as u32, row_at as u32);
+ if tables.materials.get(mat as usize).is_some_and(scene::emissive) {
let old = emitter_run(&tables.emitter_tris, instances, record as u32);
- let first = if old.len() == im.emitters as usize && tables.emitter_tris[old.clone()].iter().all(|e| !e.in_tree) { old.start } else { tables.emitter_tris.len() };
- inst.first_emitter = first as u32;
+ let first = if old.len() == im.count as usize && tables.emitter_tris[old.clone()].iter().all(|e| !e.in_tree) { old.start } else { tables.emitter_tris.len() };
+ (inst.first_emitter, row[2]) = (first as u32, first as u32);
gpu.n[2][3] = f32::from_bits(first as u32);
let (a, b) = (im.first as usize, (im.first + im.count) as usize);
- let made = crate::instance_emitters(inst, record as u32, &pool_tris[a..b], (edit.pool_first + a) as u32, &|k| Some((k, mat)), im.emitters as usize, &tables.materials, o.driven || world.movable(id));
+ let made = crate::instance_emitters(inst, record as u32, &pool_tris[a..b], (edit.pool_first + a) as u32, &|k| Some((k, mat)), im.count as usize, &tables.materials, o.driven || world.movable(id));
for (j, (e, w)) in made.into_iter().enumerate() {
new_emitters.push(((first + j) as u32, crate::GpuEmitterTri::of(&e, w, 0)));
match tables.emitter_tris.get_mut(first + j) {
@@ -2293,6 +2352,11 @@ impl LiveCore {
tables.emissive.insert(mat);
emitters_changed = true;
}
+ w_rows.put((row_at * 16) as u64, bytemuck::bytes_of(&row));
+ if rows.len() <= row_at {
+ rows.resize(row_at + 1, [0; 4]);
+ }
+ rows[row_at] = row;
}
w_records.put((record * std::mem::size_of::<scene::GpuInstance>()) as u64, bytemuck::bytes_of(&gpu));
if record >= gpu_instances.len() {
@@ -2340,6 +2404,7 @@ impl LiveCore {
w_blas.flush(q, &accel.verts);
}
w_colors.flush_section(q, &up.words, Stream::VertexColors);
+ w_rows.flush_section(q, &up.words, Stream::Rows);
w_records.flush_section(q, &up.heap, Table::Instances);
w_objects.flush_section(q, &up.heap, Table::Objects);
split.upload += tw.elapsed().as_secs_f64() * 1e3;
diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rs
index 092449b..8a85db4 100644
--- a/renderer/src/live/inplace_tests.rs
+++ b/renderer/src/live/inplace_tests.rs
@@ -414,6 +414,7 @@ fn list_is_its_triangles(what: &str, c: &LiveCore) {
let cdf = read(&up.heap.buffer, up.heap.at(Table::Emitters), (tables.emitter_tris.len() * 16) as u64);
let record_size = std::mem::size_of::<scene::GpuInstance>();
let records = read(&up.heap.buffer, up.heap.at(Table::Instances), (c.sc.gpu_instances.len() * record_size) as u64);
+ let gpu_rows = read(&up.words.buffer, up.words.at(crate::heap::Stream::Rows), up.words.cap(crate::heap::Stream::Rows));
let mut alive = 0;
for (i, e) in tables.emitter_tris.iter().enumerate() {
let r: crate::GpuEmitterTri = bytemuck::pod_read_unaligned(&list[i * size..][..size]);
@@ -440,7 +441,18 @@ fn list_is_its_triangles(what: &str, c: &LiveCore) {
for (got, want) in [r.v0, r.e1, r.e2].into_iter().zip(placed) {
assert!((glam::Vec3::from(got) - want).length() <= 1e-4 * (1.0 + want.length()), "{what}: emitter {i}'s triangle {got:?}, its instance places it at {want:?}");
}
- assert_eq!((record.n[2][3].to_bits(), record.n[2][3].to_bits() + a.x[3].to_bits()), (inst.first_emitter, i as u32 + 1), "{what}: triangle {} of instance {} finds its emitter", e.tri, e.inst);
+ if record.n[1][3].to_bits() & scene::INST_ROWS == 0 {
+ assert_eq!((record.n[2][3].to_bits(), record.n[2][3].to_bits() + a.x[3].to_bits()), (inst.first_emitter, i as u32 + 1), "{what}: triangle {} of instance {} finds its emitter", e.tri, e.inst);
+ alive += 1;
+ continue;
+ }
+ // An instance with rows: its section's row as the GPU has it says the material and where the section's
+ // emitters start, the triangle its index among them.
+ let at = (record.info[3] + a.uv[3].to_bits()) as usize;
+ let row: scene::Row = bytemuck::pod_read_unaligned(&gpu_rows[at * 16..][..16]);
+ assert_eq!(row, c.sc.rows[at], "{what}: row {at} on the GPU is the scene's");
+ assert_eq!((record.info[3], record.n[2][3].to_bits()), (inst.rows, inst.first_emitter), "{what}: instance {}'s record has its rows and its first emitter", e.inst);
+ assert_eq!((row[2].wrapping_add(a.x[3].to_bits()), scene::row_material(&row)), (i as u32, e.mat), "{what}: triangle {} of instance {} finds its emitter, of its row's material", e.tri, e.inst);
}
alive += 1;
}
@@ -893,16 +905,18 @@ fn a_material_that_starts_emitting_lights_its_meshes_instances_as_a_build_does()
// (The sun away: the meshes will light the scene.)
w.set_visible(20, false).unwrap();
w.set_material(6, late(0.0));
- // Sixteen quads in a row in one geometry, a group each, by turns of the lamp's material, which emits, and of
- // the late one; the geometry has them out of the row's order (so that a mesh tree orders them its own way under
- // software traversal).
- let (mut positions, mut indices, mut groups) = (vec![], vec![], vec![]);
+ // Sixteen quads in a row in one geometry, four to a group, the groups by turns of the lamp's material, which
+ // emits, and of the late one; the geometry has the quads out of the row's order (so that a mesh tree orders a
+ // section's triangles its own way under software traversal).
+ let (mut positions, mut indices) = (vec![], vec![]);
for q in 0..16u32 {
let x = -0.48 + 0.06 * ((q * 7) % 16) as f32;
positions.extend([x, -0.15, 0.0, x + 0.06, -0.15, 0.0, x + 0.06, 0.15, 0.0, x, 0.15, 0.0]);
indices.extend([0, 1, 2, 0, 2, 3].map(|i| 4 * q + i));
- groups.push([6 * q, 6, q % 2]);
}
+ let groups = (0..4u32).map(|k| [24 * k, 24, k % 2]).collect();
+ // (And the same quads without groups, for the mesh added in place below: one section of 32 triangles.)
+ w.set_geometry(8, Geometry { positions: positions.clone(), normals: [0.0, 0.0, 1.0].repeat(64), uvs: vec![0.0; 128], indices: indices.clone(), groups: vec![], colors: vec![] }).unwrap();
w.set_geometry(7, Geometry { positions, normals: [0.0, 0.0, 1.0].repeat(64), uvs: vec![0.0; 128], indices, groups, colors: vec![] }).unwrap();
let mesh = |geometry, material, materials| Kind::Mesh { geometry, material, own_blas: false, materials };
w.set_object(13, "one".into(), None, mesh(3, 6, vec![]), true, false).unwrap();
@@ -939,14 +953,19 @@ fn a_material_that_starts_emitting_lights_its_meshes_instances_as_a_build_does()
let mesh_of = |c: &LiveCore, id: u32| c.sc.instances[c.sc.tables.retained.instance(id).expect("a mesh is an instance").instance as usize].mesh;
assert_eq!(mesh_of(&live, 13), mesh_of(&live, 14), "the two objects share their mesh");
let two = mesh_of(&live, 15) as usize;
- assert_eq!((live.sc.meshes[two].count, live.sc.meshes[two].emitters), (32, 16), "the mesh of two materials: one emits");
+ let emitters_of = |c: &LiveCore, id: u32| {
+ let i = &c.sc.instances[c.sc.tables.retained.instance(id).unwrap().instance as usize];
+ let m = c.sc.meshes[i.mesh as usize];
+ scene::rows_emitters(m.sections(&c.sc.sections), &c.sc.rows[i.rows as usize..][..m.sect_count as usize], &c.sc.tables.materials)
+ };
+ assert_eq!((live.sc.meshes[two].count, live.sc.meshes[two].sect_count, emitters_of(&live, 15)), (32, 4, 16), "the mesh of two materials, a section a group: one emits");
// (A third object of the shared mesh, hidden when the material starts: it has its emitters when it is shown.)
w.set_visible(33, false).unwrap();
assert!(!live.commit(&mut w).unwrap(), "a mesh hidden, {with} a light tree: in place ({:?})", live.fallback);
w.set_material(6, late(30.0));
let what = format!("a material started emitting in place, {with} a light tree");
assert!(!live.commit(&mut w).unwrap(), "{what}: in place ({:?})", live.fallback);
- assert_eq!((live.sc.meshes[two].emitters, live.sc.meshes[mesh_of(&live, 13) as usize].emitters), (32, 2), "{what}: the meshes' emitters");
+ assert_eq!((emitters_of(&live, 15), emitters_of(&live, 13), emitters_of(&live, 14)), (32, 2, 2), "{what}: the instances' emitters");
list_is_its_triangles(&what, &live);
let moving = |c: &LiveCore, id: u32| {
let r = c.sc.tables.retained.instance(id).unwrap().instance;
@@ -959,16 +978,15 @@ fn a_material_that_starts_emitting_lights_its_meshes_instances_as_a_build_does()
assert!(!live.commit(&mut w).unwrap(), "{what}: in place ({:?})", live.fallback);
list_is_its_triangles(&what, &live);
lit_as_a_build(&what, &mut live, &mut open(&w).unwrap());
- if live.g.hwrt {
- w.set_object(29, "added".into(), None, Kind::Mesh { geometry: 3, material: 8, own_blas: true, materials: vec![] }, true, false).unwrap();
- w.set_transform(29, Vec3::new(-0.2, 0.1, 1.0), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
- assert!(!live.commit(&mut w).unwrap(), "a mesh added, {with} a light tree: in place ({:?})", live.fallback);
- w.set_material(8, late(20.0));
- let what = format!("the material of a mesh added in place started emitting, {with} a light tree");
- assert!(!live.commit(&mut w).unwrap(), "{what}: in place ({:?})", live.fallback);
- list_is_its_triangles(&what, &live);
- lit_as_a_build(&what, &mut live, &mut open(&w).unwrap());
- }
+ // (A mesh of many triangles added in place: under software traversal its tree orders them its own way.)
+ w.set_object(29, "added".into(), None, Kind::Mesh { geometry: 8, material: 8, own_blas: true, materials: vec![] }, true, false).unwrap();
+ w.set_transform(29, Vec3::new(-0.2, 0.1, 1.0), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ assert!(!live.commit(&mut w).unwrap(), "a mesh added, {with} a light tree: in place ({:?})", live.fallback);
+ w.set_material(8, late(20.0));
+ let what = format!("the material of a mesh added in place started emitting, {with} a light tree");
+ assert!(!live.commit(&mut w).unwrap(), "{what}: in place ({:?})", live.fallback);
+ list_is_its_triangles(&what, &live);
+ lit_as_a_build(&what, &mut live, &mut open(&w).unwrap());
w.set_transform(14, Vec3::new(0.2, -0.3, 1.2), glam::Quat::from_rotation_z(0.6), Vec3::ONE).unwrap();
let what = format!("the movable one of them moved, {with} a light tree");
assert!(!(live.commit(&mut w).unwrap() && live.g.hwrt), "{what}: in place ({:?})", live.fallback);
@@ -1297,6 +1315,184 @@ fn a_still_model_is_hidden_removed_and_moved_in_place() {
}
}
+/// Objects of one geometry share its mesh whatever their materials: one that reads the geometry's vertex colours
+/// and one that does not, a cutout that lets everything through and one that lets nothing, glass, one that emits. At
+/// the build; one more placed in place; an object given another material, which keeps the mesh (none is made, no
+/// triangle written). Each time the picture is a build's, and the picture of the same world with a geometry an
+/// object, so a mesh an object; it is not the picture of the objects all with one material, nor of the plain one
+/// reading the colours too.
+#[test]
+fn objects_of_one_geometry_share_its_mesh_whatever_their_materials() {
+ 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 json = |v: serde_json::Value| serde_json::from_value::<crate::desc::Material>(v).unwrap();
+ let plain = |extra: serde_json::Value| {
+ let mut m = serde_json::json!({ "name": "m", "color": [0.9, 0.9, 0.9], "opacity": 1, "metalness": 0, "roughness": 1, "emissive": [0, 0, 0], "emissiveIntensity": 0, "doubleSided": true });
+ m.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
+ json(m)
+ };
+ // (30 + i: the geometry of object 40 + i where each has its own.)
+ let tile = || Geometry { positions: vec![-0.4, -0.4, 0.0, 0.4, -0.4, 0.0, 0.4, 0.4, 0.0, -0.4, 0.4, 0.0], normals: [0.0, 0.0, 1.0].repeat(4), uvs: vec![0.0; 8], indices: vec![0, 1, 2, 0, 2, 3], groups: vec![], colors: vec![1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0] };
+ let mats = [61, 62, 63, 64, 65, 5];
+ // (`variant` 1: the objects all of the plain material; 2: the plain material reads the colours too.)
+ let scene = |own: bool, variant: u32| {
+ let mut w = world();
+ w.set_material(61, plain(serde_json::json!({ "vertexColors": true })));
+ w.set_material(62, plain(serde_json::json!({ "vertexColors": variant == 2 })));
+ w.set_material(63, plain(serde_json::json!({ "opacity": 0.3, "alphaTest": 0.5 })));
+ w.set_material(64, plain(serde_json::json!({ "opacity": 0.9, "alphaTest": 0.5, "color": [0.2, 0.6, 0.9] })));
+ w.set_material(65, plain(serde_json::json!({ "color": [0.5, 0.9, 0.5], "roughness": 0, "transmission": 1, "ior": 1.5 })));
+ for (i, mat) in mats.iter().enumerate() {
+ let geometry = 30 + if own { i as u32 } else { 0 };
+ w.set_geometry(geometry, tile()).unwrap();
+ let id = 40 + i as u32;
+ w.set_object(id, format!("tile{i}"), None, Kind::Mesh { geometry, material: if variant == 1 { 62 } else { *mat }, own_blas: i == 0, materials: vec![] }, true, false).unwrap();
+ w.set_transform(id, Vec3::new(-2.25 + 0.9 * i as f32, 0.55, 0.6), glam::Quat::from_rotation_y(0.2), Vec3::ONE).unwrap();
+ }
+ w
+ };
+ let mesh_of = |c: &LiveCore, id: u32| c.sc.instances[c.sc.tables.retained.instance(id).expect("a mesh is an instance").instance as usize].mesh;
+ let mut w = scene(false, 0);
+ let mut live = match open(&w) {
+ Ok(c) if c.g.hwrt => c,
+ Ok(_) => return eprintln!("skipped: no hardware RT"),
+ Err(e) => return eprintln!("skipped: {e}"),
+ };
+ w.take_changes();
+ let shared = mesh_of(&live, 40);
+ assert!((41..46).all(|id| mesh_of(&live, id) == shared), "the six objects of one geometry share its mesh");
+ assert!(live.sc.meshes[shared as usize].colored && live.sc.meshes[shared as usize].sect_count == 1);
+ let features = live.sc.up.kernel.features;
+ assert_eq!(features & (gpu::F_ROWS | gpu::F_MASKED | gpu::F_VCOLOR), gpu::F_ROWS | gpu::F_MASKED | gpu::F_VCOLOR);
+ let placed = |c: &LiveCore, id: u32| c.sc.instances[c.sc.tables.retained.instance(id).unwrap().instance as usize].clone();
+ assert!(!placed(&live, 44).cast_shadow && placed(&live, 43).cast_shadow, "glass alone casts no shadow");
+ list_is_its_triangles("objects of one geometry, at the build", &live);
+ let mut apart_world = open(&scene(true, 0)).unwrap();
+ let meshes: std::collections::HashSet<u32> = (40..46).map(|id| mesh_of(&apart_world, id)).collect();
+ assert_eq!(meshes.len(), 6, "a geometry an object: a mesh an object");
+ let (a, b) = (picture(&mut live, 64), picture(&mut apart_world, 64));
+ assert!(apart(&a, &b) < 0.5, "one mesh for six materials: the picture is {:.2} steps from six meshes'", apart(&a, &b));
+ let c = picture(&mut open(&scene(false, 1)).unwrap(), 64);
+ assert!(apart(&a, &c) > 0.5, "the materials are in the picture ({:.2} steps from the objects all of one)", apart(&a, &c));
+ let c = picture(&mut open(&scene(false, 2)).unwrap(), 64);
+ assert!(apart(&a, &c) > 0.5, "the plain material reads no colour of the mesh ({:.2} steps from where it does)", apart(&a, &c));
+ // One more of the geometry, glass, placed in place: the mesh it shares, nothing made.
+ let (meshes, triangles) = (live.sc.meshes.len(), live.sc.pool_tris.len());
+ let place = |w: &mut World, id: u32, material: u32, at: Vec3| {
+ w.set_object(id, format!("tile{}", id - 40), None, Kind::Mesh { geometry: 30, material, own_blas: false, materials: vec![] }, true, false).unwrap();
+ w.set_transform(id, at, glam::Quat::from_rotation_y(0.2), Vec3::ONE).unwrap();
+ };
+ let against_a_build = |what: &str, live: &mut LiveCore, w: &World| {
+ list_is_its_triangles(what, live);
+ let mut fresh = open(w).unwrap();
+ lit_as_a_build(what, live, &mut fresh);
+ };
+ place(&mut w, 46, 65, Vec3::new(0.2, -0.5, 0.9));
+ assert!(!live.commit(&mut w).unwrap(), "an object of the geometry placed: in place ({:?})", live.fallback);
+ assert_eq!((mesh_of(&live, 46), live.sc.meshes.len(), live.sc.pool_tris.len()), (shared, meshes, triangles), "it shares the mesh: none made");
+ against_a_build("an object of the geometry placed in place", &mut live, &w);
+ // Another material for an object: its row. The plain one emits now, the one that emitted is a cutout.
+ for (id, material, at) in [(41, 5, Vec3::new(-1.35, 0.55, 0.6)), (45, 64, Vec3::new(2.25, 0.55, 0.6))] {
+ place(&mut w, id, material, at);
+ let what = format!("object {id} given material {material}");
+ assert!(!live.commit(&mut w).unwrap(), "{what}: in place ({:?})", live.fallback);
+ assert_eq!((mesh_of(&live, id), live.sc.meshes.len(), live.sc.pool_tris.len()), (shared, meshes, triangles), "{what}: it keeps the mesh, none made");
+ assert_eq!(scene::row_material(&live.sc.rows[placed(&live, id).rows as usize]), live.sc.tables.retained.materials[&material], "{what}: its row names it");
+ against_a_build(&what, &mut live, &w);
+ }
+ // A geometry with colours that no object read at the build: its mesh was made without them, and an object that
+ // reads them, placed later, has them by a rebuild.
+ let mut w = world();
+ w.set_material(61, plain(serde_json::json!({ "vertexColors": true })));
+ w.set_material(62, plain(serde_json::json!({})));
+ w.set_geometry(30, tile()).unwrap();
+ w.set_object(40, "tile0".into(), None, Kind::Mesh { geometry: 30, material: 62, own_blas: true, materials: vec![] }, true, false).unwrap();
+ w.set_transform(40, Vec3::new(-0.6, 0.55, 0.6), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ // (And a coloured mesh in the scene: the kernel has vertex colours.)
+ w.set_geometry(31, tile()).unwrap();
+ w.set_object(41, "tile1".into(), None, Kind::Mesh { geometry: 31, material: 61, own_blas: false, materials: vec![] }, true, false).unwrap();
+ w.set_transform(41, Vec3::new(0.9, -0.6, 0.6), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ let mut live = open(&w).unwrap();
+ w.take_changes();
+ assert!(!live.sc.meshes[mesh_of(&live, 40) as usize].colored && live.sc.meshes[mesh_of(&live, 41) as usize].colored);
+ place(&mut w, 42, 61, Vec3::new(0.0, 0.55, 0.6));
+ assert!(live.commit(&mut w).unwrap(), "colours asked of a mesh made without them: a rebuild");
+ assert!(live.sc.meshes[mesh_of(&live, 42) as usize].colored && mesh_of(&live, 42) == mesh_of(&live, 40));
+ against_a_build("an object that reads its geometry's colours placed", &mut live, &w);
+}
+
+/// Glass among an instance's other sections lets the sky's and the sun's light through as an instance that is all
+/// glass does: a pane and its frame as one mesh of two materials, against the two as a mesh each, before a wall, in
+/// a scene with a cutout and in one without (the kernel then tests no hit for a cutout, and still steps through the
+/// glass). A shadow ray steps through the first's glass by its row and never meets the second's (its mask); a
+/// sample of the sky weighs the same against the surface's own rays, which pass the glass either way (glass is no
+/// cutout's hole), so the pictures are the same.
+#[test]
+fn glass_among_an_instances_sections_is_lit_through_as_glass_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 json = |v: serde_json::Value| serde_json::from_value::<crate::desc::Material>(v).unwrap();
+ let quads = |q: &[[f32; 4]], groups: Vec<[u32; 3]>| {
+ let (mut positions, mut indices) = (vec![], vec![]);
+ for (k, &[x0, y0, x1, y1]) in q.iter().enumerate() {
+ positions.extend([x0, y0, 0.0, x1, y0, 0.0, x1, y1, 0.0, x0, y1, 0.0]);
+ indices.extend([0, 1, 2, 0, 2, 3].map(|i| 4 * k as u32 + i));
+ }
+ Geometry { normals: [0.0, 0.0, 1.0].repeat(4 * q.len()), uvs: vec![0.0; 8 * q.len()], positions, indices, groups, colors: vec![] }
+ };
+ let (pane, frame) = ([-1.0, -1.0, 1.0, 0.6], [-1.0, 0.6, 1.0, 1.0]);
+ // (`parts` 0: the pane and its frame one mesh; 1: a mesh each; 2: neither.)
+ let scene = |parts: u32, cutout: bool| {
+ let mut w = world();
+ w.set_material(71, json(serde_json::json!({ "name": "pane", "color": [0.6, 0.9, 0.6], "opacity": 1, "metalness": 0, "roughness": 0, "emissive": [0, 0, 0], "emissiveIntensity": 0, "doubleSided": true, "transmission": 1, "ior": 1.5 })));
+ w.set_material(72, json(serde_json::json!({ "name": "frame", "color": [0.05, 0.05, 0.05], "opacity": 1, "metalness": 0, "roughness": 1, "emissive": [0, 0, 0], "emissiveIntensity": 0, "doubleSided": true })));
+ w.set_material(73, json(serde_json::json!({ "name": "grille", "color": [0.5, 0.5, 0.5], "opacity": 0.9, "metalness": 0, "roughness": 1, "emissive": [0, 0, 0], "emissiveIntensity": 0, "doubleSided": true, "alphaTest": 0.5 })));
+ // A sky of one colour, and no lamp beside it, so that the sky is sampled as a light (the rays the wall's surface
+ // samples find it too); a cutout in a corner.
+ w.set_environment(crate::desc::Environment { sky: sky(serde_json::json!({ "type": "color", "color": [1.0, 1.0, 1.0], "intensity": 0.3, "skyLightIntensity": 1 })), ..w.environment.clone() });
+ w.set_material(5, json(serde_json::json!({ "name": "off", "color": [0.2, 0.2, 0.2], "opacity": 1, "metalness": 0, "roughness": 1, "emissive": [0, 0, 0], "emissiveIntensity": 0, "doubleSided": true })));
+ if cutout {
+ w.set_object(13, "grille".into(), None, Kind::Mesh { geometry: 3, material: 73, own_blas: false, materials: vec![] }, true, false).unwrap();
+ w.set_transform(13, Vec3::new(-0.8, -0.8, 0.9), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ }
+ let at = |w: &mut World, id: u32| w.set_transform(id, Vec3::new(0.0, 0.0, 0.4), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ match parts {
+ 0 => {
+ w.set_geometry(50, quads(&[pane, frame], vec![[0, 6, 0], [6, 6, 1]])).unwrap();
+ w.set_object(30, "window".into(), None, Kind::Mesh { geometry: 50, material: 71, own_blas: false, materials: vec![71, 72] }, true, false).unwrap();
+ at(&mut w, 30);
+ }
+ 1 => {
+ for (id, geometry, q, material) in [(30, 51, pane, 71), (31, 52, frame, 72)] {
+ w.set_geometry(geometry, quads(&[q], vec![])).unwrap();
+ w.set_object(id, format!("part{id}"), None, Kind::Mesh { geometry, material, own_blas: false, materials: vec![] }, true, false).unwrap();
+ at(&mut w, id);
+ }
+ }
+ _ => {}
+ }
+ w
+ };
+ for cutout in [true, false] {
+ let mut one = match open(&scene(0, cutout)) {
+ Ok(c) if c.g.hwrt => c,
+ Ok(_) => return eprintln!("skipped: no hardware RT"),
+ Err(e) => return eprintln!("skipped: {e}"),
+ };
+ let window = one.sc.instances.iter().find(|i| i.name == "window").expect("the window is an instance").clone();
+ assert_eq!((window.bits, window.cast_shadow, one.sc.meshes[window.mesh as usize].sect_count), (scene::INST_ROWS | scene::INST_GLASS, true, 2), "glass and a frame: one mesh, which casts");
+ let wanted = gpu::F_ROWS | gpu::F_IGLASS | if cutout { gpu::F_MASKED } else { 0 };
+ assert_eq!(one.sc.up.kernel.features & (wanted | gpu::F_MASKED), wanted);
+ assert_eq!(one.sc.base.counts2[1], 1, "the sky is sampled as a light");
+ let mut two = open(&scene(1, cutout)).unwrap();
+ assert!(!two.sc.instances.iter().find(|i| i.name == "part30").unwrap().cast_shadow, "the pane alone casts no shadow");
+ let (a, b) = (picture(&mut one, 96), picture(&mut two, 96));
+ assert!(apart(&a, &b) < 0.5, "a pane among its mesh's sections, with a cutout in the scene: {cutout}: the picture is {:.2} steps from the pane's as a mesh of its own", apart(&a, &b));
+ let c = picture(&mut open(&scene(2, cutout)).unwrap(), 96);
+ assert!(apart(&a, &c) > 0.5, "the window is in the picture ({:.2} steps from none)", apart(&a, &c));
+ }
+}
+
/// A scene whose only volume is hidden has its media passes made when it is loaded: the frame that shows the volume
/// compiles nothing (an idle fireball's first fire).
#[test]
diff --git a/renderer/src/live/load.rs b/renderer/src/live/load.rs
index 2a4a761..212157a 100644
--- a/renderer/src/live/load.rs
+++ b/renderer/src/live/load.rs
@@ -15,6 +15,10 @@ pub(super) struct LoadedScene {
pub(super) pool_tris: Vec<[glam::Vec3A; 3]>,
pub(super) meshes: Vec<scene::InstMesh>,
pub(super) instances: Vec<scene::Instance>,
+ /// The meshes' sections and the instances' rows as the GPU has them (`scene::Scene::sections`, `rows`); a record
+ /// an edit places has its row at `EditState::row_at`.
+ pub(super) sections: Vec<scene::Section>,
+ pub(super) rows: Vec<scene::Row>,
/// The instances' kernel records as uploaded (movable ones are rewritten when they move), then the procedural
/// objects' (from `proc_first`).
pub(super) gpu_instances: Vec<scene::GpuInstance>,
@@ -250,6 +254,7 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &P
let instanced = !sc.gpu_instances.is_empty() || !sc.procs.is_empty();
let instance_features = gpu::instance_features(&sc);
let (pool_tris, meshes, instances) = (std::mem::take(&mut sc.pool_tris), std::mem::take(&mut sc.meshes), std::mem::take(&mut sc.instances));
+ let (sections, rows) = (std::mem::take(&mut sc.sections), std::mem::take(&mut sc.rows));
let mut gpu_instances = std::mem::take(&mut sc.gpu_instances);
let proc_first = gpu_instances.len();
gpu_instances.extend_from_slice(&sc.proc_records);
@@ -288,8 +293,9 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &P
rebind: false,
uniform_said: false,
base: room_base,
+ row_base: rows.len(),
pool_first: prep.groups.iter().sum(),
blobs,
};
- Ok((LoadedScene { timings, triangles, tris, tri_nodes, tri_instances, pool_tris, meshes, instances, gpu_instances, procs, proc_first, moving_instances: tables.retained.moves_instances(), instanced, instance_features, name: sc.name.clone(), up, base, tables, fixed_features, dynamic, edit, emit, mat_runs, tri_order }, view, env))
+ Ok((LoadedScene { timings, triangles, tris, tri_nodes, tri_instances, pool_tris, meshes, instances, sections, rows, gpu_instances, procs, proc_first, moving_instances: tables.retained.moves_instances(), instanced, instance_features, name: sc.name.clone(), up, base, tables, fixed_features, dynamic, edit, emit, mat_runs, tri_order }, view, env))
}
diff --git a/renderer/src/main.rs b/renderer/src/main.rs
index d89642f..68636b2 100644
--- a/renderer/src/main.rs
+++ b/renderer/src/main.rs
@@ -552,7 +552,7 @@ fn render(g: &gpu::Gpu, job: &Job, presets: &Path, init_ms: f64, hosts: &mut Hos
"scene": sc.name,
"out": job.out,
"width": w, "height": h, "spp": spp,
- "triangles": sc.stats.get("triangles").map_or(sc.tris.len(), |t| *t as usize), "instances": sc.instances.len(),
+ "triangles": sc.stats.get("triangles").map_or(sc.tris.len(), |t| *t as usize), "instances": sc.instances.len(), "meshes": sc.meshes.len(), "pool_triangles": sc.pool_tris.len(),
"instanced_triangles": sc.stats.get("instanced_triangles").copied().unwrap_or(0.0) as u64, "flat_triangles": sc.tris.len(), "bvh_nodes": prep.nodes.len(), "emitters": prep.emitter_tris.len(), "lights": sc.lights.len(), "textures": sc.textures.len(),
"adapter": g.adapter_info.name, "backend": format!("{:?}", g.adapter_info.backend), "hwrt": g.hwrt,
"ev100": ev100, "denoise": denoiser, "preset": preset.name,
diff --git a/renderer/src/scene.rs b/renderer/src/scene.rs
index a93117a..26c59b1 100644
--- a/renderer/src/scene.rs
+++ b/renderer/src/scene.rs
@@ -51,8 +51,8 @@ pub fn copy_row(mut row: ObjectRow, dark: bool) -> ObjectRow {
row
}
-/// A glTF mesh placed by several static instances (hardware RT): its triangles once, in model space, in the `pool_*`
-/// arrays; one BLAS, one TLAS instance per placement.
+/// A mesh its instances place: its triangles once, in model space, in the `pool_*` arrays; one BLAS, one TLAS
+/// instance per placement. A geometry's (`section_mesh`: its materials are its instances'), or a model's.
#[derive(Clone, Copy, Debug)]
pub struct InstMesh {
pub first: u32,
@@ -71,9 +71,91 @@ pub struct InstMesh {
pub hi: Vec3A,
/// Its triangles change (a shared pose, `PoseGroup`): its BLAS is rebuilt with them.
pub deforms: bool,
- /// How many emitters an instance of it has in the light list: its triangles of an emitting material, numbered in
- /// their attributes as they lie in the triangles' table (x.w - 1; `number_emitters`). 0: it does not emit.
+ /// A model's mesh: how many emitters an instance of it has in the light list, its triangles of an emitting
+ /// material, numbered in their attributes as they lie in the triangles' table (x.w - 1; `number_emitters`). 0: it
+ /// does not emit. (A mesh with sections: `rows_emitters`, an instance's.)
pub emitters: u32,
+ /// Its sections (`Section`), in `Scene::sections`: a mesh of a geometry alone, whose materials are its instances'
+ /// (`Instance::rows`). None (`sect_count` 0): a model's mesh, its materials on its triangles and its triangles
+ /// by class (`opaque`, `glass`, `emitters`; a mesh with sections says all opaque there, and no emitters).
+ pub sect_first: u32,
+ pub sect_count: u32,
+ /// Its triangles carry its geometry's vertex colours (a material says whether it reads them).
+ pub colored: bool,
+}
+
+/// 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)]
+pub struct Section {
+ /// Its first triangle in the mesh, and how many.
+ pub first: u32,
+ pub count: u32,
+ /// Which of the object's materials (a group's material index; past the last, the last).
+ pub slot: u32,
+}
+
+/// An instance's row for a section of its mesh, as the kernel reads it (the words' heap, heap.rs `Stream::Rows`):
+/// the material with the class bits `ROW_*`, the section's first triangle in the triangles' table, its first emitter in
+/// the light list (`NO_EMITTER`: it does not emit), and a word to spare.
+pub type Row = [u32; 4];
+pub const ROW_MATERIAL: u32 = 0xff_ffff;
+/// The material is alpha-tested; it is glass (shadow rays pass).
+pub const ROW_CUTOUT: u32 = 1 << 24;
+pub const ROW_GLASS: u32 = 1 << 25;
+pub const NO_EMITTER: u32 = u32::MAX;
+
+/// The row of a section drawn with material `mat`; where its triangles and its emitters are is set where the tables
+/// are laid out (lib.rs `prepare`, the live edits).
+pub fn row_of(mat: u32, materials: &[GpuMaterial]) -> Row {
+ let class = materials.get(mat as usize).map_or(0, |m| [0, ROW_CUTOUT, ROW_GLASS][mesh_class(m) as usize]);
+ [mat | class, 0, NO_EMITTER, 0]
+}
+
+/// The material a row names.
+pub fn row_material(r: &Row) -> u32 {
+ r[0] & ROW_MATERIAL
+}
+
+/// Whether an instance with these rows casts shadows: as its object says, and never when every section is glass
+/// (such an instance is out of a shadow ray's way by its mask; glass among other sections is passed at the hit).
+pub fn rows_cast(rows: &[Row], cast_shadow: bool) -> bool {
+ cast_shadow && !rows.iter().all(|r| r[0] & ROW_GLASS != 0)
+}
+
+/// The bits of an instance's record for its rows (`INST_ROWS`, and which classes are among them).
+pub fn rows_bits(rows: &[Row]) -> u32 {
+ let any = |bit: u32| rows.iter().any(|r| r[0] & bit != 0);
+ INST_ROWS | if any(ROW_CUTOUT) { INST_CUTOUT } else { 0 } | if any(ROW_GLASS) { INST_GLASS } else { 0 }
+}
+
+/// How many emitters an instance with these rows has in the light list: every triangle of its sections whose
+/// material emits, a section after another, a section's in its triangles' order (`section_emitters`).
+pub fn rows_emitters(sections: &[Section], rows: &[Row], materials: &[GpuMaterial]) -> u32 {
+ sections.iter().zip(rows).filter(|(_, r)| materials.get(row_material(r) as usize).is_some_and(emissive)).map(|(s, _)| s.count).sum()
+}
+
+/// A triangle's place among its instance's emitters and its material, from its attributes (its section and its
+/// index in it), the instance's rows and where each section's emitters start (`section_emitters`). None: its
+/// section's material does not emit.
+pub fn section_slot(a: &GpuTriAttr, rows: &[Row], starts: &[Option<u32>]) -> Option<(usize, u32)> {
+ let s = a.uv[3].to_bits() as usize;
+ Some(((starts.get(s).copied()?? + a.x[3].to_bits()) as usize, row_material(rows.get(s)?)))
+}
+
+/// Where each section's emitters start among its instance's (None: its material does not emit).
+pub fn section_emitters(sections: &[Section], rows: &[Row], materials: &[GpuMaterial]) -> Vec<Option<u32>> {
+ let mut at = 0;
+ sections
+ .iter()
+ .zip(rows)
+ .map(|(s, r)| {
+ materials.get(row_material(r) as usize).is_some_and(emissive).then(|| {
+ at += s.count;
+ at - s.count
+ })
+ })
+ .collect()
}
/// Pool triangles of the deforming meshes, which the build puts first in the pool.
@@ -83,9 +165,13 @@ pub fn deforming_pool(meshes: &[InstMesh]) -> usize {
impl InstMesh {
/// Its BLAS geometries, those with triangles: each one's first triangle in the mesh, how many, and whether it is
- /// flagged opaque (all but the glass: a query that forces opacity sees every one alike, a shadow ray culls the
- /// glass).
- pub fn parts(&self) -> Vec<(u32, u32, bool)> {
+ /// flagged opaque. A mesh with sections (`sections`: the scene's): one a section, all flagged opaque, whatever
+ /// an instance's materials are. A model's mesh: one a class, all flagged opaque but the glass (a query that forces
+ /// opacity sees every one alike, a shadow ray culls the glass).
+ pub fn parts(&self, sections: &[Section]) -> Vec<(u32, u32, bool)> {
+ if self.sect_count > 0 {
+ return self.sections(sections).iter().map(|s| (s.first, s.count, true)).collect();
+ }
let cutout = self.count - self.opaque - self.glass;
[(0, self.opaque, true), (self.opaque, cutout, true), (self.opaque + cutout, self.glass, false)].into_iter().filter(|p| p.1 > 0).collect()
}
@@ -93,10 +179,15 @@ impl InstMesh {
/// Where its second and its third geometry start in the mesh (0: there is none): the record has them, for a hit's
/// triangle from its geometry and primitive (trace_hw.wgsl `hit_tri`).
pub fn part_offsets(&self) -> [u32; 2] {
- let p = self.parts();
+ let p = self.parts(&[]);
[p.get(1).map_or(0, |p| p.0), p.get(2).map_or(0, |p| p.0)]
}
+ /// Its sections among the scene's (none: a model's mesh).
+ pub fn sections<'a>(&self, sections: &'a [Section]) -> &'a [Section] {
+ &sections[self.sect_first as usize..(self.sect_first + self.sect_count) as usize]
+ }
+
/// Whether an instance of it casts shadows: as its object says, and never when the mesh is all glass. Such an
/// instance is out of a shadow ray's way by its mask, as one that casts none is; a mesh with glass among other
/// triangles has it culled by its geometry's flag (`parts`, gpu.rs `F_IGLASS`).
@@ -135,13 +226,19 @@ pub struct Instance {
/// keep its mesh and its place above the triangles: it comes back in place. (One that an edit took out is hidden
/// and not this: a rebuild draws it again.)
pub masked: bool,
- /// Its first emitter in the light list, if its mesh has emitters (`InstMesh::emitters`): set where the list is
- /// made (lib.rs `prepare`, the live edits); the record carries it (n2.w), for the rays that hit an emitter of it.
+ /// Its first emitter in the light list, if it has emitters (`InstMesh::emitters`; with sections,
+ /// `rows_emitters`): set where the list is made (lib.rs `prepare`, the live edits); the record carries it (n2.w),
+ /// for the rays that hit an emitter of a model's mesh, and a section's row has where the section's start.
pub first_emitter: u32,
+ /// Its rows in `Scene::rows`, one a section of its mesh (`InstMesh::sect_count`), and the record's bits for them
+ /// (`rows_bits`; 0: a model's instance, without rows).
+ pub rows: u32,
+ pub bits: u32,
}
/// Kernel record of an instance (`instances` binding): world matrix rows, normal matrix rows (inverse transpose),
-/// (first triangle in the GPU order, object index, texture-LOD offset bits, first cutout triangle - first), and the
+/// (first triangle in the GPU order, object index, texture-LOD offset bits, its rows' first or, without rows, first
+/// cutout triangle - first), and the
/// world matrix rows of the previous frame (a movable instance's motion vectors; the same rows when it did not move).
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, bytemuck::Pod, bytemuck::Zeroable)]
@@ -161,9 +258,23 @@ impl Instance {
let nm = glam::Mat3::from_mat4(w).inverse().transpose();
let row = |r: usize| [w.x_axis[r], w.y_axis[r], w.z_axis[r], w.w_axis[r]];
let nrow = |r: usize, w: f32| [nm.x_axis[r], nm.y_axis[r], nm.z_axis[r], w];
- let mirrored = f32::from_bits(if mirrors(w) { INST_MIRRORED } else { 0 });
+ let mirrored = f32::from_bits(self.bits | if mirrors(w) { INST_MIRRORED } else { 0 });
GpuInstance { m: [row(0), row(1), row(2)], n: [nrow(0, f32::from_bits(parts[1])), nrow(1, mirrored), nrow(2, f32::from_bits(self.first_emitter))], info: [first, self.object, lod_offset(w).to_bits(), parts[0]], p: [row(0), row(1), row(2)] }
}
+ /// What `gpu` takes as `parts` for an instance of `m`: its rows' first with sections, else the mesh's part
+ /// offsets.
+ pub fn parts(&self, m: &InstMesh) -> [u32; 2] {
+ if m.sect_count > 0 { [self.rows, 0] } else { m.part_offsets() }
+ }
+ /// A triangle's attributes as a flattened triangle has them: with sections, the material its row names in place
+ /// of the section, and no index in it (`rows`: the instance's).
+ pub fn resolved(&self, a: &GpuTriAttr, rows: &[Row]) -> GpuTriAttr {
+ if self.bits & INST_ROWS == 0 {
+ return *a;
+ }
+ let mat = rows.get(a.uv[3].to_bits() as usize).map_or(0, row_material);
+ GpuTriAttr { uv: [a.uv[0], a.uv[1], a.uv[2], f32::from_bits(mat)], x: [a.x[0], a.x[1], a.x[2], 0.0], ..*a }
+ }
/// Model-space triangle `t` of its mesh in world space (the same transform the flattening path applies).
pub fn tri(&self, t: &[Vec3A; 3]) -> [Vec3A; 3] {
t.map(|v| self.world.transform_point3a(v))
@@ -196,6 +307,13 @@ pub fn placed_tri(w: Mat4, p: &[Vec3; 3], n: &[Vec3; 3], uv: &[Vec2; 3], tangent
/// Bit of an instance record's n1.w, beside the units' flags there (units.rs `UNIT_*`): the instance mirrors its mesh
/// (the kernel's `inst_sign`).
pub const INST_MIRRORED: u32 = 4;
+/// More bits there: the instance has rows (its record's info.w is their first; `Instance::rows`), and a row of it is
+/// a cutout's, a glass's (what a walk of a unit asks before it reads a triangle's row).
+pub const INST_ROWS: u32 = 8;
+pub const INST_CUTOUT: u32 = 16;
+pub const INST_GLASS: u32 = 32;
+/// Every bit of n1.w that is the instance's own, not a unit's.
+pub const INST_BITS: u32 = INST_MIRRORED | INST_ROWS | INST_CUTOUT | INST_GLASS;
/// Whether a placement mirrors what it places (a negative determinant).
pub fn mirrors(w: Mat4) -> bool {
@@ -457,7 +575,7 @@ pub struct GpuMaterial {
pub params: [f32; 4], // metallic, roughness, specular, normal scale
pub tex0: [i32; 4], // base, normal, roughness(G), metalness(B)
pub tex1: [i32; 4], // emissive, occlusion(R), flags, material function + 1 (0 = none)
- pub uv: [f32; 4], // uv repeat xy, transmission texture (R) + 1 (0 = none; glTF), -
+ pub uv: [f32; 4], // uv repeat xy, transmission texture (R) + 1 (0 = none; glTF), 1 = it reads vertex colours
pub uv2: [f32; 4], // uv offset xy, -, alpha cutoff (0 = opaque)
pub layer: [f32; 4], // transmission (glass), index of refraction, clearcoat, clearcoat roughness
pub mp: [[f32; 4]; 8], // material function parameters
@@ -596,6 +714,10 @@ pub struct Scene {
pub pool_attrs: Vec<GpuTriAttr>,
pub meshes: Vec<InstMesh>,
pub instances: Vec<Instance>,
+ /// The meshes' sections (`InstMesh::sect_first`) and the instances' rows (`Instance::rows`): as the kernel reads
+ /// the rows once `prepare` has set where each section's triangles and emitters are.
+ pub sections: Vec<Section>,
+ pub rows: Vec<Row>,
/// Kernel records of `instances` (`prepare`, hardware RT).
pub gpu_instances: Vec<GpuInstance>,
/// Where engine handles landed in the GPU tables, for edits without a rebuild (`LiveCore::commit`).
@@ -663,9 +785,10 @@ pub struct Retained {
pub sun: Option<u32>,
/// Posed models sharing a pose (`PoseGroup`: its members' proxies name it, `MeshKind::Pose`).
pub pose_groups: Vec<PoseGroup>,
- /// Meshes: (geometry, GPU materials: one, or a group's each) -> the shared mesh (objects with the same geometry and
- /// materials share its BLAS). live/edits.rs `edit_geometry` keeps it.
- pub own_mesh: HashMap<(u32, Vec<u32>), u32>,
+ /// Meshes and instanced objects: (geometry, whether by its groups: `by_groups`) -> the shared mesh (objects of the
+ /// same geometry share its BLAS, whatever their materials: those are their instances' rows). live/edits.rs
+ /// `edit_geometry` keeps it.
+ pub own_mesh: HashMap<(u32, bool), u32>,
/// 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,
@@ -722,7 +845,7 @@ pub enum MeshKind {
Model,
/// A shared pose's (`Retained::pose_groups`): the group's mesh is re-skinned, its members move as instances.
Pose(u32),
- /// An `own_blas` mesh, shared by the objects of its geometry and material (`Retained::own_mesh`).
+ /// A geometry's mesh, shared by the objects of the geometry (`Retained::own_mesh`).
Own,
}
@@ -1065,7 +1188,7 @@ pub fn build_material(id: u32, m: &desc::Material, textures: &HashMap<u32, world
params: [m.metalness, m.roughness, 0.5 * m.specular_intensity.unwrap_or(1.0), m.normal_scale.map(|s| s[0]).unwrap_or(1.0)],
tex0: [slot(&m.map, true)?, slot(&m.normal_map, false)?, slot(&m.roughness_map, false)?, slot(&m.metalness_map, false)?],
tex1: [slot(&m.emissive_map, true)?, slot(&m.ao_map, false)?, if m.unlit { MAT_UNLIT } else if m.double_sided { MAT_DOUBLE_SIDED } else { 0 }, 0],
- uv: [repeat[0], repeat[1], slot(&m.transmission_map, false)? as f32 + 1.0, 0.0],
+ uv: [repeat[0], repeat[1], slot(&m.transmission_map, false)? as f32 + 1.0, if m.vertex_colors { 1.0 } else { 0.0 }],
uv2: [offset[0], offset[1], 0.0, m.alpha_test.unwrap_or(0.0)],
layer: [m.transmission.unwrap_or(0.0).clamp(0.0, 1.0), m.ior.unwrap_or(1.5).max(1.0), m.clearcoat.unwrap_or(0.0).clamp(0.0, 1.0), m.clearcoat_roughness.unwrap_or(0.0).clamp(0.0, 1.0)],
mp: [[0.0; 4]; 8],
@@ -1375,6 +1498,20 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
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![]);
+ // The geometries whose meshes carry vertex colours: one with colours that some object draws with a material that
+ // reads them (the mesh is every object's of that geometry, so it is settled before the first is placed).
+ let colored_meshes: std::collections::HashSet<(u32, bool)> = w
+ .objects
+ .values()
+ .filter_map(|o| match &o.kind {
+ Kind::Mesh { geometry, material, materials, .. } => Some((geometry, materials.iter().chain(std::iter::once(material)).collect::<Vec<_>>(), by_groups(w.geometries.get(geometry)?, materials.len()))),
+ Kind::Instanced { geometry, materials, procedural: false, .. } => Some((geometry, materials.iter().take(1).collect(), false)),
+ _ => None,
+ })
+ .filter(|(g, mats, _)| w.geometries.get(g).is_some_and(|g| !g.colors.is_empty()) && mats.iter().any(|k| w.materials.get(k).is_some_and(|m| m.vertex_colors)))
+ .map(|(g, _, grouped)| (*g, grouped))
+ .collect();
let mut mesh_of: HashMap<(String, Option<Vec<String>>), Option<u32>> = HashMap::new();
// Posed skinned models that share a pose with another share its mesh (`PoseGroup`). THREERT_POSE_SHARE=0 skins
// each model alone (A/B).
@@ -1400,8 +1537,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
pose_key_of.retain(|_, k| count[k] >= 2);
}
let mut pose_group_of: HashMap<PoseKey, Option<u32>> = HashMap::new();
- // Instanced objects' shared meshes by (geometry, GPU material); their flattened instances' triangle ranges.
- let mut inst_mesh_of: HashMap<(u32, u32), u32> = HashMap::new();
+ // Flattened instances' triangle ranges.
let mut tri_instances: Vec<(u32, u32, u32)> = vec![];
// 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 { .. })));
@@ -1415,34 +1551,27 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
match &n.kind {
Kind::Mesh { geometry, material, own_blas, materials: mesh_mats } if instancing => {
// A mesh is an instance of its geometry's mesh: the triangles in model space in the pool, one BLAS,
- // shared by the objects of the same geometry and materials, whatever those are (`mesh_class`: a
- // cutout or glass is a part of the mesh; one that emits has each instance's emitters in the light
- // list, `InstMesh::emitters`). A move is the instance's transform (`InstanceRef::moves`). One that is
- // hidden (`World::shown`), or placed without size (`placed_world`), is an instance too, which no ray
- // sees and whose row has no power: it comes back in place (`Instance::masked`).
+ // shared by the objects of the geometry whatever their materials, which are the instance's rows
+ // (`section_mesh`, `Row`: a cutout, glass, one that emits). A move is the instance's transform
+ // (`InstanceRef::moves`). One that is hidden (`World::shown`), or placed without size
+ // (`placed_world`), is an instance too, which no ray sees and whose object entry has no power: it
+ // comes back in place (`Instance::masked`).
let g = w.geometries.get(geometry).ok_or_else(|| anyhow!("object {}: unknown geometry {geometry}", n.name))?;
let mat = *retained.materials.get(material).ok_or_else(|| anyhow!("object {}: unknown material {material}", n.name))?;
// Several materials: each geometry group's triangles with its own (three.js's material array).
let gpu_mats = mesh_mats.iter().map(|k| retained.materials.get(k).copied().ok_or_else(|| anyhow!("object {}: unknown material {k}", n.name))).collect::<Result<Vec<u32>>>()?;
- let per_tri = group_materials(g, &gpu_mats);
- let key = (*geometry, if per_tri.is_some() { gpu_mats } else { vec![mat] });
+ let grouped = by_groups(g, gpu_mats.len());
+ let key = (*geometry, grouped);
let mesh = match retained.own_mesh.get(&key) {
Some(&k) => Some(k),
None => {
- let (t, a, order, im) = own_mesh(g, mat, per_tri.as_deref(), &materials, pool_tris.len() as u32);
- (!t.is_empty()).then(|| {
- // Coloured where the triangle's own material asks (each group's; without groups, the mesh's).
- let wants = |k: &u32| w.materials.get(k).is_some_and(|m| m.vertex_colors);
- let vc_tri = group_materials(g, &mesh_mats.iter().map(|k| u32::from(wants(k))).collect::<Vec<_>>());
- let vc = !g.colors.is_empty() && match &vc_tri { Some(v) => v.iter().any(|f| *f == Some(1)), None => wants(material) };
- let colors = vc.then(|| {
- let c = tri_colors(g, false, vc_tri.as_deref());
- order.iter().map(|&k| c[k]).collect()
- });
- meshes.push(im);
- put_colors(&mut pool_vcolors, pool_tris.len(), colors);
- pool_tris.extend(t);
- pool_attrs.extend(a);
+ let d = section_mesh(g, grouped, pool_tris.len() as u32, sections.len() as u32, colored_meshes.contains(&key));
+ (!d.tris.is_empty()).then(|| {
+ meshes.push(d.mesh);
+ sections.extend(d.sections);
+ put_colors(&mut pool_vcolors, pool_tris.len(), d.colors);
+ pool_tris.extend(d.tris);
+ pool_attrs.extend(d.attrs);
let k = meshes.len() as u32 - 1;
retained.own_mesh.insert(key, k);
k
@@ -1459,14 +1588,16 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
objects.extend_from_slice(&object_row(pivot, if unseen { 0.0 } else { n.power }, size, n.custom, [1.0; 3])[..stride]);
retained.edits_meshes |= *own_blas || n.driven;
*retained.proxy(*id) = Proxy { object: Some(oi), card: None, draw: Draw::Instance(InstanceRef { instance: instances.len() as u32, mesh: MeshKind::Own, moves: n.driven || w.movable(*id) }) };
- instances.push(Instance { mesh, world: m, object: oi, cast_shadow: meshes[mesh as usize].casts(n.cast_shadow), name: n.name.clone(), sub: None, hidden: unseen, masked: unseen, first_emitter: 0 });
+ let mine = section_rows(meshes[mesh as usize].sections(&sections), if grouped { &gpu_mats } else { std::slice::from_ref(&mat) }, &materials);
+ instances.push(Instance { mesh, world: m, object: oi, cast_shadow: rows_cast(&mine, n.cast_shadow), name: n.name.clone(), sub: None, hidden: unseen, masked: unseen, first_emitter: 0, rows: rows.len() as u32, bits: rows_bits(&mine) });
+ rows.extend(mine);
}
}
Kind::Instanced { geometry, procedural, materials: mats, capacity } if shown => {
// Copies of one geometry: one shared mesh (one BLAS), an instance and an object entry per copy, the
// copies' records and entries contiguous (live/edits.rs `update_instanced` rewrites them in place).
- // A material that only emits is such a mesh too: each copy has its emitters in the light list
- // (`InstMesh::emitters`), a hidden copy's at no weight (its object has no power). A copy may mirror
+ // With a material that emits each copy has its emitters in the light list (`rows_emitters`), a
+ // hidden copy's at no weight (its object has no power). A copy may mirror
// the mesh (`INST_MIRRORED`). Without instancing each copy is its own triangles, and changing the
// instances rebuilds.
let empty = world::InstanceTable::default();
@@ -1488,25 +1619,23 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
let g = w.geometries.get(geometry).ok_or_else(|| anyhow!("object {}: unknown geometry {geometry}", n.name))?;
let material = mats.first().ok_or_else(|| anyhow!("object {}: an instanced mesh needs a material", n.name))?;
let mat = *retained.materials.get(material).ok_or_else(|| anyhow!("object {}: unknown material {material}", n.name))?;
- let class = mesh_class(&materials[mat as usize]);
let emits = emissive(&materials[mat as usize]);
let vc = colored(g, &mut std::iter::once(material));
if instancing {
- let mesh = match inst_mesh_of.get(&(*geometry, mat)) {
+ // (The geometry whole, with the object's first material: the mesh an object of one material has.)
+ let key = (*geometry, false);
+ let mesh = match retained.own_mesh.get(&key) {
Some(&k) => Some(k),
None => {
- let (tr, a) = own_mesh_tris(g, mat);
- (!tr.is_empty()).then(|| {
- let mut im = own_inst_mesh(&tr, pool_tris.len() as u32, class);
- if emits {
- im.emitters = tr.len() as u32;
- }
- meshes.push(im);
- put_colors(&mut pool_vcolors, pool_tris.len(), vc.then(|| tri_colors(g, false, None)));
- pool_tris.extend(tr);
- pool_attrs.extend(a);
+ let d = section_mesh(g, false, pool_tris.len() as u32, sections.len() as u32, colored_meshes.contains(&key));
+ (!d.tris.is_empty()).then(|| {
+ meshes.push(d.mesh);
+ sections.extend(d.sections);
+ put_colors(&mut pool_vcolors, pool_tris.len(), d.colors);
+ pool_tris.extend(d.tris);
+ pool_attrs.extend(d.attrs);
let k = meshes.len() as u32 - 1;
- inst_mesh_of.insert((*geometry, mat), k);
+ retained.own_mesh.insert(key, k);
k
})
}
@@ -1514,10 +1643,12 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
if let Some(mesh) = mesh {
let object = (objects.len() / stride) as u32;
retained.proxy(*id).draw = Draw::Instanced(InstancedPlace { first: instances.len() as u32, capacity: *capacity, object, mesh: Some(mesh), drawn: t.count });
+ let mine = section_rows(meshes[mesh as usize].sections(&sections), std::slice::from_ref(&mat), &materials);
for (i, &(wm, hidden)) in placed.iter().enumerate() {
let (lo, hi) = meshes[mesh as usize].placed_bounds(wm);
objects.extend_from_slice(&copy_row(entry(i, wm, Vec3::from(hi - lo)), emits && hidden)[..stride]);
- instances.push(Instance { mesh, world: wm, object: object + i as u32, cast_shadow: meshes[mesh as usize].casts(n.cast_shadow), name: n.name.clone(), sub: Some(i as u32), hidden, masked: false, first_emitter: 0 });
+ instances.push(Instance { mesh, world: wm, object: object + i as u32, cast_shadow: rows_cast(&mine, n.cast_shadow), name: n.name.clone(), sub: Some(i as u32), hidden, masked: false, first_emitter: 0, rows: rows.len() as u32, bits: rows_bits(&mine) });
+ rows.extend(mine.iter().copied());
}
}
continue;
@@ -1669,9 +1800,9 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
ohi = ohi.max(q);
}
let count = classed[..FLAT].iter().map(Vec::len).sum::<usize>() as u32;
- meshes.push(InstMesh { first: first_pool, count, opaque: classed[0].len() as u32, glass: classed[2].len() as u32, rest_first: 0, rest_count: 0, lo, hi, deforms: false, emitters });
+ meshes.push(InstMesh { first: first_pool, count, opaque: classed[0].len() as u32, glass: classed[2].len() as u32, rest_first: 0, rest_count: 0, lo, hi, deforms: false, emitters, sect_first: 0, sect_count: 0, colored: false });
rigid.instances.push((*ni, instances.len() as u32));
- instances.push(Instance { mesh: meshes.len() as u32 - 1, world: w_n, object: oi, cast_shadow: meshes[meshes.len() - 1].casts(n.cast_shadow), name: n.name.clone(), sub: None, hidden: false, masked: false, first_emitter: 0 });
+ instances.push(Instance { mesh: meshes.len() as u32 - 1, world: w_n, object: oi, cast_shadow: meshes[meshes.len() - 1].casts(n.cast_shadow), name: n.name.clone(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: 0 });
}
for &(k, mat) in &classed[FLAT] {
let t = &local[k].1;
@@ -1737,7 +1868,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
}
// Other poses reach further (a stride, a swing): object bounds a quarter wider each way.
let pad = (hi - lo) * 0.25;
- meshes.push(InstMesh { first, count: tri_order.len() as u32, opaque: classed[0].len() as u32, glass: classed[2].len() as u32, rest_first: 0, rest_count: 0, lo: lo - pad, hi: hi + pad, deforms: true, emitters: 0 });
+ meshes.push(InstMesh { first, count: tri_order.len() as u32, opaque: classed[0].len() as u32, glass: classed[2].len() as u32, rest_first: 0, rest_count: 0, lo: lo - pad, hi: hi + pad, deforms: true, emitters: 0, sect_first: 0, sect_count: 0, colored: false });
retained.pose_groups.push(PoseGroup { mesh: meshes.len() as u32 - 1, uri: uri.clone(), nodes: nodes.clone(), animation: a.clone(), order: tri_order, members: vec![] });
retained.pose_groups.len() as u32 - 1
});
@@ -1753,7 +1884,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
let oi = (objects.len() / stride) as u32;
objects.extend_from_slice(&object_row(pivot, n.power, size, n.custom, [1.0; 3])[..stride]);
let i = instances.len() as u32;
- instances.push(Instance { mesh, world: m, object: oi, cast_shadow: meshes[mesh as usize].casts(n.cast_shadow), name: n.name.clone(), sub: None, hidden: false, masked: false, first_emitter: 0 });
+ instances.push(Instance { mesh, world: m, object: oi, cast_shadow: meshes[mesh as usize].casts(n.cast_shadow), name: n.name.clone(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: 0 });
*retained.proxy(*id) = Proxy { object: Some(oi), card: None, draw: Draw::Instance(InstanceRef { instance: i, mesh: MeshKind::Pose(g), moves: true }) };
retained.pose_groups[g as usize].members.push((*id, i));
continue;
@@ -1797,7 +1928,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
}
let count = classed[..FLAT].iter().map(Vec::len).sum::<usize>() as u32;
let emitters = pool_emitters(&classed, &emitting);
- meshes.push(InstMesh { first, count, opaque: classed[0].len() as u32, glass: classed[2].len() as u32, rest_first, rest_count: classed[FLAT].len() as u32, lo, hi, deforms: false, emitters });
+ meshes.push(InstMesh { first, count, opaque: classed[0].len() as u32, glass: classed[2].len() as u32, rest_first, rest_count: classed[FLAT].len() as u32, lo, hi, deforms: false, emitters, sect_first: 0, sect_count: 0, colored: false });
meshes.len() as u32 - 1
});
if std::env::var("THREERT_INSTANCING").is_ok_and(|v| v == "log") {
@@ -1821,7 +1952,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
let oi = (objects.len() / stride) as u32;
objects.extend_from_slice(&object_row(pivot, n.power, size, n.custom, [1.0; 3])[..stride]);
retained.proxy(*id).object = Some(oi);
- let inst = Instance { mesh, world: m, object: oi, cast_shadow: meshes[mesh as usize].casts(n.cast_shadow), name: n.name.clone(), sub: None, hidden: false, masked: false, first_emitter: 0 };
+ let inst = Instance { mesh, world: m, object: oi, cast_shadow: meshes[mesh as usize].casts(n.cast_shadow), name: n.name.clone(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: 0 };
// 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);
@@ -2115,6 +2246,8 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
pool_attrs,
meshes,
instances,
+ sections,
+ rows,
gpu_instances: vec![],
})
}
@@ -2319,32 +2452,90 @@ pub fn put_colors(dst: &mut Vec<[u32; 3]>, at: usize, c: Option<Vec<[u32; 3]>>)
dst.extend(c);
}
-/// An `own_blas` mesh's triangles in model space and their attributes, as the pool holds them. The build and the live
-/// view's in-place edits (live/edits.rs `edit_geometry`) both make them here, so either path gives the same data.
-pub fn own_mesh_tris(g: &world::Geometry, mat: u32) -> (Vec<[Vec3A; 3]>, Vec<GpuTriAttr>) {
- let (mut tris, mut flags, mut attrs) = (vec![], vec![], vec![]);
- append_arrays(g, Mat4::IDENTITY, mat, 0, None, &mut tris, &mut flags, &mut attrs);
- (tris, attrs)
+/// Whether an object with `materials` materials draws `g` by its groups (three.js's material array: each group with
+/// its own, a triangle in no group not drawn) and not whole, with one material.
+pub fn by_groups(g: &world::Geometry, materials: usize) -> bool {
+ materials > 1 && !g.groups.is_empty()
}
-/// A mesh's triangles in model space as the pool holds them, ordered by class (`mesh_class`: a geometry of the mesh's
-/// BLAS each), their attributes, where each came from among the geometry's drawn triangles, and the mesh at pool index
-/// `first`. One material, or each group's (`per_tri`: `group_materials`).
-pub fn own_mesh(g: &world::Geometry, mat: u32, per_tri: Option<&[Option<u32>]>, materials: &[GpuMaterial], first: u32) -> (Vec<[Vec3A; 3]>, Vec<GpuTriAttr>, Vec<usize>, InstMesh) {
+/// What `section_mesh` makes: a mesh's triangles in model space and their attributes as the pool holds them, their
+/// vertex colours if it carries them, the mesh and its sections.
+pub struct MeshData {
+ pub tris: Vec<[Vec3A; 3]>,
+ pub attrs: Vec<GpuTriAttr>,
+ pub colors: Option<Vec<[u32; 3]>>,
+ pub mesh: InstMesh,
+ pub sections: Vec<Section>,
+}
+
+/// The mesh of a geometry at pool index `first`, its sections from `sect_first` on: a section after another, each
+/// the triangles of a group in the geometry's order (`grouped`: `by_groups`; a triangle is its last group's, and
+/// one in no group is not drawn), or the whole geometry as one. A triangle's attributes hold its section (uv.w) and
+/// its index in it (x.w, `rank_in_sections`): nothing of a material, so every object of the geometry shares the mesh.
+/// The build and the live view's in-place edits both make it here.
+pub fn section_mesh(g: &world::Geometry, grouped: bool, first: u32, sect_first: u32, colored: bool) -> MeshData {
+ let mut group: Vec<Option<u32>> = vec![if grouped { None } else { Some(0) }; g.indices.len() / 3];
+ if grouped {
+ for (k, &[start, count, _]) in g.groups.iter().enumerate() {
+ for t in (start / 3) as usize..((start + count) / 3) as usize {
+ if let Some(slot) = group.get_mut(t) {
+ *slot = Some(k as u32);
+ }
+ }
+ }
+ }
let (mut t, mut flags, mut a) = (vec![], vec![], vec![]);
- append_arrays(g, Mat4::IDENTITY, mat, 0, per_tri, &mut t, &mut flags, &mut a);
- let material = |k: usize| &materials[a[k].uv[3].to_bits() as usize];
+ append_arrays(g, Mat4::IDENTITY, 0, 0, Some(&group), &mut t, &mut flags, &mut a);
+ // (`append_arrays` left each triangle's group where its material goes.)
+ let group_of = |k: usize| a[k].uv[3].to_bits();
let mut order: Vec<usize> = (0..t.len()).collect();
- order.sort_by_key(|&k| mesh_class(material(k)));
- let of = |class: u32| order.iter().filter(|&&k| mesh_class(material(k)) == class).count() as u32;
- let mut im = own_inst_mesh(&t, first, 0);
- (im.opaque, im.glass) = (of(0), of(2));
- im.emitters = order.iter().filter(|&&k| emissive(material(k))).count() as u32;
- (order.iter().map(|&k| t[k]).collect(), order.iter().map(|&k| a[k]).collect(), order, im)
+ order.sort_by_key(|&k| group_of(k));
+ let (mut sections, mut attrs): (Vec<Section>, Vec<GpuTriAttr>) = (vec![], Vec::with_capacity(order.len()));
+ let mut last = None;
+ for &k in &order {
+ if last != Some(group_of(k)) {
+ last = Some(group_of(k));
+ sections.push(Section { first: attrs.len() as u32, count: 0, slot: if grouped { g.groups[group_of(k) as usize][2] } else { 0 } });
+ }
+ let (at, s) = (sections.len() as u32 - 1, sections.last_mut().unwrap());
+ let mut b = a[k];
+ (b.uv[3], b.x[3]) = (f32::from_bits(at), f32::from_bits(s.count));
+ s.count += 1;
+ attrs.push(b);
+ }
+ let tris: Vec<[Vec3A; 3]> = order.iter().map(|&k| t[k]).collect();
+ let colored = colored && !g.colors.is_empty();
+ let colors = colored.then(|| {
+ let c = tri_colors(g, false, Some(&group.iter().map(|x| x.map(|_| 1)).collect::<Vec<_>>()));
+ order.iter().map(|&k| c[k]).collect()
+ });
+ let mesh = InstMesh { sect_first, sect_count: sections.len() as u32, colored, ..own_inst_mesh(&tris, first, 0) };
+ MeshData { tris, attrs, colors, mesh, sections }
+}
+
+/// Each triangle's index in its section (x.w) as the triangles lie in `attrs`: its rank among those of its section
+/// (uv.w). What a mesh's triangles get again when they are put in another order (a unit's tree's): an emitter's
+/// place in its section's run is this.
+pub fn rank_in_sections(attrs: &mut [GpuTriAttr]) {
+ let mut seen: Vec<u32> = vec![];
+ for a in attrs {
+ let s = a.uv[3].to_bits() as usize;
+ if seen.len() <= s {
+ seen.resize(s + 1, 0);
+ }
+ a.x[3] = f32::from_bits(seen[s]);
+ seen[s] += 1;
+ }
+}
+
+/// An instance's rows for `sections`, drawn with the object's materials `mats` (GPU indices; a slot past the last is
+/// the last, as three.js clamps).
+pub fn section_rows(sections: &[Section], mats: &[u32], materials: &[GpuMaterial]) -> Vec<Row> {
+ sections.iter().map(|s| row_of(mats[(s.slot as usize).min(mats.len() - 1)], materials)).collect()
}
-/// A material that emits: a mesh's triangles of it are its instances' emitters in the light list
-/// (`InstMesh::emitters`).
+/// A material that emits: the triangles drawn with it are their instance's emitters in the light list
+/// (`rows_emitters`; a model's mesh: `InstMesh::emitters`).
pub fn emissive(g: &GpuMaterial) -> bool {
g.emissive[..3].iter().any(|e| *e > 0.0)
}
@@ -2376,7 +2567,7 @@ pub fn number_emitters(attrs: &mut [GpuTriAttr], materials: &[GpuMaterial]) -> u
n
}
-/// The `InstMesh` of an `own_blas` mesh's triangles at pool index `first`, all of one class (`mesh_class`).
+/// The `InstMesh` of triangles at pool index `first`, all of one class (`mesh_class`), without sections.
pub fn own_inst_mesh(tris: &[[Vec3A; 3]], first: u32, class: u32) -> InstMesh {
let (mut lo, mut hi) = (Vec3A::splat(f32::MAX), Vec3A::splat(f32::MIN));
for t in tris {
@@ -2386,7 +2577,7 @@ pub fn own_inst_mesh(tris: &[[Vec3A; 3]], first: u32, class: u32) -> InstMesh {
}
}
let count = tris.len() as u32;
- InstMesh { first, count, opaque: if class == 0 { count } else { 0 }, glass: if class == 2 { count } else { 0 }, rest_first: 0, rest_count: 0, lo, hi, deforms: false, emitters: 0 }
+ InstMesh { first, count, opaque: if class == 0 { count } else { 0 }, glass: if class == 2 { count } else { 0 }, rest_first: 0, rest_count: 0, lo, hi, deforms: false, emitters: 0, sect_first: 0, sect_count: 0, colored: false }
}
/// The GPU material of each triangle of a mesh with several (`Kind::Mesh::materials`, here GPU indices) by its
@@ -2573,7 +2764,7 @@ mod instance_tests {
let local = tri_attr(p, n, uv, None, 7);
for (w, mirrored) in [(keeps, false), (keeps * Mat4::from_scale(Vec3::new(-1.0, 1.0, 1.0)), true)] {
assert_eq!(mirrors(w), mirrored);
- let inst = Instance { mesh: 0, world: w, object: 3, cast_shadow: true, name: "x".into(), sub: None, hidden: false, masked: false, first_emitter: 0 };
+ let inst = Instance { mesh: 0, world: w, object: 3, cast_shadow: true, name: "x".into(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: 0 };
assert_eq!(inst.gpu(0, [0, 0]).n[1][3].to_bits(), if mirrored { INST_MIRRORED } else { 0 }, "the record says whether it mirrors");
let (placed, got, got_colors) = inst.flat(&[p[0].into(), p[1].into(), p[2].into()], &local, Some(colors));
// The world-space triangle: its vertices in the order the build flattens a placement in.
@@ -2608,7 +2799,7 @@ mod instance_tests {
let mats = [opaque, cutout];
let p = [Vec3::ZERO, Vec3::X, Vec3::Y];
let a = |m: u32| tri_attr(p, [Vec3::Z; 3], [Vec2::ZERO, Vec2::X, Vec2::Y], None, m);
- let inst = |shadow: bool| Instance { mesh: 0, world: Mat4::IDENTITY, object: 0, cast_shadow: shadow, name: "x".into(), sub: None, hidden: false, masked: false, first_emitter: 0 };
+ let inst = |shadow: bool| Instance { mesh: 0, world: Mat4::IDENTITY, object: 0, cast_shadow: shadow, name: "x".into(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: 0 };
assert_eq!(instance_tri_flags(&inst(true), &a(0), &mats), 0);
assert_eq!(instance_tri_flags(&inst(true), &a(1), &mats), TRI_MASKED);
assert_eq!(instance_tri_flags(&inst(false), &a(1), &mats), TRI_MASKED | TRI_NO_SHADOW);
@@ -2640,7 +2831,7 @@ mod instance_tests {
w.set_instances(2, 3, Some(m), None, None).unwrap();
let sc = build(&w, Path::new("."), &crate::default_presets_dir(), None).unwrap();
assert_eq!((sc.instances.len(), sc.tris.len()), (4, 0), "a copy that mirrors the mesh is an instance as the others");
- assert_eq!(sc.instances.iter().map(|i| i.gpu(0, [0, 0]).n[1][3].to_bits()).collect::<Vec<_>>(), [INST_MIRRORED, 0, 0, 0], "and its record says so");
+ assert_eq!(sc.instances.iter().map(|i| i.gpu(0, [0, 0]).n[1][3].to_bits()).collect::<Vec<_>>(), [INST_MIRRORED | INST_ROWS, INST_ROWS, INST_ROWS, INST_ROWS], "and its record says so, beside that it has rows");
}
/// An instanced object whose material only emits is placed as any other: one shared mesh, which has the emitters,
@@ -2660,7 +2851,8 @@ mod instance_tests {
let m = [Mat4::from_scale(Vec3::splat(2.0)), Mat4::from_translation(Vec3::X), Mat4::from_scale(Vec3::ZERO), Mat4::from_translation(Vec3::Y)];
w.set_instances(2, 3, Some(m.iter().flat_map(|m| m.to_cols_array()).collect()), None, None).unwrap();
let mut sc = build(&w, Path::new("."), &crate::default_presets_dir(), None).unwrap();
- assert_eq!((sc.meshes.len(), sc.meshes[0].emitters, sc.instances.len(), sc.tris.len()), (1, 1, 4, 0));
+ assert_eq!((sc.meshes.len(), sc.meshes[0].sect_count, sc.instances.len(), sc.tris.len()), (1, 1, 4, 0));
+ assert_eq!(sc.instances.iter().map(|i| (i.rows, i.bits)).collect::<Vec<_>>(), [(0, INST_ROWS), (1, INST_ROWS), (2, INST_ROWS), (3, INST_ROWS)], "a row a copy");
let (st, first) = (sc.object_stride(), sc.retained.instanced(2).unwrap().object as usize);
assert_eq!((0..4).map(|i| sc.objects[(first + i) * st][3]).collect::<Vec<_>>(), [2.0, 2.0, 0.0, 0.0], "a hidden copy's entry has no power");
let prep = crate::prepare_as(true, false, &mut sc, &mut vec![]);
@@ -2708,32 +2900,68 @@ mod instance_tests {
}
}
- /// A mesh of several materials (a geometry group each) lies by class, opaque then cutout then glass, whatever the
- /// order of its groups; each triangle keeps its material, `order` says where it came from among the geometry's
- /// drawn triangles (one in no group is not drawn), and the mesh counts its parts and the triangles that emit.
+ /// A mesh of a geometry drawn by its groups lies by section, a group after another: a triangle in no group is not
+ /// drawn, one in two groups is its last group's. Its triangles hold their section and their index in it and
+ /// nothing of a material; an instance's rows say the materials, by the groups' slots: their classes, whether it
+ /// casts, how many emitters it has and where each section's start. Drawn with one material, the geometry whole is
+ /// one section.
#[test]
- fn a_mesh_of_several_materials_lies_by_class() {
- // Five quads along x: glass, a cutout, one in no group, an opaque one that emits, an opaque one.
+ fn a_mesh_lies_by_section_and_an_instances_rows_say_its_materials() {
+ // Five quads along x: a group each but the third, which has none; a fifth group takes the first quad's second
+ // triangle.
let (mut positions, mut indices) = (vec![], vec![]);
for q in 0..5u32 {
let x = q as f32;
positions.extend([x, 0.0, 0.0, x + 1.0, 0.0, 0.0, x + 1.0, 1.0, 0.0, x, 1.0, 0.0]);
indices.extend([0, 1, 2, 0, 2, 3].map(|i| 4 * q + i));
}
- let g = world::Geometry { normals: [0.0, 0.0, 1.0].repeat(20), uvs: vec![0.0; 40], positions, indices, groups: vec![[0, 6, 0], [6, 6, 1], [18, 6, 2], [24, 6, 3]], colors: vec![] };
- let materials = [GpuMaterial { layer: [1.0, 1.5, 0.0, 0.0], ..Default::default() }, GpuMaterial { uv2: [0.0, 0.0, 0.0, 0.5], ..Default::default() }, GpuMaterial { emissive: [1.0, 1.0, 1.0, 0.0], ..Default::default() }, GpuMaterial::default()];
- let per_tri = group_materials(&g, &[0, 1, 2, 3]).unwrap();
- assert_eq!(per_tri, [Some(0), Some(0), Some(1), Some(1), None, None, Some(2), Some(2), Some(3), Some(3)]);
- let (t, a, order, im) = own_mesh(&g, 0, Some(&per_tri), &materials, 10);
- assert_eq!(order, [4, 5, 6, 7, 2, 3, 0, 1], "the opaque triangles, the cutout's, the glass's");
- assert_eq!(a.iter().map(|a| a.uv[3].to_bits()).collect::<Vec<_>>(), [2, 2, 3, 3, 1, 1, 0, 0]);
- assert_eq!(t.iter().map(|t| t[0].x.min(t[1].x).min(t[2].x)).collect::<Vec<_>>(), [3.0, 3.0, 4.0, 4.0, 1.0, 1.0, 0.0, 0.0], "each where its material is");
- assert_eq!((im.first, im.count, im.opaque, im.glass, im.emitters), (10, 8, 4, 2, 2));
- assert_eq!((im.parts(), im.part_offsets()), (vec![(0, 4, true), (4, 2, true), (6, 2, false)], [4, 6]));
+ let colors: Vec<f32> = (0..20).flat_map(|v| [(v / 4) as f32 / 4.0, 0.0, 0.0]).collect();
+ let g = world::Geometry { normals: [0.0, 0.0, 1.0].repeat(20), uvs: vec![0.0; 40], positions, indices, groups: vec![[0, 6, 0], [6, 6, 1], [18, 6, 2], [24, 6, 3], [3, 3, 1]], colors: vec![] };
+ assert!(by_groups(&g, 2) && !by_groups(&g, 1) && !by_groups(&world::Geometry { groups: vec![], ..g.clone() }, 4));
+ let d = section_mesh(&g, true, 10, 7, true);
+ let sect = |first, count, slot| Section { first, count, slot };
+ assert_eq!(d.sections, [sect(0, 1, 0), sect(1, 2, 1), sect(3, 2, 2), sect(5, 2, 3), sect(7, 1, 1)]);
+ assert_eq!(d.tris.iter().map(|t| t[0].x.min(t[1].x).min(t[2].x)).collect::<Vec<_>>(), [0.0, 1.0, 1.0, 3.0, 3.0, 4.0, 4.0, 0.0], "each triangle in its last group's section");
+ assert_eq!(d.attrs.iter().map(|a| (a.uv[3].to_bits(), a.x[3].to_bits())).collect::<Vec<_>>(), [(0, 0), (1, 0), (1, 1), (2, 0), (2, 1), (3, 0), (3, 1), (4, 0)]);
+ let im = d.mesh;
+ assert_eq!((im.first, im.count, im.opaque, im.glass, im.emitters, im.sect_first, im.sect_count, im.colored), (10, 8, 8, 0, 0, 7, 5, false), "no colours: the geometry has none");
assert_eq!((im.lo, im.hi), (Vec3A::new(0.0, 0.0, 0.0), Vec3A::new(5.0, 1.0, 0.0)), "bounds of what is drawn");
- // One material: as the geometry has them.
- let (_, a1, order1, one) = own_mesh(&g, 1, None, &materials, 0);
- assert_eq!((order1, a1.len(), one.opaque, one.glass, one.emitters), ((0..10).collect::<Vec<_>>(), 10, 0, 0, 0), "a cutout mesh");
+ let mut all = vec![sect(9, 9, 9); 7];
+ all.extend(&d.sections);
+ assert_eq!(im.parts(&all), [(0, 1, true), (1, 2, true), (3, 2, true), (5, 2, true), (7, 1, true)], "a geometry a section, all flagged opaque");
+ assert!(d.colors.is_none());
+ // Its geometry's colours, where it has them and they are asked for: the drawn triangles', as they lie.
+ let tinted = section_mesh(&world::Geometry { colors, ..g.clone() }, true, 0, 0, true);
+ let red = |c: &[u32; 3]| c[0] & 0xff;
+ assert!(tinted.mesh.colored && !section_mesh(&world::Geometry { colors: vec![1.0; 60], ..g.clone() }, true, 0, 0, false).mesh.colored);
+ assert_eq!(tinted.colors.as_ref().map(|c| c.iter().map(red).collect::<Vec<_>>()), Some(vec![0, 137, 137, 225, 225, 255, 255, 0]));
+ // An instance's rows: glass, a cutout, an emitter, a plain material by the slots 0 to 3.
+ let materials = [GpuMaterial { layer: [1.0, 1.5, 0.0, 0.0], ..Default::default() }, GpuMaterial { uv2: [0.0, 0.0, 0.0, 0.5], ..Default::default() }, GpuMaterial { emissive: [1.0, 1.0, 1.0, 0.0], ..Default::default() }, GpuMaterial::default()];
+ let rows = section_rows(&d.sections, &[0, 1, 2, 3], &materials);
+ assert_eq!(rows, [[ROW_GLASS, 0, NO_EMITTER, 0], [1 | ROW_CUTOUT, 0, NO_EMITTER, 0], [2, 0, NO_EMITTER, 0], [3, 0, NO_EMITTER, 0], [1 | ROW_CUTOUT, 0, NO_EMITTER, 0]]);
+ assert_eq!(rows.iter().map(row_material).collect::<Vec<_>>(), [0, 1, 2, 3, 1]);
+ assert_eq!((rows_cast(&rows, true), rows_cast(&rows, false), rows_bits(&rows)), (true, false, INST_ROWS | INST_CUTOUT | INST_GLASS));
+ let starts = section_emitters(&d.sections, &rows, &materials);
+ assert_eq!((rows_emitters(&d.sections, &rows, &materials), &starts[..]), (2, &[None, None, Some(0), None, None][..]));
+ assert_eq!((section_slot(&d.attrs[4], &rows, &starts), section_slot(&d.attrs[5], &rows, &starts)), (Some((1, 2)), None), "an emitter's place: its section's start and its index");
+ // Two materials for four slots: a slot past the last is the last. Emitters in two sections, one after another.
+ let two = section_rows(&d.sections, &[2, 0], &materials);
+ assert_eq!(two.iter().map(row_material).collect::<Vec<_>>(), [2, 0, 0, 0, 0]);
+ assert_eq!((rows_emitters(&d.sections, &two, &materials), rows_bits(&two), rows_cast(&two, true)), (1, INST_ROWS | INST_GLASS, true));
+ let lit = section_rows(&d.sections, &[2, 3, 3, 2], &materials);
+ assert_eq!((rows_emitters(&d.sections, &lit, &materials), section_emitters(&d.sections, &lit, &materials)), (3, vec![Some(0), None, None, Some(1), None]));
+ // All glass: it casts no shadow, whatever its object says.
+ let glass = section_rows(&d.sections, &[0, 0], &materials);
+ assert_eq!((rows_cast(&glass, true), rows_bits(&glass)), (false, INST_ROWS | INST_GLASS));
+ // Put in another order (a unit's tree's), the triangles are numbered again in their sections.
+ let mut back: Vec<GpuTriAttr> = d.attrs.iter().rev().copied().collect();
+ rank_in_sections(&mut back);
+ assert_eq!(back.iter().map(|a| (a.uv[3].to_bits(), a.x[3].to_bits())).collect::<Vec<_>>(), [(4, 0), (3, 0), (3, 1), (2, 0), (2, 1), (1, 0), (1, 1), (0, 0)]);
+ // One material: the geometry whole, as it has its triangles, one section.
+ let one = section_mesh(&g, false, 0, 0, false);
+ assert_eq!((one.sections.clone(), one.mesh.sect_count, one.attrs.len()), (vec![sect(0, 10, 0)], 1, 10));
+ assert_eq!(one.attrs.iter().map(|a| (a.uv[3].to_bits(), a.x[3].to_bits())).collect::<Vec<_>>(), (0..10).map(|k| (0, k)).collect::<Vec<_>>());
+ assert_eq!(section_rows(&one.sections, &[1], &materials), [[1 | ROW_CUTOUT, 0, NO_EMITTER, 0]]);
}
/// A model's glass is a part of its mesh (tests/render/data/frame-pane.glb: an opaque, a cutout and a glass quad;
@@ -2752,16 +2980,17 @@ mod instance_tests {
let mut sc = build(&w, Path::new(".."), &crate::default_presets_dir(), None).unwrap();
assert_eq!(sc.meshes.iter().map(|m| (m.count, m.opaque, m.glass, m.rest_count)).collect::<Vec<_>>(), [(6, 2, 2, 0)]);
assert_eq!((sc.instances.len(), sc.tris.len()), (2, 0));
- assert_eq!((sc.meshes[0].parts(), sc.meshes[0].part_offsets()), (vec![(0, 2, true), (2, 2, true), (4, 2, false)], [2, 4]));
+ assert_eq!((sc.meshes[0].parts(&sc.sections), sc.meshes[0].part_offsets()), (vec![(0, 2, true), (2, 2, true), (4, 2, false)], [2, 4]));
+ assert!(sc.rows.is_empty() && sc.instances.iter().all(|i| i.bits == 0), "a model's instance has no rows");
crate::prepare_as(true, false, &mut sc, &mut vec![]);
assert!(sc.gpu_instances.iter().all(|r| (r.info[3], r.n[0][3].to_bits()) == (2, 4)), "the records have the two starts");
let f = crate::gpu::instance_features(&sc);
assert_eq!(f & (crate::gpu::F_IGLASS | crate::gpu::F_MASKED), crate::gpu::F_IGLASS | crate::gpu::F_MASKED);
// A mesh of one kind, or of two: the geometries it has, in the same order.
let t = [[Vec3A::ZERO, Vec3A::X, Vec3A::Y]; 3];
- assert_eq!((own_inst_mesh(&t, 0, 2).parts(), own_inst_mesh(&t, 0, 2).part_offsets()), (vec![(0, 3, false)], [0, 0]));
+ assert_eq!((own_inst_mesh(&t, 0, 2).parts(&[]), own_inst_mesh(&t, 0, 2).part_offsets()), (vec![(0, 3, false)], [0, 0]));
let two = InstMesh { opaque: 0, glass: 1, ..own_inst_mesh(&t, 0, 1) };
- assert_eq!((two.parts(), two.part_offsets()), (vec![(0, 2, true), (2, 1, false)], [2, 0]));
+ assert_eq!((two.parts(&[]), two.part_offsets()), (vec![(0, 2, true), (2, 1, false)], [2, 0]));
}
/// A cutout on exactly an emitter's vertices leaves the mesh with it (`flatten_coincident`), in a model that stays
diff --git a/renderer/src/tables.rs b/renderer/src/tables.rs
index 2c1c86f..56c7a42 100644
--- a/renderer/src/tables.rs
+++ b/renderer/src/tables.rs
@@ -156,7 +156,8 @@ impl Tables {
}
// (A material of instances' triangles that gets a function, or loses it: the kernel's variant goes by
// whether there is one, `gpu::F_IFUNC`, which the build decides. One that turns glass, or stops being
- // glass: its triangles are a geometry of their mesh's BLAS by that, `scene::mesh_class`.)
+ // glass: an instance's row and mask say so, a model's mesh has its triangles in a geometry apart by it. One
+ // whose alpha test changes never comes here: that is structural, world.rs `same_texture_refs`.)
let old = &self.materials[mi as usize];
if ((gm.tex1[3] != 0) != (old.tex1[3] != 0) || (gm.layer[0] > 0.0) != (old.layer[0] > 0.0)) && self.fixed_mats.contains(&mi) {
return Ok(None);
diff --git a/renderer/src/units.rs b/renderer/src/units.rs
index b53e97c..b889e46 100644
--- a/renderer/src/units.rs
+++ b/renderer/src/units.rs
@@ -304,8 +304,8 @@ pub fn top_tree(units: &[UnitBox]) -> Result<Vec<GpuNode>, String> {
/// aside, which no comparison in the walk sees). (The third word is every instance's: its first emitter.)
pub fn unit_record(mut r: GpuInstance, root: u32, cast_shadow: bool) -> GpuInstance {
r.n[0][3] = f32::from_bits(root);
- // (Beside the record's own bit there: `scene::INST_MIRRORED`.)
- r.n[1][3] = f32::from_bits(r.n[1][3].to_bits() & crate::scene::INST_MIRRORED | if cast_shadow { UNIT_SHADOW } else { 0 } | if translation_alone(&r) { UNIT_SHIFTED } else { 0 });
+ // (Beside the record's own bits there: `scene::INST_BITS`.)
+ r.n[1][3] = f32::from_bits(r.n[1][3].to_bits() & crate::scene::INST_BITS | if cast_shadow { UNIT_SHADOW } else { 0 } | if translation_alone(&r) { UNIT_SHIFTED } else { 0 });
r
}
@@ -871,6 +871,10 @@ pub(crate) mod cpu {
pub(crate) nodes: &'a [GpuNode],
pub(crate) tri_verts: &'a [[f32; 4]],
pub(crate) instances: &'a [GpuInstance],
+ /// Each triangle's section (its attributes' uv.w) and the instances' rows: what a unit with rows has its
+ /// glass by (`row_flags`). Empty where no unit has rows.
+ pub(crate) sections: &'a [u32],
+ pub(crate) rows: &'a [crate::scene::Row],
/// `P.motion.z`, `P.motion.w`.
pub(crate) top: u32,
pub(crate) units: u32,
@@ -1046,6 +1050,13 @@ pub(crate) mod cpu {
self.trace_units(o, d, inv_d, hit, mode, &mut stack)
}
+ /// shaders/trace_units.wgsl `row_flags`.
+ fn row_flags(&self, first: u32, ti: u32) -> Walk<u32> {
+ let section = *self.sections.get(ti as usize).ok_or(format!("reads the section of triangle {ti}"))?;
+ let x = self.rows.get((first + section) as usize).ok_or(format!("reads row {first} + {section}"))?[0];
+ Ok(if x & crate::scene::ROW_CUTOUT != 0 { crate::scene::TRI_MASKED } else { 0 } | if x & crate::scene::ROW_GLASS != 0 { crate::scene::TRI_NO_SHADOW } else { 0 })
+ }
+
/// shaders/trace_units.wgsl `trace_units`, statement for statement.
pub(crate) fn trace_units(&self, o: Vec3A, d: Vec3A, inv_d: Vec3A, hit_in: Hit, mode: u32, stack: &mut [u32; STACK]) -> Walk<Hit> {
let mut hit = hit_in;
@@ -1059,6 +1070,7 @@ pub(crate) mod cpu {
}
let (mut sp, mut node) = (0usize, top);
let mut rec = NO_INST;
+ let (mut ubits, mut urows) = (0u32, 0u32);
let (mut ro, mut rd, mut rinv) = (o, d, inv_d);
let (mut off, mut first, mut base) = (top, 0u32, 0usize);
loop {
@@ -1096,6 +1108,7 @@ pub(crate) mod cpu {
}
off = u.n[0][3].to_bits();
first = u.info[0];
+ (ubits, urows) = (u.n[1][3].to_bits(), u.info[3]);
base = sp;
node = off;
continue;
@@ -1107,7 +1120,10 @@ pub(crate) mod cpu {
let x = self.intersect_tri(ro, rd, ti, hit.t)?;
if x < hit.t {
// (A unit's glass: shadow rays pass it.)
- let flags = self.tri_verts.get(ti as usize * 3).ok_or(format!("reads triangle {ti}"))?[3].to_bits();
+ let mut flags = self.tri_verts.get(ti as usize * 3).ok_or(format!("reads triangle {ti}"))?[3].to_bits();
+ if ubits & (crate::scene::INST_CUTOUT | crate::scene::INST_GLASS) != 0 {
+ flags |= self.row_flags(urows, ti)?;
+ }
if mode == TRACE_SHADOW && flags & crate::scene::TRI_NO_SHADOW != 0 {
continue;
}
@@ -1339,7 +1355,7 @@ mod tests {
fn record(&self, mesh: usize, world: Mat4, cast: bool) -> GpuInstance {
let (first, _, root, ..) = self.meshes[mesh].unwrap();
- let inst = crate::scene::Instance { mesh: mesh as u32, world, object: 0, cast_shadow: cast, name: String::new(), sub: None, hidden: false, masked: false, first_emitter: 0 };
+ let inst = crate::scene::Instance { mesh: mesh as u32, world, object: 0, cast_shadow: cast, name: String::new(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: 0 };
unit_record(inst.gpu(first, [0, 0]), root, cast)
}
@@ -1377,7 +1393,7 @@ mod tests {
fn kernel(&self) -> Kernel<'_> {
let budget = 64 * (self.nodes.len() as u64 + self.tri_verts.len() as u64) + 1024;
- Kernel { nodes: &self.nodes, tri_verts: &self.tri_verts, instances: &self.instances, top: self.top, units: self.count, steps: Default::default(), budget, deepest: Default::default(), reads: Default::default() }
+ Kernel { nodes: &self.nodes, tri_verts: &self.tri_verts, instances: &self.instances, sections: &[], rows: &[], top: self.top, units: self.count, steps: Default::default(), budget, deepest: Default::default(), reads: Default::default() }
}
/// Every triangle a ray could meet, tested one by one with the kernel's own triangle test (the still scene's in
@@ -1953,7 +1969,7 @@ mod tests {
// A built tree is a level short of the bound: two of them joined are at it.
assert!(check_tree(&build_sah(&(0..1 << 12).map(|k| (Vec3A::splat(k as f32), Vec3A::splat(k as f32 + 1.0))).collect::<Vec<_>>(), 12).0, 64, |_, _| Ok(())).unwrap() <= 12);
// The record's word for a placement by a translation alone.
- let rec = |world: Mat4| unit_record(crate::scene::Instance { mesh: 0, world, object: 0, cast_shadow: true, name: String::new(), sub: None, hidden: false, masked: false, first_emitter: 0 }.gpu(0, [0, 0]), 9, true);
+ let rec = |world: Mat4| unit_record(crate::scene::Instance { mesh: 0, world, object: 0, cast_shadow: true, name: String::new(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: 0 }.gpu(0, [0, 0]), 9, true);
let shifted = |m: Mat4| rec(m).n[1][3].to_bits() & UNIT_SHIFTED != 0;
assert!(shifted(Mat4::IDENTITY));
assert!(shifted(Mat4::from_translation(Vec3::new(3.0, -2.0, 0.5))));
diff --git a/renderer/src/units_cost.rs b/renderer/src/units_cost.rs
index b222162..1d274a4 100644
--- a/renderer/src/units_cost.rs
+++ b/renderer/src/units_cost.rs
@@ -75,7 +75,7 @@ impl Laid {
}
fn kernel(&self) -> Kernel<'_> {
- Kernel { nodes: &self.nodes, tri_verts: &self.tri_verts, instances: &self.instances, top: self.top, units: self.units, steps: Default::default(), budget: 1 << 26, deepest: Default::default(), reads: Default::default() }
+ Kernel { nodes: &self.nodes, tri_verts: &self.tri_verts, instances: &self.instances, sections: &[], rows: &[], top: self.top, units: self.units, steps: Default::default(), budget: 1 << 26, deepest: Default::default(), reads: Default::default() }
}
}
@@ -409,7 +409,7 @@ fn units_pile() {
let made = (u.kept.builds - was.0, u.kept.changes - was.1, u.kept.refits - was.2);
// At rest: the kernel's buffers as a session would have written them.
for (j, p) in pieces.iter().enumerate() {
- let inst = scene::Instance { mesh, world: pose(p, 1.0), object: 0, cast_shadow: true, name: String::new(), sub: None, hidden: false, masked: false, first_emitter: 0 };
+ let inst = scene::Instance { mesh, world: pose(p, 1.0), object: 0, cast_shadow: true, name: String::new(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: 0 };
l.instances[first_rec + j] = units::unit_record(inst.gpu(first_tri, [tris.len() as u32, 0]), root as u32, true);
}
let at = u.layout.top_first as usize;
diff --git a/renderer/src/world.rs b/renderer/src/world.rs
index d972a0a..3992024 100644
--- a/renderer/src/world.rs
+++ b/renderer/src/world.rs
@@ -1618,6 +1618,13 @@ mod tests {
w.set_transform(2, Vec3::X, Quat::IDENTITY, Vec3::ONE).unwrap();
let c = w.take_changes();
assert!(!c.structural && c.materials.contains(&1) && c.powers.contains(&1) && c.camera);
+ // An alpha test that comes, changes or goes: a rebuild (an instance's row says whether its material is a
+ // cutout's, and the kernel's variant goes by whether there is one).
+ for (test, what) in [(Some(0.5), "an alpha test"), (Some(0.3), "another threshold"), (None, "no alpha test again")] {
+ m.alpha_test = test;
+ w.set_material(1, m.clone());
+ assert!(w.take_changes().structural, "{what}: structural");
+ }
m.map = Some(7);
w.set_material(1, m);
assert!(w.take_changes().structural, "texture slots are structural");