The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.
Rust electron-alternativegame-engineglobal-illuminationgraphicsjavascript-runtimemetalpath-tracingray-tracingreal-time-renderingrenderingrustthreejstypescriptvoxelvulkanwebgpuwgpu
Android: the kernel reads its tables whole (Adreno misread the views: colour cast, GPU hang) (#145)
Evan (Yifeng) Wangaf25e72c68e3
diff --git a/docs/RUNTIME.md b/docs/RUNTIME.mdindex 687f6d0..f1904ae 100644--- a/docs/RUNTIME.md+++ b/docs/RUNTIME.md@@ -1638,15 +1638,34 @@ layout and its kernels' source are what they were (`gpu.rs` `the_options_defaulton scenes that are not all at hand. What was measured again on this source, on the same handheld, is under "Checkedon the device", and differs where it says so.-- **Uniform tables** (`GpuOptions::uniform_tables`, `THREERT_UNIFORM_TABLES=1|0`; default on Android; never with the- merged layout). The driver gave the kernel other buffers' contents for four of its read-only storage buffers, each+- **The tables read whole** (`GpuOptions::table_views`, `THREERT_TABLE_VIEWS=1|0`; default 0 on Android, 1+ elsewhere; kernel flag `whole_tables`). Since 2026-11-15 (#89) the kernel's seven typed tables are views of their+ sections of the tables' buffer, each a binding of its own (12 to 18, merged.rs `TABLE_VIEWS`). The Adreno 740+ driver read the storage views wrong (checked on the device, 2026-11-16, ThreeRT for Android 0.5.0 at `3d2297e`):+ - `materials` (binding 12): every scene in a blown-out colour cast (OpenStrikeRT's Foundry pink, Range green, the+ weapon and the soldiers one colour). Reading the materials alone from the buffer whole drew right.+ - `emitters` (14): with the materials read whole, the first frame after an emissive object's power changed in a+ scene with no other emitters on (a muzzle flash in Range, or in an imported map: what a map switch in practice+ with bots leads to) did not end: `kgsl … gpu timeout`, the host thread blocked for good. Copied into a buffer of+ its own at offset 0 each frame, the emitters' table hung the same: the binding, not its sharing a buffer with+ `tables` or its offset. Read whole: no hang.+ - Without the views the kernel reads all seven from `tables` (binding 4) by the offsets in the parameters+ (`Params::table_first`), as the merged layout does (pathtrace.wgsl `@if(merged || whole_tables)`), and there are+ no uniform tables (below), so none of their bounds either. On the device the frame costs what it does with the+ uniform copies (Foundry at 249 × 140, one bounce: 52 ms read whole, 51 ms with the uniform copies and the other+ three read whole). `THREERT_TABLE_VIEWS=1` on the device brings back the views (and the uniform copies), for A/B.+ - Elsewhere the views stay; `THREERT_TABLE_VIEWS=0` reads the tables whole on any device, to the same image bit+ for bit (`live::instanced_tests::the_tables_read_whole_render_what_the_views_do`, offline and live after a power+ edit).+- **Uniform tables** (`GpuOptions::uniform_tables`, `THREERT_UNIFORM_TABLES=1|0`; default on Android with the views,+ `THREERT_TABLE_VIEWS=1`; never with the merged layout or the tables read whole). The driver gave the kernel other buffers' contents for four of its read-only storage buffers, eacha binding of its own then: `tex_info` (binding 14), `objects` (15), `instances` (17), `media` (18), all numberedafter the acceleration structure (13). As uniform buffers they read right.- Since 2026-11-15 the four are views of their sections of the tables' buffer ("The scene's tables"), still at- bindings of their own (15 to 18), and the acceleration structure is the group's last binding (19). **Whether- the driver reads them right there is not known: no device has run it.** Until one has, Android keeps the- uniform copies; `THREERT_UNIFORM_TABLES=0` on the device is the run that decides (if it draws right, the copies- and their bounds can go).+ bindings of their own (15 to 18), and the acceleration structure is the group's last binding (19). The device+ did not read those views right either (2026-11-16, `THREERT_TABLE_VIEWS=1 THREERT_UNIFORM_TABLES=0`: Range all+ white), and with the uniform copies the other three views were still wrong (above): Android now reads the+ tables whole and has no uniform copies; they stay for `THREERT_TABLE_VIEWS=1`.- The kernel's source has them under `@if(uniform_tables)` (pathtrace.wgsl): four sized uniform arrays atbindings 15 to 18 (merged.rs `UNIFORM_TABLES`; their lengths WESL constants), and their accessors hold everyindex to the array (`min(i, last)`), so nothing is read outside a uniform buffer.@@ -1662,7 +1681,7 @@ on the device", and differs where it says so.| buffer | size | decision ||---|---|---|- | `tables` (4) and its views `materials` (12), `lights` (13), `emitters` (14) | megabytes in a lit scene | storage: the device drew right with materials, lights and emitters as storage buffers (bindings 4 to 6 then) |+ | `tables` (4) and, with the views, `materials` (12), `lights` (13), `emitters` (14) | megabytes in a lit scene | storage: the device drew right with materials, lights and emitters as storage buffers of their own (bindings 4 to 6, before #89) and reads them right from `tables` whole; not as the views (above) || `words` (5): the environment's CDF, the procedural geometry's data, vertex colours | megabytes | storage; the environment's light sampling is off on Android, below || `tri_verts` (1), `attrs` (2), `nodes` (3), `prev_verts` (6) | per triangle | storage (megabytes) || `accum` (11), group 1 (radiance cache, the trace's outputs, `finish`'s records, the loop guard's count) | per pixel, per cache entry | written by the kernel: cannot be uniform |@@ -1682,6 +1701,7 @@ on the device", and differs where it says so.| `THREERT_CUTOUT_LITE` | Android: 1 | hardware traversal: 1 = shadow and any-hit rays take alpha cutouts as opaque; 2 = camera rays also step through at most 4 cutouts | a map with cutout foliage: the trace 235 ms, 41 ms without cutouts || `THREERT_LAST_DIRECT` | Android: 1 | the path's last vertex (at the bounce limit, past the camera hit) takes its direct light | with one bounce and no radiance cache (which cost 30-60 % more trace) sunlit ground lit nothing and interiors were black || `THREERT_LIGHT_PICK` | 0 | past the camera hit, the directional lights and one of the other kinds (local lights, emitters, the sky), weighted by their number: two shadow rays a vertex instead of four; unbiased, noisier | a handheld's host sets it with `THREERT_LAST_DIRECT` |+ | `THREERT_LIGHT_TILES` | Android: 0 | a scene with more than `RIS_EXACT` shadow-casting local lights has no light tiles (`F_LISTS`, #87): its lights are resampled unguided, as before the tiles (not a flag of the source: the scene's feature is left off, gpu.rs `light_tiles_on`) | OpenStrikeRT's Foundry, 249 × 140, one bounce, the tables read whole: 48 ms with the tiles, 31 ms without (30 fps, the 0.4 clients' rate); `THREERT_LIGHT_PICK=1` instead: 38 ms |`THREERT_CHECKED=1` (or a mask: 2 bounds, 4 loop bounding, 8 ray-query initialization) compiles the kernel withnaga's runtime checks, to tell a driver's fault from the kernel's.diff --git a/renderer/shaders/pathtrace.wgsl b/renderer/shaders/pathtrace.wgslindex 32f42a2..8501203 100644--- a/renderer/shaders/pathtrace.wgsl+++ b/renderer/shaders/pathtrace.wgsl@@ -16,6 +16,8 @@// of `FEAT`, a pipeline-overridable constant// merged the merged binding layout (merged.rs: at most eight storage buffers a stage, a browser's)// uniform_tables four tables in uniform buffers (merged.rs `UNIFORM_TABLES`: Android's drivers)+// whole_tables the seven typed tables read from the tables' buffer whole, as `merged` reads them, and+// no views of their sections (gpu.rs `GpuOptions::table_views`: Android's drivers)// guard the loop guard (gpu.rs `loop_guard_of`, `guard_loops`)// The numbers a variant is compiled for are WESL constants (`import constants::`, gpu.rs `KernelVariant::constants`): the// uniform tables' lengths, the loop guard's limit.@@ -184,11 +186,11 @@ fn energy_at(i: u32) -> vec4<f32> { return table_f(P.table_first[2].y + i); }fn glass_energy_at(i: u32) -> vec4<f32> { return table_f(P.table_first[2].z + i); }// The seven tables read at every hit or light, through `material_at`, `light_at`, `emitter_at`, `tex_info_at`,// `object_at`, `instance_at` and `medium_at` in every layout.-@if(merged) {- // The merged layout (merged.rs: a browser's eight storage buffers): from the buffer whole, a record made of its- // vec4s (their counts: the tests hold them to the renderer's records). Slower than the views below where it was- // measured (docs/RUNTIME.md "The scene's tables"): an offset from the parameters at every read, the records'- // assembly.+@if(merged || whole_tables) {+ // The merged layout (merged.rs: a browser's eight storage buffers), and a device whose driver reads the views below+ // wrong (gpu.rs `GpuOptions::table_views`: Android): from the buffer whole, a record made of its vec4s (their+ // counts: the tests hold them to the renderer's records). Slower than the views below where it was measured+ // (docs/RUNTIME.md "The scene's tables"): an offset from the parameters at every read, the records' assembly.const MATERIAL_VEC4: u32 = 18u;const LIGHT_VEC4: u32 = 5u;const INSTANCE_VEC4: u32 = 10u;diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rsindex ba3283c..8cea2c1 100644--- a/renderer/src/gpu.rs+++ b/renderer/src/gpu.rs@@ -17,6 +17,9 @@ pub struct Gpu {pub adapter_info: wgpu::AdapterInfo,/// The kernel's bounded tables are uniform buffers (`GpuOptions::uniform_tables`; merged.rs `UNIFORM_TABLES`).pub uniform_tables: bool,+ /// The kernel reads its seven typed tables from the tables' buffer whole, not from views of their sections+ /// (`GpuOptions::table_views`; merged.rs `TABLE_VIEWS`).+ pub whole_tables: bool,/// The kernel's switches this device was opened with (`KernelSwitches`): they are in `source`.pub switches: KernelSwitches,/// The approximations a live view's kernel takes (`A_*`): the options' (`GpuOptions::approx`) unless a view asked@@ -282,6 +285,8 @@ pub(crate) struct LayoutShape {pub hwrt: bool,pub merged: bool,pub uniform_tables: bool,+ /// No views of the tables' sections (`Gpu::whole_tables`).+ pub whole_tables: bool,pub guard: bool,}@@ -302,7 +307,7 @@ const ACCELERATION_STRUCTURE: wgpu::BindingType = wgpu::BindingType::Acceleratio/// variant of the kernel's source declares (`the_kernels_layouts_are_its_declarations`).pub(crate) fn kernel_layout_entries(shape: LayoutShape) -> [Vec<wgpu::BindGroupLayoutEntry>; 3] {use crate::merged::{DEFERRED_BINDING, GUARD_BINDING, LISTS_BINDING, LIVE_BINDING, TABLE_VIEWS, UNIFORM_TABLES};- let LayoutShape { hwrt, merged, uniform_tables, guard } = shape;+ let LayoutShape { hwrt, merged, uniform_tables, whole_tables, guard } = shape;let (read, write) = (storage_buffer(true), storage_buffer(false));// Group 0: the parameters; triangles and their attributes; the tables' heap, the words' heap; the dynamic// triangles' previous vertices; the texture pages and their sampler, the environment, the density grids' atlas@@ -325,8 +330,9 @@ pub(crate) fn kernel_layout_entries(shape: LayoutShape) -> [Vec<wgpu::BindGroupLscene.push(layout_entry(3, read));}// The tables the kernel reads at every hit or light, bound again as typed views of their sections (the merged- // layout has no binding for them), four of them uniform copies where a driver needs it.- if !merged {+ // layout has no binding for them, nor has a device that reads them from the buffer whole), four of them uniform+ // copies where a driver needs it.+ if !merged && !whole_tables {let copied = |b: u32| uniform_tables && UNIFORM_TABLES.iter().any(|t| t.binding == b);scene.extend(TABLE_VIEWS.iter().map(|&(_, b)| layout_entry(b, if copied(b) { UNIFORM_BUFFER } else { read })));}@@ -934,6 +940,9 @@ pub struct KernelVariant {pub merged: bool,/// Four tables in uniform buffers (merged.rs `UNIFORM_TABLES`; `GpuOptions::uniform_tables`). Never with `merged`.pub uniform_tables: bool,+ /// The seven typed tables read from the tables' buffer whole, as the merged layout reads them, with the layout as+ /// written otherwise (`GpuOptions::table_views`). Never with `uniform_tables`.+ pub whole_tables: bool,/// The loop guard's limit, in a kernel with the guard (`loop_guard_of`, `guard_loops`).pub guard: Option<u32>,}@@ -945,7 +954,7 @@ impl KernelVariant {}/// The flags of the kernel's conditional translation (pathtrace.wgsl's head).- pub fn flags(&self) -> [(&'static str, bool); 11] {+ pub fn flags(&self) -> [(&'static str, bool); 12] {let (k, f) = (&self.switches, |bit: u32| self.features & bit != 0);[("hwrt", self.hwrt),@@ -958,6 +967,7 @@ impl KernelVariant {("units", f(F_UNITS)),("merged", self.merged),("uniform_tables", self.uniform_tables),+ ("whole_tables", self.whole_tables),("guard", self.guard.is_some()),]}@@ -989,6 +999,7 @@ pub fn kernel_wgsl(src: &str, v: &KernelVariant) -> String {/// `kernel_wgsl`, saying what did not compile instead of panicking (a scene's own functions are a game's code).pub fn try_kernel_wgsl(src: &str, v: &KernelVariant) -> Result<String, String> {assert!(!(v.merged && v.uniform_tables), "the uniform tables are never in the merged layout");+ assert!(!(v.whole_tables && v.uniform_tables), "the uniform tables are copies of views the kernel reading the tables whole does not have");let mut out = try_wesl_wgsl(src, &v.flags(), &v.constants())?;if v.guard.is_some() {guard_loops(&mut out);@@ -1187,6 +1198,12 @@ pub struct GpuOptions {/// buffers (merged.rs `UNIFORM_TABLES`). None: where a driver needs it, which is Android. Never with the merged/// layout, whose tables are one buffer of its own.pub uniform_tables: Option<bool>,+ /// The seven tables the kernel reads at every hit or light (materials, lights, emitters, texture rects, objects,+ /// instances, media) as views of their sections, each a binding of its own (merged.rs `TABLE_VIEWS`), or read from+ /// the tables' buffer whole by the offsets in the parameters, as the merged layout reads them. None: views, but on+ /// Android: Adreno 740's driver read the views wrong (docs/RUNTIME.md "Android"). Without views there are no+ /// uniform tables either.+ pub table_views: Option<bool>,/// A directory to keep compiled pipelines in between runs (pipeline_cache.rs). None: nothing is kept.pub pipeline_cache: Option<std::path::PathBuf>,pub kernel: KernelSwitches,@@ -1206,15 +1223,23 @@ impl GpuOptions {fn from_vars(var: &dyn Fn(&str) -> Option<String>, android: bool) -> GpuOptions {GpuOptions {uniform_tables: var("THREERT_UNIFORM_TABLES").map(|v| v == "1"),+ table_views: var("THREERT_TABLE_VIEWS").map(|v| v == "1"),pipeline_cache: var("THREERT_PIPELINE_CACHE").filter(|d| !d.is_empty()).map(std::path::PathBuf::from),kernel: KernelSwitches::from_vars(var, android),approx: var("THREERT_APPROX").and_then(|v| v.trim().parse().ok()),}}- /// Whether the device has the uniform tables: as asked, else on Android; not in the merged layout.+ /// Whether the kernel reads its tables from views of their sections: as asked, else everywhere but Android; never+ /// in the merged layout.+ fn table_views_on(&self, merged: bool, android: bool) -> bool {+ !merged && self.table_views.unwrap_or(!android)+ }++ /// Whether the device has the uniform tables (copies of four of the views): as asked, else on Android; only with+ /// the views.fn uniform_tables_on(&self, merged: bool, android: bool) -> bool {- !merged && self.uniform_tables.unwrap_or(android)+ self.table_views_on(merged, android) && self.uniform_tables.unwrap_or(android)}}@@ -1622,6 +1647,16 @@ pub const F_GRID: u32 = 1 << 25;/// guided live by the light tiles (pathtrace.wgsl "Light tiles"; the live view's `light_tiles` pass runs for such a/// scene).pub const F_LISTS: u32 = 1 << 27;+/// 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):+/// there the lights are resampled as in a scene of fewer, unguided (docs/RUNTIME.md "Android").+pub fn light_tiles_on() -> bool {+ light_tiles_of(std::env::var("THREERT_LIGHT_TILES").ok().as_deref(), cfg!(target_os = "android"))+}++fn light_tiles_of(var: Option<&str>, android: bool) -> bool {+ var.map_or(!android, |v| v == "1")+}/// Local lights the kernel sums exactly (pathtrace.wgsl `RIS_EXACT`; the test below holds the two together).pub const RIS_EXACT: usize = 8;/// The features that change the kernel's source (an `@if` flag) rather than switch code in it (`FEAT`).@@ -1680,7 +1715,7 @@ pub fn instance_features(scene: &Scene) -> u32 {// (F_GRID also for a volume function that calls `vgrid` on a node without a grid: it reads zeros.)let grid = !scene.grids.is_empty() || (!scene.media.is_empty() && scene.volume_fns.iter().any(|(_, code, helpers)| code.contains("vgrid(") || helpers.contains("vgrid(")));let media = if scene.media.is_empty() { 0 } else { F_MEDIA } | if scene.media.iter().any(|m| m.a[2] != 0) { F_HMEDIA } else { 0 } | if grid { F_GRID } else { 0 };- let particles = if scene.particles.iter().any(|p| !p.translucent) || !scene.gpu_particles.is_empty() { F_PEMIT } else { 0 } | if scene.procs.is_empty() { 0 } else { F_PROC } | if scene.tinted { F_TINT } else { 0 } | if scene.gpu_vcolors.is_empty() { 0 } else { F_VCOLOR } | if scene.lights.iter().filter(|l| l.pos[3] != 0.0 && l.ext[3] >= 0.5).count() > RIS_EXACT { F_LISTS } else { 0 };+ let particles = if scene.particles.iter().any(|p| !p.translucent) || !scene.gpu_particles.is_empty() { F_PEMIT } else { 0 } | if scene.procs.is_empty() { 0 } else { F_PROC } | if scene.tinted { F_TINT } else { 0 } | if scene.gpu_vcolors.is_empty() { 0 } else { F_VCOLOR } | if light_tiles_on() && scene.lights.iter().filter(|l| l.pos[3] != 0.0 && l.ext[3] >= 0.5).count() > RIS_EXACT { F_LISTS } else { 0 };if scene.gpu_instances.is_empty() {return media | particles;}@@ -1830,15 +1865,16 @@ impl Gpu {}).await?;let pipeline_cache = cache_feature.and_then(|_| crate::pipeline_cache::PipelineCache::open(&device, options.pipeline_cache.as_ref()?, &adapter_info));let uniform_tables = options.uniform_tables_on(merged, cfg!(target_os = "android"));+ let whole_tables = !merged && !options.table_views_on(merged, cfg!(target_os = "android"));let switches = options.kernel;let approx = options.approx.unwrap_or(A_LIVE) & A_LIVE;let src = kernel_template();// Bounds checks are not needed: all indices come from our own BVH / scene builder.let module = unsafe {- let wgsl = kernel_wgsl(&src, &KernelVariant { merged, uniform_tables, guard: loop_guard_of(false), ..KernelVariant::new(hwrt, switches, 0) });+ let wgsl = kernel_wgsl(&src, &KernelVariant { merged, uniform_tables, whole_tables, guard: loop_guard_of(false), ..KernelVariant::new(hwrt, switches, 0) });device.create_shader_module_trusted(wgpu::ShaderModuleDescriptor { label: Some("pathtrace"), source: wgpu::ShaderSource::Wgsl(wgsl.into()) }, kernel_checks())};- let [entries, vis_entries, tl_entries] = kernel_layout_entries(LayoutShape { hwrt, merged, uniform_tables, guard: guard_room(hwrt) });+ let [entries, vis_entries, tl_entries] = kernel_layout_entries(LayoutShape { hwrt, merged, uniform_tables, whole_tables, guard: guard_room(hwrt) });let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: None, entries: &entries });let vis_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("vis"), entries: &vis_entries });let one = device.create_texture(&wgpu::TextureDescriptor {@@ -1878,7 +1914,7 @@ impl Gpu {} else {(None, None, None, None)};- Ok(Gpu { instance, adapter, timestamps, device, queue, adapter_info, uniform_tables, switches, approx, approx_default: approx, pipeline_cache, source: src, module, merged, modules: Default::default(), pipeline_layout: pl, pipelines: Default::default(), layout, vis_layout, no_vis, no_vis_bufs, no_vis_view, no_grid_view, grid_layout, hwrt, pages: Default::default(), tl_layout, tl_pipeline_layout, tl_vis_layout, no_vis_tl, tl_pipelines: Default::default(), kernel_passes: Default::default(), proc_cache: Default::default(), proc_blases: Default::default() })+ Ok(Gpu { instance, adapter, timestamps, device, queue, adapter_info, uniform_tables, whole_tables, switches, approx, approx_default: approx, pipeline_cache, source: src, module, merged, modules: Default::default(), pipeline_layout: pl, pipelines: Default::default(), layout, vis_layout, no_vis, no_vis_bufs, no_vis_view, no_grid_view, grid_layout, hwrt, pages: Default::default(), tl_layout, tl_pipeline_layout, tl_vis_layout, no_vis_tl, tl_pipelines: Default::default(), kernel_passes: Default::default(), proc_cache: Default::default(), proc_blases: Default::default() })}/// Whether this device's kernel buffers have the loop guard's count (`guard_room`; always in the merged layout).@@ -1946,7 +1982,7 @@ impl Gpu {};let src = splice(&splice(&splice(&self.source, "material-functions", &k.functions), "volume-functions", &k.volume_functions), "geometry-functions", &k.geometry_functions);// The variant: this device's traversal, switches, layout and loop guard, this scene's features.- let v = KernelVariant { merged: self.merged, uniform_tables: self.uniform_tables, guard: loop_guard_of(patches & F_UNITS != 0), ..KernelVariant::new(self.hwrt, self.switches, patches) };+ let v = KernelVariant { merged: self.merged, uniform_tables: self.uniform_tables, whole_tables: self.whole_tables, guard: loop_guard_of(patches & F_UNITS != 0), ..KernelVariant::new(self.hwrt, self.switches, patches) };// A scene's functions that do not compile (a game's own WGSL) cost the game its functions, not the// app its renderer: the kernel is made without them, and the game's log says why. (A panic here took// the engine down, and ThreeRT for Android then took the device for one without a renderer.)@@ -3150,7 +3186,7 @@ impl Gpu {if !self.hwrt {entries.push(buffer_entry(3, &p.nodes));}- if !self.merged {+ if !self.merged && !self.whole_tables {for &(table, binding) in &crate::merged::TABLE_VIEWS {let copy = b.uniform.and_then(|u| u.iter().zip(&crate::merged::UNIFORM_TABLES).find(|(_, t)| t.binding == binding).map(|(c, _)| c));entries.push(match copy {@@ -3571,9 +3607,9 @@ mod tests {out};let mut checked = 0;- for (hwrt, merged, uniform_tables) in [(true, false, false), (true, false, true), (false, false, false), (false, false, true), (false, true, false)] {+ for (hwrt, merged, uniform_tables, whole_tables) in [(true, false, false, false), (true, false, true, false), (true, false, false, true), (false, false, false, false), (false, false, true, false), (false, false, false, true), (false, true, false, false)] {for room in [false, true] {- let mut layout: Vec<Entry> = kernel_layout_entries(LayoutShape { hwrt, merged, uniform_tables, guard: room }).iter().enumerate().flat_map(|(g, es)| es.iter().map(move |e| (g as u32, e.binding, e.ty))).collect();+ let mut layout: Vec<Entry> = kernel_layout_entries(LayoutShape { hwrt, merged, uniform_tables, whole_tables, guard: room }).iter().enumerate().flat_map(|(g, es)| es.iter().map(move |e| (g as u32, e.binding, e.ty))).collect();layout.sort_by_key(|e| (e.0, e.1));for guard in [None, Some(1 << 16)] {// (As written, a kernel with the guard needs the room.)@@ -3585,20 +3621,21 @@ mod tests {if guard.is_none() && !merged {want.retain(|e| (e.0, e.1) != (1, crate::merged::GUARD_BINDING));}- let v = KernelVariant { merged, uniform_tables, guard, ..KernelVariant::new(hwrt, KernelSwitches::default(), features) };+ let v = KernelVariant { merged, uniform_tables, whole_tables, guard, ..KernelVariant::new(hwrt, KernelSwitches::default(), features) };assert_eq!(declared(&v), want, "{v:?} in a layout {} room for the guard", if room { "with" } else { "without" });checked += 1;}}}}- assert_eq!(checked, 2 * 3 + 2 * 6 + 8);+ assert_eq!(checked, 3 * 3 + 3 * 6 + 8);}/// The native default has no loop guard, and the live passes are their file. Every variant the kernel's flags/// make is valid WGSL (naga, wgpu's front end): each traversal with no switch, each alone and all of them, by no- /// scene feature, each alone and all of them (units are software traversal's), with the uniform tables, and with- /// the loop guard. (The merged layout's: merged.rs.) Prints the default variants' SHA-256 (`--nocapture`).+ /// scene feature, each alone and all of them (units are software traversal's), with the uniform tables, with the+ /// tables read whole, and with the loop guard. (The merged layout's: merged.rs.) Prints the default variants'+ /// SHA-256 (`--nocapture`).#[test]fn every_kernel_variant_is_valid() {use sha2::{Digest, Sha256};@@ -3628,6 +3665,7 @@ mod tests {}let all_features = KernelVariant::new(hwrt, k, if hwrt { F_SOURCE & !F_UNITS } else { F_SOURCE });naga_valid(&kernel_wgsl(&template, &KernelVariant { uniform_tables: true, ..all_features }));+ naga_valid(&kernel_wgsl(&template, &KernelVariant { whole_tables: true, ..all_features }));naga_valid(&kernel_wgsl(&template, &KernelVariant { guard: Some(1 << 16), ..all_features }));}}@@ -3688,7 +3726,7 @@ mod tests {let desktop = GpuOptions::from_vars(&vars(&[]), false);assert_eq!(desktop, GpuOptions::default());assert_eq!(desktop.kernel, KernelSwitches { strict: false, cutout_lite: 0, last_direct: false, last_sun: false, light_pick: false });- assert!(!desktop.uniform_tables_on(false, false));+ assert!(!desktop.uniform_tables_on(false, false) && desktop.table_views_on(false, false));for hwrt in [false, true] {assert!(KernelVariant::new(hwrt, desktop.kernel, 0).flags().iter().all(|&(name, on)| on == (name == "hwrt" && hwrt)));}@@ -3697,16 +3735,26 @@ mod tests {// `sun`: the directional lights alone at the last vertex, in place of all of them, on either platform.let sun = GpuOptions::from_vars(&vars(&[("THREERT_LAST_DIRECT", "sun")]), true);assert_eq!((sun.kernel.last_direct, sun.kernel.last_sun), (false, true));- assert_eq!((android.uniform_tables, android.pipeline_cache.clone()), (None, None));- assert!(android.uniform_tables_on(false, true) && !android.uniform_tables_on(true, true));+ assert_eq!((android.uniform_tables, android.table_views, android.pipeline_cache.clone()), (None, None, None));+ // Android reads the tables whole (no views, so no uniform copies of four of them); with the views asked for,+ // the uniform copies as before.+ assert!(!android.table_views_on(false, true) && !android.uniform_tables_on(false, true) && !android.uniform_tables_on(true, true));+ let views = GpuOptions::from_vars(&vars(&[("THREERT_TABLE_VIEWS", "1")]), true);+ assert!(views.table_views_on(false, true) && views.uniform_tables_on(false, true) && !views.table_views_on(true, true));// Set: what is asked, on either platform.let off = GpuOptions::from_vars(&vars(&[("THREERT_UNIFORM_TABLES", "0"), ("THREERT_KERNEL_STRICT", "0"), ("THREERT_CUTOUT_LITE", "0"), ("THREERT_LAST_DIRECT", "0")]), true);assert_eq!((off.kernel, off.uniform_tables_on(false, true)), (KernelSwitches::default(), false));let on = GpuOptions::from_vars(&vars(&[("THREERT_UNIFORM_TABLES", "1"), ("THREERT_CUTOUT_LITE", "2"), ("THREERT_LIGHT_PICK", "1"), ("THREERT_PIPELINE_CACHE", "/data/cache/pipelines")]), false);assert!(on.uniform_tables_on(false, false) && !on.uniform_tables_on(true, false));+ // Elsewhere the views unless asked otherwise; without them no uniform tables, whatever is asked.+ assert!(on.table_views_on(false, false) && !on.table_views_on(true, false));+ let whole = GpuOptions::from_vars(&vars(&[("THREERT_TABLE_VIEWS", "0"), ("THREERT_UNIFORM_TABLES", "1")]), false);+ assert!(!whole.table_views_on(false, false) && !whole.uniform_tables_on(false, false));assert_eq!(on.kernel, KernelSwitches { strict: false, cutout_lite: 2, last_direct: false, last_sun: false, light_pick: true });assert_eq!(on.pipeline_cache.as_deref(), Some(std::path::Path::new("/data/cache/pipelines")));assert_eq!(GpuOptions::from_vars(&vars(&[("THREERT_PIPELINE_CACHE", "")]), true).pipeline_cache, None);+ // The light tiles: everywhere but Android unless asked.+ assert_eq!([light_tiles_of(None, false), light_tiles_of(None, true), light_tiles_of(Some("1"), true), light_tiles_of(Some("0"), false)], [true, false, true, false]);// (And the environment map's light sampling, which is the scene's preparation's: lib.rs `env_nee_on`.)assert_eq!([crate::env_nee_of(None, false), crate::env_nee_of(None, true), crate::env_nee_of(Some("1"), true), crate::env_nee_of(Some("0"), false)], [true, false, true, false]);}diff --git a/renderer/src/live/mod.rs b/renderer/src/live/mod.rsindex 72b3009..bb769ae 100644--- a/renderer/src/live/mod.rs+++ b/renderer/src/live/mod.rs@@ -1224,6 +1224,75 @@ mod instanced_tests {assert_eq!((r.m[0][3], r.m[1][3], r.p[0][3], r.p[1][3]), (3.0, 1.0, 2.0, 0.0), "moved: last frame's rows kept");}+ /// A wall, a small movable panel in front of it, and an emissive quad that lights both from the side; a camera.+ fn lit_world() -> World {+ let mut w = World::default();+ let mat = |color: f32, emissive: f32| serde_json::from_value(serde_json::json!({ "name": "m", "color": [color, color * 0.5, color], "opacity": 1, "metalness": 0, "roughness": 1, "emissive": [1, 1, 1], "emissiveIntensity": emissive, "doubleSided": true })).unwrap();+ w.set_material(1, mat(0.8, 0.0));+ w.set_material(5, mat(0.0, 40.0));+ let quad = |s: f32| Geometry { positions: vec![-s, -s, 0.0, s, -s, 0.0, s, s, 0.0, -s, s, 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![] };+ w.set_geometry(2, quad(1.0)).unwrap();+ w.set_geometry(3, quad(0.25)).unwrap();+ let mesh = |geometry, material, own_blas| Kind::Mesh { geometry, material, own_blas, materials: vec![] };+ // A wall, a small movable panel in front of it, and an emissive quad that lights both from the side.+ w.set_object(10, "wall".into(), None, mesh(2, 1, false), true, false).unwrap();+ w.set_object(11, "panel".into(), None, mesh(3, 1, true), true, true).unwrap();+ w.set_transform(11, Vec3::new(-0.4, 0.0, 0.5), glam::Quat::IDENTITY, Vec3::ONE).unwrap();+ w.set_object(12, "lamp".into(), None, mesh(3, 5, false), true, false).unwrap();+ w.set_transform(12, Vec3::new(0.6, 0.3, 1.5), glam::Quat::from_rotation_y(2.6), Vec3::ONE).unwrap();+ let cam = serde_json::from_value(serde_json::json!({ "fov": 50, "near": 0.1, "far": 100, "exposure": { "mode": "manual", "ev100": 0 } })).unwrap();+ w.set_object(4, "camera".into(), None, Kind::Camera(cam), true, false).unwrap();+ w.set_transform(4, Vec3::new(0.0, 0.0, 5.0), glam::Quat::IDENTITY, Vec3::ONE).unwrap();+ w.set_settings(crate::world::Settings { camera: Some(4), ..Default::default() });+ w+ }++ /// The tables read whole (`gpu::GpuOptions::table_views` off: what a device is opened with on Android), on this+ /// machine's GPU: the scene renders offline to the views' image bit for bit, and so does a live frame after an+ /// emissive object's power changed in place. (Skipped without a GPU, or where the layout is the merged one.)+ #[test]+ fn the_tables_read_whole_render_what_the_views_do() {+ let open = |views: bool| gpu::Gpu::new_with(gpu::GpuOptions { table_views: Some(views), ..Default::default() });+ let (views, whole) = match (open(true), open(false)) {+ (Ok(a), Ok(b)) => (a, b),+ (Err(e), _) | (_, Err(e)) => return eprintln!("skipped: {e}"),+ };+ if views.merged {+ return eprintln!("skipped: the merged layout reads the tables whole already");+ }+ assert!(whole.whole_tables && !views.whole_tables && !whole.uniform_tables);+ let w = lit_world();+ let presets = crate::default_presets_dir();+ let offline = |g: &gpu::Gpu| {+ let mut sc = crate::scene::build(&w, Path::new("."), &presets, None).unwrap();+ (sc.width, sc.height) = (64, 36);+ let prep = crate::prepare(g, &mut sc, &mut vec![]);+ let frame = g.render(&sc, &prep.tri_verts, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, crate::ltree::nodes_of(prep.light_tree.as_ref()), &prep.env, &prep.env_cdf, &prep.energy, prep.params, 16, &mut vec![]).unwrap();+ frame.color.iter().flatten().map(|v| v.to_bits()).collect::<Vec<u32>>()+ };+ let (a, b) = (offline(&views), offline(&whole));+ let lit = a.iter().filter(|v| f32::from_bits(**v) > 0.0).count();+ assert!(lit > a.len() / 16, "the scene is lit ({lit} of {} numbers)", a.len());+ let differ = a.iter().zip(&b).filter(|(x, y)| x != y).count();+ assert_eq!(differ, 0, "{differ} of {} numbers differ between the views and the tables read whole", a.len());+ // Live, lockstep: two frames, the lamp dimmed in place between them.+ let live = |g: gpu::Gpu, w: &mut World| {+ let mut core = LiveCore::new(g, w, Path::new("."), &presets, 64, 36).unwrap();+ core.fixed_dt = Some(1.0 / 30.0);+ w.take_changes();+ core.render(1, |_, _| {});+ w.set_power(12, 0.25).unwrap();+ assert!(!core.commit(w).unwrap(), "a power edit in place");+ core.render(1, |_, _| {});+ let _ = core.g.device.poll(wgpu::PollType::wait_indefinitely());+ core.read_hdr().unwrap().iter().map(|v| v.to_bits()).collect::<Vec<u32>>()+ };+ let (mut w2, mut w3) = (lit_world(), lit_world());+ let (x, y) = (live(views, &mut w2), live(whole, &mut w3));+ assert!(x.iter().any(|v| *v != 0), "the live frame has a picture");+ assert_eq!(x, y, "the live frames differ between the views and the tables read whole");+ }+/// The uniform tables (`gpu::GpuOptions::uniform_tables`: what a device is opened with on Android), on this/// machine's GPU: a lit scene with an instanced mesh renders offline to the default device's image, bit for bit;/// live, the four uniform buffers hold what their tables hold when a frame is traced, and after an edit in place@@ -1239,24 +1308,7 @@ mod instanced_tests {return eprintln!("skipped: the merged layout has no uniform tables");}assert!(uniform.uniform_tables && !plain.uniform_tables);- let mut w = World::default();- let mat = |color: f32, emissive: f32| serde_json::from_value(serde_json::json!({ "name": "m", "color": [color, color * 0.5, color], "opacity": 1, "metalness": 0, "roughness": 1, "emissive": [1, 1, 1], "emissiveIntensity": emissive, "doubleSided": true })).unwrap();- w.set_material(1, mat(0.8, 0.0));- w.set_material(5, mat(0.0, 40.0));- let quad = |s: f32| Geometry { positions: vec![-s, -s, 0.0, s, -s, 0.0, s, s, 0.0, -s, s, 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![] };- w.set_geometry(2, quad(1.0)).unwrap();- w.set_geometry(3, quad(0.25)).unwrap();- let mesh = |geometry, material, own_blas| Kind::Mesh { geometry, material, own_blas, materials: vec![] };- // A wall, a small movable panel in front of it, and an emissive quad that lights both from the side.- w.set_object(10, "wall".into(), None, mesh(2, 1, false), true, false).unwrap();- w.set_object(11, "panel".into(), None, mesh(3, 1, true), true, true).unwrap();- w.set_transform(11, Vec3::new(-0.4, 0.0, 0.5), glam::Quat::IDENTITY, Vec3::ONE).unwrap();- w.set_object(12, "lamp".into(), None, mesh(3, 5, false), true, false).unwrap();- w.set_transform(12, Vec3::new(0.6, 0.3, 1.5), glam::Quat::from_rotation_y(2.6), Vec3::ONE).unwrap();- let cam = serde_json::from_value(serde_json::json!({ "fov": 50, "near": 0.1, "far": 100, "exposure": { "mode": "manual", "ev100": 0 } })).unwrap();- w.set_object(4, "camera".into(), None, Kind::Camera(cam), true, false).unwrap();- w.set_transform(4, Vec3::new(0.0, 0.0, 5.0), glam::Quat::IDENTITY, Vec3::ONE).unwrap();- w.set_settings(crate::world::Settings { camera: Some(4), ..Default::default() });+ let mut w = lit_world();let presets = crate::default_presets_dir();// Offline: the same bytes.