M13.11: advanced 3d gpu
Advanced 3D runs render entirely on the GPU: every motion-blur sub-sample rasterised, resolved and averaged, the depth-based iris depth of field (Classic 3D bokeh spans, highlight boost, progressive levels), the sRGB encode and the composite over the GPU canvas (Accelerator::render_3d, Renderer::prepare_adv_run, adv3d.wgsl). Wireframe outlines draw on the GPU. Fixes NaN environment lookups for straight up/down normals on Metal. bench --gpu gains an Advanced 3D comp (--adv3d). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
0f591e0856
commit
bb24b931a6
+41
-16
@@ -278,6 +278,12 @@ pub trait Accelerator: Send + Sync {
|
||||
fn raster_3d(&self, _scene: &three_d::adv::Scene) -> Option<three_d::adv::Target> {
|
||||
None
|
||||
}
|
||||
/// Render a whole prepared Advanced 3D run (every motion-blur sub-sample rasterised and
|
||||
/// resolved, averaged, depth of field, encoding) with [`three_d::adv::render_prepared`]'s
|
||||
/// semantics. `None` = not handled (the CPU path runs, using [`Self::raster_3d`]).
|
||||
fn render_3d(&self, _run: &three_d::adv::Prepared) -> Option<three_d::adv::Rendered> {
|
||||
None
|
||||
}
|
||||
/// A particle simulation backend (GPU particles) for the stepped particle effects, with
|
||||
/// the CPU simulation's semantics. `None` = they simulate on the CPU.
|
||||
fn particles(&self) -> Option<&dyn effectcraft_effects::psim::ParticleSim> {
|
||||
@@ -588,22 +594,8 @@ impl<'a> Renderer<'a> {
|
||||
|
||||
/// Draw a Wireframe-quality layer: its bounds as a one-pixel outline.
|
||||
fn draw_wireframe(&self, ctx: &EvalCtx, layer: &Layer, canvas: &mut Image) {
|
||||
let Some(b) = content_bounds(ctx, layer) else { return };
|
||||
let s = self.opts.scale;
|
||||
let (l2c, _) = ctx.layer_to_comp(layer);
|
||||
let m = Mat3::scale(vec2(s, s)) * self.outer.map_or(l2c, |o| o * l2c);
|
||||
let c = [(b[0], b[1]), (b[2], b[1]), (b[2], b[3]), (b[0], b[3])].map(|(x, y)| m.apply(vec2(x, y)));
|
||||
let (w, h) = (canvas.width as i64, canvas.height as i64);
|
||||
for i in 0..4 {
|
||||
let (p, q) = (c[i], c[(i + 1) % 4]);
|
||||
let n = ((q.x - p.x).abs().max((q.y - p.y).abs()) * 2.0).ceil().clamp(1.0, 1.0e5) as usize;
|
||||
for j in 0..=n {
|
||||
let t = j as f64 / n as f64;
|
||||
let (x, y) = ((p.x + (q.x - p.x) * t).floor() as i64, (p.y + (q.y - p.y) * t).floor() as i64);
|
||||
if x >= 0 && y >= 0 && x < w && y < h {
|
||||
canvas.set(x as u32, y as u32, [1.0, 1.0, 1.0, 1.0]);
|
||||
}
|
||||
}
|
||||
for (x, y) in self.wireframe_pixels(ctx, layer, (canvas.width, canvas.height)) {
|
||||
canvas.set(x, y, [1.0, 1.0, 1.0, 1.0]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1567,6 +1559,39 @@ impl<'a> Renderer<'a> {
|
||||
three_d::compose::gpu_run(self, ctx, run, out)
|
||||
}
|
||||
|
||||
/// A run of consecutive 3D layers of an Advanced 3D comp prepared for an accelerator's
|
||||
/// compositor ([`three_d::adv::Prepared`]): rendered as one scene and composited (Normal,
|
||||
/// premultiplied over) onto the canvas. `None` = not an Advanced 3D comp, or a layer needs the
|
||||
/// 2D compositing path (blend mode, track matte, Preserve Transparency): draw it with
|
||||
/// [`Self::draw_3d_run`].
|
||||
pub fn prepare_adv_run<'p>(&'p self, ctx: &'p EvalCtx<'a>, run: &'p [&'p Layer], out: (u32, u32)) -> Option<three_d::adv::Prepared<'p, 'a>> {
|
||||
three_d::adv::prepare_run(self, ctx, run, out)
|
||||
}
|
||||
|
||||
/// The pixels a Wireframe-quality layer sets (white, opaque) on a `size` canvas: its
|
||||
/// bounds' outline, one pixel wide. Empty when the layer has no bounds.
|
||||
pub fn wireframe_pixels(&self, ctx: &EvalCtx, layer: &Layer, size: (u32, u32)) -> Vec<(u32, u32)> {
|
||||
let Some(b) = content_bounds(ctx, layer) else { return vec![] };
|
||||
let s = self.opts.scale;
|
||||
let (l2c, _) = ctx.layer_to_comp(layer);
|
||||
let m = Mat3::scale(vec2(s, s)) * self.outer.map_or(l2c, |o| o * l2c);
|
||||
let c = [(b[0], b[1]), (b[2], b[1]), (b[2], b[3]), (b[0], b[3])].map(|(x, y)| m.apply(vec2(x, y)));
|
||||
let (w, h) = (size.0 as i64, size.1 as i64);
|
||||
let mut out = vec![];
|
||||
for i in 0..4 {
|
||||
let (p, q) = (c[i], c[(i + 1) % 4]);
|
||||
let n = ((q.x - p.x).abs().max((q.y - p.y).abs()) * 2.0).ceil().clamp(1.0, 1.0e5) as usize;
|
||||
for j in 0..=n {
|
||||
let t = j as f64 / n as f64;
|
||||
let (x, y) = ((p.x + (q.x - p.x) * t).floor() as i64, (p.y + (q.y - p.y) * t).floor() as i64);
|
||||
if x >= 0 && y >= 0 && x < w && y < h {
|
||||
out.push((x as u32, y as u32));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Run the layer's effect stack on `target` (an accelerator's resident image): GPU-capable
|
||||
/// runs through [`FxTarget::gpu`], the others through [`FxTarget::cpu`], with the CPU's
|
||||
/// parameters and environment. `adjustment`: the stack runs on the comp below (adjustment
|
||||
|
||||
@@ -99,32 +99,81 @@ fn mb_samples(r: &Renderer, ctx: &EvalCtx, layers: &[&Layer]) -> usize {
|
||||
if r.opts.draft { 4 } else { ctx.comp.motion_blur_samples.clamp(2, 64) as usize }
|
||||
}
|
||||
|
||||
/// Render `layers` as one Advanced 3D scene: premultiplied pixels in the canvas's encoding and
|
||||
/// the camera depth of each pixel (∞ where nothing was drawn). With motion blur the scene is
|
||||
/// rendered at sub-samples spread over the comp's shutter (angle and phase) and averaged; the
|
||||
/// depth is the nearest over the samples.
|
||||
pub(crate) fn render_layers(r: &Renderer, ctx: &EvalCtx, layers: &[&Layer], out: (u32, u32)) -> Option<(Image, Vec<f32>)> {
|
||||
let n = mb_samples(r, ctx, layers);
|
||||
let (mut img, depth, linear) = if n <= 1 {
|
||||
let s = scene::build(r, ctx, layers, out);
|
||||
/// An Advanced 3D run prepared for an accelerator ([`crate::Accelerator::render_3d`], the GPU
|
||||
/// compositor's walk): the motion-blur sub-sample scenes (built on demand, one at a time), the
|
||||
/// camera's depth of field and the output encoding. The accelerator rasterises every
|
||||
/// sub-sample, resolves the supersampling, averages the sub-samples (nearest depth), applies
|
||||
/// the depth of field and encodes, as [`render_prepared`] does on the CPU.
|
||||
pub struct Prepared<'p, 'a> {
|
||||
r: &'p Renderer<'a>,
|
||||
ctx: &'p EvalCtx<'a>,
|
||||
layers: &'p [&'p Layer],
|
||||
/// Output size (pixels).
|
||||
pub out: (u32, u32),
|
||||
/// Motion-blur sub-samples (1 = none).
|
||||
pub samples: usize,
|
||||
/// Depth of field (the camera at the frame time; `None` = off, Draft 3D or draft renders).
|
||||
pub dof: Option<super::camera::Dof>,
|
||||
/// Render scale (circles of confusion are in comp pixels).
|
||||
pub scale: f64,
|
||||
/// The scene is in the working encoding already (linear projects): no sRGB encode.
|
||||
pub linear: bool,
|
||||
}
|
||||
|
||||
impl<'p, 'a> Prepared<'p, 'a> {
|
||||
pub fn new(r: &'p Renderer<'a>, ctx: &'p EvalCtx<'a>, layers: &'p [&'p Layer], out: (u32, u32)) -> Self {
|
||||
let cam = camera_for(r, ctx);
|
||||
Prepared {
|
||||
r,
|
||||
ctx,
|
||||
layers,
|
||||
out,
|
||||
samples: mb_samples(r, ctx, layers),
|
||||
dof: cam.dof.filter(|_| !ctx.comp.draft_3d && !r.opts.draft),
|
||||
scale: r.opts.scale,
|
||||
linear: r.pipe.linear || r.pipe.linear_blend,
|
||||
}
|
||||
}
|
||||
|
||||
/// The scene of sub-sample `i` (`0..samples`), spread over the comp's shutter (angle and
|
||||
/// phase).
|
||||
pub fn scene(&self, i: usize) -> Scene {
|
||||
let n = self.samples;
|
||||
if n <= 1 {
|
||||
return scene::build(self.r, self.ctx, self.layers, self.out);
|
||||
}
|
||||
let ctx = self.ctx;
|
||||
let fd = ctx.comp.frame_duration().seconds();
|
||||
let (angle, phase) = (ctx.comp.shutter_angle / 360.0, ctx.comp.shutter_phase / 360.0);
|
||||
let f = phase + angle * i as f64 / (n - 1) as f64;
|
||||
let sub = ctx.at(ctx.time + effectcraft_time::Tick::from_seconds_f64(f * fd));
|
||||
scene::build_at(self.r, ctx, Some(&sub), self.layers, self.out)
|
||||
}
|
||||
}
|
||||
|
||||
/// What an accelerator returns for a [`Prepared`] run: `None` when nothing was drawn, else the
|
||||
/// premultiplied image in the canvas's encoding and the camera depth of each pixel (∞ where
|
||||
/// nothing was drawn; the nearest over the motion-blur sub-samples).
|
||||
pub type Rendered = Option<(Image, Vec<f32>)>;
|
||||
|
||||
/// Render a prepared run on the CPU compositor (each scene rasterised by the accelerator's
|
||||
/// [`crate::Accelerator::raster_3d`] when there is one): the reference for
|
||||
/// [`crate::Accelerator::render_3d`].
|
||||
pub fn render_prepared(p: &Prepared) -> Rendered {
|
||||
let (r, n, out) = (p.r, p.samples, p.out);
|
||||
let (mut img, depth) = if n <= 1 {
|
||||
let s = p.scene(0);
|
||||
if s.indices.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let (img, depth) = raster_resolved(r, &s);
|
||||
(img, depth, s.linear_io)
|
||||
raster_resolved(r, &s)
|
||||
} else {
|
||||
let fd = ctx.comp.frame_duration().seconds();
|
||||
let (angle, phase) = (ctx.comp.shutter_angle / 360.0, ctx.comp.shutter_phase / 360.0);
|
||||
let mut acc = Image::new(out.0, out.1);
|
||||
let mut depth = vec![f32::INFINITY; (out.0 * out.1) as usize];
|
||||
let mut linear = false;
|
||||
let mut any = false;
|
||||
let k = 1.0 / n as f32;
|
||||
for i in 0..n {
|
||||
let f = phase + angle * i as f64 / (n - 1) as f64;
|
||||
let sub = ctx.at(ctx.time + effectcraft_time::Tick::from_seconds_f64(f * fd));
|
||||
let s = scene::build_at(r, ctx, Some(&sub), layers, out);
|
||||
linear = s.linear_io;
|
||||
let s = p.scene(i);
|
||||
if s.indices.is_empty() {
|
||||
continue;
|
||||
}
|
||||
@@ -140,18 +189,43 @@ pub(crate) fn render_layers(r: &Renderer, ctx: &EvalCtx, layers: &[&Layer], out:
|
||||
if !any {
|
||||
return None;
|
||||
}
|
||||
(acc, depth, linear)
|
||||
(acc, depth)
|
||||
};
|
||||
let cam = camera_for(r, ctx);
|
||||
if let Some(dof) = cam.dof.filter(|_| !ctx.comp.draft_3d && !r.opts.draft) {
|
||||
img = depth_of_field(&img, &depth, &dof, r.opts.scale);
|
||||
if let Some(dof) = &p.dof {
|
||||
img = depth_of_field(&img, &depth, dof, p.scale);
|
||||
}
|
||||
if !linear {
|
||||
if !p.linear {
|
||||
encode(&mut img);
|
||||
}
|
||||
Some((img, depth))
|
||||
}
|
||||
|
||||
/// Render `layers` as one Advanced 3D scene: premultiplied pixels in the canvas's encoding and
|
||||
/// the camera depth of each pixel (∞ where nothing was drawn). With motion blur the scene is
|
||||
/// rendered at sub-samples spread over the comp's shutter (angle and phase) and averaged; the
|
||||
/// depth is the nearest over the samples. The whole run goes to the accelerator when it
|
||||
/// implements [`crate::Accelerator::render_3d`].
|
||||
pub(crate) fn render_layers(r: &Renderer, ctx: &EvalCtx, layers: &[&Layer], out: (u32, u32)) -> Option<(Image, Vec<f32>)> {
|
||||
let p = Prepared::new(r, ctx, layers, out);
|
||||
if let Some(a) = r.active_accel()
|
||||
&& let Some(res) = a.render_3d(&p)
|
||||
{
|
||||
return res;
|
||||
}
|
||||
render_prepared(&p)
|
||||
}
|
||||
|
||||
/// The run as one prepared scene for an accelerator's compositor when it can be composited
|
||||
/// directly over the canvas (Normal-mode layers without track mattes or Preserve Transparency;
|
||||
/// those go through [`draw_run`]'s 2D path; environment backgrounds draw their sky first). `None`
|
||||
/// when the comp isn't Advanced 3D.
|
||||
pub(crate) fn prepare_run<'p, 'a>(r: &'p Renderer<'a>, ctx: &'p EvalCtx<'a>, run: &'p [&'p Layer], out: (u32, u32)) -> Option<Prepared<'p, 'a>> {
|
||||
if !active(r, ctx) || run.iter().any(|l| l.environment_background || needs_2d_composite(ctx, l)) {
|
||||
return None;
|
||||
}
|
||||
Some(Prepared::new(r, ctx, run, out))
|
||||
}
|
||||
|
||||
/// Layers whose blend mode, track matte or Preserve Transparency needs the 2D compositing path.
|
||||
fn needs_2d_composite(ctx: &EvalCtx, l: &Layer) -> bool {
|
||||
l.blend_mode != effectcraft_color::BlendMode::Normal
|
||||
|
||||
@@ -311,11 +311,16 @@ impl Builder {
|
||||
let wn = n.apply_vec(vec3(nn[0] as f64, nn[1] as f64, nn[2] as f64)).normalize();
|
||||
let t = p.tangents.get(k).copied().unwrap_or([1.0, 0.0, 0.0, 1.0]);
|
||||
let wt = m.apply_vec(vec3(t[0] as f64, t[1] as f64, t[2] as f64)).normalize();
|
||||
// Degenerate normals and tangents (zero length: NaN once normalised) get the shader's
|
||||
// fallbacks here, so every rasteriser shades them alike (GPU compilers may not keep
|
||||
// NaN comparisons).
|
||||
let finite = |v: Vec3, or: [f32; 3]| if v.x.is_finite() && v.y.is_finite() && v.z.is_finite() { [v.x as f32, v.y as f32, v.z as f32] } else { or };
|
||||
let [tx, ty, tz] = finite(wt, [1.0, 0.0, 0.0]);
|
||||
self.s.vertices.push(Vertex {
|
||||
pos: [w.x as f32, w.y as f32, w.z as f32],
|
||||
normal: [wn.x as f32, wn.y as f32, wn.z as f32],
|
||||
normal: finite(wn, [0.0, 0.0, -1.0]),
|
||||
uv: p.uvs.get(k).copied().unwrap_or([0.0, 0.0]),
|
||||
tangent: [wt.x as f32, wt.y as f32, wt.z as f32, if det < 0.0 { -t[3] } else { t[3] }],
|
||||
tangent: [tx, ty, tz, if det < 0.0 { -t[3] } else { t[3] }],
|
||||
material: mat,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -203,6 +203,32 @@ pub fn bokeh_blur(img: &Image, iris: &Iris, r: f64) -> Image {
|
||||
let ry = (r / a).round().max(0.0) as usize;
|
||||
return effectcraft_raster::box_blur(img, rx, ry, 1, false);
|
||||
}
|
||||
match kernel(iris, r) {
|
||||
Some((kernels, norm)) => span_gather(img, &kernels, norm),
|
||||
None => img.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Weighted row-span kernels (see [`Iris::spans`]).
|
||||
pub type SpanKernels = Vec<(f32, Vec<(i32, f64, f64)>)>;
|
||||
|
||||
/// [`bokeh_blur`]'s gather kernel at radius `r` as weighted row spans and their normaliser
|
||||
/// (accelerators run the same gather). Fast Rectangle is the box of the iris' width and height
|
||||
/// (what [`bokeh_blur`]'s separable box computes). `None` = the identity (no blur).
|
||||
pub fn kernel(iris: &Iris, r: f64) -> Option<(SpanKernels, f32)> {
|
||||
if r < 0.3 {
|
||||
return None;
|
||||
}
|
||||
if iris.sides == 0 {
|
||||
let a = iris.aspect.clamp(0.01, 100.0).sqrt();
|
||||
let rx = (r * a).round().max(0.0) as i32;
|
||||
let ry = (r / a).round().max(0.0) as i32;
|
||||
if rx == 0 && ry == 0 {
|
||||
return None;
|
||||
}
|
||||
let spans = (-ry..=ry).map(|dy| (dy, -rx as f64 - 0.5, rx as f64 + 0.5)).collect();
|
||||
return Some((vec![(1.0, spans)], ((2 * rx + 1) * (2 * ry + 1)) as f32));
|
||||
}
|
||||
// The iris as row spans (prefix-sum gather: cost ∝ kernel height, not area). The
|
||||
// diffraction fringe adds the rim: the full iris minus a shrunken one.
|
||||
let outer = iris.spans(r);
|
||||
@@ -216,10 +242,21 @@ pub fn bokeh_blur(img: &Image, iris: &Iris, r: f64) -> Image {
|
||||
kernels.push((-f, inner));
|
||||
}
|
||||
let norm: f32 = kernels.iter().map(|(wt, sp)| wt * area(sp)).sum();
|
||||
if norm <= 0.0 {
|
||||
return img.clone();
|
||||
(norm > 0.0).then_some((kernels, norm))
|
||||
}
|
||||
|
||||
/// [`progressive_blur`]'s blur levels for a radius range: `None` = no blur at all; one level
|
||||
/// when the range is narrow (every pixel takes it); else up to eight spanning `lo..=hi`
|
||||
/// (each pixel blends the two around its own radius).
|
||||
pub fn progressive_levels(lo: f32, hi: f32) -> Option<Vec<f32>> {
|
||||
if !lo.is_finite() || hi < 0.3 {
|
||||
return None;
|
||||
}
|
||||
span_gather(img, &kernels, norm)
|
||||
if hi - lo < 0.75 {
|
||||
return Some(vec![(lo + hi) * 0.5]);
|
||||
}
|
||||
let n = (((hi - lo) / 2.0).ceil() as usize + 1).clamp(2, 8);
|
||||
Some((0..n).map(|i| lo + (hi - lo) * i as f32 / (n - 1) as f32).collect())
|
||||
}
|
||||
|
||||
/// Depth-varying blur: `radius` gives each pixel's blur radius. The image is blurred at up to
|
||||
@@ -227,14 +264,11 @@ pub fn bokeh_blur(img: &Image, iris: &Iris, r: f64) -> Image {
|
||||
/// its own radius.
|
||||
pub fn progressive_blur(img: &Image, iris: &Iris, radius: &[f32]) -> Image {
|
||||
let (lo, hi) = radius.iter().fold((f32::INFINITY, 0.0f32), |(a, b), &r| (a.min(r), b.max(r)));
|
||||
if !lo.is_finite() || hi < 0.3 {
|
||||
return img.clone();
|
||||
let Some(levels) = progressive_levels(lo, hi) else { return img.clone() };
|
||||
let n = levels.len();
|
||||
if n == 1 {
|
||||
return bokeh_blur(img, iris, levels[0] as f64);
|
||||
}
|
||||
if hi - lo < 0.75 {
|
||||
return bokeh_blur(img, iris, ((lo + hi) * 0.5) as f64);
|
||||
}
|
||||
let n = (((hi - lo) / 2.0).ceil() as usize + 1).clamp(2, 8);
|
||||
let levels: Vec<f32> = (0..n).map(|i| lo + (hi - lo) * i as f32 / (n - 1) as f32).collect();
|
||||
let blurred: Vec<Image> = levels.par_iter().map(|&r| bokeh_blur(img, iris, r as f64)).collect();
|
||||
let mut out = Image::new(img.width, img.height);
|
||||
out.data.par_iter_mut().enumerate().for_each(|(i, o)| {
|
||||
|
||||
Reference in New Issue
Block a user