EffectCraft: An open-source motion graphics and compositing tool written by scratch in pure Rust
Merge main into M12.7 (bokeh DOF: the GPU 3D path takes the CPU's bokeh-blurred plane buffers)
Brandon Thomasbe282ce194f5
diff --cc crates/gpu/src/classic3d.rsindex 0d141c921,000000000..9e73edb3fmode 100644,000000..100644--- a/crates/gpu/src/classic3d.rs+++ b/crates/gpu/src/classic3d.rs@@@ -1,244 -1,0 +1,233 @@@+//! Classic 3D runs on the GPU (`classic3d.wgsl`): the CPU prepares the planes+//! ([`Renderer::prepare_3d_run`](effectcraft_render::Renderer::prepare_3d_run): layer buffers,- //! homographies, materials, lights, track mattes), the GPU blurs depth of field, packs the++//! homographies, materials, lights, track mattes, bokeh depth of field), the GPU packs the+//! buffers into one atlas texture and runs the per-pixel depth sort, lighting, ray-cast shadows+//! and blending of `render::three_d::compose` in one kernel.++use std::collections::HashMap;++use effectcraft_geom::Mat4;+use effectcraft_project::LightKind;+use effectcraft_render::three_d::{LightState, PlaneGeo, Run3d};++use crate::context::{Enc, GpuImage, Params};+use crate::ops::mode_id;++/// Fragments kept per pixel (`MAX_FRAGS` in the shader). Runs that could stack more planes on+/// one pixel render on the CPU.+const MAX_FRAGS: usize = 32;++/// Little-endian words for the shader's storage structs.+#[derive(Default)]+struct Words(Vec<u8>);++impl Words {+ fn f(&mut self, v: [f32; 4]) {+ for x in v {+ self.0.extend_from_slice(&x.to_le_bytes());+ }+ }+ fn u(&mut self, v: [u32; 4]) {+ for x in v {+ self.0.extend_from_slice(&x.to_le_bytes());+ }+ }+ fn d(&mut self, v: [f64; 4]) {+ self.f(v.map(|x| x as f32));+ }+ /// Pad an empty array to one element (`size` bytes) so its binding is valid.+ fn at_least(mut self, size: usize) -> Vec<u8> {+ if self.0.len() < size {+ self.0.resize(size, 0);+ }+ self.0+ }+}++fn affine_rows(w: &mut Words, m: &Mat4) {+ for r in 0..3 {+ w.d(m.0[r]);+ }+}++/// Shelf-pack rectangles into an atlas no larger than `max` on a side: (width, height,+/// positions).+fn pack(sizes: &[(u32, u32)], max: u32) -> Option<(u32, u32, Vec<(u32, u32)>)> {+ let maxw = sizes.iter().map(|s| s.0).max()?;+ if maxw > max {+ return None;+ }+ let area: f64 = sizes.iter().map(|s| s.0 as f64 * s.1 as f64).sum();+ let limit = maxw.max((area.sqrt() * 1.25).ceil() as u32).min(max);+ let mut order: Vec<usize> = (0..sizes.len()).collect();+ order.sort_by_key(|&i| std::cmp::Reverse(sizes[i].1));+ let mut pos = vec![(0, 0); sizes.len()];+ let (mut x, mut y, mut shelf, mut width) = (0u32, 0u32, 0u32, 0u32);+ for i in order {+ let (w, h) = sizes[i];+ if x + w > limit {+ y += shelf;+ x = 0;+ shelf = 0;+ }+ pos[i] = (x, y);+ x += w;+ shelf = shelf.max(h);+ width = width.max(x);+ }+ let height = y + shelf;+ (height <= max).then_some((width.max(1), height.max(1), pos))+}++/// Upper bound of the planes drawn on any one pixel: a pixel covered by a set of planes lies in+/// each one's box, so every plane of the set overlaps the box of any member.+fn max_overlap(boxes: &[[i64; 4]]) -> usize {+ boxes.iter().map(|a| boxes.iter().filter(|b| a[0] < b[2] && b[0] < a[2] && a[1] < b[3] && b[1] < a[3]).count()).max().unwrap_or(0)+}++fn light_kind(k: LightKind) -> u32 {+ match k {+ LightKind::Ambient | LightKind::Environment => 0,+ LightKind::Parallel => 1,+ LightKind::Point => 2,+ LightKind::Spot => 3,+ }+}++fn write_geo(w: &mut Words, g: &PlaneGeo) {+ // The homography is defined up to scale: normalise it (by a positive factor, keeping the+ // sign tests) into f32's comfortable range.+ let m = g.hinv.0.iter().flatten().fold(0.0f64, |a, v| a.max(v.abs()));+ let k = if m > 0.0 { 1.0 / m } else { 1.0 };+ for r in 0..3 {+ w.d([g.hinv.0[r][0] * k, g.hinv.0[r][1] * k, g.hinv.0[r][2] * k, 0.0]);+ }+ w.d([g.depth[0], g.depth[1], g.depth[2], 0.0]);+ affine_rows(w, &g.world);+ w.d([g.normal.x, g.normal.y, g.normal.z, 0.0]);+ w.d([g.cam.eye.x, g.cam.eye.y, g.cam.eye.z, if g.cam.ortho { 1.0 } else { 0.0 }]);+ let f = g.cam.forward();+ w.d([f.x, f.y, f.z, 0.0]);+}++fn write_light(w: &mut Words, l: &LightState) {+ w.u([light_kind(l.kind), l.falloff, l.casts_shadows as u32, 0]);+ w.d([l.pos.x, l.pos.y, l.pos.z, 0.0]);+ w.d([l.dir.x, l.dir.y, l.dir.z, 0.0]);+ w.f([l.color[0], l.color[1], l.color[2], 0.0]);+ w.d([l.cone_half, l.feather, l.radius, l.falloff_distance]);+ w.d([l.shadow_darkness, l.shadow_diffusion, 0.0, 0.0]);+}++const PLANE_BYTES: usize = 12 * 16;+const GEO_BYTES: usize = 10 * 16;+const LIGHT_BYTES: usize = 6 * 16;++/// Composite a prepared Classic 3D run over `canvas`. `None` when it cannot run here (the+/// caller draws it on the CPU).+pub(crate) fn draw_run(e: &mut Enc, run: &Run3d, canvas: &GpuImage) -> Option<GpuImage> {+ let (w, h) = (canvas.width, canvas.height);+ let boxes: Vec<[i64; 4]> = run.planes.iter().filter(|p| p.draw).map(|p| p.bbox).collect();+ if boxes.is_empty() {+ return Some(canvas.clone());+ }+ if max_overlap(&boxes) > MAX_FRAGS+ || run.planes.iter().any(|p| p.winv.0[3] != [0.0, 0.0, 0.0, 1.0] || p.geos.iter().any(|g| g.world.0[3] != [0.0, 0.0, 0.0, 1.0]))+ {+ return None;+ }- // Plane textures: the (cached) layer upload, depth-of-field blurred when asked.++ // Plane textures: the layer uploads (cached per buffer; bokeh depth of field is already in++ // them).+ let mut texs: Vec<(GpuImage, [f64; 2])> = Vec::with_capacity(run.planes.len());+ for p in &run.planes {- let mut img = e.g.upload_buf(&p.buf)?;- let mut off = p.buf.offset;- if let Some((sigma, pad)) = p.dof {- let (pw, ph) = (img.width + 2 * pad, img.height + 2 * pad);- if !e.g.fits(pw, ph) {- return None;- }- let padded = e.image(pw, ph);- e.copy_into(&img, &padded, pad, pad);- img = crate::effects::gaussian_blur(e, &padded, sigma, sigma, false);- off = [off[0] + pad as f64, off[1] + pad as f64];- }- texs.push((img, off));++ texs.push((e.g.upload_buf(&p.buf)?, p.buf.offset));+ }+ let sizes: Vec<(u32, u32)> = texs.iter().map(|(t, _)| (t.width, t.height)).collect();+ let (aw, ah, pos) = pack(&sizes, e.g.max_dim)?;+ if (aw as u64) * (ah as u64) * 16 > 2 << 30 {+ return None;+ }+ let atlas = e.image(aw, ah);+ for ((t, _), &(x, y)) in texs.iter().zip(&pos) {+ e.copy_into(t, &atlas, x, y);+ }+ // Track mattes (shared by the planes of one layer).+ let mut mattes: Vec<f32> = vec![];+ let mut matte_ix: HashMap<usize, u32> = HashMap::new();+ let n_px = w as usize * h as usize;+ let mut planes = Words::default();+ let mut geos = Words::default();+ let mut n_geos = 0u32;+ for ((p, (t, off)), &(ax, ay)) in run.planes.iter().zip(&texs).zip(&pos) {+ let matte = match &p.matte {+ Some(m) if m.len() == n_px => {+ let key = std::sync::Arc::as_ptr(m) as usize;+ let next = matte_ix.len() as u32 + 1;+ let ix = *matte_ix.entry(key).or_insert(next);+ if ix == next {+ mattes.extend_from_slice(m);+ }+ ix+ }+ Some(_) => return None,+ None => 0,+ };+ planes.f([ax as f32, ay as f32, t.width as f32, t.height as f32]);+ planes.d([off[0], off[1], p.buf.scale, if p.bicubic { 1.0 } else { 0.0 }]);+ planes.d(p.bbox.map(|v| v as f64));+ planes.d(p.bounds);+ affine_rows(&mut planes, &p.winv);+ planes.f([p.mat.ambient, p.mat.diffuse, p.mat.specular, p.mat.exponent() as f32]);+ planes.f([p.mat.metal, p.mat.light_transmission, p.opacity, 0.0]);+ let flags = p.draw as u32 | (p.preserve as u32) << 1 | (p.mat.accepts_lights as u32) << 2;+ planes.u([n_geos, p.geos.len() as u32, flags, mode_id(p.mode)]);+ planes.u([p.mat.casts_shadows, p.mat.accepts_shadows, p.layer_id, p.order as u32]);+ planes.u([matte, run.seed ^ p.layer_id, 0, 0]);+ for g in &p.geos {+ write_geo(&mut geos, g);+ }+ n_geos += p.geos.len() as u32;+ }+ if (mattes.len() * 4) as u64 > e.g.device.limits().max_storage_buffer_binding_size as u64 {+ return None;+ }+ let mut lights = Words::default();+ for l in &run.lights {+ write_light(&mut lights, l);+ }+ let mut casters = Words::default();+ for c in &run.casters {+ casters.0.extend_from_slice(&(*c as u32).to_le_bytes());+ }+ let pb = e.bytes(planes.at_least(PLANE_BYTES));+ let gb = e.bytes(geos.at_least(GEO_BYTES));+ let lb = e.bytes(lights.at_least(LIGHT_BYTES));+ let cb = e.bytes(casters.at_least(16));+ let mb = e.data(&mattes);+ let mut p = Params::default();+ p.u[0] = [run.planes.len() as u32, run.lights.len() as u32, run.casters.len() as u32, 0];+ let out = e.image(w, h);+ e.dispatch_ext("classic3d", &p, &atlas, Some(canvas), &out, Some(&mb), (w.div_ceil(16), h.div_ceil(16)), Some([&pb, &gb, &lb, &cb]));+ Some(out)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn shelf_packing_fits_and_does_not_overlap() {+ let sizes = [(100, 40), (30, 90), (60, 60), (100, 10), (5, 5)];+ let (w, h, pos) = pack(&sizes, 256).unwrap();+ for (i, (&(x, y), &(sw, sh))) in pos.iter().zip(&sizes).enumerate() {+ assert!(x + sw <= w && y + sh <= h);+ for (j, (&(x2, y2), &(sw2, sh2))) in pos.iter().zip(&sizes).enumerate() {+ if i != j {+ assert!(x + sw <= x2 || x2 + sw2 <= x || y + sh <= y2 || y2 + sh2 <= y, "{i} and {j} overlap");+ }+ }+ }+ assert!(pack(&[(300, 10)], 256).is_none());+ assert_eq!(max_overlap(&[[0, 0, 10, 10], [5, 5, 15, 15], [20, 20, 30, 30]]), 2);+ }+}diff --cc crates/render/src/three_d/compose.rsindex 37fe59115,85b60a764..beed82f0c--- a/crates/render/src/three_d/compose.rs+++ b/crates/render/src/three_d/compose.rs@@@ -216,41 -206,14 +207,15 @@@ fn prepare_with<'a>let cam = camera_for(r, ctx);let outer = r.collapse3d.map_or(Mat4::IDENTITY, |c| c.world);let world = outer * ctx.world_matrix(layer) * local;- // Depth of field: blur the layer by its circle of confusion at its centre.- let mut bounds = buf_bounds(&buf);- let mut deferred = None;+ // Depth of field: a bokeh blur by each buffer pixel's circle of confusion (constant for a+ // layer facing the camera, progressive for a tilted one).if let Some(dof) = cam.dof.filter(|_| !ctx.comp.draft_3d && !r.opts.draft) {- let b = buf_bounds(&buf);- let centre = world.apply(vec3((b[0] + b[2]) * 0.5, (b[1] + b[3]) * 0.5, 0.0));- let z = cam.depth(centre);- let coc = dof.coc(z);- // Comp pixels on screen per layer pixel at that depth.- let k = cam.zoom / z.max(NEAR) * world.apply_vec(vec3(1.0, 0.0, 0.0)).length().max(1e-9);- let radius = coc * 0.5 / k * buf.scale;- if radius > 0.3 {- let sigma = radius / 1.5;- let pad = (sigma * 3.0).ceil() as u32 + 1;- if defer_dof {- let s = buf.scale.max(1e-9);- let (w, h) = ((buf.img.width + 2 * pad) as f64, (buf.img.height + 2 * pad) as f64);- let o = [buf.offset[0] + pad as f64, buf.offset[1] + pad as f64];- bounds = [-o[0] / s, -o[1] / s, (w - o[0]) / s, (h - o[1]) / s];- deferred = Some((sigma, pad));- } else {- let padded = buf.img.padded(pad);- // The (cached, shared) layer buffer stays untouched; the blurred copy is per frame.- buf = Arc::new(Buf {- img: effectcraft_raster::gaussian_blur(&padded, sigma, sigma, false),- offset: [buf.offset[0] + pad as f64, buf.offset[1] + pad as f64],- scale: buf.scale,- });- bounds = buf_bounds(&buf);- }- }+ buf = dof_blur(&cam, &dof, world, buf);}++ let bounds = buf_bounds(&buf);let n = if in_run { mb_samples(r, ctx, layer) } else { 1 };let geos: Vec<Geo> = if n <= 1 {- geo(&cam, world, &buf, comp, s, out).into_iter().collect()+ geo(&cam, world, bounds, comp, s, out).into_iter().collect()} else {let fd = ctx.comp.frame_duration().seconds();let angle = ctx.comp.shutter_angle / 360.0;@@@ -351,23 -355,6 +356,23 @@@ pub(crate) fn draw_run(r: &Renderer, ctreturn;}let out = (canvas.width, canvas.height);- let g = gather(r, ctx, run, out, false);++ let g = gather(r, ctx, run, out);+ let casters: Vec<&Item> = g.items.iter().chain(g.extra.iter()).filter(|i| i.mat.casts_shadows != 0 && !i.geos.is_empty()).collect();+ composite(canvas, &g.items, &g.lights, &casters, run[0].id.0 as u32);+ for l in run.iter().filter(|l| l.switches.quality == effectcraft_project::Quality::Wireframe) {+ r.draw_layer(ctx, l, canvas, false);+ }+}++/// The prepared planes of a run: drawn items (stack order), shadow casters outside the run, and+/// the lights.+struct Gathered<'a> {+ items: Vec<Item<'a>>,+ extra: Vec<Item<'a>>,+ lights: Vec<LightState>,+}+- fn gather<'a>(r: &Renderer<'a>, ctx: &EvalCtx<'a>, run: &[&'a Layer], out: (u32, u32), defer_dof: bool) -> Gathered<'a> {++fn gather<'a>(r: &Renderer<'a>, ctx: &EvalCtx<'a>, run: &[&'a Layer], out: (u32, u32)) -> Gathered<'a> {// A collapsed precomp's 3D layers are lit by the outer comp's lights.let lights = scene_lights(&r.collapse3d.map_or(*ctx, |c| c.parent));let mut items: Vec<Item> = run@@@ -625,86 -615,6 +629,82 @@@ fn occlusion(c: &Item, p: Vec3, l: &Ligout}+// ------------------------------------------------------------------ accelerator export++/// A Classic 3D run prepared for an accelerator ([`Renderer::prepare_3d_run`]): every plane+/// with its geometry, material and buffer, ready for the per-pixel depth sort, lighting and+/// ray-cast shadows of [`draw_run`] on another device.+#[derive(Clone, Debug)]+pub struct Run3d {+ /// Drawn planes in stack order, then shadow casters from outside the run (`draw` false).+ pub planes: Vec<Plane3d>,+ /// Indices (into `planes`) of the shadow casters, in the CPU's order.+ pub casters: Vec<usize>,+ pub lights: Vec<LightState>,+ /// Dissolve seed of the run.+ pub seed: u32,+}++/// One plane of a [`Run3d`].+#[derive(Clone, Debug)]+pub struct Plane3d {- /// The layer buffer (blending space). When `dof` is set, the plane shows this buffer padded- /// by `dof.1` pixels on every side and Gaussian-blurred with sigma `dof.0`- /// (`raster::gaussian_blur`, no edge repeat).++ /// The layer buffer (blending space; depth of field already applied).+ pub buf: Arc<Buf>,- pub dof: Option<(f64, u32)>,+ pub bicubic: bool,+ /// One per motion-blur sub-sample (equal weights).+ pub geos: Vec<Geo>,+ pub mat: Material,+ pub opacity: f32,+ pub draw: bool,+ /// Screen-space track matte factor (output size, row-major).+ pub matte: Option<Arc<Vec<f32>>>,+ pub preserve: bool,+ /// World → layer, and the (blurred) buffer's layer-space bounds.+ pub winv: Mat4,+ pub bounds: [f64; 4],+ /// Output pixel bounds of all geometries.+ pub bbox: [i64; 4],+ /// Stack order (coplanar fragments draw lower orders first).+ pub order: usize,+ pub layer_id: u32,+ pub mode: BlendMode,+}++/// Prepare a run of 3D layers for an accelerator. `None` when the run must be drawn on the CPU+/// (adjustment or wireframe layers, Advanced 3D).+pub(crate) fn gpu_run(r: &Renderer, ctx: &EvalCtx, run: &[&Layer], out: (u32, u32)) -> Option<Run3d> {+ if run.is_empty() || run.iter().any(|l| l.switches.adjustment || l.switches.quality == effectcraft_project::Quality::Wireframe) {+ return None;+ }+ if ctx.comp.renderer == effectcraft_project::Renderer::Advanced3D && r.collapse3d.is_none() {+ return None;+ }- let g = gather(r, ctx, run, out, true);++ let g = gather(r, ctx, run, out);+ let planes: Vec<Plane3d> = g+ .items+ .into_iter()+ .chain(g.extra)+ .map(|it| Plane3d {+ layer_id: it.layer.id.0 as u32,+ mode: it.layer.blend_mode,+ buf: it.buf,- dof: it.dof,+ bicubic: it.bicubic,+ geos: it.geos,+ mat: it.mat,+ opacity: it.opacity,+ draw: it.draw,+ matte: it.matte,+ preserve: it.preserve,+ winv: it.winv,+ bounds: it.bounds,+ bbox: it.bbox,+ order: it.order,+ })+ .collect();+ let casters = planes.iter().enumerate().filter(|(_, p)| p.mat.casts_shadows != 0 && !p.geos.is_empty()).map(|(i, _)| i).collect();+ Some(Run3d { planes, casters, lights: g.lights, seed: run[0].id.0 as u32 })+}+// ------------------------------------------------------------------ auxiliary render pass/// One surface seen through an output pixel (aux pass).