Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

The raster experiment is removed (#269)

Yujia56057906887d
diff --git a/docs/MATERIAL_FUNCTIONS.md b/docs/MATERIAL_FUNCTIONS.md
index 61335c6..c508460 100644
--- a/docs/MATERIAL_FUNCTIONS.md
+++ b/docs/MATERIAL_FUNCTIONS.md
@@ -664,8 +664,7 @@ What procedural surfaces are, today (ROADMAP § 6 step 1):
- Not light-sampled: an emissive procedural surface lights others only through their BSDF rays (as emissive media).
- Always instances: moving a `ProceduralMesh` rewrites its record and TLAS transform, never rebuilds the scene; its
motion vectors come from the previous transform. Replacing its boxes or data (`needsUpdate`) rebuilds.
-- Live primary visibility is traced (the raster experiment draws triangles only), and a click picks the boxes (the CPU
- does not run the function).
+- A click picks the boxes (the CPU does not run the function).
Hits carry `PROC_BIT | material << 23 | box` as their triangle, the octahedral object-space normal (15 bits per
component) in u, the attribute in v and the mesh's record (pathtrace.wgsl `proc_hit`), so `surface()` takes them apart
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index d76c508..958b8dd 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -2879,6 +2879,16 @@ Mutations: 26. 25 failed a test there was; one, a texture put on a shelf too low
Found by review: a translucent particle's material given another function kept the kernel's old dispatch for the
translucency pass, which has its particles' functions alone; the kernel is made again where those are others.
+**The raster experiment is removed (2026-11-24, after it).** Primary visibility by rasterization (§ 1's decision
+experiment, `THREERT_RASTER=1`) stayed in the code after its verdict: a render pass of the world-space triangles,
+a texture in the kernel's second bind group, a parameter and a branch at every path's first hit. It drew nothing
+in a scene with a mesh since meshes became instances. All of it is gone; § 1 keeps the experiment's record and
+figures. The kernel's parameter has the frame's jitter and the "rays off" switch still (`jitter`).
+Tests: the "rays off" switch had none and has one (`rays_off_is_another_picture_and_on_again_the_first`: what was
+in shadow is lit, on again the picture is the first); three mutations of the parameter's places, one of which the
+test's first form let through. A live keyframe of a heavy interior reads as before, with and without the loop
+guard.
+
**A particle system is a mesh and an instance (2026-11-24).** Particles were world-space triangles of their own
kind: two a particle among the scene's dynamic triangles (the translucent ones after everything else, in a BLAS of
their own), a row a triangle, their emitters by a nominal area in the triangles' attributes, every size fixed when
diff --git a/docs/RUNTIME.md b/docs/RUNTIME.md
index 378a04f..59f4a23 100644
--- a/docs/RUNTIME.md
+++ b/docs/RUNTIME.md
@@ -2307,7 +2307,7 @@ on the device", and differs where it says so.
initialization) tells a driver's fault from the kernel's.
- **The pipeline cache** (`GpuOptions::pipeline_cache`, `THREERT_PIPELINE_CACHE=<directory>`; `pipeline_cache.rs`).
The driver compiles a kernel variant for about ten seconds. With a directory given, the device has a wgpu
- `PipelineCache` (Vulkan only), every compute pipeline of the engine and the raster pass's are made with it, and it
+ `PipelineCache` (Vulkan only), every compute pipeline of the engine is made with it, and it
is saved after a kernel variant, a scene's passes and the live passes are compiled. Opening a game a second time
went from 10.6 s to 0.4 s (the author's; on this source a scene's pipelines compile for 16 to 31 s the first time
and are there in under a second from the cache, below).
@@ -2366,8 +2366,8 @@ source under ThreeRT for Android 0.4.0, which sets `THREERT_PIPELINE_CACHE` and
figure.
- **Hardware against software traversal** (`THREERT_HWRT=0`, same size and bounce): Sunlit room 78 ms against
149 ms and Material balls 74 against 96 are faster without ray queries; OpenStrikeRT is 336 against 146. A ray
- query has a high fixed cost on this driver; ray queries stay the default. `THREERT_RASTER=1` (raster primary
- visibility): Sunlit room 136 against 149 ms.
+ query has a high fixed cost on this driver; ray queries stay the default. (Raster primary visibility, an
+ experiment since removed, read 136 against 149 ms in the Sunlit room.)
- **Not looked at on the device:** voxel worlds and procedural geometry (then `env_cdf`'s second half), particles, media,
a map with cutout foliage (`THREERT_CUTOUT_LITE`'s figures are the author's), `THREERT_ENV_NEE=1`, and the
motion vectors of moving objects (`prev_verts`): soldiers were looked at standing, not frame by frame in motion.
diff --git a/renderer/shaders/pathtrace.wgsl b/renderer/shaders/pathtrace.wgsl
index 654d053..5b2e590 100644
--- a/renderer/shaders/pathtrace.wgsl
+++ b/renderer/shaders/pathtrace.wgsl
@@ -112,7 +112,7 @@ struct Params {
fog_color: vec4<f32>, // ambient inscattering radiance, max opacity
vol: vec4<f32>, // volumetric scattering albedo (0 = off), HG anisotropy, extinction scale in range, -
vol2: vec4<f32>, // volumetric albedo tint rgb, range (m, 0 = unlimited)
- raster: vec4<f32>, // live: primary visibility from the raster pass (1 = on), this frame's sub-pixel jitter x, y (every camera ray's); ray tracing off (1)
+ jitter: vec4<f32>, // live: this frame's sub-pixel jitter x, y (every camera ray's); ray tracing off (1); -
cache: vec4<f32>, // live radiance cache (1 = on), history cap in samples, history cap in frames, -
motion: vec4<f32>, // live motion vectors: 1 = on, -, -, - (first dynamic triangle: group_first[1].x)
group_first: array<vec4<u32>, 2>, // first global triangle of each traversal group ([1].x = the first dynamic one)
@@ -450,7 +450,7 @@ fn inst_attr(r: Instance, a: TriAttr) -> TriAttr {
// Path vertex index of the current shading point (cheaper procedural detail / fewer candidates past the first hit).
var<private> cur_depth: u32;
-// Live "ray tracing off" (P.raster.w, LiveCore::rays): set once the camera's own ray has found its surface. From then
+// Live "ray tracing off" (P.jitter.z, LiveCore::rays): set once the camera's own ray has found its surface. From then
// on `trace` reports a miss, so nothing is shadowed, a bounce sees the sky and a mirror reflects the sky: what a
// rasterizer without shadow maps draws, on any GPU, from the same scene and the same shading. The switch is a uniform:
// no kernel is rebuilt to flip it.
@@ -746,24 +746,6 @@ fn proc_normal(h: Hit) -> vec3<f32> {
return normalize(vec3<f32>(dot(r.n0.xyz, n), dot(r.n1.xyz, n), dot(r.n2.xyz, n)));
}
-// Live primary visibility rasterized by the viewport (triangle index + 1, 0 = sky) at this frame's jitter.
-@group(1) @binding(0) var vis_tex: texture_2d<u32>;
-
-// The camera ray's hit on a known triangle (two-sided, no t range): the raster pass already resolved visibility.
-fn tri_hit(ti: u32, o: vec3<f32>, d: vec3<f32>) -> Hit {
- let ix = tri_indices(ti) * VERTEX_VEC4;
- let a = vertices[ix.x].xyz;
- let e1 = vertices[ix.y].xyz - a;
- let e2 = vertices[ix.z].xyz - a;
- let p = cross(d, e2);
- let det = dot(e1, p);
- let inv = 1.0 / select(det, 1e-20, abs(det) < 1e-20);
- let s = o - a;
- let u = dot(s, p) * inv;
- let q = cross(s, e1);
- return Hit(dot(e2, q) * inv, ti, clamp(u, 0.0, 1.0), clamp(dot(d, q) * inv, 0.0, 1.0), NO_INST, ti);
-}
-
// The software BVH walk (without `hwrt`: trace_hw.wgsl's traversal is the hardware's).
@if(!hwrt) fn ray_aabb(o: vec3<f32>, inv_d: vec3<f32>, bmin: vec3<f32>, bmax: vec3<f32>, tmax: f32) -> f32 {
@@ -3682,7 +3664,7 @@ fn finish(@builtin(global_invocation_id) gid: vec3<u32>) {
let depth = (fl >> 8u) & 0xffu;
cur_depth = depth;
mirror_path = (fl & DF_MIRROR) != 0u;
- rays_off = LIVE && P.raster.w > 0.5;
+ rays_off = LIVE && P.jitter.z > 0.5;
if (has(F_LISTS)) {
lt_list = r0.z & ~(LT_LIST - 1u);
lt_list_n = r0.z & (LT_LIST - 1u);
@@ -3752,11 +3734,11 @@ fn guide_hit(origin: vec3<f32>, dir: vec3<f32>, footprint: f32, through_glass: b
// Rough surfaces have no single reflected point. A stochastic second-bounce hit would move
// their guide even when both the object and camera stand still.
accum[q].spec.w = 0.0;
- if (px.color.w > 0.0 && rough < MIRROR_ROUGHNESS && P.raster.w == 0.0 &&
+ if (px.color.w > 0.0 && rough < MIRROR_ROUGHNESS && P.jitter.z == 0.0 &&
(any(specular.rgb > vec3<f32>(0.005)) || diffuse.w > 0.0)) {
cur_depth = 1u;
mirror_path = true;
- let ndc = ((vec2<f32>(gid.xy) + P.raster.yz) / vec2<f32>(P.size.xy) * 2.0 - 1.0) * vec2<f32>(1.0, -1.0);
+ let ndc = ((vec2<f32>(gid.xy) + P.jitter.xy) / vec2<f32>(P.size.xy) * 2.0 - 1.0) * vec2<f32>(1.0, -1.0);
let d = normalize(P.cam_fwd.xyz + P.cam_right.xyz * ndc.x * P.cam_pos.w * P.cam_fwd.w + P.cam_up.xyz * ndc.y * P.cam_pos.w);
let x = P.cam_pos.xyz + d * px.color.w;
let width = px.color.w * 2.0 * P.cam_pos.w / lod_height();
@@ -3860,7 +3842,7 @@ fn media_composite(@builtin(global_invocation_id) gid: vec3<u32>) {
cur_depth = 0u;
mirror_path = false;
var px = accum[pix];
- let ndc = vec2<f32>((f32(gid.x) + P.raster.y) / f32(w) * 2.0 - 1.0, 1.0 - (f32(gid.y) + P.raster.z) / f32(h) * 2.0);
+ let ndc = vec2<f32>((f32(gid.x) + P.jitter.x) / f32(w) * 2.0 - 1.0, 1.0 - (f32(gid.y) + P.jitter.y) / f32(h) * 2.0);
let d = normalize(P.cam_fwd.xyz + P.cam_right.xyz * (ndc.x * P.cam_pos.w * P.cam_fwd.w) + P.cam_up.xyz * (ndc.y * P.cam_pos.w));
let ft = px.color.w;
let mm = media_march(P.cam_pos.xyz, d, select(1.0e30, ft, ft > 0.0), true, rng_dim(D_MEDIA));
@@ -3921,15 +3903,13 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
cur_depth = 0u;
let cam = rng4(rng_dim(D_CAMERA));
- // Raster primary: one visibility sample per pixel at the frame's jitter (lens sampling would need its own rays).
- let raster = LIVE && P.raster.x > 0.5 && P.cam_right.w <= 0.0;
// Live: one sub-pixel jitter a frame for the whole image (live/frame.rs: Halton 2, 3), which the temporal upscaler
- // resolves (live.wgsl `upscale`) and the raster pass draws at. Offline, every sample draws its own.
+ // resolves (live.wgsl `upscale`). Offline, every sample draws its own.
var jx = cam.x;
var jy = cam.y;
if (LIVE) {
- jx = P.raster.y;
- jy = P.raster.z;
+ jx = P.jitter.x;
+ jy = P.jitter.y;
}
let ndc = vec2<f32>((f32(gid.x) + jx) / f32(w) * 2.0 - 1.0, 1.0 - (f32(gid.y) + jy) / f32(h) * 2.0);
var d = normalize(P.cam_fwd.xyz + P.cam_right.xyz * (ndc.x * P.cam_pos.w * P.cam_fwd.w) + P.cam_up.xyz * (ndc.y * P.cam_pos.w));
@@ -3995,23 +3975,9 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
mirror_path = false;
for (var depth = 0u; depth <= P.counts.z; depth++) {
cur_depth = depth;
- var hit: Hit;
- if (raster && depth == 0u) {
- let id = textureLoad(vis_tex, vec2<i32>(gid.xy), 0).x;
- if (id == 0u) {
- hit = Hit(INF, 0xffffffffu, 0.0, 0.0, NO_INST, 0u);
- } else {
- hit = tri_hit(id - 1u, o, d);
- // The raster pass draws cutout triangles whole: the alpha test decides here, else trace past them.
- if (has(F_MASKED) && (tri_flags(hit.part) & TRI_MASKED) != 0u && !alpha_pass(hit.tri, NO_INST, hit.part, hit.u, hit.v, hit.t)) {
- hit = trace(o, d, INF, TRACE_CLOSEST);
- }
- }
- } else {
- hit = trace(o, d, INF, TRACE_CLOSEST);
- }
+ var hit = trace(o, d, INF, TRACE_CLOSEST);
// Ray tracing off: the camera ray above was the last one traced for this pixel.
- if (depth == 0u) { rays_off = LIVE && P.raster.w > 0.5; }
+ if (depth == 0u) { rays_off = LIVE && P.jitter.z > 0.5; }
if (has(F_FOG) && P.fog.x > 0.0) {
// Height fog on every segment (attenuation + ambient inscattering); lit volumetric scattering on camera rays.
let t0 = select(0.0, P.fog.w, depth == 0u);
diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rs
index f7db396..a01d7bd 100644
--- a/renderer/src/gpu.rs
+++ b/renderer/src/gpu.rs
@@ -78,14 +78,13 @@ pub struct Gpu {
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
warming: std::sync::Arc<std::sync::Mutex<std::collections::HashSet<(u32, u64, u32)>>>,
layout: wgpu::BindGroupLayout,
- /// Group 1, the live viewport's: primary visibility (texture_2d<u32>), the radiance cache (`CacheBuffers`) and
- /// what the live passes read of a trace (`KernelBufs`). Offline renders bind `no_vis` (1x1 texture `no_vis_view`,
- /// one-entry cache).
- pub vis_layout: wgpu::BindGroupLayout,
- pub no_vis: wgpu::BindGroup,
- /// `no_vis`'s buffers (the merged layout: an offline kernel's source is written for their lengths).
- no_vis_bufs: KernelBufs,
- pub no_vis_view: wgpu::TextureView,
+ /// Group 1, the live viewport's: the radiance cache (`CacheBuffers`) and what the live passes read of a trace
+ /// (`KernelBufs`). Offline renders bind `no_live` (a one-entry cache).
+ pub live_layout: wgpu::BindGroupLayout,
+ pub no_live: wgpu::BindGroup,
+ /// `no_live`'s buffers (the merged layout: an offline kernel's source is written for their lengths).
+ #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
+ no_live_bufs: KernelBufs,
/// Binding 19 of scenes without density grids (one cell), and the grid pass's bind group layout (grid_sim.wgsl).
no_grid_view: wgpu::TextureView,
grid_layout: wgpu::BindGroupLayout,
@@ -101,10 +100,11 @@ pub struct Gpu {
/// pipelines (`translucent`, `volume_train`) by the kernel's variant key.
tl_layout: Option<wgpu::BindGroupLayout>,
tl_pipeline_layout: Option<wgpu::PipelineLayout>,
- /// Its group 1: `vis_layout` without `finish`'s records, which the pass does not read (with them its three groups
- /// are one buffer past Metal's 29 a stage), and `no_vis` made for it.
- pub tl_vis_layout: Option<wgpu::BindGroupLayout>,
- no_vis_tl: Option<wgpu::BindGroup>,
+ /// Its group 1: `live_layout` without `finish`'s records, which the pass does not read (with them its three groups
+ /// are one buffer past Metal's 29 a stage), and `no_live` made for it.
+ pub tl_live_layout: Option<wgpu::BindGroupLayout>,
+ #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
+ no_live_tl: Option<wgpu::BindGroup>,
tl_pipelines: PipelineMap<(u32, u64, bool, u32), TranslucentPipelines>,
/// The kernel's passes beside `main` (`kernel_pass`) by kernel variant and entry point.
kernel_passes: PipelineMap<(u32, u64, &'static str, u32)>,
@@ -143,7 +143,7 @@ pub struct Params {
pub fog_color: [f32; 4], // ambient inscattering radiance rgb, max opacity
pub vol: [f32; 4], // volumetric scattering albedo (0 = off), phase anisotropy, extinction scale in range, -
pub vol2: [f32; 4], // volumetric albedo tint rgb, range (m, 0 = unlimited)
- pub raster: [f32; 4], // live primary visibility from the raster pass (1 = on), sub-pixel jitter x, y; ray tracing off (1)
+ pub jitter: [f32; 4], // live: this frame's sub-pixel jitter x, y (every camera ray's); ray tracing off (1); -
pub cache: [f32; 4], // live radiance cache (1 = on), history cap in samples, history cap in frames, -
pub motion: [f32; 4], // live motion vectors: 1 = on, -, -, - (first dynamic triangle: group_first[1][0])
/// First global triangle of each traversal group (`Prepared::groups`; group 4 = the first dynamic one). Hardware
@@ -385,11 +385,10 @@ pub(crate) fn kernel_layout_entries(shape: LayoutShape) -> [Vec<wgpu::BindGroupL
if hwrt {
scene.push(layout_entry(ACC_BINDING, ACCELERATION_STRUCTURE));
}
- // Group 1: the raster pass's visibility; then, merged, the one buffer (`heap::Live`, the loop guard's count in
- // it); as written, the radiance cache's three, the light tiles' lists, the specular rays, the motion vectors, the
+ // Group 1: merged, the one buffer (`heap::Live`, the loop guard's count in it); as written, the radiance cache's three, the light tiles' lists, the specular rays, the motion vectors, the
// direct light, the pixels left for `finish`, and the loop guard's count where a kernel of this device may have
// the guard (one without it does not name the binding).
- let mut live = vec![layout_entry(0, wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Uint, view_dimension: wgpu::TextureViewDimension::D2, multisampled: false })];
+ let mut live = vec![];
if merged {
live.push(layout_entry(LIVE_BINDING, write));
} else {
@@ -1732,21 +1731,20 @@ pub(crate) fn live_sizes(entries: u64, refl: u64, motion: u64, direct: u64, list
[CACHE_SIZE * 4, CACHE_SIZE * 32, crate::merged::GUARD_WORDS as u64 * 4, entries * 32, refl, motion, direct, lists]
}
-/// Group-1 bind group of the kernel: a primary-visibility texture, the radiance cache and the
-/// reflection resolve's inputs (`KernelBufs`); in the merged layout, the texture and the one buffer.
-/// `deferred`: with `finish`'s records (`vis_layout`; the translucency pass's `tl_vis_layout` is without).
-pub fn vis_bind_group(d: &wgpu::Device, layout: &wgpu::BindGroupLayout, view: &wgpu::TextureView, b: &KernelBufs, deferred: bool) -> wgpu::BindGroup {
+/// Group-1 bind group of the kernel: the radiance cache and the reflection resolve's inputs (`KernelBufs`); in the
+/// merged layout, the one buffer.
+/// `deferred`: with `finish`'s records (`live_layout`; the translucency pass's `tl_live_layout` is without).
+pub fn live_bind_group(d: &wgpu::Device, layout: &wgpu::BindGroupLayout, b: &KernelBufs, deferred: bool) -> wgpu::BindGroup {
fn e(binding: u32, b: &Buf) -> wgpu::BindGroupEntry<'_> {
wgpu::BindGroupEntry { binding, resource: b.binding() }
}
- let tex = wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(view) };
match &b.merged {
- Some(heap) => d.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("vis"), layout, entries: &[tex, wgpu::BindGroupEntry { binding: crate::merged::LIVE_BINDING, resource: heap.buffer.as_entire_binding() }] }),
+ Some(heap) => d.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("live"), layout, entries: &[wgpu::BindGroupEntry { binding: crate::merged::LIVE_BINDING, resource: heap.buffer.as_entire_binding() }] }),
None => {
- let mut entries = vec![tex, e(1, &b.cache.keys), e(2, &b.cache.acc), e(3, &b.cache.val), e(crate::merged::LISTS_BINDING, &b.lists), e(5, &b.refl), e(6, &b.motion), e(7, &b.direct)];
+ let mut entries = vec![e(1, &b.cache.keys), e(2, &b.cache.acc), e(3, &b.cache.val), e(crate::merged::LISTS_BINDING, &b.lists), e(5, &b.refl), e(6, &b.motion), e(7, &b.direct)];
entries.extend(b.deferred.as_ref().filter(|_| deferred).map(|r| e(crate::merged::DEFERRED_BINDING, r)));
entries.extend(b.guard.as_ref().map(|g| e(crate::merged::GUARD_BINDING, g)));
- d.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("vis"), layout, entries: &entries })
+ d.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("live"), layout, entries: &entries })
}
}
}
@@ -2273,20 +2271,9 @@ impl Gpu {
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, whole_tables, guard: guard_room(hwrt) });
+ let [entries, live_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 {
- label: Some("no vis"),
- size: wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 },
- mip_level_count: 1,
- sample_count: 1,
- dimension: wgpu::TextureDimension::D2,
- format: wgpu::TextureFormat::R32Uint,
- usage: wgpu::TextureUsages::TEXTURE_BINDING,
- view_formats: &[],
- });
- let no_vis_view = one.create_view(&Default::default());
+ let live_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("live"), entries: &live_entries });
let no_grid_view = grid_texture(&device, "no grid", [1, 1, 1], false).create_view(&Default::default());
let grid_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("grid sim"),
@@ -2300,15 +2287,15 @@ impl Gpu {
layout_entry(6, storage_buffer(true)),
],
});
- let no_vis_bufs = KernelBufs::new(&device, merged, guard_room(hwrt), 1, 64, 64, 64, 64);
- let no_vis = vis_bind_group(&device, &vis_layout, &no_vis_view, &no_vis_bufs, true);
- let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(&layout), Some(&vis_layout)], immediate_size: 0 });
- let (tl_layout, tl_pipeline_layout, tl_vis_layout, no_vis_tl) = if hwrt {
+ let no_live_bufs = KernelBufs::new(&device, merged, guard_room(hwrt), 1, 64, 64, 64, 64);
+ let no_live = live_bind_group(&device, &live_layout, &no_live_bufs, true);
+ let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(&layout), Some(&live_layout)], immediate_size: 0 });
+ let (tl_layout, tl_pipeline_layout, tl_live_layout, no_live_tl) = if hwrt {
let l = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("translucent"), entries: &tl_entries });
- let tl_vis: Vec<_> = vis_entries.iter().filter(|e| merged || e.binding != crate::merged::DEFERRED_BINDING).copied().collect();
- let vl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("vis, translucent"), entries: &tl_vis });
+ let tl_vis: Vec<_> = live_entries.iter().filter(|e| merged || e.binding != crate::merged::DEFERRED_BINDING).copied().collect();
+ let vl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("live, translucent"), entries: &tl_vis });
let tpl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("translucent"), bind_group_layouts: &[Some(&layout), Some(&vl), Some(&l)], immediate_size: 0 });
- let nv = vis_bind_group(&device, &vl, &no_vis_view, &no_vis_bufs, false);
+ let nv = live_bind_group(&device, &vl, &no_live_bufs, false);
(Some(l), Some(tpl), Some(vl), Some(nv))
} else {
(None, None, None, None)
@@ -2318,7 +2305,7 @@ impl Gpu {
dlss_sdk,
#[cfg(dlss)]
dlss_rr,
- instance, adapter, timestamps, device, queue, adapter_info, uniform_tables, whole_tables, switches, approx, approx_default: approx, pipeline_cache, source: std::sync::Arc::new(src), module, merged, modules: Default::default(), pipeline_layout: pl, pipelines: Default::default(), warming: Default::default(), layout, vis_layout, no_vis, no_vis_bufs, no_vis_view, no_grid_view, grid_layout, fill: Default::default(), hwrt, pages: Default::default(), streams: 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(),
+ instance, adapter, timestamps, device, queue, adapter_info, uniform_tables, whole_tables, switches, approx, approx_default: approx, pipeline_cache, source: std::sync::Arc::new(src), module, merged, modules: Default::default(), pipeline_layout: pl, pipelines: Default::default(), warming: Default::default(), layout, live_layout, no_live, no_live_bufs, no_grid_view, grid_layout, fill: Default::default(), hwrt, pages: Default::default(), streams: Default::default(), tl_layout, tl_pipeline_layout, tl_live_layout, no_live_tl, tl_pipelines: Default::default(), kernel_passes: Default::default(), proc_cache: Default::default(), proc_blases: Default::default(),
})
}
@@ -4148,14 +4135,14 @@ impl Gpu {
let mut p = base;
p.size[2] = s;
up.place(&mut p);
- self.no_vis_bufs.place(&mut p);
+ self.no_live_bufs.place(&mut p);
self.queue.write_buffer(&up.params, 0, bytemuck::bytes_of(&p));
let mut enc = d.create_command_encoder(&Default::default());
{
let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("translucent"), timestamp_writes: None });
pass.set_pipeline(&pipeline);
pass.set_bind_group(0, &up.bg, &[]);
- pass.set_bind_group(1, self.no_vis_tl.as_ref().unwrap(), &[]);
+ pass.set_bind_group(1, self.no_live_tl.as_ref().unwrap(), &[]);
pass.set_bind_group(2, &tbg, &[]);
pass.dispatch_workgroups(w.div_ceil(8), h.div_ceil(8), 1);
}
@@ -4232,7 +4219,7 @@ impl Gpu {
}
let (b_accum, b_params, bg) = (&up.accum, &up.params, &up.bg);
let accum_size = b_accum.size();
- let stopped_before = self.guard_trips(&self.no_vis_bufs, &up.kernel)?;
+ let stopped_before = self.guard_trips(&self.no_live_bufs, &up.kernel)?;
let t1 = Instant::now();
@@ -4248,14 +4235,14 @@ impl Gpu {
let mut p = base;
p.size[2] = s + k;
up.place(&mut p);
- self.no_vis_bufs.place(&mut p);
+ self.no_live_bufs.place(&mut p);
self.queue.write_buffer(b_params, 0, bytemuck::bytes_of(&p));
let mut enc = d.create_command_encoder(&Default::default());
{
let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { label: None, timestamp_writes: None });
pass.set_pipeline(&pipeline);
pass.set_bind_group(0, bg, &[]);
- pass.set_bind_group(1, &self.no_vis, &[]);
+ pass.set_bind_group(1, &self.no_live, &[]);
pass.dispatch_workgroups(w.div_ceil(8), h.div_ceil(8), 1);
}
self.queue.submit([enc.finish()]);
@@ -4265,7 +4252,7 @@ impl Gpu {
}
timings.push(("trace_ms".into(), t1.elapsed().as_secs_f64() * 1000.0));
// The loop guard, if the kernel has it: a render in which it stopped a loop has wrong pixels, and is an error.
- if let (Some(before), Some(now)) = (stopped_before, self.guard_trips(&self.no_vis_bufs, &up.kernel)?) {
+ if let (Some(before), Some(now)) = (stopped_before, self.guard_trips(&self.no_live_bufs, &up.kernel)?) {
if now != before {
return Err(anyhow!("the loop guard stopped {} of the kernel's invocations at {} iterations (THREERT_LOOP_GUARD): a traversal that does not end on this scene's data, or a limit too low for it", now.wrapping_sub(before), loop_guard_of(up.kernel.features & F_UNITS != 0).unwrap_or(0)));
}
diff --git a/renderer/src/lib.rs b/renderer/src/lib.rs
index 2cc0a10..40181d9 100644
--- a/renderer/src/lib.rs
+++ b/renderer/src/lib.rs
@@ -845,7 +845,7 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut
fog_color: [0.0; 4],
vol: [0.0; 4],
vol2: [0.0; 4],
- raster: [0.0; 4],
+ jitter: [0.0; 4],
cache: [0.0; 4],
// (z, w: software traversal's units: the top tree's root and their count, as bits; trace_units.wgsl. y is
// `render --signals`'.)
diff --git a/renderer/src/live/frame.rs b/renderer/src/live/frame.rs
index 669ba83..3fa9fbf 100644
--- a/renderer/src/live/frame.rs
+++ b/renderer/src/live/frame.rs
@@ -1,5 +1,5 @@
//! One frame of the live view (`LiveCore::render`): the trace, the live passes, the radiance cache's and the media's
-//! training, the raster visibility pass, and the GPU timing and profile.
+//! training, and the GPU timing and profile.
use super::*;
@@ -21,15 +21,15 @@ pub(super) const TIMER_SLOTS: usize = 4;
/// Gap (ms) past which a slot's post pass is not its trace's frame's (`frame_gpu_ms`).
pub(super) const TIMER_GAP_MS: f32 = 2.0;
-/// A frame's GPU time (ms) from its slot's timestamps (trace, post, raster, particle pass pairs; zero: not run): from
-/// its first pass (particles, raster or trace) to the end of its post pass. The post pass follows the trace's command
+/// A frame's GPU time (ms) from its slot's timestamps (trace, post, a free pair, particle pass pairs; zero: not run):
+/// from its first pass (particles or trace) to the end of its post pass. The post pass follows the trace's command
/// buffer within ~0.2 ms, after the frame's further samples (`spp` - 1 more traces, untimed, each about as long as
/// the first). In 2–3 % of the crowd scene's frames (Metal) a slot read the post pair of the frame that used the slot
/// next, 4 frames on: the span then read 70–80 ms while frames came every 16.7 ms. A post pass that begins more than
/// TIMER_GAP_MS past where those traces would end (twice their length) is not this frame's: the frame is counted as
/// its passes, the further traces at the first one's length.
pub(super) fn frame_gpu_ms(t: &[u64; 8], spp: u32, period_ns: f32) -> Option<f32> {
- let start = [t[6], t[4], t[0]].into_iter().filter(|&v| v > 0).min()?;
+ let start = [t[6], t[0]].into_iter().filter(|&v| v > 0).min()?;
if t[3] <= start {
return None;
}
@@ -45,7 +45,7 @@ impl FrameTimer {
pub(super) fn new(d: &wgpu::Device) -> FrameTimer {
let n = TIMER_SLOTS as u64;
FrameTimer {
- // Per slot: trace pass begin / end, post pass begin / end, raster pass begin / end, particle pass begin / end
+ // Per slot: trace pass begin / end, post pass begin / end, a free pair, particle pass begin / end
// (Metal writes a pass's timestamps in pairs).
queries: d.create_query_set(&wgpu::QuerySetDescriptor { label: Some("frame timer"), ty: wgpu::QueryType::Timestamp, count: (n * 8) as u32 }),
resolve: d.create_buffer(&wgpu::BufferDescriptor { label: None, size: n * 4 * wgpu::QUERY_RESOLVE_BUFFER_ALIGNMENT, usage: wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false }),
@@ -79,103 +79,6 @@ impl FrameTimer {
}
}
-/// Primary visibility by rasterization (the decision experiment of docs/ROADMAP.md § 1): every triangle drawn into a
-/// triangle-index target (+ depth) at the frame's sub-pixel jitter; the kernel starts each live path at that triangle
-/// instead of tracing the camera ray. `live --raster` / THREERT_RASTER=1.
-pub(super) struct Raster {
- pub(super) pipeline: wgpu::RenderPipeline,
- pub(super) layout: wgpu::BindGroupLayout,
- pub(super) uniform: wgpu::Buffer,
- pub(super) vis: wgpu::TextureView,
- pub(super) depth: wgpu::TextureView,
-}
-
-pub(super) const RASTER_WGSL: &str = r#"
-struct R { pos: vec4<f32>, fwd: vec4<f32>, right: vec4<f32>, up: vec4<f32>, jit: vec4<f32> }; // pos.w = tan(fov/2), fwd.w = aspect, right.w = the indices' first word, jit = ndc offset xy, near
-@group(0) @binding(0) var<uniform> r: R;
-@group(0) @binding(1) var<storage, read> vertices: array<vec4<f32>>; // a vertex: three rows, the first (position, u) (kernel layout)
-@group(0) @binding(2) var<storage, read> words: array<u32>; // the triangles' indices, three a triangle
-struct V { @builtin(position) p: vec4<f32>, @location(0) @interpolate(flat) id: u32 };
-@vertex fn vs(@builtin(vertex_index) vi: u32) -> V {
- let ti = vi / 3u;
- let p = vertices[words[bitcast<u32>(r.right.w) + vi] * 3u].xyz;
- let d = p - r.pos.xyz;
- let z = dot(d, r.fwd.xyz);
- // Reversed infinite depth: near / z.
- return V(vec4<f32>(dot(d, r.right.xyz) / (r.pos.w * r.fwd.w) + r.jit.x * z, dot(d, r.up.xyz) / r.pos.w + r.jit.y * z, r.jit.z, z), ti + 1u);
-}
-@fragment fn fs(v: V) -> @location(0) u32 { return v.id; }
-"#;
-
-impl Raster {
- pub(super) fn new(g: &gpu::Gpu, w: u32, h: u32) -> Raster {
- let d = &g.device;
- let module = d.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("raster"), source: wgpu::ShaderSource::Wgsl(RASTER_WGSL.into()) });
- let layout = d.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
- label: Some("raster"),
- entries: &[
- wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStages::VERTEX, ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None }, count: None },
- wgpu::BindGroupLayoutEntry { binding: 1, visibility: wgpu::ShaderStages::VERTEX, ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Storage { read_only: true }, has_dynamic_offset: false, min_binding_size: None }, count: None },
- wgpu::BindGroupLayoutEntry { binding: 2, visibility: wgpu::ShaderStages::VERTEX, ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Storage { read_only: true }, has_dynamic_offset: false, min_binding_size: None }, count: None },
- ],
- });
- let pl = d.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(&layout)], immediate_size: 0 });
- let pipeline = d.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
- label: Some("raster vis"),
- layout: Some(&pl),
- vertex: wgpu::VertexState { module: &module, entry_point: Some("vs"), buffers: &[], compilation_options: Default::default() },
- fragment: Some(wgpu::FragmentState { module: &module, entry_point: Some("fs"), targets: &[Some(wgpu::TextureFormat::R32Uint.into())], compilation_options: Default::default() }),
- primitive: wgpu::PrimitiveState { cull_mode: None, ..Default::default() },
- depth_stencil: Some(wgpu::DepthStencilState { format: wgpu::TextureFormat::Depth32Float, depth_write_enabled: Some(true), depth_compare: Some(wgpu::CompareFunction::Greater), stencil: Default::default(), bias: Default::default() }),
- multisample: Default::default(),
- multiview_mask: None,
- cache: g.cache(),
- });
- g.save_pipeline_cache();
- let tex = |format, usage| {
- d.create_texture(&wgpu::TextureDescriptor { label: Some("raster"), size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, format, usage, view_formats: &[] })
- .create_view(&Default::default())
- };
- let vis = tex(wgpu::TextureFormat::R32Uint, wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING);
- let depth = tex(wgpu::TextureFormat::Depth32Float, wgpu::TextureUsages::RENDER_ATTACHMENT);
- let uniform = d.create_buffer(&wgpu::BufferDescriptor { label: Some("raster"), size: 80, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
- Raster { pipeline, layout, uniform, vis, depth }
- }
-
- /// Records the visibility pass for the scene's first `tris` triangles (their vertices; their indices in
- /// the words' heap) at internal size (iw, ih), sampling at jitter (jx, jy).
- #[allow(clippy::too_many_arguments)]
- pub(super) fn record(&self, g: &gpu::Gpu, e: &mut wgpu::CommandEncoder, vertices: &wgpu::Buffer, words: &crate::heap::Heap<crate::heap::Stream>, tris: u32, cam: &Camera, aspect: f32, (iw, ih): (u32, u32), (jx, jy): (f32, f32), timestamps: Option<wgpu::RenderPassTimestampWrites>) {
- let u: [[f32; 4]; 5] = [
- [cam.pos.x, cam.pos.y, cam.pos.z, cam.tan_half_fov],
- [cam.fwd.x, cam.fwd.y, cam.fwd.z, aspect],
- [cam.right.x, cam.right.y, cam.right.z, f32::from_bits((words.at(crate::heap::Stream::Indices) / 4) as u32)],
- [cam.up.x, cam.up.y, cam.up.z, 0.0],
- // Pixel centres sample at +0.5; shift the image so they sample at the jittered position instead.
- [2.0 * (0.5 - jx) / iw as f32, -2.0 * (0.5 - jy) / ih as f32, 0.01, 0.0],
- ];
- g.queue.write_buffer(&self.uniform, 0, bytemuck::cast_slice(&u));
- let bg = g.device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: None,
- layout: &self.layout,
- entries: &[wgpu::BindGroupEntry { binding: 0, resource: self.uniform.as_entire_binding() }, wgpu::BindGroupEntry { binding: 1, resource: vertices.as_entire_binding() }, wgpu::BindGroupEntry { binding: 2, resource: words.buffer.as_entire_binding() }],
- });
- let mut pass = e.begin_render_pass(&wgpu::RenderPassDescriptor {
- label: Some("raster vis"),
- color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: &self.vis, depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), store: wgpu::StoreOp::Store } })],
- depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { view: &self.depth, depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(0.0), store: wgpu::StoreOp::Discard }), stencil_ops: None }),
- timestamp_writes: timestamps,
- occlusion_query_set: None,
- multiview_mask: None,
- });
- pass.set_viewport(0.0, 0.0, iw as f32, ih as f32, 0.0, 1.0);
- pass.set_scissor_rect(0, 0, iw, ih);
- pass.set_pipeline(&self.pipeline);
- pass.set_bind_group(0, &bg, &[]);
- pass.draw(0..tris * 3, 0..1);
- }
-}
-
/// The live kernel's world-space radiance cache (docs/ROADMAP.md § 1, step 1): its buffers and per-frame resolve.
pub(super) struct RadianceCache {
pub(super) bufs: gpu::CacheBuffers,
@@ -392,7 +295,7 @@ impl LiveCore {
let media_composite = media.then(|| g.kernel_pass(kernel, "media_composite"));
// The pixels a sample's trace leaves at the radiance cache (pathtrace.wgsl `finish`).
let finish = self.targets.kernel.deferred.as_ref().filter(|_| self.cache.is_some()).map(|d| (g.kernel_pass(kernel, "finish"), d));
- // This frame's sub-pixel jitter (Halton 2, 3), every camera ray's and the raster visibility pass's: 8 phases at
+ // This frame's sub-pixel jitter (Halton 2, 3), every camera ray's: 8 phases at
// full resolution, as many more as an output pixel has fewer traced ones (8 / scale^2: the upscaler needs each
// output pixel visited), in the 12 bits a side the samples carry it in.
let jitter = if reconstruction.unjittered() {
@@ -424,8 +327,7 @@ impl LiveCore {
if let Some(u) = &self.sc.up.units {
(p.motion[2], p.motion[3]) = (f32::from_bits(u.layout.top_first), f32::from_bits(u.count));
}
- p.raster = [(self.raster.is_some() && !self.sc.instanced) as u32 as f32, jitter.0, jitter.1, 0.0];
- p.raster[3] = if self.rays { 0.0 } else { 1.0 };
+ p.jitter = [jitter.0, jitter.1, if self.rays { 0.0 } else { 1.0 }, 0.0];
if moving {
// The kernel finds the first dynamic triangle in Params::group_first (group 4), a u32.
p.motion[0] = 1.0;
@@ -450,8 +352,7 @@ impl LiveCore {
self.targets.kernel.place(&mut p);
g.queue.write_buffer(&self.sc.up.params, 0, bytemuck::bytes_of(&p));
let mut e = g.device.create_command_encoder(&Default::default());
- // Particles: placed for this frame's time and camera, then the dynamic BLASes rebuilt (before the raster and
- // the trace).
+ // Particles: placed for this frame's time and camera, then their BLASes built again (before the trace).
// The grid programs (density grids changed on the GPU), before anything reads the grids.
if k == 0 && gpu::Gpu::has_grid_sim(&self.sc.up) {
let sources = std::mem::take(&mut self.grid_sources);
@@ -494,10 +395,6 @@ impl LiveCore {
if k == 0 {
g.sync_tables(&self.sc.up, &mut e);
}
- if let (Some(r), 0, false) = (&self.raster, k, self.sc.instanced) {
- let tw = self.timer.as_ref().zip(timed).map(|(t, slot)| wgpu::RenderPassTimestampWrites { query_set: &t.queries, beginning_of_pass_write_index: Some(slot as u32 * 8 + 4), end_of_pass_write_index: Some(slot as u32 * 8 + 5) });
- r.record(g, &mut e, &self.sc.up.vertices, &self.sc.up.words, self.sc.tris.len() as u32, &cam, self.aspect, (iw, ih), jitter, tw);
- }
{
let tw = match (&self.profile, &self.timer, timed) {
(Some(p), _, _) if k == 0 => Some(wgpu::ComputePassTimestampWrites { query_set: &p.queries, beginning_of_pass_write_index: Some(0), end_of_pass_write_index: Some(1) }),
@@ -550,8 +447,8 @@ impl LiveCore {
let at = slot as u64 * 4 * wgpu::QUERY_RESOLVE_BUFFER_ALIGNMENT;
e.resolve_query_set(&t.queries, q..q + 2, &t.resolve, at);
e.copy_buffer_to_buffer(&t.resolve, at, &t.reads[slot].0, 0, 16);
- // Raster and particle pairs (pairs 2 and 3); zeros when the pass did not run.
- for (pair, ran) in [(2u32, self.raster.is_some() && !self.sc.instanced), (3, self.sc.up.particles.is_some() || self.sc.up.gpu_particles.is_some())] {
+ // The free pair and the particle pair (pairs 2 and 3); zeros when the pass did not run.
+ for (pair, ran) in [(2u32, false), (3, self.sc.up.particles.is_some() || self.sc.up.gpu_particles.is_some())] {
let at = at + pair as u64 * wgpu::QUERY_RESOLVE_BUFFER_ALIGNMENT;
if ran {
e.resolve_query_set(&t.queries, q + pair * 2..q + pair * 2 + 2, &t.resolve, at);
diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rs
index b7ad424..fb1fd17 100644
--- a/renderer/src/live/inplace_tests.rs
+++ b/renderer/src/live/inplace_tests.rs
@@ -482,37 +482,6 @@ fn an_emitting_particle_lights_both_its_sides_beside_a_lights_card() {
assert!(b > 20.0 && (a / b - 1.0).abs() < 0.05, "the wall beside the particle: {a:.1} of 255 with its back to the wall, {b:.1} with its face");
}
-/// Primary visibility by rasterization (`Raster`): a path starts at the triangle the pass drew at its pixel, which is
-/// the one its camera ray hits: the picture is the traced one's. The pass draws world-space triangles and is off in a
-/// scene with instances, which every mesh of a world is: a scene of rect lights' cards alone.
-#[test]
-fn a_rasterized_first_hit_is_the_traced_one() {
- 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 mut w = World::default();
- // (Turned to face the camera: a card lights the side of its node's -z.)
- for (id, at, turn) in [(21, Vec3::new(-0.9, 0.2, 0.0), 3.6), (22, Vec3::new(0.8, -0.3, 1.0), 2.5)] {
- let card = serde_json::from_value(serde_json::json!({ "type": "rect", "color": [1, 0.6, 0.3], "castShadow": true, "intensity": 3, "width": 1.2, "height": 0.8, "range": 0 })).unwrap();
- w.set_object(id, format!("card{id}"), None, Kind::Light(card), true, false).unwrap();
- w.set_transform(id, at, glam::Quat::from_rotation_y(turn), Vec3::ONE).unwrap();
- }
- w.set_object(4, "camera".into(), None, Kind::Camera(camera(50.0, None, manual(0.0))), true, false).unwrap();
- w.set_transform(4, Vec3::new(0.0, 0.0, 5.0), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
- w.set_settings(Settings { camera: Some(4), ..Default::default() });
- let (mut traced, mut drawn) = match (open(&w), open(&w)) {
- (Ok(a), Ok(b)) => (a, b),
- (Err(e), _) | (_, Err(e)) => return eprintln!("skipped: {e}"),
- };
- assert!(!drawn.sc.instanced && drawn.sc.tris.len() == 4 && traced.raster.is_none(), "a scene of four world-space triangles, traced unless asked");
- drawn.raster = Some(super::frame::Raster::new(&drawn.g, drawn.w, drawn.h));
- (drawn.kernel_bg, drawn.tl_kernel_bg) = super::kernel_bind_groups(&drawn.g, drawn.raster.as_ref(), &drawn.targets);
- let (a, b) = (picture(&mut traced, 64), picture(&mut drawn, 64));
- let lit = a.chunks_exact(4).filter(|p| p[0] > 100).count();
- assert!(lit > a.len() / 4 / 50, "the cards are in the picture ({lit} pixels)");
- // (0 steps as measured; 4.9 with each index read one word on.)
- assert!(apart(&a, &b) < 0.5, "the picture is {:.2} steps from the traced one", apart(&a, &b));
-}
-
/// A mesh changed in place to triangles of more vertices (a crease: its two triangles share no corner any more) takes
/// another run of vertices, and the mesh that lies after it keeps its own; changed back, it stays where it is. Each
/// is read back through its indices, and the picture is a build's.
@@ -613,6 +582,33 @@ fn a_moved_card_beside_another_is_written_where_it_lies() {
}
}
+/// Ray tracing off and on again (`LiveCore::set_rays`): off, nothing is shadowed (what the panel shadowed on the
+/// wall is lit); on again, the picture is the first one's.
+#[test]
+fn rays_off_is_another_picture_and_on_again_the_first() {
+ let presets = crate::default_presets_dir();
+ let w = world();
+ let mut live = match gpu::Gpu::new().and_then(|g| LiveCore::new(g, &w, Path::new("."), &presets, 96, 54)) {
+ Ok(c) => c,
+ Err(e) => return eprintln!("skipped: {e}"),
+ };
+ // (Pixels more than 20 steps apart in a colour: where a shadow was, where light had bounced.)
+ let changed = |a: &[u8], b: &[u8]| a.chunks_exact(4).zip(b.chunks_exact(4)).filter(|(x, y)| (0..3).any(|c| x[c].abs_diff(y[c]) > 20)).count();
+ let on = picture(&mut live, 48);
+ live.set_rays(false);
+ forget(&mut live);
+ let off = picture(&mut live, 48);
+ live.set_rays(true);
+ forget(&mut live);
+ let again = picture(&mut live, 48);
+ // What changes is what was in shadow: lit now, none dimmed as much. (Measured: 47 pixels, none on again.)
+ let by = |a: &[u8], b: &[u8], up: bool| a.chunks_exact(4).zip(b.chunks_exact(4)).filter(|(x, y)| (0..3).any(|c| if up { y[c] > x[c].saturating_add(20) } else { x[c] > y[c].saturating_add(20) })).count();
+ let (lit, dimmed) = (by(&on, &off, true), by(&on, &off, false));
+ eprintln!("rays off: {lit} pixels lit, {dimmed} dimmed");
+ assert!(changed(&on, &off) > 20 && lit > 20 && dimmed * 4 < lit, "rays off: {} pixels of the traced picture changed, {lit} lit and {dimmed} dimmed", changed(&on, &off));
+ assert!(changed(&on, &again) < 4 && apart(&on, &again) < 0.2, "rays on again: {} pixels from the first picture, {:.2} steps", changed(&on, &again), apart(&on, &again));
+}
+
/// A particle that drifts, beside a system that stands still: its vertices' previous positions are the pass's last
/// (the motion vectors at its pixels are its step back, and nothing else moves), and the pass leaves the vertices'
/// UVs as the build made them.
diff --git a/renderer/src/live/load.rs b/renderer/src/live/load.rs
index 0ca0de9..9a20026 100644
--- a/renderer/src/live/load.rs
+++ b/renderer/src/live/load.rs
@@ -40,9 +40,6 @@ pub(super) struct LoadedScene {
/// Some object's move is an instance's transform (`Retained::moves_instances`: kept where the proxies change,
/// here and in a geometry edit): the frame's kernel then writes motion vectors.
pub(super) moving_instances: bool,
- /// The scene has instanced meshes or procedural geometry (the raster experiment draws only flattened triangles:
- /// primary visibility is traced).
- pub(super) instanced: bool,
/// Kernel features of the scene's structure (gpu::instance_features), which edits cannot change.
pub(super) instance_features: u32,
pub(super) name: String,
@@ -281,7 +278,6 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &P
base.ltile[3] = super::LIST_CANDIDATES;
base.cam_fwd[3] = w as f32 / h as f32;
let (tris, tri_nodes, tri_instances) = (std::mem::take(&mut sc.tris), std::mem::take(&mut sc.tri_nodes), std::mem::take(&mut sc.tri_instances));
- let instanced = !sc.gpu_instances.is_empty() || !sc.procs.is_empty();
let instance_features = gpu::instance_features(&sc);
let pool_place: Vec<[u32; 2]> = if up.units.is_some() { sc.pool_attrs.iter().map(|a| [a.uv[3].to_bits(), a.x[3].to_bits()]).collect() } else { vec![] };
let (pool_tris, meshes, instances) = (std::mem::take(&mut sc.pool_tris), std::mem::take(&mut sc.meshes), std::mem::take(&mut sc.instances));
@@ -339,5 +335,5 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &P
verts: Holes::new(vertices, vertices + room.tris * 3),
free_skinned: vec![],
};
- Ok((LoadedScene { timings, triangles, tris, tri_nodes, tri_instances, pool_tris, dynamic_verts, skins, skin_trees, pool_place, meshes, instances, sections, rows, gpu_instances, procs, proc_first, moving_instances: tables.retained.moves_instances(), instanced, instance_features, name: sc.name.clone(), up, base, tables, fixed_features, shaders, translucent_mats, translucent_used, volume_fns, dynamic, edit, emit, mat_runs, tri_order, codes_sent: vec![] }, view, env))
+ Ok((LoadedScene { timings, triangles, tris, tri_nodes, tri_instances, pool_tris, dynamic_verts, skins, skin_trees, pool_place, meshes, instances, sections, rows, gpu_instances, procs, proc_first, moving_instances: tables.retained.moves_instances(), instance_features, name: sc.name.clone(), up, base, tables, fixed_features, shaders, translucent_mats, translucent_used, volume_fns, dynamic, edit, emit, mat_runs, tri_order, codes_sent: vec![] }, view, env))
}
diff --git a/renderer/src/live/mod.rs b/renderer/src/live/mod.rs
index e028ddf..919c562 100644
--- a/renderer/src/live/mod.rs
+++ b/renderer/src/live/mod.rs
@@ -165,10 +165,9 @@ struct LiveParams {
pub(super) const LIST_CANDIDATES: u32 = 2;
/// The kernel's group-1 bind groups over a view's targets: the trace's, and the translucency pass's where the device
-/// has one (`gpu::Gpu::tl_vis_layout`: without `finish`'s records).
-fn kernel_bind_groups(g: &gpu::Gpu, raster: Option<&Raster>, targets: &Targets) -> (wgpu::BindGroup, Option<wgpu::BindGroup>) {
- let vis = raster.map_or(&g.no_vis_view, |r| &r.vis);
- (gpu::vis_bind_group(&g.device, &g.vis_layout, vis, &targets.kernel, true), g.tl_vis_layout.as_ref().map(|l| gpu::vis_bind_group(&g.device, l, vis, &targets.kernel, false)))
+/// has one (`gpu::Gpu::tl_live_layout`: without `finish`'s records).
+fn kernel_bind_groups(g: &gpu::Gpu, targets: &Targets) -> (wgpu::BindGroup, Option<wgpu::BindGroup>) {
+ (gpu::live_bind_group(&g.device, &g.live_layout, &targets.kernel, true), g.tl_live_layout.as_ref().map(|l| gpu::live_bind_group(&g.device, l, &targets.kernel, false)))
}
#[derive(Clone, Copy, PartialEq, Debug)]
@@ -351,13 +350,11 @@ pub struct LiveCore {
profile: Option<Profile>,
/// GPU time per frame without stalls (timestamp queries; None: measured by draining the queue twice a second).
timer: Option<FrameTimer>,
- /// Rasterized primary visibility (None: the kernel traces camera rays).
- raster: Option<Raster>,
/// World-space radiance cache (pathtrace.wgsl; None: THREERT_CACHE=0, paths trace every bounce).
cache: Option<RadianceCache>,
/// Kernel group 1: primary visibility + radiance cache + what the live passes read of a trace.
kernel_bg: wgpu::BindGroup,
- /// The same for the translucency pass (`gpu::Gpu::tl_vis_layout`; hardware traversal).
+ /// The same for the translucency pass (`gpu::Gpu::tl_live_layout`; hardware traversal).
tl_kernel_bg: Option<wgpu::BindGroup>,
/// Span (relative to the dynamic tail) re-transformed by the last in-place update whose previous-frame vertices
/// (`Uploaded::prev_verts`) still hold the frame before it: synced to the current ones next frame.
@@ -586,9 +583,8 @@ impl LiveCore {
}
});
let timer = (g.timestamps && profile.is_none()).then(|| FrameTimer::new(&g.device));
- let raster = std::env::var("THREERT_RASTER").is_ok_and(|v| v == "1").then(|| Raster::new(&g, w, h));
let cache = cache_on.then(|| RadianceCache { bufs: targets.kernel.cache.clone(), resolve: g.cache_resolve_pipeline() });
- let (kernel_bg, tl_kernel_bg) = kernel_bind_groups(&g, raster.as_ref(), &targets);
+ let (kernel_bg, tl_kernel_bg) = kernel_bind_groups(&g, &targets);
// (Read whenever a kernel of this session may have the guard: under software traversal a scene's first unit
// brings it, `gpu::loop_guard_of`.)
let guard_read = (gpu::loop_guard_of(!g.hwrt).is_some() && targets.kernel.guard.is_some())
@@ -605,7 +601,7 @@ impl LiveCore {
let mut core = LiveCore {
kernel: None,
more_features: Default::default(),
- reconstructor, quality: Quality::Native, frame_generation: FrameGeneration::Off, latency: Latency::Auto, rendering_control: None, pending_emitters: vec![], flipped: vec![], top_builds: 0, particle_spawns: Default::default(), grid_sources: Default::default(), g, passes, targets, sc, view, env, presets: presets.to_path_buf(), assets: assets.to_path_buf(), w, h, seq: 0, aspect: w as f32 / h as f32, cam, prev_cam: cam, frame: 0, history_len: 0.0, reset: true, bloom: Default::default(), vignette: 0.0, post: [0.0; 4], blur: (0.0, 0.0), inflight: Default::default(), gpu_ms: 0.0, gpu_frame: 0, gpu_trace_ms: 0.0, edit_ms: 0.0, instanced_ms: 0.0, build_ms: 0.0, edit_split: EditSplit::default(), rebuild_ms: 0.0, fallback: None, fallbacks: 0, bounces: 4, rays: true, view_mode: std::env::var("THREERT_VIEW_MODE").ok().and_then(|v| v.parse().ok()).unwrap_or(0), fixed_dt: None, triangles, scene_name, time: 0.0, frame_dt: 1.0 / 60.0, last_frame: Instant::now(), post_key: String::new(), render_scale: 1.0, dynamic_res: false, min_scale: MIN_SCALE, display_scale: 1.0, over_budget: (0, 0), born: Instant::now(), governed: Instant::now(), profile, timer, raster, cache, kernel_bg, tl_kernel_bg, prev_span: None, reposed: false, emitters_moved: false, emitters_reweigh: false, pose_spans: vec![], pose_reposed: false, inst_moving: vec![], inst_moved: false, prev_isz: (0, 0), light_tiles: None, lit_changed: 0, spark_lights: false, shown_spp: 1, cpu_skin_ms: 0.0, cpu_upload_ms: 0.0, gpu_blas_ms: 0.0, cpu_wait_ms: 0.0, guard_trips: guard_read.as_ref().map(|_| 0), guard_read };
+ reconstructor, quality: Quality::Native, frame_generation: FrameGeneration::Off, latency: Latency::Auto, rendering_control: None, pending_emitters: vec![], flipped: vec![], top_builds: 0, particle_spawns: Default::default(), grid_sources: Default::default(), g, passes, targets, sc, view, env, presets: presets.to_path_buf(), assets: assets.to_path_buf(), w, h, seq: 0, aspect: w as f32 / h as f32, cam, prev_cam: cam, frame: 0, history_len: 0.0, reset: true, bloom: Default::default(), vignette: 0.0, post: [0.0; 4], blur: (0.0, 0.0), inflight: Default::default(), gpu_ms: 0.0, gpu_frame: 0, gpu_trace_ms: 0.0, edit_ms: 0.0, instanced_ms: 0.0, build_ms: 0.0, edit_split: EditSplit::default(), rebuild_ms: 0.0, fallback: None, fallbacks: 0, bounces: 4, rays: true, view_mode: std::env::var("THREERT_VIEW_MODE").ok().and_then(|v| v.parse().ok()).unwrap_or(0), fixed_dt: None, triangles, scene_name, time: 0.0, frame_dt: 1.0 / 60.0, last_frame: Instant::now(), post_key: String::new(), render_scale: 1.0, dynamic_res: false, min_scale: MIN_SCALE, display_scale: 1.0, over_budget: (0, 0), born: Instant::now(), governed: Instant::now(), profile, timer, cache, kernel_bg, tl_kernel_bg, prev_span: None, reposed: false, emitters_moved: false, emitters_reweigh: false, pose_spans: vec![], pose_reposed: false, inst_moving: vec![], inst_moved: false, prev_isz: (0, 0), light_tiles: None, lit_changed: 0, spark_lights: false, shown_spp: 1, cpu_skin_ms: 0.0, cpu_upload_ms: 0.0, gpu_blas_ms: 0.0, cpu_wait_ms: 0.0, guard_trips: guard_read.as_ref().map(|_| 0), guard_read };
core.spark_lights = core.sc.tables.emitter_tris.iter().any(|e| e.nominal);
core.apply_post();
Ok(core)
@@ -847,7 +843,7 @@ impl LiveCore {
return;
}
self.targets.kernel.deferred = Some(gpu::deferred_buffer(&self.g.device, (pixels + pixels / 4).min(self.w as u64 * self.h as u64)));
- (self.kernel_bg, self.tl_kernel_bg) = kernel_bind_groups(&self.g, self.raster.as_ref(), &self.targets);
+ (self.kernel_bg, self.tl_kernel_bg) = kernel_bind_groups(&self.g, &self.targets);
}
/// The view at another size (its host's window, in pixels): the targets that follow the size are made again
@@ -865,13 +861,10 @@ impl LiveCore {
(self.w, self.h, self.aspect) = (w, h, w as f32 / h as f32);
self.reconstructor.invalidate();
self.targets.resize(&self.g, &self.passes, w, h);
- if self.raster.is_some() {
- self.raster = Some(Raster::new(&self.g, w, h));
- }
if let Some(c) = &mut self.cache {
c.bufs = self.targets.kernel.cache.clone();
}
- (self.kernel_bg, self.tl_kernel_bg) = kernel_bind_groups(&self.g, self.raster.as_ref(), &self.targets);
+ (self.kernel_bg, self.tl_kernel_bg) = kernel_bind_groups(&self.g, &self.targets);
self.g.set_accum(&mut self.sc.up, &self.targets.accum);
self.apply_post();
// As a new view: no history, no frame before this one.