Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

Motion blur: each pixel gathered along the longest motion near it, as a box shutter spreads light

shinyobjectz929c03d5e450
diff --git a/systems/post/src/lib.rs b/systems/post/src/lib.rs
index 1a47a364..45869aea 100644
--- a/systems/post/src/lib.rs
+++ b/systems/post/src/lib.rs
@@ -13,6 +13,8 @@ pub mod camera;
pub mod lens;
pub mod views;
pub mod motion_blur;
+// raea's motion blur: the shutter's own (docs/raytracing.feature RT29)
+pub mod shutter;
pub mod dof;
pub mod effect_stack;
pub mod outline;
diff --git a/systems/post/src/motion_blur.rs b/systems/post/src/motion_blur.rs
index 4b4ed056..c51afd9b 100644
--- a/systems/post/src/motion_blur.rs
+++ b/systems/post/src/motion_blur.rs
@@ -1,5 +1,6 @@
-//! The camera's motion blur: raea/3d's MotionBlur, Bevy's own MotionBlur on the camera, its values keyed per
-//! frame, so a blur ramp plays as it renders; a frame without it has the component removed, so off is Bevy without it.
+//! The camera's motion blur: raea/3d's MotionBlur, raea's Shutter on the camera (shutter.rs; RAEA_MOTION_BLUR=bevy
+//! puts Bevy's own MotionBlur there instead, to compare), its values keyed per frame, so a blur ramp plays as it
+//! renders; a frame without it has the component removed, so off is the camera without it.
//!
//! Camera columns: mb_on (keyed: 1 where the frame has a MotionBlur), mb_shutter (the shutter angle, a fraction of a
//! frame, keyed), mb_samples
@@ -14,6 +15,8 @@ use super::*;
use bevy::core_pipeline::prepass::{DepthPrepass, MotionVectorPrepass};
use bevy::post_process::motion_blur::MotionBlur;
+use crate::shutter::Shutter;
+
/// Whether a camera row has a MotionBlur in some frame.
pub fn has_blur(vals: &BTreeMap<String, V>) -> bool {
vals.contains_key("mb_on")
@@ -32,13 +35,37 @@ fn blur_of(v: &BTreeMap<String, V>) -> Option<MotionBlur> {
(num(v, "mb_on", 0.0) > 0.5 && b.shutter_angle > 0.0).then_some(b)
}
+/// Whether the camera's blur is Bevy's MotionBlur (RAEA_MOTION_BLUR=bevy) rather than raea's Shutter.
+fn bevy_blur() -> bool {
+ std::env::var("RAEA_MOTION_BLUR").is_ok_and(|v| v == "bevy")
+}
+
+/// raea's shutter for a frame's blur: as long open, two taps a pixel for each of Bevy's samples each way.
+fn shutter_of(b: &MotionBlur) -> Shutter {
+ Shutter { open: b.shutter_angle, taps: 2 * b.samples }
+}
+
/// The frame's blur onto the camera: inserted, changed or removed as the frame's columns say.
-pub fn sync_motion_blur(frame: Res<FrameRows>, mut commands: Commands, cams: Query<(Entity, Option<&MotionBlur>), With<Camera3d>>) {
- for (e, mb) in &cams {
+pub fn sync_motion_blur(frame: Res<FrameRows>, mut commands: Commands, cams: Query<(Entity, Option<&MotionBlur>, Option<&Shutter>), With<Camera3d>>) {
+ let bevy = bevy_blur();
+ for (e, mb, shutter) in &cams {
let Some(v) = frame.vals(e) else { continue };
if !has_blur(&v) {
continue;
}
+ if !bevy {
+ match (blur_of(&v).map(|b| shutter_of(&b)), shutter) {
+ (Some(want), Some(s)) if *s == want => {}
+ (Some(want), _) => {
+ commands.entity(e).insert(want);
+ }
+ (None, Some(_)) => {
+ commands.entity(e).remove::<Shutter>();
+ }
+ (None, None) => {}
+ }
+ continue;
+ }
match (blur_of(&v), mb) {
(Some(want), Some(m)) if m.shutter_angle == want.shutter_angle && m.samples == want.samples => {}
(Some(want), _) => {
@@ -54,8 +81,8 @@ pub fn sync_motion_blur(frame: Res<FrameRows>, mut commands: Commands, cams: Que
/// The shaders' frame counter at the frame being drawn, while motion blur is on (its noise is seeded by it), so every
/// update of frame f samples the same.
-pub fn pin_frame_count(clock: Res<Clock>, cams: Query<Has<MotionBlur>, With<Camera3d>>, mut count: ResMut<bevy::diagnostic::FrameCount>) {
- if !cams.iter().any(|mb| mb) {
+pub fn pin_frame_count(clock: Res<Clock>, cams: Query<(Has<MotionBlur>, Has<Shutter>), With<Camera3d>>, mut count: ResMut<bevy::diagnostic::FrameCount>) {
+ if !cams.iter().any(|(mb, s)| mb || s) {
return;
}
let want = clock.0.max(0) as u32;
@@ -64,8 +91,9 @@ pub fn pin_frame_count(clock: Res<Clock>, cams: Query<Has<MotionBlur>, With<Came
}
}
-/// The systems, on every engine (they do nothing without a MotionBlur).
+/// The systems and raea's shutter pass, on every engine (they do nothing without a blur).
pub fn install(app: &mut App) {
+ crate::shutter::install(app);
app.add_systems(Last, pin_frame_count.after(bevy::diagnostic::update_frame_count));
}
@@ -85,4 +113,10 @@ mod tests {
v.insert("mb_shutter".to_string(), V::N(0.0));
assert!(blur_of(&v).is_none());
}
+
+ #[test]
+ fn the_shutter_takes_two_taps_for_each_sample_each_way() {
+ let s = shutter_of(&MotionBlur { shutter_angle: 0.5, samples: 16 });
+ assert_eq!((s.open, s.taps), (0.5, 32));
+ }
}
diff --git a/systems/post/src/shutter.rs b/systems/post/src/shutter.rs
new file mode 100644
index 00000000..e887cf3d
--- /dev/null
+++ b/systems/post/src/shutter.rs
@@ -0,0 +1,205 @@
+//! raea's motion blur (docs/raytracing.feature RT29): what a camera records while its shutter is open. The longest
+//! motion in each 20-pixel tile (across its rows, then down), then in each tile's 3x3 neighbourhood (shutter_tiles.wesl); each pixel gathered along
+//! the longest motion near it, every tap weighted as a box shutter spreads a moving pixel's light (shutter.wesl). Bevy's
+//! MotionBlur gathered each pixel along its own motion, so a still pixel beside a moving one took none of its light:
+//! a ball crossing a still frame was smeared inward only, its streak 64 px where the shutter's is 86 and 8% of its
+//! light gone. RAEA_MOTION_BLUR=bevy draws Bevy's still, to compare.
+
+use bevy::{
+ core_pipeline::{
+ prepass::{DepthPrepass, MotionVectorPrepass, ViewPrepassTextures},
+ schedule::Core3d,
+ Core3dSystems, FullscreenShader,
+ },
+ diagnostic::FrameCount,
+ post_process::bloom::bloom,
+ prelude::*,
+ render::{
+ camera::ExtractedCamera,
+ extract_component::{ExtractComponent, ExtractComponentPlugin},
+ render_resource::{
+ binding_types::{texture_2d, texture_2d_multisampled, texture_depth_2d, texture_depth_2d_multisampled, uniform_buffer_sized},
+ *,
+ },
+ renderer::{RenderContext, RenderDevice, ViewQuery},
+ texture::{CachedTexture, TextureCache},
+ view::ViewTarget,
+ Render, RenderApp, RenderStartup, RenderSystems,
+ },
+};
+
+/// A camera drawn with its shutter open for `open` of each frame, gathered by `taps` taps a pixel. Brings the depth
+/// and motion prepasses it reads.
+#[derive(Component, Clone, Copy, PartialEq, Debug, ExtractComponent)]
+#[extract_app(bevy::render::RenderApp)]
+#[require(DepthPrepass, MotionVectorPrepass)]
+pub struct Shutter {
+ pub open: f32,
+ pub taps: u32,
+}
+
+/// a tile's side in pixels, and the farthest a pixel's light is carried each way while the shutter is open (a motion
+/// longer than two tiles is drawn two tiles long)
+pub const TILE: u32 = 20;
+/// the tiles' format: each tile's longest motion while the shutter is open, in pixels (rg)
+const TILES: TextureFormat = TextureFormat::Rgba16Float;
+
+pub fn install(app: &mut App) {
+ bevy::asset::embedded_asset!(app, "shutter.wesl");
+ bevy::asset::embedded_asset!(app, "shutter_tiles.wesl");
+ app.add_plugins(ExtractComponentPlugin::<Shutter>::default());
+ let Some(render_app) = app.get_sub_app_mut(RenderApp) else { return };
+ render_app.add_systems(RenderStartup, init_pipeline);
+ render_app.add_systems(Render, textures.in_set(RenderSystems::PrepareResources));
+ render_app.add_systems(Core3d, draw.before(bloom).in_set(Core3dSystems::PostProcess));
+}
+
+/// the number of tiles across a side of `px` pixels
+fn tiles(px: u32) -> u32 {
+ px.div_ceil(TILE).max(1)
+}
+
+/// a view's tiles (each tile row's longest motion, each tile's, then each neighbourhood's) and its parameters
+#[derive(Component)]
+struct ShutterFrame {
+ rows: CachedTexture,
+ longest: CachedTexture,
+ near: CachedTexture,
+ params: Buffer,
+}
+
+fn textures(mut commands: Commands, mut cache: ResMut<TextureCache>, device: Res<RenderDevice>, frame: Res<FrameCount>, views: Query<(Entity, &ExtractedCamera, &Shutter)>) {
+ for (e, camera, s) in &views {
+ let Some(size) = camera.physical_target_size else { continue };
+ let desc = |label: &'static str, height: u32| TextureDescriptor {
+ label: Some(label),
+ size: Extent3d { width: tiles(size.x), height, depth_or_array_layers: 1 },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: TextureDimension::D2,
+ format: TILES,
+ usage: TextureUsages::TEXTURE_BINDING | TextureUsages::RENDER_ATTACHMENT,
+ view_formats: &[],
+ };
+ let rows = cache.get(&device, desc("shutter_rows", size.y.max(1)));
+ let (longest, near) = (cache.get(&device, desc("shutter_longest", tiles(size.y))), cache.get(&device, desc("shutter_near", tiles(size.y))));
+ let words: Vec<u8> = [s.open.max(0.0).to_bits(), s.taps.max(2), TILE, frame.0].iter().flat_map(|w| w.to_le_bytes()).collect();
+ let params = device.create_buffer_with_data(&BufferInitDescriptor { label: Some("shutter_params"), contents: &words, usage: BufferUsages::UNIFORM });
+ commands.entity(e).insert(ShutterFrame { rows, longest, near, params });
+ }
+}
+
+/// the passes that read the prepasses, for single-sampled prepasses or multisampled ones (MSAA)
+struct Reads {
+ tiles_layout: BindGroupLayoutDescriptor,
+ gather_layout: BindGroupLayoutDescriptor,
+ rows: CachedRenderPipelineId,
+ /// one gather pipeline a view target format: an HDR camera's (Rgba16Float) and an LDR one's
+ hdr: CachedRenderPipelineId,
+ ldr: CachedRenderPipelineId,
+}
+
+#[derive(Resource)]
+struct ShutterPipeline {
+ single: Reads,
+ multi: Reads,
+ /// the tiles' and neighbourhoods' passes, which read only the pass before's tiles
+ near_layout: BindGroupLayoutDescriptor,
+ longest: CachedRenderPipelineId,
+ near: CachedRenderPipelineId,
+}
+
+fn init_pipeline(mut commands: Commands, assets: Res<AssetServer>, fullscreen: Res<FullscreenShader>, cache: Res<PipelineCache>) {
+ let float = TextureSampleType::Float { filterable: false };
+ let params = || uniform_buffer_sized(false, core::num::NonZero::new(16));
+ let tiles_shader: Handle<Shader> = assets.load("embedded://raea_sys_post/shutter_tiles.wesl");
+ let shader: Handle<Shader> = assets.load("embedded://raea_sys_post/shutter.wesl");
+ let pipeline = |label: &'static str, layout: &BindGroupLayoutDescriptor, shader: &Handle<Shader>, entry: &'static str, format: TextureFormat, multi: bool| {
+ cache.queue_render_pipeline(RenderPipelineDescriptor {
+ label: Some(label.into()),
+ layout: vec![layout.clone()],
+ vertex: fullscreen.to_vertex_state(),
+ fragment: Some(FragmentState {
+ shader: shader.clone(),
+ shader_defs: if multi { vec!["MULTISAMPLED".into()] } else { vec![] },
+ entry_point: Some(entry.into()),
+ targets: vec![Some(ColorTargetState { format, blend: None, write_mask: ColorWrites::ALL })],
+ ..default()
+ }),
+ ..default()
+ })
+ };
+ let near_layout = BindGroupLayoutDescriptor::new("shutter_near_layout", &BindGroupLayoutEntries::sequential(ShaderStages::FRAGMENT, (texture_2d(float), params())));
+ let longest = pipeline("shutter_longest", &near_layout, &tiles_shader, "tile_max", TILES, false);
+ let near = pipeline("shutter_near", &near_layout, &tiles_shader, "neighbour_max", TILES, false);
+ let reads = |multi: bool| {
+ let (motion, depth) = if multi { (texture_2d_multisampled(float), texture_depth_2d_multisampled()) } else { (texture_2d(float), texture_depth_2d()) };
+ let tiles_layout = BindGroupLayoutDescriptor::new("shutter_tiles_layout", &BindGroupLayoutEntries::sequential(ShaderStages::FRAGMENT, (motion, params())));
+ // the frame, the motion prepass, the depth prepass, the neighbourhoods' longest motions
+ let gather_layout = BindGroupLayoutDescriptor::new("shutter_layout", &BindGroupLayoutEntries::sequential(ShaderStages::FRAGMENT, (texture_2d(float), motion, depth, texture_2d(float), params())));
+ let rows = pipeline("shutter_rows", &tiles_layout, &tiles_shader, "tile_rows", TILES, multi);
+ let hdr = pipeline("shutter", &gather_layout, &shader, "gather", super::bevy_api::HDR_FORMAT, multi);
+ let ldr = pipeline("shutter", &gather_layout, &shader, "gather", TextureFormat::Rgba8UnormSrgb, multi);
+ Reads { tiles_layout, gather_layout, rows, hdr, ldr }
+ };
+ commands.insert_resource(ShutterPipeline { single: reads(false), multi: reads(true), near_layout, longest, near });
+}
+
+/// one fullscreen triangle into `out`
+fn pass(ctx: &mut RenderContext, label: &'static str, out: &TextureView, rp: &RenderPipeline, group: &BindGroup, viewport: Option<&bevy::camera::Viewport>) {
+ let mut pass = ctx.command_encoder().begin_render_pass(&RenderPassDescriptor {
+ label: Some(label),
+ color_attachments: &[Some(RenderPassColorAttachment { view: out, depth_slice: None, resolve_target: None, ops: Operations::default() })],
+ depth_stencil_attachment: None,
+ timestamp_writes: None,
+ occlusion_query_set: None,
+ multiview_mask: None,
+ });
+ pass.set_pipeline(rp);
+ pass.set_bind_group(0, group, &[]);
+ if let Some(v) = viewport {
+ pass.set_viewport(v.physical_position.x as f32, v.physical_position.y as f32, v.physical_size.x as f32, v.physical_size.y as f32, v.depth.start, v.depth.end);
+ }
+ pass.draw(0..3, 0..1);
+}
+
+fn draw(view: ViewQuery<(&ExtractedCamera, &ViewTarget, &ViewPrepassTextures, &ShutterFrame, &Msaa)>, pipeline: Option<Res<ShutterPipeline>>, cache: Res<PipelineCache>, mut ctx: RenderContext) {
+ let Some(p) = pipeline else { return };
+ let (camera, target, prepass, f, msaa) = view.into_inner();
+ let r = if msaa.samples() > 1 { &p.multi } else { &p.single };
+ let id = if target.main_texture_format() == super::bevy_api::HDR_FORMAT { r.hdr } else { r.ldr };
+ let (Some(rows), Some(longest), Some(near), Some(gather), Some(motion), Some(depth)) = (
+ cache.get_render_pipeline(r.rows),
+ cache.get_render_pipeline(p.longest),
+ cache.get_render_pipeline(p.near),
+ cache.get_render_pipeline(id),
+ prepass.motion_vectors_view(),
+ prepass.depth_only_view(),
+ ) else {
+ return;
+ };
+ let device = ctx.render_device().clone();
+ let g = device.create_bind_group("shutter_rows_group", &cache.get_bind_group_layout(&r.tiles_layout), &BindGroupEntries::sequential((motion, f.params.as_entire_binding())));
+ pass(&mut ctx, "shutter_rows", &f.rows.default_view, rows, &g, None);
+ let g = device.create_bind_group("shutter_longest_group", &cache.get_bind_group_layout(&p.near_layout), &BindGroupEntries::sequential((&f.rows.default_view, f.params.as_entire_binding())));
+ pass(&mut ctx, "shutter_longest", &f.longest.default_view, longest, &g, None);
+ let g = device.create_bind_group("shutter_near_group", &cache.get_bind_group_layout(&p.near_layout), &BindGroupEntries::sequential((&f.longest.default_view, f.params.as_entire_binding())));
+ pass(&mut ctx, "shutter_near", &f.near.default_view, near, &g, None);
+ let post = target.post_process_write();
+ let g = device.create_bind_group(
+ "shutter_group",
+ &cache.get_bind_group_layout(&r.gather_layout),
+ &BindGroupEntries::sequential((post.source, motion, depth, &f.near.default_view, f.params.as_entire_binding())),
+ );
+ pass(&mut ctx, "shutter", post.destination, gather, &g, camera.viewport.as_ref());
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn tiles_cover_the_frame() {
+ assert_eq!((tiles(512), tiles(1920), tiles(1080), tiles(1)), (26, 96, 54, 1));
+ }
+}
diff --git a/systems/post/src/shutter.wesl b/systems/post/src/shutter.wesl
new file mode 100644
index 00000000..73d0c718
--- /dev/null
+++ b/systems/post/src/shutter.wesl
@@ -0,0 +1,123 @@
+// raea's motion blur (shutter.rs): what a camera records while its shutter is open, each pixel gathered along the
+// longest motion near it (shutter_tiles.wesl). A box shutter spreads each moving pixel's light evenly along its path,
+// so a pixel x gets from a tap y on that path 1/|v_y| a pixel of path, if y's path reaches x:
+// - a tap nearer the camera than x (in front of it): by y's own motion. So a still wall beside a moving ball takes the
+// share of the open shutter the ball is over it, which Bevy's MotionBlur (gathering by each pixel's own motion,
+// none on the wall) drew as no blur at all, the streak only half as long as it is;
+// - a tap as far as x or farther: by x's motion, the same surface along x's own path, or what x moved off to show.
+// Whatever share of the shutter nothing reaches x is x itself, still. (What a nearer still surface hides in the frame,
+// such as a wall's streak sliding out from behind a ball the camera holds still, no tap can find: there the streak stops
+// short at the ball's edge.) Each tap stands for |v_n| / n pixels of path, so
+// a pixel inside a moving surface gathers a whole one from its own path, and one a moving edge passes the share of
+// the open shutter the edge is over it, as a camera has it (McGuire et al. 2012's tiles and depth split, its cone
+// weights replaced by the box shutter's own).
+import bevy_core_pipeline::fullscreen_vertex_shader::FullscreenVertexOutput;
+
+struct Params {
+ open: f32,
+ taps: u32,
+ tile: u32,
+ frame: u32,
+}
+
+@group(0) @binding(0) var colour_tex: texture_2d<f32>;
+// the prepasses, multisampled under MSAA: textureLoad's 0 is then their first sample, as it's the mip otherwise
+@if(MULTISAMPLED) {
+@group(0) @binding(1) var motion_tex: texture_multisampled_2d<f32>;
+@group(0) @binding(2) var depth_tex: texture_depth_multisampled_2d;
+}
+@else {
+@group(0) @binding(1) var motion_tex: texture_2d<f32>;
+@group(0) @binding(2) var depth_tex: texture_depth_2d;
+}
+@group(0) @binding(3) var near_tex: texture_2d<f32>;
+@group(0) @binding(4) var<uniform> p: Params;
+
+// how much nearer than its depth a surface must be to count as in front of it: a share of the distance
+const FRONT_SOFT = 0.02;
+
+// a motion prepass's value (uv a frame) while the shutter is open, in pixels, no longer than two tiles
+fn opened_of(mv: vec2<f32>, size: vec2<f32>) -> vec2<f32> {
+ let v = mv * size * p.open;
+ let l = length(v);
+ let most = 2.0 * f32(p.tile);
+ return select(v, v * (most / l), l > most);
+}
+
+fn opened(q: vec2<i32>, size: vec2<f32>) -> vec2<f32> {
+ return opened_of(textureLoad(motion_tex, q, 0).xy, size);
+}
+
+// the pixel's own depth and motion: under MSAA its nearest sample's, so an edge pixel whose colour is part the
+// moving surface counts as that surface (its first sample alone, the background behind, drew a ring where the
+// surface's edge was: the pixel kept its part-surface colour as still background)
+struct Own {
+ depth: f32,
+ motion: vec2<f32>,
+}
+fn own(x: vec2<i32>) -> Own {
+ var o = Own(textureLoad(depth_tex, x, 0), textureLoad(motion_tex, x, 0).xy);
+ @if(MULTISAMPLED) {
+ for (var s = 1; s < i32(textureNumSamples(depth_tex)); s++) {
+ let z = textureLoad(depth_tex, x, s);
+ if z > o.depth { o = Own(z, textureLoad(motion_tex, x, s).xy); }
+ }
+ }
+ return o;
+}
+
+// 1 where depth a (reverse Z: larger is nearer, 0 the sky) is in front of depth b by FRONT_SOFT of b's distance or
+// more, 0 where it's as far or farther
+fn in_front(a: f32, b: f32) -> f32 {
+ return saturate((a - b) / (FRONT_SOFT * max(a, b) + 1e-30));
+}
+
+// 1 per pixel of path a motion of length l spreads its light over, where its path reaches d pixels away (an edge a
+// pixel soft); a motion shorter than a tap's stretch counts as the tap's own
+fn spread(l: f32, d: f32, stretch: f32) -> f32 {
+ return saturate(0.5 + 0.5 * l - d) / max(l, stretch);
+}
+
+// interleaved gradient noise (Jimenez 2014), moved each frame: where along its stretch each tap falls
+fn noise(q: vec2<i32>, frame: u32) -> f32 {
+ let x = vec2<f32>(q) + 5.588238 * f32(frame % 64u);
+ return fract(52.9829189 * fract(0.06711056 * x.x + 0.00583715 * x.y));
+}
+
+@fragment
+fn gather(in: FullscreenVertexOutput) -> @location(0) vec4<f32> {
+ let dims = vec2<i32>(textureDimensions(colour_tex));
+ let size = vec2<f32>(dims);
+ let x = vec2<i32>(in.position.xy);
+ let centre = textureLoad(colour_tex, x, 0);
+ let tiles = vec2<i32>(textureDimensions(near_tex));
+ let vn = textureLoad(near_tex, clamp(x / i32(p.tile), vec2(0), tiles - 1), 0).xy;
+ let ln = length(vn);
+ // nothing near moves a pixel while the shutter is open
+ if ln < 1.0 { return centre; }
+
+ let o = own(x);
+ let lx = length(opened_of(o.motion, size));
+ let zx = o.depth;
+ // three taps every two pixels of the path at most: a short blur (a frame played at 120 Hz moves a few pixels)
+ // needs no more (one a pixel left the tests' streaks a quarter noisier)
+ let n = clamp(u32(ceil(1.5 * ln)), 2u, max(p.taps, 2u));
+ let stretch = ln / f32(n);
+ let j = noise(x, p.frame);
+ var sum = vec3(0.0);
+ var got = 0.0;
+ for (var i = 0u; i < n; i++) {
+ let along = vn * ((f32(i) + j) / f32(n) - 0.5);
+ let y = vec2<i32>(floor(vec2<f32>(x) + 0.5 + along));
+ if any(y < vec2(0)) || any(y >= dims) { continue; }
+ let d = length(along);
+ let front = in_front(textureLoad(depth_tex, y, 0), zx);
+ let ly = length(opened(y, size));
+ let w = stretch * (front * spread(ly, d, stretch) + (1.0 - front) * spread(lx, d, stretch));
+ sum += w * textureLoad(colour_tex, y, 0).rgb;
+ got += w;
+ }
+ // the rest of the open shutter is the pixel itself
+ let rgb = (sum + max(1.0 - got, 0.0) * centre.rgb) / max(got, 1.0);
+ return vec4(rgb, centre.a);
+}
diff --git a/systems/post/src/shutter_tiles.wesl b/systems/post/src/shutter_tiles.wesl
new file mode 100644
index 00000000..28552851
--- /dev/null
+++ b/systems/post/src/shutter_tiles.wesl
@@ -0,0 +1,82 @@
+// raea's motion blur, its tiles (shutter.rs): the longest motion in each tile of the frame (across each tile's rows,
+// then down them: two passes of 20 reads, where one of 400 kept most of the GPU waiting, 1.1 ms of 1.9 at 1080p), then
+// in each tile's 3x3 neighbourhood, so a pixel the motion of something near it can reach knows it's there, however
+// still it is itself.
+
+struct Params {
+ /// the share of a frame the shutter is open
+ open: f32,
+ /// taps along the motion, per pixel
+ taps: u32,
+ /// a tile's side in pixels: also the farthest a pixel's light is carried each way
+ tile: u32,
+ /// the frame, the taps' noise
+ frame: u32,
+}
+
+// the motion prepass (tile_rows: multisampled under MSAA, its first sample read), or the pass before's tiles
+@if(MULTISAMPLED) {
+@group(0) @binding(0) var input_tex: texture_multisampled_2d<f32>;
+}
+@else {
+@group(0) @binding(0) var input_tex: texture_2d<f32>;
+}
+@group(0) @binding(1) var<uniform> p: Params;
+
+// a pixel's motion while the shutter is open, in pixels: the motion prepass's (where it was a frame before to where it
+// is, in uv) times the share the shutter is open, no longer than two tiles (a tile each way)
+fn opened(mv: vec2<f32>, size: vec2<f32>) -> vec2<f32> {
+ let v = mv * size * p.open;
+ let l = length(v);
+ let most = 2.0 * f32(p.tile);
+ return select(v, v * (most / l), l > most);
+}
+
+// the longest motion along each row of each tile: one texel a tile across, a row of the frame down
+@fragment
+fn tile_rows(@builtin(position) at: vec4<f32>) -> @location(0) vec4<f32> {
+ let size = vec2<i32>(textureDimensions(input_tex));
+ let k = i32(p.tile);
+ let row = vec2<i32>(at.xy);
+ var best = vec2(0.0);
+ for (var x = 0; x < k; x++) {
+ let q = vec2(row.x * k + x, row.y);
+ if q.x >= size.x { break; }
+ let v = opened(textureLoad(input_tex, q, 0).xy, vec2<f32>(size));
+ if dot(v, v) > dot(best, best) { best = v; }
+ }
+ return vec4(best, 0.0, 1.0);
+}
+
+// each tile's longest motion: the longest of its rows'
+@fragment
+fn tile_max(@builtin(position) at: vec4<f32>) -> @location(0) vec4<f32> {
+ let size = vec2<i32>(textureDimensions(input_tex));
+ let k = i32(p.tile);
+ let tile = vec2<i32>(at.xy);
+ var best = vec2(0.0);
+ for (var y = 0; y < k; y++) {
+ let q = vec2(tile.x, tile.y * k + y);
+ if q.y >= size.y { break; }
+ let v = textureLoad(input_tex, q, 0).xy;
+ if dot(v, v) > dot(best, best) { best = v; }
+ }
+ return vec4(best, 0.0, 1.0);
+}
+
+// each tile's longest motion among its own and its eight neighbours'
+@fragment
+fn neighbour_max(@builtin(position) at: vec4<f32>) -> @location(0) vec4<f32> {
+ let tiles = vec2<i32>(textureDimensions(input_tex));
+ let c = vec2<i32>(at.xy);
+ var best = vec2(0.0);
+ for (var y = -1; y <= 1; y++) {
+ for (var x = -1; x <= 1; x++) {
+ let q = c + vec2(x, y);
+ if any(q < vec2(0)) || any(q >= tiles) { continue; }
+ let v = textureLoad(input_tex, q, 0).xy;
+ if dot(v, v) > dot(best, best) { best = v; }
+ }
+ }
+ return vec4(best, 0.0, 1.0);
+}