Skip to content

The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.

Python

Add bloom and tone mapping

Sina Atalay5d361c6170d3
diff --git a/rust/engine/src/bloom.rs b/rust/engine/src/bloom.rs
new file mode 100644
index 00000000..1faa4e26
--- /dev/null
+++ b/rust/engine/src/bloom.rs
@@ -0,0 +1,114 @@
+//! A 3D view's bloom (`Camera.bloom`): the glow a lens and a sensor spread around the light they take in, as
+//! Filament's bloom has it in its interpolating mode (`bloom.wgsl`), which keeps the light: a share of the light the view
+//! shows is spread over levels of half the size each and added back up, the rest stays where it is, and each pixel is
+//! shown with the glow over it. The view's composite leaves its pixels' paint and light for it (`vector::Out::Color`'s
+//! `light_out`) instead of showing them; a view without lit content, or without bloom, shows its pixels as it did.
+
+/// The levels: the view halved, then halved again while a level keeps this many texels across its narrower side (a
+/// 1920x1080 view's: 960x540 down to 15x9, seven, the coarsest level's texel an eighth of the view's height; half the
+/// glow lies within a twentieth of the height of its light, nine tenths within an eighth, nearly all within a quarter:
+/// experiments/bloom), at most `LEVELS` of them.
+const NARROWEST: u32 = 8;
+const LEVELS: usize = 8;
+
+/// The passes: the first level (`spread`), each level after it (`down`), each added up (`up`), the view shown (`show`).
+pub(crate) struct Bloom {
+ layouts: [wgpu::BindGroupLayout; 3],
+ passes: [wgpu::ComputePipeline; 4],
+}
+
+/// Where a view's glow is made (for its canvas, at its size): the paint and light its composite leaves (`paint`,
+/// `light`), its levels, and what the passes are bound to, the last of them writing the canvas's color.
+pub(crate) struct Bloomed {
+ pub(crate) paint: wgpu::TextureView,
+ pub(crate) light: wgpu::TextureView,
+ params: wgpu::Buffer,
+ groups: Vec<wgpu::BindGroup>, // the first level, each level after it, each added up (coarsest first), the view shown
+ sizes: Vec<[u32; 2]>, // the levels', and last the view's
+}
+
+impl Bloom {
+ pub(crate) fn new(device: &wgpu::Device) -> Self {
+ let source = [include_str!("tone.wgsl"), include_str!("bloom.wgsl")].concat();
+ let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("bloom"), source: wgpu::ShaderSource::Wgsl(source.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: true }, view_dimension: wgpu::TextureViewDimension::D2, multisampled: false });
+ let smooth = entry(2, wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering));
+ let out = |binding, format| entry(binding, wgpu::BindingType::StorageTexture { access: wgpu::StorageTextureAccess::WriteOnly, format, view_dimension: wgpu::TextureViewDimension::D2 });
+ let level = out(3, super::RADIANCE);
+ let layout = |label, entries: &[wgpu::BindGroupLayoutEntry]| device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some(label), entries });
+ let layouts = [
+ layout("bloom down", &[params, texture(1), smooth, level]),
+ layout("bloom up", &[texture(1), smooth, level, texture(4)]),
+ layout("bloom show", &[params, smooth, texture(5), texture(6), texture(7), out(8, super::COLOR)]),
+ ];
+ let pass = |entry: &str, k: usize| {
+ let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(&layouts[k])], immediate_size: 0 });
+ let options = wgpu::PipelineCompilationOptions { zero_initialize_workgroup_memory: false, ..Default::default() }; // (none used)
+ device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some(entry), layout: Some(&pipeline_layout), module: &shader, entry_point: Some(entry), compilation_options: options, cache: None })
+ };
+ let passes = [pass("spread", 0), pass("down", 0), pass("up", 1), pass("show", 2)];
+ Self { layouts, passes }
+ }
+
+ /// Where a view of `size` drawn in `target` makes its glow (`smooth`: a bilinear sampler, clamped to the edges).
+ pub(crate) fn bloomed(&self, device: &wgpu::Device, smooth: &wgpu::Sampler, target: &wgpu::TextureView, [width, height]: [u32; 2]) -> Bloomed {
+ let mut sizes = vec![[width.div_ceil(2), height.div_ceil(2)]];
+ while sizes.len() < LEVELS {
+ let [w, h] = sizes[sizes.len() - 1].map(|v| v.div_ceil(2));
+ if w.min(h) < NARROWEST {
+ break;
+ }
+ sizes.push([w, h]);
+ }
+ let image = |label: &str, [w, h]: [u32; 2], format| {
+ let size = wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 };
+ let usage = wgpu::TextureUsages::STORAGE_BINDING | wgpu::TextureUsages::TEXTURE_BINDING;
+ device.create_texture(&wgpu::TextureDescriptor { label: Some(label), size, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, format, usage, view_formats: &[] }).create_view(&Default::default())
+ };
+ let (paint, light) = (image("bloom paint", [width, height], super::COLOR), image("bloom light", [width, height], super::RADIANCE));
+ // each level's share, and (but the coarsest's) the coarser levels added to it
+ let down: Vec<wgpu::TextureView> = sizes.iter().map(|&s| image("bloom level", s, super::RADIANCE)).collect();
+ let up: Vec<wgpu::TextureView> = sizes[..sizes.len() - 1].iter().map(|&s| image("bloom level added up", s, super::RADIANCE)).collect();
+ let params = device.create_buffer(&wgpu::BufferDescriptor { label: Some("bloom"), size: 16, 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, sampler) = (wgpu::BindingResource::TextureView, wgpu::BindingResource::Sampler(smooth));
+ let added = |l: usize| if l + 1 == sizes.len() { &down[l] } else { &up[l] }; // (the coarsest is all there is of it)
+ let mut groups = Vec::with_capacity(2 * sizes.len());
+ for l in 0..sizes.len() {
+ let source = if l == 0 { &light } else { &down[l - 1] };
+ groups.push(bind(0, &[(0, params.as_entire_binding()), (1, view(source)), (2, sampler.clone()), (3, view(&down[l]))]));
+ }
+ for l in (0..sizes.len() - 1).rev() {
+ groups.push(bind(1, &[(1, view(added(l + 1))), (2, sampler.clone()), (3, view(&up[l])), (4, view(&down[l]))]));
+ }
+ groups.push(bind(2, &[(0, params.as_entire_binding()), (2, sampler.clone()), (5, view(&paint)), (6, view(&light)), (7, view(added(0))), (8, view(target))]));
+ sizes.push([width, height]);
+ Bloomed { paint, light, params, groups, sizes }
+ }
+
+ /// A view's glow, once its composite has left its paint and light in `b`: `strength` the share of its light spread
+ /// (0 to 1), `tone` its tone mapping (1: AgX).
+ pub(crate) fn encode(&self, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, b: &Bloomed, strength: f32, tone: u32) {
+ let levels = b.sizes.len() - 1;
+ let params: [u32; 4] = [strength.to_bits(), (strength / levels as f32).to_bits(), tone, 0];
+ queue.write_buffer(&b.params, 0, bytemuck::cast_slice(&params));
+ let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("bloom"), 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);
+ };
+ for l in 0..levels {
+ dispatch(if l == 0 { 0 } else { 1 }, &b.groups[l], b.sizes[l], 8);
+ }
+ for (k, l) in (0..levels - 1).rev().enumerate() {
+ dispatch(2, &b.groups[levels + k], b.sizes[l], 8);
+ }
+ dispatch(3, &b.groups[2 * levels - 1], b.sizes[levels], 16);
+ }
+}
diff --git a/rust/engine/src/bloom.wgsl b/rust/engine/src/bloom.wgsl
new file mode 100644
index 00000000..61a5d131
--- /dev/null
+++ b/rust/engine/src/bloom.wgsl
@@ -0,0 +1,103 @@
+// A 3D view's bloom (`bloom.rs`): the glow a lens and a sensor spread around the light they take in, as Filament's
+// bloom has it (PostProcessManager::bloom; materials bloomDownsample, bloomUpsample) in its interpolating mode, which
+// keeps the light: a share of each pixel's light (the view's strength) is spread over the view, the rest stays where
+// it is. The share is taken from the light the view shows (its composite's: what lies nearer has hidden the light
+// behind it), at half the view's size (`spread`), then halved level by level (`down`), and the levels are added back up
+// from the coarsest (`up`), each as much of the glow as any other, so that it falls off about as the square of the
+// distance, out to the coarsest level's reach, as a lens's glare does. Each pixel is then shown with the glow over it
+// (`show`).
+
+// The view's glow: the share of its light spread, the share each level spreads (strength / levels), its tone mapping
+// (`tone.wgsl`'s `toned`).
+struct Glow {
+ strength: f32,
+ share: f32,
+ tone: u32,
+ unused: u32,
+};
+
+@group(0) @binding(0) var<uniform> params: Glow;
+// what a level is made from: the level before (the first's: the view's light), or the coarser levels added up
+@group(0) @binding(1) var source: texture_2d<f32>;
+@group(0) @binding(2) var bilinear: sampler; // clamped to the edges
+@group(0) @binding(3) var level: texture_storage_2d<rgba16float, write>;
+@group(0) @binding(4) var own: texture_2d<f32>; // a level's own share (`down`'s), which the coarser levels are added to
+@group(0) @binding(5) var paint: texture_2d<f32>; // the view's display paint, premultiplied, its alpha how much is lit
+@group(0) @binding(6) var light: texture_2d<f32>; // its light (exposed, premultiplied), its alpha how much is covered
+@group(0) @binding(7) var glow: texture_2d<f32>; // the glow, at half the view's size: its levels added up
+@group(0) @binding(8) var shown: texture_storage_2d<rgba8unorm, write>;
+
+// `source`'s light a step (x, y) of `t` from uv, bilinearly.
+fn tap(uv: vec2<f32>, t: vec2<f32>, x: f32, y: f32) -> vec3<f32> {
+ return textureSampleLevel(source, bilinear, uv + t * vec2<f32>(x, y), 0.0).rgb;
+}
+
+// Texel `id` of `level` from the level before it (`source`, twice its size): the mean of the 6 x 6 texels around it,
+// weighted toward its middle, by 13 bilinear taps (Jimenez's, as Filament's: the four around its centre, half the weight,
+// and four overlapping squares of four around them, an eighth each), which keeps the light (each texel of the level
+// before counts a quarter in all, as in a 2 x 2 box) and lets little alias where a small light moves across the texels.
+fn halved(id: vec2<u32>) -> vec3<f32> {
+ let uv = (vec2<f32>(id) + 0.5) / vec2<f32>(textureDimensions(level));
+ let t = 1.0 / vec2<f32>(textureDimensions(source));
+ let inner = tap(uv, t, -1.0, -1.0) + tap(uv, t, 1.0, -1.0) + tap(uv, t, -1.0, 1.0) + tap(uv, t, 1.0, 1.0);
+ let sides = tap(uv, t, 0.0, -2.0) + tap(uv, t, -2.0, 0.0) + tap(uv, t, 2.0, 0.0) + tap(uv, t, 0.0, 2.0);
+ let corners = tap(uv, t, -2.0, -2.0) + tap(uv, t, 2.0, -2.0) + tap(uv, t, -2.0, 2.0) + tap(uv, t, 2.0, 2.0);
+ return 0.125 * (inner + tap(uv, t, 0.0, 0.0)) + 0.0625 * sides + 0.03125 * corners;
+}
+
+// The first level: the share of the view's light each level spreads, at half its size.
+@compute @workgroup_size(8, 8)
+fn spread(@builtin(global_invocation_id) id: vec3<u32>) {
+ if (any(id.xy >= textureDimensions(level))) {
+ return;
+ }
+ textureStore(level, id.xy, vec4<f32>(halved(id.xy) * params.share, 1.0));
+}
+
+// Each level after it: the level before, at half its size.
+@compute @workgroup_size(8, 8)
+fn down(@builtin(global_invocation_id) id: vec3<u32>) {
+ if (any(id.xy >= textureDimensions(level))) {
+ return;
+ }
+ textureStore(level, id.xy, vec4<f32>(halved(id.xy), 1.0));
+}
+
+// Each level added up, from the coarsest: its own share and the coarser levels' (`source`, half its size), read through
+// a tent over the 3 x 3 of its texels around each (Filament's), which keeps the light.
+@compute @workgroup_size(8, 8)
+fn up(@builtin(global_invocation_id) id: vec3<u32>) {
+ if (any(id.xy >= textureDimensions(level))) {
+ return;
+ }
+ let uv = (vec2<f32>(id.xy) + 0.5) / vec2<f32>(textureDimensions(level));
+ let t = 1.0 / vec2<f32>(textureDimensions(level));
+ let sides = tap(uv, t, -1.0, 0.0) + tap(uv, t, 1.0, 0.0) + tap(uv, t, 0.0, -1.0) + tap(uv, t, 0.0, 1.0);
+ let corners = tap(uv, t, -1.0, -1.0) + tap(uv, t, 1.0, -1.0) + tap(uv, t, -1.0, 1.0) + tap(uv, t, 1.0, 1.0);
+ let coarser = (4.0 * tap(uv, t, 0.0, 0.0) + 2.0 * sides + corners) / 16.0;
+ textureStore(level, id.xy, vec4<f32>(textureLoad(own, id.xy, 0).rgb + coarser, 1.0));
+}
+
+// Each pixel as the view shows it with the glow over it (the composite's `seen`, the glow added): the glow is light,
+// over the whole pixel. Where the pixel is lit, it adds to what the glow leaves of the lit surfaces' light, and the two
+// are tone mapped once; where it shows display paint (the background, what has no material, what is fixed in the
+// frame), the glow is shown by the tone mapping on its own and added to the paint, as a display adds light (white stays
+// white); where it shows nothing, the glow is all it shows, as opaque as it is bright.
+@compute @workgroup_size(16, 16)
+fn show(@builtin(global_invocation_id) id: vec3<u32>) {
+ let size = textureDimensions(shown);
+ if (any(id.xy >= size)) {
+ return;
+ }
+ let p = textureLoad(paint, id.xy, 0);
+ let l = textureLoad(light, id.xy, 0);
+ let g = textureSampleLevel(glow, bilinear, (vec2<f32>(id.xy) + 0.5) / vec2<f32>(size), 0.0).rgb;
+ let over = toned(g, params.tone);
+ let covered = max(l.a, p.a);
+ let painted = covered - p.a;
+ var c = max(p.rgb, min(p.rgb + over * painted, vec3<f32>(painted))) + over * (1.0 - covered);
+ if (p.a > 0.0) {
+ c += toned(((1.0 - params.strength) * l.rgb + g * p.a) / p.a, params.tone) * p.a;
+ }
+ textureStore(shown, id.xy, vec4<f32>(c, covered + max(over.r, max(over.g, over.b)) * (1.0 - covered)));
+}
diff --git a/rust/engine/src/tone.wgsl b/rust/engine/src/tone.wgsl
new file mode 100644
index 00000000..930a3e64
--- /dev/null
+++ b/rust/engine/src/tone.wgsl
@@ -0,0 +1,46 @@
+// How light shows on a display: the radiance a view's lit content sends toward the eye, scaled by the exposure,
+// clipped or rolled off by AgX, encoded as sRGB (as every color is: `paint.wgsl`'s are).
+
+// Linear light (0-1) encoded as sRGB.
+fn gamma(c: vec3<f32>) -> vec3<f32> {
+ let l = clamp(c, vec3<f32>(0.0), vec3<f32>(1.0));
+ return select(1.055 * pow(l, vec3<f32>(1.0 / 2.4)) - 0.055, 12.92 * l, l <= vec3<f32>(0.0031308));
+}
+
+// AgX (Sobotka's, as Filament has it): the sRGB scene value into its working space (Rec.2020, inset), its log2 over
+// 16.5 stops through a sigmoid, back out (outset), to linear sRGB.
+const AGX_IN: mat3x3<f32> = mat3x3<f32>(
+ vec3<f32>(0.544904663, 0.140439629, 0.088826896),
+ vec3<f32>(0.373779945, 0.754110565, 0.178877349),
+ vec3<f32>(0.081385728, 0.105433482, 0.732250240),
+);
+const AGX_OUT: mat3x3<f32> = mat3x3<f32>(
+ vec3<f32>(1.127100582, -0.141329763, -0.141329763),
+ vec3<f32>(-0.110606643, 1.157823702, -0.110606643),
+ vec3<f32>(-0.016493939, -0.016493939, 1.251936407),
+);
+const REC2020_TO_SRGB: mat3x3<f32> = mat3x3<f32>(
+ vec3<f32>(1.660217713, -0.124553686, -0.018154913),
+ vec3<f32>(-0.587557716, 1.132944579, -0.100604647),
+ vec3<f32>(-0.072829428, -0.008347784, 1.118831740),
+);
+
+fn agx(c: vec3<f32>) -> vec3<f32> {
+ var v = max(AGX_IN * max(c, vec3<f32>(0.0)), vec3<f32>(1e-10));
+ v = clamp((log2(v) + 12.47393) / (4.026069 + 12.47393), vec3<f32>(0.0), vec3<f32>(1.0));
+ let x2 = v * v;
+ let x4 = x2 * x2;
+ let x6 = x4 * x2;
+ v = -17.86 * x6 * v + 78.01 * x6 - 126.7 * x4 * v + 92.06 * x4 - 28.72 * x2 * v + 4.361 * x2 - 0.1718 * v + 0.002857;
+ return REC2020_TO_SRGB * pow(max(AGX_OUT * v, vec3<f32>(0.0)), vec3<f32>(2.2));
+}
+
+// What exposed light shows as (sRGB-encoded): clipped (tone 0) or rolled off by AgX (1).
+fn toned(c: vec3<f32>, tone: u32) -> vec3<f32> {
+ return gamma(select(clamp(c, vec3<f32>(0.0), vec3<f32>(1.0)), clamp(agx(c), vec3<f32>(0.0), vec3<f32>(1.0)), tone == 1u));
+}
+
+// What a radiance shows as: scaled by the exposure, then shown.
+fn displayed(radiance: vec3<f32>, exposure: f32, tone: u32) -> vec3<f32> {
+ return toned(radiance * exposure, tone);
+}
diff --git a/rust/engine/src/vector.wgsl b/rust/engine/src/vector.wgsl
index 9e58a078..0d9a7c22 100644
--- a/rust/engine/src/vector.wgsl
+++ b/rust/engine/src/vector.wgsl
@@ -91,12 +91,16 @@ const NONE: u32 = 0xffffffffu;
// where what lies under carries light (`frame.counts.w` bit 1): the raster base's light (`blend.wgsl`'s `Base`), or
// what the group before left; `base` its paint then (1x1 where none)
@group(1) @binding(17) var base_light: texture_2d<f32>;
+// a 3D view's see-through points among its layers (`points_before`): the depths of each pixel's nearest layers
+// (`bound`), and its slabs, layer j - 1 the points between the j-th and the (j+1)-th of them (else 1x1)
+@group(1) @binding(20) var slab_bounds: texture_2d<f32>;
+@group(1) @binding(21) var slabs: texture_2d_array<f32>;
// A 3D view's see-through fragments (`blend.wgsl` appends them): per pixel a list, its head's index + 1 (0: none)
struct Node {
depth: f32, // at the pixel's centre
color: u32, // straight RGBA8
- key: u32, // record << 11 | samples covered << 3 | winding sign << 2 | kind (0 mesh or points, 3 stroke)
+ key: u32, // record << 11 | samples covered << 3 | winding sign << 2 | kind (0 mesh, 3 stroke)
next: u32, // the next node + 1 (0: none)
};
@@ -1314,11 +1318,13 @@ fn painted(o: u32, layer: u32, up: vec2<f32>) -> vec4<f32> {
// without the light's code and a mix's light (whose registers it would pay for unused).
override lighting: bool = false;
-// Whether the view lays rasters (a 2D view's points and meshes, a 3D view's raster base) and see-through fragments'
-// lists: a view without them composites by a pipeline without their code, whose registers (as many as the pixel's
-// longest path through the composite needs) every pixel of the view would pay for unused.
+// Whether the view lays rasters (a 2D view's points and meshes, a 3D view's raster base), see-through fragments'
+// lists and see-through points' slabs: a view without them composites by a pipeline without their code, whose
+// registers (as many as the pixel's longest path through the composite needs) every pixel of the view would pay for
+// unused.
override rasters: bool = true;
override lists: bool = true;
+override points: bool = false;
// A layer's paint as a mix: a fill with a material lit.
fn paint_of(o: u32, layer: u32, up: vec2<f32>) -> Mix {
@@ -1482,42 +1488,72 @@ fn node_layer(f: Found) -> Layer {
return Layer(1u, f.node.depth * (1.0 - frame.depth.x), 1.0);
}
-// What `slab` leaves: the pixel, the first fragment it did not lay (at 0: none left), the base's samples it did not.
-struct Slab {
- px: Pixel,
- next: Found,
- samples: u32,
-};
-
const SAME_LAYER: f32 = 1e-5; // a stroke's own fragments this close are one layer (its joints)
const FEW: u32 = 8u; // layers a pixel where depths cross sorts at once
+const SLABS: u32 = 4u; // a pixel's nearest layers its see-through points are laid among (`bound`)
+const NO_LAYER: f32 = -3.0e38; // nearer than every layer: where a pixel has fewer than SLABS (`bound`)
+
+// A pixel's see-through points that come before a layer at depth z, from slab `first` on, composited in their order,
+// and the first slab still to come. Slab j holds its points between the j-th and the (j+1)-th of its nearest layers
+// (`bound`), blended in their order (`blend_lists.wgsl`): it comes before the (j+1)-th, wherever the composite meets
+// that depth (a layer it hides, it never meets: the slab comes before the next it lays); the last, after everything.
+struct Points {
+ mix: Mix,
+ next: u32,
+};
-// The pixel with what comes before `until` of its fragments from `first` on and of its base's `samples` (a bit
-// each: not laid yet) laid over it as one layer: composited sample by sample (a base sample under its fragments,
-// nearest last; a stroke's overlapping pieces once), then the samples' mean, so no seam shows where a mesh's
-// triangles meet inside the pixel, nor where the base and the fragments share it.
-fn slab(px: Pixel, head: u32, first: Found, samples: u32, until: Layer, gid: vec2<u32>) -> Slab {
- if (!lists || ((first.at == 0u || !before(node_layer(first), until)) && samples == 0u)) {
- return Slab(px, first, samples);
+fn points_before(first: u32, z: f32, gid: vec2<u32>) -> Points {
+ var out = Points(Mix(), first);
+ if (!points || first > SLABS) {
+ return out;
}
+ let bounds = textureLoad(slab_bounds, gid, 0);
+ for (var j = first; j <= SLABS; j++) {
+ if (j < SLABS && z > bounds[j]) {
+ break; // farther than the layer after slab j
+ }
+ if (bounds[j - 1u] > NO_LAYER) {
+ out.mix = over(painted_mix(textureLoad(slabs, gid, i32(j - 1u), 0)), out.mix);
+ }
+ out.next = j + 1u;
+ }
+ return out;
+}
+
+// The pixel with what comes before `until` of its fragments from `u.next` on, of its base's `u.samples` (a bit each:
+// not laid yet) and of its points laid over it as one layer: composited sample by sample (a base sample under its
+// fragments, nearest last; a stroke's overlapping pieces once; points over every sample), then the samples' mean, so
+// no seam shows where a mesh's triangles meet inside the pixel, nor where the base and the fragments share it.
+fn slab(u: Under, head: u32, until: Layer, gid: vec2<u32>) -> Under {
+ if (!lists || ((u.next.at == 0u || !before(node_layer(u.next), until)) && u.samples == 0u)) {
+ return u;
+ }
+ var out = u;
var acc: array<Mix, 8>;
var kept: array<vec2<u32>, 8>; // per sample, the last fragment laid: its layer (record and kind), its depth
- var left = samples;
var laid = false;
for (var s = 0u; s < 8u; s++) {
acc[s] = Mix();
kept[s] = vec2<u32>(NONE, 0u);
- if ((samples & (1u << s)) != 0u && before(Layer(0u, base_sample_depth(gid, s) * (1.0 - frame.depth.x), 1.0), until)) {
+ if ((u.samples & (1u << s)) != 0u && before(Layer(0u, base_sample_depth(gid, s) * (1.0 - frame.depth.x), 1.0), until)) {
acc[s] = base_sample(gid, s);
- left &= ~(1u << s);
+ out.samples &= ~(1u << s);
laid = true;
}
}
- var f = first;
+ var f = u.next;
loop {
if (f.at == 0u || !before(node_layer(f), until)) {
break;
}
+ let farther = points_before(out.slab, node_layer(f).z, gid);
+ out.slab = farther.next;
+ if (farther.mix[1].a > 0.0) {
+ for (var s = 0u; s < frame.lists.w; s++) {
+ acc[s] = over(farther.mix, acc[s]);
+ }
+ out.shown += 1u;
+ }
let c = rgba8(f.node.color);
let p = painted_mix(vec4<f32>(c.rgb * c.a, c.a));
let mask = (f.node.key >> 3u) & 0xffu;
@@ -1532,37 +1568,44 @@ fn slab(px: Pixel, head: u32, first: Found, samples: u32, until: Layer, gid: vec
laid = true;
f = next_node(head, f);
}
- var out = Slab(px, f, left);
+ out.next = f;
if (laid) {
var sum = Mix();
for (var s = 0u; s < 8u; s++) {
sum += acc[s];
}
- out.px = lay(px, divided(sum, f32(frame.lists.w)), 1.0, vec2<u32>(0u), vec2<i32>(0), vec2<i32>(0));
+ out.px = lay(out.px, divided(sum, f32(frame.lists.w)), 1.0, vec2<u32>(0u), vec2<i32>(0), vec2<i32>(0));
}
return out;
}
-// What lies under the layers from `until` on: the base and the see-through fragments.
+// What lies under the layers from `until` on: the base, the see-through fragments and points.
struct Under {
px: Pixel,
next: Found, // the first fragment not laid
base_left: bool, // the base (as one layer) not laid
samples: u32, // where the pixel has fragments, the base's samples not laid (instead)
+ slab: u32, // the first of its points' slabs not laid (`points_before`)
+ shown: u32, // how many times points were laid
};
-// The pixel with the base and the see-through fragments (its list from `head`) that come before `until` laid over
-// it, in their order.
+// The pixel with the base, the see-through fragments (its list from `head`) and points that come before `until` laid
+// over it, in their order: the points once the base is (they lie in front of its opaque samples).
fn under(u: Under, head: u32, base: Layer, until: Layer, gid: vec2<u32>, up: vec2<f32>) -> Under {
var out = u;
if (u.base_left && before(base, until)) {
out.px = settle(out.px, base, gid, up);
out.base_left = false;
}
- let s = slab(out.px, head, out.next, out.samples, until, gid);
- out.px = s.px;
- out.next = s.next;
- out.samples = s.samples;
+ out = slab(out, head, until, gid);
+ if (!out.base_left) {
+ let farther = points_before(out.slab, until.z, gid);
+ out.slab = farther.next;
+ if (farther.mix[1].a > 0.0) {
+ out.px = lay(out.px, farther.mix, 1.0, vec2<u32>(0u), vec2<i32>(0), vec2<i32>(0));
+ out.shown += 1u;
+ }
+ }
return out;
}
@@ -1589,8 +1632,15 @@ struct Begun {
up: vec2<f32>,
};
+// Pixel gid's see-through fragments' list (only in the listed rows are the heads this frame's): its head (0: none).
+fn head_at(gid: vec2<u32>) -> u32 {
+ if (lists && frame.lists.x == 1u && gid.y >= frame.lists.y && gid.y < frame.lists.z) {
+ return list_head(gid.y * u32(frame.size.x) + gid.x);
+ }
+ return 0u;
+}
+
fn begin(gid: vec2<u32>) -> Begun {
- let size = vec2<u32>(frame.size.xy);
let tile = (gid.y / TILE) * frame.tiles.x + gid.x / TILE;
let pixel = vec2<f32>(gid);
let centre = pixel + 0.5;
@@ -1612,24 +1662,20 @@ fn begin(gid: vec2<u32>) -> Begun {
if ((frame.counts.z == 1u && base_at(gid)[1].a >= 1.0) || frame.counts.z == 2u) {
hidden = base_layer.z;
}
- // its see-through fragments (only in the listed rows are the heads this frame's)
- var head = 0u;
- if (lists && frame.lists.x == 1u && gid.y >= frame.lists.y && gid.y < frame.lists.z) {
- head = list_head(gid.y * size.x + gid.x);
- }
- // where it has fragments, its base sample by sample among them; elsewhere one layer
+ // its see-through fragments: where it has some, its base sample by sample among them; elsewhere one layer
+ let head = head_at(gid);
let none = Found(Node(0.0, 0u, 0u, 0u), 0u);
let all = (1u << frame.lists.w) - 1u;
- let fresh = Under(start, next_node(head, none), frame.counts.z == 1u && head == 0u, select(0u, all, frame.counts.z == 1u && head != 0u));
+ let fresh = Under(start, next_node(head, none), frame.counts.z == 1u && head == 0u, select(0u, all, frame.counts.z == 1u && head != 0u), 1u, 0u);
let first = tile_entry(tile);
let end = tile_entry(tile + 1u);
let entries = frame.tiles.x * frame.tiles.y + 1u; // where the tiles' entries begin
return Begun(fresh, base_layer, hidden, head, first, end, entries, pixel, centre, up);
}
-// The pixel's mix once what lies under nothing more (the base, the fragments left) is laid.
+// The pixel's mix once what lies under nothing more (the base, the fragments and points left) is laid.
fn finish(u0: Under, b: Begun, gid: vec2<u32>) -> Mix {
- let u = under(u0, b.head, b.base_layer, Layer(NONE, -3.0e38, 0.0), gid, b.up);
+ let u = under(u0, b.head, b.base_layer, Layer(NONE, NO_LAYER, 0.0), gid, b.up);
return u.px.s.a * u.px.s.inside + (1.0 - u.px.s.a) * u.px.s.outside;
}
@@ -1712,8 +1758,7 @@ fn laid(gid: vec2<u32>, b: Begun) -> Laid {
return Laid(true, finish(u, b, gid));
}
-// The pixel where depths cross: every layer again, in their order: gathered (up to FEW, sorted as they come), else
-// taken one at a time.
+// The pixel where depths cross: every layer again, in their order.
fn crossed(gid: vec2<u32>, b: Begun) -> Mix {
let base_layer = b.base_layer;
let hidden = b.hidden;
@@ -1725,45 +1770,44 @@ fn crossed(gid: vec2<u32>, b: Begun) -> Mix {
let centre = b.centre;
let up = b.up;
var u = b.fresh;
- var last = Layer(0u, 3.0e38, 0.0);
- var few: array<Layer, FEW>;
- var n = 0u;
- for (var k = first; k < end && n <= FEW; k++) {
- let e = tile_entry(entries + k);
- let o = e & 0xffffffu;
- let mask = e >> 24u;
- let local = vec2<i32>(pixel - rect_of(o).xy);
- let bsize = vec2<i32>(rect_of(o).zw);
- if (local.x < 0 || local.y < 0 || local.x >= bsize.x || local.y >= bsize.y) {
- continue;
- }
- for (var step = 0u; step < 3u && n <= FEW; step++) {
- let l = layer_at(o, mask, step, local, centre);
- if (l.c <= 1e-5 || l.z > hidden) {
+ // its layers in their order, FEW at a time: one pass over its tile's list keeps the FEW first after the last laid,
+ // sorted as they come (a pixel where n layers cross costs n / FEW passes, not n)
+ var last = Layer(0u, 3.0e38, 0.0); // nothing laid yet: before everything
+ // the last laid, if a whole path layer and nothing since: its paint, and the pixel before it
+ var prev = Layer(NONE, 0.0, 0.0);
+ var prev_paint = Mix();
+ var prev_under = u.px;
+ loop {
+ var few: array<Layer, FEW>;
+ var n = 0u;
+ for (var k = first; k < end; k++) {
+ let e = tile_entry(entries + k);
+ let o = e & 0xffffffu;
+ let mask = e >> 24u;
+ let local = vec2<i32>(pixel - rect_of(o).xy);
+ let bsize = vec2<i32>(rect_of(o).zw);
+ if (local.x < 0 || local.y < 0 || local.x >= bsize.x || local.y >= bsize.y) {
continue;
}
- if (n == FEW) {
- n = FEW + 1u; // too many: one at a time
- break;
- }
- var j = n;
- for (; j > 0u && before(l, few[j - 1u]); j--) {
- few[j] = few[j - 1u];
+ for (var step = 0u; step < 3u; step++) {
+ let l = layer_at(o, mask, step, local, centre);
+ if (l.c <= 1e-5 || l.z > hidden || !before(last, l) || (n == FEW && !before(l, few[FEW - 1u]))) {
+ continue;
+ }
+ var j = min(n, FEW - 1u);
+ for (; j > 0u && before(l, few[j - 1u]); j--) {
+ few[j] = few[j - 1u];
+ }
+ few[j] = l;
+ n = min(n + 1u, FEW);
}
- few[j] = l;
- n++;
}
- }
- if (n <= FEW) {
- // the last laid, if a whole path layer and nothing since: its paint, and the pixel before it
- var prev = Layer(NONE, 0.0, 0.0);
- var prev_paint = Mix();
- var prev_under = u.px;
for (var i = 0u; i < n; i++) {
let before_under = u.base_left;
let next_before = u.next.at;
+ let shown_before = u.shown;
u = under(u, head, base_layer, few[i], gid, up);
- if (u.base_left != before_under || u.next.at != next_before) {
+ if (u.base_left != before_under || u.next.at != next_before || u.shown != shown_before) {
prev = Layer(NONE, 0.0, 0.0);
}
let path = few[i].key != 0u && atlas_of((few[i].key >> 2u) - 1u).w == NONE;
@@ -1796,35 +1840,67 @@ fn crossed(gid: vec2<u32>, b: Begun) -> Mix {
prev_under = laid_before;
}
}
- } else {
- last = Layer(0u, 3.0e38, 0.0);
- loop {
- var next = Layer(NONE, -3.0e38, 0.0);
- for (var k = first; k < end; k++) {
- let e = tile_entry(entries + k);
+ if (n < FEW) {
+ break;
+ }
+ last = few[FEW - 1u];
+ }
+ return finish(u, b, gid);
+}
+
+// A pixel's nearest layers' depths met so far, far to near (NO_LAYER past the last), with a layer at depth z among them:
+// where all SLABS are met, only if it is nearer than the farthest, which makes room.
+fn nearer(k: vec4<f32>, z: f32) -> vec4<f32> {
+ var out = k;
+ if (out.w > NO_LAYER) {
+ if (z >= out.x) {
+ return out;
+ }
+ out = vec4<f32>(out.yzw, NO_LAYER);
+ }
+ var j = SLABS - 1u;
+ for (; j > 0u && out[j - 1u] < z; j--) {
+ out[j] = out[j - 1u];
+ }
+ out[j] = z;
+ return out;
+}
+
+// A 3D view's slab bounds: the depths of pixel gid's SLABS nearest layers, far to near (NO_LAYER where it has fewer),
+// its paths' and its see-through fragments', as the composite takes them (`layer_at`, `node_layer`), but what is fixed
+// in the frame (in front of everything, it parts no points). A see-through point counts those farther than it
+// (`blend_lists.wgsl`'s `slab_of`): with none, it is blended into the base; else into the slab between two of them,
+// which the composite lays between them (`points_before`). A point behind SLABS layers is behind them all: the base.
+fn bound(gid: vec2<u32>) -> vec4<f32> {
+ let tile = (gid.y / TILE) * frame.tiles.x + gid.x / TILE;
+ let entries = frame.tiles.x * frame.tiles.y + 1u;
+ let pixel = vec2<f32>(gid);
+ var k = vec4<f32>(NO_LAYER);
+ for (var i = tile_entry(tile); i < tile_entry(tile + 1u); i++) {
+ let e = tile_entry(entries + i);
let o = e & 0xffffffu;
- let mask = e >> 24u;
- let local = vec2<i32>(pixel - rect_of(o).xy);
- let bsize = vec2<i32>(rect_of(o).zw);
- if (local.x < 0 || local.y < 0 || local.x >= bsize.x || local.y >= bsize.y) {
- continue;
- }
- for (var step = 0u; step < 3u; step++) {
- let l = layer_at(o, mask, step, local, centre);
- if (l.c > 1e-5 && l.z <= hidden && before(last, l) && before(l, next)) {
- next = l;
- }
- }
- }
- if (next.key == NONE) {
- break;
+ let local = vec2<i32>(pixel - rect_of(o).xy);
+ let size = vec2<i32>(rect_of(o).zw);
+ if (local.x < 0 || local.y < 0 || local.x >= size.x || local.y >= size.y) {
+ continue;
+ }
+ for (var step = 0u; step < 3u; step++) {
+ let l = layer_at(o, e >> 24u, step, local, pixel + 0.5);
+ if (l.c > 1e-5 && l.z > -1.0) {
+ k = nearer(k, l.z);
}
- u = under(u, head, base_layer, next, gid, up);
- u.px = settle(u.px, next, gid, up);
- last = next;
}
}
- return finish(u, b, gid);
+ var at = head_at(gid);
+ loop {
+ if (at == 0u) {
+ break;
+ }
+ let f = Found(list_node(at - 1u), at);
+ k = nearer(k, node_layer(f).z);
+ at = f.node.next;
+ }
+ return k;
}
const TILE: u32 = 16u;
diff --git a/rust/engine/src/vector_compute.wgsl b/rust/engine/src/vector_compute.wgsl
index 9bb17fac..b0ebb236 100644
--- a/rust/engine/src/vector_compute.wgsl
+++ b/rust/engine/src/vector_compute.wgsl
@@ -1,6 +1,6 @@
// `vector.wgsl`'s compute passes: the flatten, a thread per slot, writing the
// records to storage; the composite, a thread per pixel, writing the view as a storage texture, and (a 3D view's)
-// the pixels where depths cross, a thread each.
+// the pixels where depths cross, a thread each; and a 3D view's slab bounds, a thread per pixel.
@group(1) @binding(3) var view_out: texture_storage_2d<rgba8unorm, write>;
@group(1) @binding(19) var light_out: texture_storage_2d<rgba16float, write>; // (1x1 where the group shows its pixels)
@@ -76,6 +76,17 @@ fn keep(@builtin(global_invocation_id) gid: vec3<u32>) {
store(gid.xy, finish(b.fresh, b, gid.xy));
}
+// A 3D view's slab bounds (`bound`), for its see-through points to find their slab by, before they are drawn.
+@group(2) @binding(0) var bounds_out: texture_storage_2d<rgba32float, write>;
+
+@compute @workgroup_size(16, 16)
+fn bound_slabs(@builtin(global_invocation_id) gid: vec3<u32>) {
+ if (gid.x >= u32(frame.size.x) || gid.y >= u32(frame.size.y)) {
+ return;
+ }
+ textureStore(bounds_out, gid.xy, bound(gid.xy));
+}
+
@compute @workgroup_size(1)
fn count_crossings() {
let groups = (atomicLoad(&crossings.count) + 63u) / 64u;