mirror of
https://github.com/storytold/lightcraft.git
synced 2026-12-02 20:19:40 -05:00
Merge pull request #4967 from wanikhawar/perf/lens-blur-one-pass
perf(lens-blur): one pass for the four blur levels, and no full-image copy (#4949)
This commit is contained in:
1 file changed
+174
-29
@@ -489,18 +489,18 @@ fn blur(img: &mut Rgb32f, coc: &[f32], r: f32, boost: f32, origin: (usize, usize
|
||||
let w = img.width;
|
||||
// highlights brightened before they are spread (the bokeh), the rest as it is
|
||||
let gain = |c: [f32; 3]| 1.0 + BOOST_GAIN * boost * smooth(0.5, 1.0, lightcraft_color::luminance_2020(c));
|
||||
let levels: Vec<Level> = (1..=LEVELS).map(|k| crate::timed("lens blur level", || level(img, coc, k, r, &gain, origin))).collect();
|
||||
let levels = levels(img, coc, r, &gain, origin);
|
||||
// each pixel between the two levels around its circle of confusion (level 0: the image)
|
||||
let src = img.clone();
|
||||
crate::for_rows(&mut img.data, w, |y, row| {
|
||||
for (x, px) in row.iter_mut().enumerate() {
|
||||
let i = y * w + x;
|
||||
let t = coc.get(i).copied().unwrap_or(0.0) * LEVELS as f32;
|
||||
let k = (t.floor().max(0.0) as usize).min(LEVELS - 1);
|
||||
let fr = (t - k as f32).clamp(0.0, 1.0);
|
||||
let cur = *px;
|
||||
let at = |k: usize| match k {
|
||||
0 => src.data.get(i).copied().unwrap_or(*px),
|
||||
k => levels.get(k - 1).map_or(*px, |l| l.sample(x, y)),
|
||||
0 => cur,
|
||||
k => levels.get(k - 1).map_or(cur, |l| l.sample(x, y)),
|
||||
};
|
||||
let (a, b) = (at(k), at(k + 1));
|
||||
*px = std::array::from_fn(|c| a[c] + (b[c] - a[c]) * fr);
|
||||
@@ -524,37 +524,123 @@ impl Level {
|
||||
}
|
||||
}
|
||||
|
||||
/// Level `k` of [`LEVELS`] (radius `k / LEVELS · r` pixels): the disc blur of the pixels at least
|
||||
/// that far out of focus.
|
||||
fn level(img: &Rgb32f, coc: &[f32], k: usize, r: f32, gain: &(impl Fn([f32; 3]) -> f32 + Sync), origin: (usize, usize)) -> Level {
|
||||
/// Rows of the image per band of the one-pass level fill (at least; a band is never shorter than
|
||||
/// the coarsest level's cells).
|
||||
const BAND_ROWS: usize = 64;
|
||||
|
||||
/// One level's grid: radius `radius` pixels, cells `f` pixels wide, `lw × lh` of them, taking the
|
||||
/// pixels whose circle of confusion lies in `lo..hi`.
|
||||
struct Grid {
|
||||
radius: f32,
|
||||
f: usize,
|
||||
shift: (usize, usize),
|
||||
lw: usize,
|
||||
lh: usize,
|
||||
lo: f32,
|
||||
hi: f32,
|
||||
}
|
||||
|
||||
/// What a band of image rows adds to one level: the cell rows from `cy_lo` on it touches.
|
||||
#[derive(Default)]
|
||||
struct BandCells {
|
||||
cy_lo: usize,
|
||||
cells: Vec<[f32; 4]>,
|
||||
}
|
||||
|
||||
/// The [`LEVELS`] levels (level `k`, from 1: radius `k / LEVELS · r` pixels, the disc blur of the
|
||||
/// pixels at least that far out of focus), filled in one pass over `img`: each pixel is read and
|
||||
/// its `gain` computed once, then added to every level's cells.
|
||||
fn levels(img: &Rgb32f, coc: &[f32], r: f32, gain: &(impl Fn([f32; 3]) -> f32 + Sync), origin: (usize, usize)) -> Vec<Level> {
|
||||
crate::timed("lens blur levels", || levels_banded(img, coc, r, gain, origin, BAND_ROWS))
|
||||
}
|
||||
|
||||
/// [`levels`] with bands of at least `min_band` rows. Bands are fixed by the rows (aligned to the
|
||||
/// whole output's), not by the threads, so the sums come out the same on any machine.
|
||||
fn levels_banded(img: &Rgb32f, coc: &[f32], r: f32, gain: &(impl Fn([f32; 3]) -> f32 + Sync), origin: (usize, usize), min_band: usize) -> Vec<Level> {
|
||||
let (w, h) = (img.width, img.height);
|
||||
let radius = r * k as f32 / LEVELS as f32;
|
||||
let (f, shift, lw, lh) = level_grid(w, h, radius, origin);
|
||||
let (grid_w, grid_h) = (w.saturating_add(shift.0), h.saturating_add(shift.1));
|
||||
// a pixel counts in this level when its own circle of confusion reaches it
|
||||
let (lo, hi) = ((k - 1) as f32 / LEVELS as f32, k as f32 / LEVELS as f32);
|
||||
let mut cells = vec![[0f32; 4]; lw * lh];
|
||||
crate::for_rows(&mut cells, lw, |cy, row| {
|
||||
for (cx, cell) in row.iter_mut().enumerate() {
|
||||
let mut acc = [0f32; 4];
|
||||
for vy in cy * f..((cy + 1) * f).min(grid_h) {
|
||||
for vx in cx * f..((cx + 1) * f).min(grid_w) {
|
||||
let (Some(x), Some(y)) = (vx.checked_sub(shift.0), vy.checked_sub(shift.1)) else { continue };
|
||||
let i = y * w + x;
|
||||
let (Some(c), Some(d)) = (img.data.get(i), coc.get(i)) else { continue };
|
||||
// (a non-finite pixel would spread over the whole disc: left out)
|
||||
if !c.iter().all(|v| v.is_finite()) {
|
||||
continue;
|
||||
let grids: Vec<Grid> = (1..=LEVELS)
|
||||
.map(|k| {
|
||||
let radius = r * k as f32 / LEVELS as f32;
|
||||
let (f, shift, lw, lh) = level_grid(w, h, radius, origin);
|
||||
Grid { radius, f, shift, lw, lh, lo: (k - 1) as f32 / LEVELS as f32, hi: k as f32 / LEVELS as f32 }
|
||||
})
|
||||
.collect();
|
||||
let band = grids.iter().map(|g| g.f).max().unwrap_or(1).max(min_band).max(1);
|
||||
// where the first band's boundary falls above row 0 (the bands follow the whole output's rows)
|
||||
let above = origin.1 % band;
|
||||
let count = if h == 0 { 0 } else { (h - 1 + above) / band + 1 };
|
||||
let mut bands: Vec<Vec<BandCells>> = (0..count).map(|_| Vec::new()).collect();
|
||||
crate::for_rows(&mut bands, 1, |bi, slot| {
|
||||
let Some(slot) = slot.first_mut() else { return };
|
||||
let y0 = (bi * band).saturating_sub(above);
|
||||
let y1 = ((bi + 1) * band).saturating_sub(above).min(h);
|
||||
*slot = grids
|
||||
.iter()
|
||||
.map(|g| {
|
||||
let cy_lo = (y0 + g.shift.1) / g.f;
|
||||
let cy_hi = (y1.saturating_sub(1) + g.shift.1) / g.f;
|
||||
BandCells { cy_lo, cells: vec![[0f32; 4]; g.lw.saturating_mul(cy_hi.saturating_sub(cy_lo) + 1)] }
|
||||
})
|
||||
.collect();
|
||||
// each pixel's gain, once for all the levels (NaN: left out, a non-finite pixel would
|
||||
// spread over the whole disc)
|
||||
let mut gains = vec![f32::NAN; w];
|
||||
for y in y0..y1 {
|
||||
let Some(pixels) = img.data.get(y * w..(y + 1) * w) else { continue };
|
||||
let cocs = coc.get(y * w..).unwrap_or(&[]);
|
||||
for (g0, c) in gains.iter_mut().zip(pixels) {
|
||||
*g0 = if c.iter().all(|v| v.is_finite()) { gain(*c) } else { f32::NAN };
|
||||
}
|
||||
for (g, bc) in grids.iter().zip(slot.iter_mut()) {
|
||||
let Some(base) = ((y + g.shift.1) / g.f).checked_sub(bc.cy_lo).map(|r| r * g.lw) else { continue };
|
||||
let Some(row) = bc.cells.get_mut(base..base + g.lw) else { continue };
|
||||
let (mut cx, mut rem) = (g.shift.0 / g.f, g.shift.0 % g.f);
|
||||
for ((c, d), g0) in pixels.iter().zip(cocs).zip(&gains) {
|
||||
if !g0.is_nan()
|
||||
&& let Some(cell) = row.get_mut(cx)
|
||||
{
|
||||
let wt = FOCUS_WEIGHT + smooth(g.lo, g.hi, *d);
|
||||
let gw = g0 * wt;
|
||||
*cell = [cell[0] + c[0] * gw, cell[1] + c[1] * gw, cell[2] + c[2] * gw, cell[3] + wt];
|
||||
}
|
||||
rem += 1;
|
||||
if rem == g.f {
|
||||
rem = 0;
|
||||
cx += 1;
|
||||
}
|
||||
let wt = FOCUS_WEIGHT + smooth(lo, hi, *d);
|
||||
let g = gain(*c) * wt;
|
||||
acc = [acc[0] + c[0] * g, acc[1] + c[1] * g, acc[2] + c[2] * g, acc[3] + wt];
|
||||
}
|
||||
}
|
||||
*cell = acc;
|
||||
}
|
||||
});
|
||||
Level { img: disc(&cells, lw, lh, radius / f as f32), f, shift }
|
||||
// each level's band partials, in band order, moved out so a level's are freed once it is summed
|
||||
let mut parts: Vec<Vec<BandCells>> = (0..grids.len()).map(|_| Vec::with_capacity(bands.len())).collect();
|
||||
for band in bands {
|
||||
for (level, bc) in parts.iter_mut().zip(band) {
|
||||
level.push(bc);
|
||||
}
|
||||
}
|
||||
grids
|
||||
.iter()
|
||||
.zip(parts)
|
||||
.map(|(g, parts)| {
|
||||
let mut cells = vec![[0f32; 4]; g.lw * g.lh];
|
||||
// one past the last cell row a band's partial holds
|
||||
let end = |bc: &BandCells| bc.cy_lo + bc.cells.len().checked_div(g.lw).unwrap_or(0);
|
||||
// a cell row is the sum of what the bands (in order) added to it; the bands' cell rows
|
||||
// only grow, so the ones that reach row `cy` (one or two) are found by bisection
|
||||
crate::for_rows(&mut cells, g.lw, |cy, row| {
|
||||
let first = parts.partition_point(|bc| end(bc) <= cy);
|
||||
for bc in parts.get(first..).unwrap_or(&[]).iter().take_while(|bc| bc.cy_lo <= cy) {
|
||||
let Some(part) = cy.checked_sub(bc.cy_lo).and_then(|r| bc.cells.get(r * g.lw..(r + 1) * g.lw)) else { continue };
|
||||
for (cell, p) in row.iter_mut().zip(part) {
|
||||
*cell = std::array::from_fn(|c| cell[c] + p[c]);
|
||||
}
|
||||
}
|
||||
});
|
||||
drop(parts);
|
||||
Level { img: disc(&cells, g.lw, g.lh, g.radius / g.f as f32), f: g.f, shift: g.shift }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Grid scale and dimensions for one disc level, bounded even when a window's grid is offset.
|
||||
@@ -1085,6 +1171,65 @@ mod tests {
|
||||
assert!(subject_point(&Rgb32f::new(0, 0), &s, None).is_none());
|
||||
}
|
||||
|
||||
/// One level gathered cell by cell, as the one-pass fill replaced it: the reference for [`levels_banded`].
|
||||
fn level_reference(img: &Rgb32f, coc: &[f32], k: usize, r: f32, gain: &(impl Fn([f32; 3]) -> f32 + Sync), origin: (usize, usize)) -> Level {
|
||||
let (w, h) = (img.width, img.height);
|
||||
let radius = r * k as f32 / LEVELS as f32;
|
||||
let (f, shift, lw, lh) = level_grid(w, h, radius, origin);
|
||||
let (grid_w, grid_h) = (w.saturating_add(shift.0), h.saturating_add(shift.1));
|
||||
// a pixel counts in this level when its own circle of confusion reaches it
|
||||
let (lo, hi) = ((k - 1) as f32 / LEVELS as f32, k as f32 / LEVELS as f32);
|
||||
let mut cells = vec![[0f32; 4]; lw * lh];
|
||||
crate::for_rows(&mut cells, lw, |cy, row| {
|
||||
for (cx, cell) in row.iter_mut().enumerate() {
|
||||
let mut acc = [0f32; 4];
|
||||
for vy in cy * f..((cy + 1) * f).min(grid_h) {
|
||||
for vx in cx * f..((cx + 1) * f).min(grid_w) {
|
||||
let (Some(x), Some(y)) = (vx.checked_sub(shift.0), vy.checked_sub(shift.1)) else { continue };
|
||||
let i = y * w + x;
|
||||
let (Some(c), Some(d)) = (img.data.get(i), coc.get(i)) else { continue };
|
||||
// (a non-finite pixel would spread over the whole disc: left out)
|
||||
if !c.iter().all(|v| v.is_finite()) {
|
||||
continue;
|
||||
}
|
||||
let wt = FOCUS_WEIGHT + smooth(lo, hi, *d);
|
||||
let g = gain(*c) * wt;
|
||||
acc = [acc[0] + c[0] * g, acc[1] + c[1] * g, acc[2] + c[2] * g, acc[3] + wt];
|
||||
}
|
||||
}
|
||||
*cell = acc;
|
||||
}
|
||||
});
|
||||
Level { img: disc(&cells, lw, lh, radius / f as f32), f, shift }
|
||||
}
|
||||
|
||||
/// The one-pass fill of all four levels matches gathering each level on its own: bands that
|
||||
/// cut cells, a window origin, a non-finite pixel and a varying circle of confusion included.
|
||||
#[test]
|
||||
fn one_pass_levels_match_gathering_each_level_alone() {
|
||||
let (w, h) = (300, 200);
|
||||
let mut img = scene(w, h, 150, 100);
|
||||
img.set(40, 30, [3.0, 2.0, 1.0]);
|
||||
img.set(251, 177, [6.0; 3]);
|
||||
img.set(120, 60, [f32::NAN, 0.5, 0.5]);
|
||||
let coc: Vec<f32> = (0..w * h).map(|i| ((i % w) as f32 / w as f32 + (i / w) as f32 / h as f32) / 2.0).collect();
|
||||
let (r, origin) = (200.0, (37, 53));
|
||||
let gain = |c: [f32; 3]| 1.0 + BOOST_GAIN * 0.7 * smooth(0.5, 1.0, lightcraft_color::luminance_2020(c));
|
||||
let merged = levels_banded(&img, &coc, r, &gain, origin, 7);
|
||||
assert_eq!(merged.len(), LEVELS);
|
||||
let mut scales = Vec::new();
|
||||
for (i, m) in merged.iter().enumerate() {
|
||||
let alone = level_reference(&img, &coc, i + 1, r, &gain, origin);
|
||||
assert_eq!((m.f, m.shift), (alone.f, alone.shift), "level {}", i + 1);
|
||||
assert_eq!(m.img.data.len(), alone.img.data.len());
|
||||
for (a, b) in m.img.data.iter().flatten().zip(alone.img.data.iter().flatten()) {
|
||||
assert!((a - b).abs() <= 1e-5 * a.abs().max(b.abs()) + 1e-6, "level {}: {a} vs {b}", i + 1);
|
||||
}
|
||||
scales.push(m.f);
|
||||
}
|
||||
assert!(scales.windows(2).all(|p| p[0] < p[1]), "the levels share a grid: {scales:?}");
|
||||
}
|
||||
|
||||
/// Hostile settings and images: no panic, no NaN.
|
||||
#[test]
|
||||
fn hostile_input_never_panics() {
|
||||
|
||||
Reference in new issue
Block a user