The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.
Python
Add depth and occlusion passes
apoogdka08c719a5281
diff --git a/rust/engine/src/blend.wgsl b/rust/engine/src/blend.wgslindex 32299fff..e3d5399b 100644--- a/rust/engine/src/blend.wgsl+++ b/rust/engine/src/blend.wgsl@@ -43,6 +43,7 @@ struct Instance {};const NONE: u32 = 0xffffffffu;+const OVERLAY: u32 = 1u; // fixed in the frameconst LIT: u32 = 4u;const TEXTURED: u32 = 8u;const NEAREST: u32 = 16u;@@ -182,13 +183,12 @@ fn fs_none() -> @location(0) vec4<f32> {return vec4<f32>(0.0);}+// A face's edges show as its face does: the record's draw holds the faces a reveal shows (`Raster::shown`).struct Stroked {@builtin(position) @invariant position: vec4<f32>, // counted and covered alike, to the bit@location(0) @interpolate(flat) color: vec4<f32>,- @location(1) u: f32,- @location(2) t: f32,- @location(3) @interpolate(flat) window: vec2<f32>,- @location(4) @interpolate(flat) i: u32,+ @location(1) t: f32,+ @location(2) @interpolate(flat) i: u32,};// Offset of a joint between a segment with normal n and its neighbour with normal m (miter, limit 10).@@ -244,12 +244,10 @@ fn ribbon(code: u32, i: u32, width: f32, color: vec4<f32>) -> Stroked {}out.position = to_clip(vec3<f32>(px, z));out.color = color;- out.u = select(vertex(a).w, vertex(b).w, at_b);out.t = 0.0;if (color.a < 0.0) {out.t = along(i, px);}- out.window = params_of(i).xy;out.i = i;return out;}@@ -259,19 +257,11 @@ fn vs_stroke(@builtin(vertex_index) code: u32, @builtin(instance_index) i: u32)return ribbon(code, i, params_of(i).z, stroke_of(i));}--fn stroked(in: Stroked) -> vec4<f32> {- if (in.u < in.window.x || in.u > in.window.y) {- discard;- }return premultiplied(in.color);}fn stroked_gradient(in: Stroked) -> vec4<f32> {- if (in.u < in.window.x || in.u > in.window.y) {- discard;- }return premultiplied(gradient(in.i, brush_of(in.i).z, brush2_of(in.i).y, brush_of(in.i).w, in.t, extra_of(in.i).y));}@@ -386,9 +376,11 @@ fn carry(r0: vec4<f32>, r1: vec4<f32>, r2: vec4<f32>, n: vec3<f32>) -> vec3<f32>return vec3<f32>(dot(cross(r1.xyz, r2.xyz), n), dot(cross(r2.xyz, r0.xyz), n), dot(cross(r0.xyz, r1.xyz), n));}-// CE's light: half the cube of the cosine toward the light, halved again when facing away.-fn shade(normal: vec3<f32>, p: vec3<f32>) -> f32 {- let n = normalize(select(normal, -normal, dot(view.toward.xyz, normal) < 0.0));+// CE's light: half the cube of the cosine toward the light, halved again when facing away, on the side the eye sees+// from p (a 3D view's perspective; else, or `fixed` in the frame, the side toward the view).+fn shade(normal: vec3<f32>, p: vec3<f32>, fixed: bool) -> f32 {+ let seen = select(view.toward.xyz, view.eye.xyz - p, view.eye.w > 0.5 && !fixed);+ let n = normalize(select(normal, -normal, dot(seen, normal) < 0.0));let l = normalize(view.light.xyz - p);let amount = 0.5 * pow(dot(n, l), 3.0);return select(amount, amount * 0.5, amount < 0.0);@@ -414,7 +406,7 @@ fn vs_mesh(@builtin(vertex_index) index: u32, @builtin(instance_index) i: u32) -}// CE's light, once a vertex (a material's lights are the fragment's)if ((flags & LIT) != 0u && dot(n, n) > 1e-20) {- light = shade(n, p);+ light = shade(n, p, (flags & OVERLAY) != 0u);color = vec4<f32>(clamp(color.rgb + light, vec3<f32>(0.0), vec3<f32>(1.0)), color.a);}}diff --git a/rust/engine/src/blend_lists.wgsl b/rust/engine/src/blend_lists.wgslindex af0a3635..e2077ab8 100644--- a/rust/engine/src/blend_lists.wgsl+++ b/rust/engine/src/blend_lists.wgsl@@ -29,15 +29,18 @@ fn vs_sprites(@builtin(vertex_index) v: u32) -> Dotted {//// See-through points need no lists to be in depth order: disks facing the camera, sorted far to// near (`sprites`: among equal depths, the view's order), they composite exactly by blending in-// that order, however many a pixel stacks. So only where the other see-through layers can paint-// (their footprints together) or its paths can (their boxes) are they appended too, and there the-// lists hold every see-through fragment; everywhere else they blend over the opaque samples. A-// view whose only see-through layers are points has no lists.+// that order, however many a pixel stacks. Among the view's other see-through layers (its paths',+// its listed fragments') they keep that order by slabs: a pass of the composite's (`vector.wgsl`'s+// `bound`) leaves the depths of each pixel's nearest layers, and a point's fragment counts those+// farther than it. With none, it blends into the base over the opaque samples, as everywhere+// where nothing else is see-through; else into its slab, the pixel's points between two of those+// layers, which the composite lays between them. So a point is never listed, and a pixel's points+// cost the composite a few slabs, however many there are.struct Node {depth: f32,color: u32, // straight RGBA8- key: u32, // record << 11 | samples covered << 3 | winding sign << 2 | kind (0 mesh or points, 3 a mesh's edges)+ key: u32, // record << 11 | samples covered << 3 | winding sign << 2 | kind (0 mesh, 3 a mesh's edges)next: u32, // the next node + 1 (0: none)};@@ -45,8 +48,6 @@ struct Node {@group(2) @binding(1) var<storage, read_write> nodes: array<Node>;@group(2) @binding(2) var<storage, read_write> appended: atomic<u32>;@group(2) @binding(3) var opaque_depth: texture_depth_multisampled_2d;-@group(2) @binding(4) var<storage, read> heads_in: array<u32>;-@group(2) @binding(5) var<storage, read> nodes_in: array<Node>;// Where sample s of n lies from its pixel's center (the standard patterns; others: the center).fn sample_offset(n: u32, s: u32) -> vec2<f32> {@@ -100,21 +101,13 @@ fn straight(c: vec4<f32>) -> vec4<f32> {@fragmentfn fs_stroke_append(in: Stroked, @builtin(sample_mask) mask: u32, @builtin(sample_index) sample: u32) {- let slope = slopes(in.position);- if (in.u < in.window.x || in.u > in.window.y) {- return;- }- append(in.i, in.position, slope, mask, sample, in.color, 3u, true);+ append(in.i, in.position, slopes(in.position), mask, sample, in.color, 3u, true);}@fragmentfn fs_stroke_gradient_append(in: Stroked, @builtin(sample_mask) mask: u32, @builtin(sample_index) sample: u32) {- let slope = slopes(in.position);- if (in.u < in.window.x || in.u > in.window.y) {- return;- }let c = gradient(in.i, brush_of(in.i).z, brush2_of(in.i).y, brush_of(in.i).w, in.t, extra_of(in.i).y);- append(in.i, in.position, slope, mask, sample, c, 3u, true);+ append(in.i, in.position, slopes(in.position), mask, sample, c, 3u, true);}@fragment@@ -122,28 +115,67 @@ fn fs_mesh_append(in: Shaded, @builtin(sample_mask) mask: u32, @builtin(sample_iappend(in.i, in.position, slopes(in.position), mask, sample, straight(shaded(in)), 0u, true);}-@fragment-fn fs_points_append(in: Dotted, @builtin(sample_mask) mask: u32, @builtin(sample_index) sample: u32) {- append(in.i, in.position, slopes(in.position), mask, sample, dot_color(in), 0u, true);+// ── slabs ─────────────────────────────────────────────────────────────────────++// the depths of each pixel's nearest layers, far to near (`vector.wgsl`'s `bound`)+@group(2) @binding(0) var slab_bounds: texture_2d<f32>;++// The slab a see-through point's fragment blends into: how many of its pixel's nearest layers lie+// farther than it, its depth taken as the composite takes a listed fragment's (`node_layer`:+// pushed back by the bias, so that a layer through it shows).+fn slab_of(in: Dotted) -> u32 {+ let bounds = textureLoad(slab_bounds, vec2<u32>(in.position.xy), 0);+ let z = -in.position.z * (1.0 - view.toward.w);+ return u32(bounds.x > z) + u32(bounds.y > z) + u32(bounds.z > z) + u32(bounds.w > z);}-// A sprite where no see-through fragment is listed: blended over whatever is farther (a read of-// the heads, not an atomic: a shader with side effects would run per sample).-fn sprite_unlisted(in: Dotted) -> vec4<f32> {- let c = dot_color(in);- let pixel = vec2<u32>(in.position.xy);- if (c.a <= 0.0 || heads_in[pixel.y * u32(view.pixels.x) + pixel.x] != 0u) {+// A see-through point with no layer behind it: blended into the base (depth tested), as dotted.+fn in_base(in: Dotted) -> vec4<f32> {+ if (slab_of(in) != 0u) {discard;}- return premultiplied(c);+ return dotted(in);+}++@fragment+fn fs_sprites_base(in: Dotted) -> @location(0) vec4<f32> {+ return in_base(in);}@fragment-fn fs_sprites_unlisted(in: Dotted) -> @location(0) vec4<f32> {- return sprite_unlisted(in);+fn fs_sprites_base_with_light(in: Dotted) -> Base {+ return painted(in_base(in));}+// The slabs, one target each: slab j's in target j - 1.+struct Slabs {+ @location(0) first: vec4<f32>,+ @location(1) second: vec4<f32>,+ @location(2) third: vec4<f32>,+ @location(3) fourth: vec4<f32>,+};++// A see-through point with layers behind it: blended into its slab, over the share of the pixel's+// samples where it is in front of the opaque depth (as the base's pass tests them, one by one).@fragment-fn fs_sprites_unlisted_with_light(in: Dotted) -> Base {- return painted(sprite_unlisted(in));+fn fs_sprites_slabs(in: Dotted) -> Slabs {+ let j = slab_of(in);+ let c = dot_color(in);+ let n = u32(view.pixels.z);+ var front = 0u;+ for (var s = 0u; s < n; s += 1u) {+ front += u32(in.position.z >= textureLoad(opaque_depth, vec2<u32>(in.position.xy), s));+ }+ if (j == 0u || c.a <= 0.0 || front == 0u) {+ discard;+ }+ let p = premultiplied(c) * (f32(front) / f32(n));+ var out = Slabs(vec4<f32>(0.0), vec4<f32>(0.0), vec4<f32>(0.0), vec4<f32>(0.0));+ switch j {+ case 1u: { out.first = p; }+ case 2u: { out.second = p; }+ case 3u: { out.third = p; }+ default: { out.fourth = p; }+ }+ return out;}diff --git a/rust/engine/src/depth.wgsl b/rust/engine/src/depth.wgslnew file mode 100644index 00000000..e61bbf7a--- /dev/null+++ b/rust/engine/src/depth.wgsl@@ -0,0 +1,72 @@+// A 3D view's base depth for the composite: the raster pass's depth, its samples' nearest, as one float a pixel.++@group(0) @binding(0) var depth_in: texture_depth_multisampled_2d;+@group(0) @binding(1) var depth_one: texture_depth_2d;+@group(0) @binding(2) var depth_out: texture_storage_2d<r32float, write>;++// What parts a face's samples from its plane: a share of its depth (rounding, 8 f32 steps; its edges' pull, 16:+// `blend.wgsl`'s PULL; 8 to spare) and its depth slope times a share of a pixel (the rasterizer's snapping of corners+// to half a 1/256 step, one triangle's and its neighbour's; the edges' pull, 4 of them; 2 to spare).+const STROKES: vec2<f32> = vec2<f32>(32.0 * 1.2e-7, 8.0 / 512.0);++// A sample's place in its pixel (the standard patterns: their offsets sum to zero).+fn sample_offset(n: u32, s: u32) -> vec2<f32> {+ if (n == 4u) {+ var four = array<vec2<f32>, 4>(vec2(-2.0, -6.0), vec2(6.0, -2.0), vec2(-6.0, 2.0), vec2(2.0, 6.0));+ return four[s] / 16.0;+ }+ if (n == 8u) {+ var eight = array<vec2<f32>, 8>(vec2(1.0, -3.0), vec2(-1.0, 3.0), vec2(5.0, 1.0), vec2(-3.0, -5.0), vec2(-5.0, 5.0), vec2(-7.0, -1.0), vec2(3.0, 7.0), vec2(7.0, -7.0));+ return eight[s] / 16.0;+ }+ return vec2<f32>(0.0);+}++// The pixel's depth: where its samples lie on one plane (one face covers it, its edges' strokes on it), the plane's at+// the pixel's centre (their mean: the pattern's offsets sum to zero), pushed back by all that parts a face's samples+// from its plane (`STROKES`), so a path on that face meets it however steep the face and wherever its edges are; else+// its nearest sample's (reversed Z: the greatest).+@compute @workgroup_size(16, 16)+fn nearest_of_samples(@builtin(global_invocation_id) gid: vec3<u32>) {+ let size = textureDimensions(depth_in);+ if (gid.x >= size.x || gid.y >= size.y) {+ return;+ }+ let n = textureNumSamples(depth_in);+ var z = array<f32, 8>();+ var nearest = 0.0;+ var mean = 0.0;+ var gradient = vec2<f32>(0.0); // (least squares: the offsets' moments, then their products with the depths)+ var moments = vec3<f32>(0.0);+ for (var s = 0u; s < min(n, 8u); s++) {+ z[s] = textureLoad(depth_in, vec2<i32>(gid.xy), i32(s));+ nearest = max(nearest, z[s]);+ mean += z[s] / f32(n);+ let o = sample_offset(n, s);+ moments += vec3<f32>(o.x * o.x, o.y * o.y, o.x * o.y);+ }+ var flat = n > 1u && n <= 8u;+ if (flat) {+ var b = vec2<f32>(0.0);+ for (var s = 0u; s < n; s++) {+ b += sample_offset(n, s) * (z[s] - mean);+ }+ let det = moments.x * moments.y - moments.z * moments.z;+ gradient = vec2<f32>(b.x * moments.y - b.y * moments.z, b.y * moments.x - b.x * moments.z) / det;+ let tolerance = STROKES.x * nearest + STROKES.y * (abs(gradient.x) + abs(gradient.y));+ for (var s = 0u; s < n; s++) {+ flat = flat && abs(z[s] - mean - dot(gradient, sample_offset(n, s))) <= tolerance;+ }+ }+ let centre = mean - STROKES.x * mean - STROKES.y * (abs(gradient.x) + abs(gradient.y));+ textureStore(depth_out, gid.xy, vec4<f32>(-select(nearest, centre, flat), 0.0, 0.0, 0.0)); // from the far plane, as paths'+}++@compute @workgroup_size(16, 16)+fn single_sample(@builtin(global_invocation_id) gid: vec3<u32>) {+ let size = textureDimensions(depth_one);+ if (gid.x >= size.x || gid.y >= size.y) {+ return;+ }+ textureStore(depth_out, gid.xy, vec4<f32>(-textureLoad(depth_one, vec2<i32>(gid.xy), 0), 0.0, 0.0, 0.0));+}diff --git a/rust/engine/src/occlusion.rs b/rust/engine/src/occlusion.rsnew file mode 100644index 00000000..eb5ce842--- /dev/null+++ b/rust/engine/src/occlusion.rs@@ -0,0 +1,144 @@+//! A 3D view's ambient occlusion (`Camera.ambient_occlusion`): how much of the light from all around reaches the+//! surface each pixel shows, as the surfaces near it shut it out — Filament's scalable ambient obscurance (McGuire,+//! Mara and Luebke 2012), as new_filament ports it (`occlusion.wgsl`). The view's opaque depth comes first, its opaque+//! meshes' (`vs_depth`) and then its opaque paths' where nearer (`vector::Out::Opaque`); from it come distances along+//! the view, a pyramid of them, the occlusion and its low-pass, which the view's lit passes read (`light.wgsl`: what+//! an ambient or environment light gives a surface, times it).++use std::f32::consts::TAU;++/// The taps a pixel's occlusion is sought with, and the turns of their spiral (Filament's high quality; its spiral's+/// start interleaved 4 x 4: `occlusion.wgsl`'s `start`).+const SAMPLES: f32 = 16.0;+const TURNS: f32 = 7.0;+/// How far a surface's depth is taken nearer than it is, as a share of its distance (Filament's default bias): no+/// surface shuts out its own light.+const BIAS: f32 = 0.0005;+/// The depth within which the low-pass takes a neighbour as the surface's own, as a share of the radius (Filament's+/// defaults: 5 cm of 30).+const SAME_SURFACE: f32 = 1.0 / 6.0;++/// The passes: a mesh's depth as its view sees it (the raster pipeline's `vs_depth`), and the occlusion's: distances,+/// a level of the pyramid, the occlusion, its low-pass.+pub(crate) struct Occlusion {+ pub(crate) depth: wgpu::RenderPipeline,+ layouts: [wgpu::BindGroupLayout; 4],+ passes: [wgpu::ComputePipeline; 4],+}++/// Where a view's occlusion is found (made for its canvas, at its size): its opaque depth, drawn by the view's passes,+/// then (`Occlusion::encode`) what the occlusion makes of it, last of all `out`, which the lit passes read.+pub(crate) struct Occluded {+ pub(crate) depth: wgpu::TextureView,+ pub(crate) out: wgpu::TextureView,+ params: wgpu::Buffer,+ groups: Vec<wgpu::BindGroup>, // the distances, each level of the pyramid, the occlusion, its low-pass+ sizes: Vec<[u32; 2]>, // the pyramid's levels, from the whole view's+}++impl Occlusion {+ /// Its passes: the depth's with the raster pipeline's shader (`blend`) and scene layout.+ pub(crate) fn new(device: &wgpu::Device, blend: &wgpu::ShaderModule, scene: &wgpu::BindGroupLayout) -> Self {+ let depth = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {+ label: Some("occlusion depth"),+ layout: Some(&device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(scene)], immediate_size: 0 })),+ vertex: wgpu::VertexState { module: blend, entry_point: Some("vs_depth"), compilation_options: Default::default(), buffers: &[] },+ fragment: None,+ primitive: wgpu::PrimitiveState::default(),+ depth_stencil: Some(wgpu::DepthStencilState {+ format: wgpu::TextureFormat::Depth32Float,+ depth_write_enabled: Some(true),+ depth_compare: Some(wgpu::CompareFunction::GreaterEqual), // (reversed Z, as the view's raster passes)+ stencil: Default::default(),+ bias: Default::default(),+ }),+ multisample: wgpu::MultisampleState::default(),+ multiview_mask: None,+ cache: None,+ });+ let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("occlusion"), source: wgpu::ShaderSource::Wgsl(include_str!("occlusion.wgsl").into()) });+ let entry = |binding, ty| wgpu::BindGroupLayoutEntry { binding, visibility: wgpu::ShaderStages::COMPUTE, ty, count: None };+ let params = entry(0, wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None });+ let texture = |binding| entry(binding, wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Float { filterable: false }, view_dimension: wgpu::TextureViewDimension::D2, multisampled: false });+ let out = entry(6, wgpu::BindingType::StorageTexture { access: wgpu::StorageTextureAccess::WriteOnly, format: wgpu::TextureFormat::R32Float, view_dimension: wgpu::TextureViewDimension::D2 });+ let depth_in = entry(1, wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Depth, view_dimension: wgpu::TextureViewDimension::D2, multisampled: false });+ let make = |label: &str, entries: &[wgpu::BindGroupLayoutEntry]| {+ let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some(label), entries });+ let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(&layout)], immediate_size: 0 });+ let options = wgpu::PipelineCompilationOptions { zero_initialize_workgroup_memory: false, ..Default::default() }; // (written before read)+ let pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some(label), layout: Some(&pipeline_layout), module: &shader, entry_point: Some(label), compilation_options: options, cache: None });+ (layout, pass)+ };+ let [(l0, p0), (l1, p1), (l2, p2), (l3, p3)] = [+ make("linearize", &[params, depth_in, out]),+ make("depth_mip", &[texture(7), out]),+ make("sao", &[params, texture(3), texture(4), out]),+ make("blur", &[params, texture(3), texture(5), out]),+ ];+ Self { depth, layouts: [l0, l1, l2, l3], passes: [p0, p1, p2, p3] }+ }++ /// Where a view of `size` finds its occlusion.+ pub(crate) fn occluded(&self, device: &wgpu::Device, [width, height]: [u32; 2]) -> Occluded {+ // the pyramid's levels: down to about 32 pixels across the view's longer side, 2 to 8 of them (Filament's)+ let levels = (32 - width.max(height).leading_zeros()).saturating_sub(5).clamp(2, 8);+ let sizes: Vec<[u32; 2]> = (0..levels).map(|l| [(width >> l).max(1), (height >> l).max(1)]).collect();+ let texture = |label: &str, [w, h]: [u32; 2], levels: u32, format, usage| {+ let size = wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 };+ device.create_texture(&wgpu::TextureDescriptor { label: Some(label), size, mip_level_count: levels, sample_count: 1, dimension: wgpu::TextureDimension::D2, format, usage, view_formats: &[] })+ };+ let written = wgpu::TextureUsages::STORAGE_BINDING | wgpu::TextureUsages::TEXTURE_BINDING;+ let r32 = |label| texture(label, sizes[0], 1, wgpu::TextureFormat::R32Float, written).create_view(&Default::default());+ let depth = texture("occlusion depth", sizes[0], 1, wgpu::TextureFormat::Depth32Float, wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING).create_view(&Default::default());+ let (distances, raw, out) = (r32("distances"), r32("occlusion"), r32("occlusion low-passed"));+ let pyramid = texture("distances' pyramid", sizes[1], levels - 1, wgpu::TextureFormat::R32Float, written);+ let level: Vec<wgpu::TextureView> = (0..levels - 1).map(|l| pyramid.create_view(&wgpu::TextureViewDescriptor { base_mip_level: l, mip_level_count: Some(1), ..Default::default() })).collect();+ let mips = pyramid.create_view(&Default::default());+ let params = device.create_buffer(&wgpu::BufferDescriptor { label: Some("occlusion"), size: 64, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });+ let bind = |k: usize, entries: &[(u32, wgpu::BindingResource)]| {+ let entries: Vec<wgpu::BindGroupEntry> = entries.iter().map(|(binding, resource)| wgpu::BindGroupEntry { binding: *binding, resource: resource.clone() }).collect();+ device.create_bind_group(&wgpu::BindGroupDescriptor { label: None, layout: &self.layouts[k], entries: &entries })+ };+ let view = wgpu::BindingResource::TextureView;+ let mut groups = vec![bind(0, &[(0, params.as_entire_binding()), (1, view(&depth)), (6, view(&distances))])];+ // level l from level l - 1 (the distances themselves for the first)+ for l in 1..levels as usize {+ let finer = if l == 1 { &distances } else { &level[l - 2] };+ groups.push(bind(1, &[(7, view(finer)), (6, view(&level[l - 1]))]));+ }+ groups.push(bind(2, &[(0, params.as_entire_binding()), (3, view(&distances)), (4, view(&mips)), (6, view(&raw))]));+ groups.push(bind(3, &[(0, params.as_entire_binding()), (3, view(&distances)), (5, view(&raw)), (6, view(&out))]));+ Occluded { depth, out, params, groups, sizes }+ }++ /// A view's occlusion, once its opaque depth is drawn: `projection` the view's (rows; a 3D view's: depth z / w =+ /// near / distance, see `feed.view`), how much (`amount`, Filament's intensity) and how far around (`radius`, in+ /// the world's units).+ pub(crate) fn encode(&self, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, o: &Occluded, projection: &[[f32; 4]; 4], amount: f32, radius: f32) {+ let length = |r: [f32; 4]| (r[0] * r[0] + r[1] * r[1] + r[2] * r[2]).sqrt();+ let unit = length(projection[3]); // w a unit along the view: one over the focal distance+ let (tan_x, tan_y, near) = (unit / length(projection[0]), unit / length(projection[1]), projection[2][3] / unit);+ let peak = 0.1 * radius;+ let [width, height] = o.sizes[0];+ let params: [f32; 16] = [+ tan_x, tan_y, near, (o.sizes.len() - 1) as f32,+ radius, 2.0, TAU * peak * amount / SAMPLES, BIAS, // (twice the power: Filament's 1)+ peak * peak, 1.0 / (radius * radius), 0.5 * height as f32 / tan_y, 0.0,+ 0.0, TURNS * TAU / (SAMPLES - 0.5), SAMPLES, 1.0 / (SAME_SURFACE * radius),+ ];+ queue.write_buffer(&o.params, 0, bytemuck::cast_slice(¶ms));+ let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("occlusion"), timestamp_writes: None });+ let mut dispatch = |k: usize, group: &wgpu::BindGroup, [w, h]: [u32; 2], tile: u32| {+ pass.set_pipeline(&self.passes[k]);+ pass.set_bind_group(0, group, &[]);+ pass.dispatch_workgroups(w.div_ceil(tile), h.div_ceil(tile), 1);+ };+ let n = o.groups.len();+ dispatch(0, &o.groups[0], [width, height], 8);+ for (l, size) in o.sizes.iter().enumerate().skip(1) {+ dispatch(1, &o.groups[l], *size, 8);+ }+ dispatch(2, &o.groups[n - 2], [width, height], 8);+ dispatch(3, &o.groups[n - 1], [width, height], 16);+ }+}diff --git a/rust/engine/src/occlusion.wgsl b/rust/engine/src/occlusion.wgslnew file mode 100644index 00000000..82070dfc--- /dev/null+++ b/rust/engine/src/occlusion.wgsl@@ -0,0 +1,238 @@+// A 3D view's ambient occlusion (`occlusion.rs`): Filament's scalable ambient obscurance (materials/ssao: sao.mat,+// saoImpl.fs, mipmapDepth.mat, bilateralBlur.mat), as new_filament ports it (engine_ao, engine_depthmip,+// engine_aoblur), over the view's opaque depth: as distances along the view (`linearize`), a pyramid of them+// (`depth_mip`), the occlusion (`sao`), and its low-pass, which stops where depth jumps (`blur`).++// The view: its half extent at unit distance (x, y), its near plane's distance, its pyramid's coarsest level; the+// occlusion's radius, twice its power, its intensity's share a tap, its bias; its peak squared, one over its radius+// squared, the view's pixels a unit at unit distance across it (y); the spiral's start, its turn a tap, the taps, one+// over the depth within which the low-pass takes a neighbour as the same surface.+struct Params {+ proj: vec4<f32>,+ ao0: vec4<f32>,+ ao1: vec4<f32>,+ ao2: vec4<f32>,+};++@group(0) @binding(0) var<uniform> params: Params;+@group(0) @binding(1) var depth: texture_depth_2d; // the view's opaque depth (reversed Z: near / distance; 0: none)+@group(0) @binding(3) var depth0: texture_2d<f32>; // distances along the view (0: nothing there)+@group(0) @binding(4) var depth_mips: texture_2d<f32>; // the pyramid: its level l + 1 in mip l+@group(0) @binding(5) var ao_src: texture_2d<f32>; // the occlusion before its low-pass+@group(0) @binding(6) var out: texture_storage_2d<r32float, write>;+@group(0) @binding(7) var finer: texture_2d<f32>; // the pyramid's level before the one written++// ── the view's distances ────────────────────────────────────────────────────────────────────++@compute @workgroup_size(8, 8)+fn linearize(@builtin(global_invocation_id) id: vec3<u32>) {+ if (any(id.xy >= textureDimensions(depth))) {+ return;+ }+ let d = textureLoad(depth, id.xy, 0);+ textureStore(out, id.xy, vec4<f32>(select(0.0, params.proj.z / d, d > 0.0)));+}++// ── the pyramid: each texel one of its four children, on a rotated grid (no averaging: every level holds real+// surfaces' distances) ─────────────────────────────────────────────────────────────────────────++@compute @workgroup_size(8, 8)+fn depth_mip(@builtin(global_invocation_id) id: vec3<u32>) {+ if (any(id.xy >= textureDimensions(out))) {+ return;+ }+ let c = vec2<i32>(id.xy);+ let child = clamp(2 * c + vec2<i32>(c.y & 1, c.x & 1), vec2<i32>(0), vec2<i32>(textureDimensions(finer)) - 1);+ textureStore(out, c, vec4<f32>(textureLoad(finer, child, 0).x));+}++// ── the occlusion ─────────────────────────────────────────────────────────────────────────────++// Where a pixel's spiral starts, as a share of a turn and of a tap's step out: one of 16, interleaved 4 x 4 in Bayer's+// order, so the low-pass (as wide as the interleave) averages every start in every neighbourhood: 16 taps look as+// smooth as 32 interleaved-gradient ones (Jimenez 2014, Filament's), which streak at 16 (experiments/ambient-occlusion).+const STARTS = array<f32, 16>(0.0, 8.0, 2.0, 10.0, 12.0, 4.0, 14.0, 6.0, 3.0, 11.0, 1.0, 9.0, 15.0, 7.0, 13.0, 5.0);++fn start(p: vec2<u32>) -> f32 {+ let b = p & vec2<u32>(3u);+ return (STARTS[b.y * 4u + b.x] + 0.5) / 16.0;+}++fn sq(x: f32) -> f32 {+ return x * x;+}++fn depth_texel(p: vec2<i32>) -> f32 {+ return textureLoad(depth0, clamp(p, vec2<i32>(0), vec2<i32>(textureDimensions(depth0)) - 1), 0).x;+}++// A tap at uv on the pyramid's level `level`: the distance its texel there holds (its edge held beyond it), and where+// that distance was seen — the view's own pixel it is a copy of (the child rule, down to level 0), at its centre. A+// tap is a real point of a surface, where it is: Filament's places the distance at uv itself, which lifts a tap off+// a slanted plane by the depth's change over the texel's offset, and a flat floor seen at a slant shuts out its own+// light.+fn tap(uv: vec2<f32>, level: u32) -> vec3<f32> {+ let size0 = vec2<i32>(textureDimensions(depth0));+ if (level == 0u) {+ let c = clamp(vec2<i32>(floor(uv * vec2<f32>(size0))), vec2<i32>(0), size0 - 1);+ return vec3<f32>((vec2<f32>(c) + 0.5) / vec2<f32>(size0), textureLoad(depth0, c, 0).x);+ }+ let size = vec2<i32>(textureDimensions(depth_mips, level - 1u));+ var c = clamp(vec2<i32>(floor(uv * vec2<f32>(size))), vec2<i32>(0), size - 1);+ let z = textureLoad(depth_mips, c, i32(level) - 1).x;+ for (var k = i32(level) - 1; k >= 0; k--) {+ let finer = max(size0 >> vec2<u32>(u32(k)), vec2<i32>(1));+ c = clamp(2 * c + vec2<i32>(c.y & 1, c.x & 1), vec2<i32>(0), finer - 1);+ }+ return vec3<f32>((vec2<f32>(c) + 0.5) / vec2<f32>(size0), z);+}++// Where the view sees at uv (y down) and distance z: x right, y up, z toward the viewer.+fn view_pos(uv: vec2<f32>, z: f32) -> vec3<f32> {+ let ndc = vec2<f32>(uv.x * 2.0 - 1.0, 1.0 - 2.0 * uv.y);+ return vec3<f32>(ndc.x * params.proj.x * z, ndc.y * params.proj.y * z, -z);+}++fn inv_depth(z: f32) -> f32 {+ return 1.0 / max(z, 1e-6);+}++// How much of the light from all around reaches the surface pixel `id` shows (1: all of it; nothing there: all).+fn visibility(id: vec2<u32>) -> f32 {+ let p = vec2<i32>(id);+ let texel = 1.0 / vec2<f32>(textureDimensions(depth0));+ let frag = vec2<f32>(id) + 0.5;+ let uv = frag * texel;+ let z = depth_texel(p);+ if (z <= 0.0) {+ return 1.0;+ }+ let origin = view_pos(uv, z);+ // its normal: per axis, the difference toward the neighbour that continues its surface (1 / z is affine across a+ // plane: the one whose next neighbour it extrapolates best)+ let zl = depth_texel(p - vec2<i32>(1, 0));+ let zr = depth_texel(p + vec2<i32>(1, 0));+ let hx = abs(vec2<f32>(2.0 * inv_depth(zl) - inv_depth(depth_texel(p - vec2<i32>(2, 0))), 2.0 * inv_depth(zr) - inv_depth(depth_texel(p + vec2<i32>(2, 0)))) - inv_depth(z));+ let dpdx = select(view_pos(uv + vec2<f32>(texel.x, 0.0), zr) - origin, origin - view_pos(uv - vec2<f32>(texel.x, 0.0), zl), hx.x < hx.y);+ let zu = depth_texel(p - vec2<i32>(0, 1)); // the row above+ let zd = depth_texel(p + vec2<i32>(0, 1)); // the row below+ let hy = abs(vec2<f32>(2.0 * inv_depth(zd) - inv_depth(depth_texel(p + vec2<i32>(0, 2))), 2.0 * inv_depth(zu) - inv_depth(depth_texel(p - vec2<i32>(0, 2)))) - inv_depth(z));+ let dpdy = select(view_pos(uv - vec2<f32>(0.0, texel.y), zu) - origin, origin - view_pos(uv + vec2<f32>(0.0, texel.y), zd), hy.x < hy.y);+ let n = normalize(cross(dpdx, dpdy));+ // the taps: a spiral out to the radius as the view sees it there, each farther tap read from a coarser level+ let noise = start(id);+ let a0 = 6.2831853 * 2.4 * noise + params.ao2.x;+ var dir = vec2<f32>(cos(a0), sin(a0));+ let ci = cos(params.ao2.y);+ let si = sin(params.ao2.y);+ let samples = params.ao2.z;+ let disk = params.ao1.z * params.ao0.x / z;+ var occluded = 0.0;+ for (var i = 0.0; i < samples; i += 1.0) {+ let t = sq((i + noise + 0.5) / (samples - 0.5));+ let r = max(1.0, t * disk);+ // (the view's y grows downward, Filament's upward: the tap mirrored keeps its spiral)+ let q = uv + r * vec2<f32>(dir.x, -dir.y) * texel;+ dir = vec2<f32>(dir.x * ci - dir.y * si, dir.x * si + dir.y * ci);+ let level = u32(clamp(floor(log2(r)) - 3.0, 0.0, params.proj.w));+ let s = tap(q, level);+ if (s.z <= 0.0) {+ continue; // nothing there+ }+ let v = view_pos(s.xy, s.z) - origin;+ let vv = dot(v, v);+ let vn = dot(v, n);+ let w = sq(max(0.0, 1.0 - vv * params.ao1.y));+ occluded += w * max(0.0, vn + origin.z * params.ao0.w) / (vv + params.ao1.x);+ }+ occluded = sqrt(occluded * params.ao0.z);+ return pow(clamp(1.0 - occluded, 0.0, 1.0), params.ao0.y);+}++@compute @workgroup_size(8, 8)+fn sao(@builtin(global_invocation_id) id: vec3<u32>) {+ if (any(id.xy >= textureDimensions(depth0))) {+ return;+ }+ textureStore(out, id.xy, vec4<f32>(visibility(id.xy)));+}++// ── its low-pass: a separable Gaussian (sigma 2.5 pixels) over the neighbours on the pixel's own surface — each+// weighted by how far its distance is from the surface's plane through the pixel, 1 - (off / threshold)^2, so+// a slope keeps its neighbours and no occlusion bleeds across a jump in depth; both 1-D passes in one dispatch, a+// tile and its apron in workgroup memory ─────────────────────────────────────────────────────────++const T: i32 = 16; // the tile+const A: i32 = 5; // its apron+const S: i32 = 26; // T + 2 A+const GAUSS = array<f32, 6>(1.0, 0.92311635, 0.72614904, 0.48675226, 0.27803730, 0.13533528); // exp(-i^2 / 12.5)+var<workgroup> tile_ao: array<f32, 676>; // S x S+var<workgroup> tile_z: array<f32, 676>;+var<workgroup> rows: array<f32, 416>; // S rows of the tile's T columns, low-passed across++// Along a line of distances with z0 at the centre and zm, zp either side: d(1 / z) a step on the pixel's surface,+// the side's that changes least (the other may be across an edge; none where neither is a surface).+fn slope(z0: f32, zm: f32, zp: f32) -> f32 {+ let m = select(1e30, 1.0 / z0 - 1.0 / zm, zm > 0.0);+ let p = select(1e30, 1.0 / zp - 1.0 / z0, zp > 0.0);+ let g = select(p, m, abs(m) < abs(p));+ return select(g, 0.0, abs(g) >= 1e30);+}++// A neighbour i steps away at distance z, its Gaussian weight g, seen from a pixel at z0 whose surface's 1 / z changes+// by s a step: its weight (nothing there: none).+fn weight(z0: f32, s: f32, i: f32, z: f32, g: f32) -> f32 {+ let off = (z - 1.0 / max(1.0 / z0 + i * s, 1e-12)) * params.ao2.w;+ return select(0.0, g * max(0.0, 1.0 - off * off), z > 0.0);+}++@compute @workgroup_size(16, 16)+fn blur(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(local_invocation_index) li: u32) {+ let size = vec2<i32>(textureDimensions(depth0));+ let origin = vec2<i32>(wg.xy) * T;+ for (var k = i32(li); k < S * S; k += 256) {+ let q = clamp(origin - A + vec2<i32>(k % S, k / S), vec2<i32>(0), size - 1);+ tile_ao[k] = textureLoad(ao_src, q, 0).x;+ tile_z[k] = textureLoad(depth0, q, 0).x;+ }+ workgroupBarrier();+ for (var k = i32(li); k < T * S; k += 256) {+ let c = (k / T) * S + k % T + A;+ let z = tile_z[c];+ var sum = tile_ao[c];+ if (z > 0.0) {+ let s = slope(z, tile_z[c - 1], tile_z[c + 1]);+ var total = 1.0;+ for (var i = 1; i <= A; i++) {+ let wl = weight(z, s, -f32(i), tile_z[c - i], GAUSS[i]);+ let wr = weight(z, s, f32(i), tile_z[c + i], GAUSS[i]);+ sum += tile_ao[c - i] * wl + tile_ao[c + i] * wr;+ total += wl + wr;+ }+ sum /= total;+ }+ rows[k] = sum;+ }+ workgroupBarrier();+ let p = origin + vec2<i32>(lid.xy);+ if (any(p >= size)) {+ return;+ }+ let x = i32(lid.x);+ let y = i32(lid.y) + A;+ let c = y * S + x + A;+ let z = tile_z[c];+ var sum = rows[y * T + x];+ if (z > 0.0) {+ let s = slope(z, tile_z[c - S], tile_z[c + S]);+ var total = 1.0;+ for (var i = 1; i <= A; i++) {+ let wu = weight(z, s, -f32(i), tile_z[c - i * S], GAUSS[i]);+ let wd = weight(z, s, f32(i), tile_z[c + i * S], GAUSS[i]);+ sum += rows[(y - i) * T + x] * wu + rows[(y + i) * T + x] * wd;+ total += wu + wd;+ }+ sum /= total;+ }+ textureStore(out, p, vec4<f32>(sum));+}