diff --git a/crates/gpu/src/render.rs b/crates/gpu/src/render.rs index 31489ba476..4f94600e1a 100644 --- a/crates/gpu/src/render.rs +++ b/crates/gpu/src/render.rs @@ -254,6 +254,30 @@ impl<'a> Cx<'a> { ); } + /// The rectangle `r` ([x0, y0, x1, y1), in pixels) of `b`, an interleaved RGB image `img_w` pixels + /// wide, read back (one row copy recorded per row, into a buffer of just the rectangle). + pub fn read_rect(&mut self, b: &Buf, img_w: usize, r: [usize; 4]) -> Rgb32f { + let (cw, ch) = (r[2] - r[0], r[3] - r[1]); + let out = self.gpu.buffer(cw * ch * 3); + let enc = self.enc.get_or_insert_with(|| self.gpu.encoder()); + for y in 0..ch { + let from = (((r[1] + y) * img_w + r[0]) * 3 * 4) as u64; + enc.copy_buffer_to_buffer(b.raw(), from, out.raw(), (y * cw * 3 * 4) as u64, (cw * 3 * 4) as u64); + } + self.read_rgb(&out, cw, ch) + } + + /// `src`, a compact image of the rectangle `r`, written into `dst`, an interleaved RGB image + /// `img_w` pixels wide (one row copy recorded per row). + pub fn write_rect(&mut self, src: &Buf, dst: &Buf, img_w: usize, r: [usize; 4]) { + let (cw, ch) = (r[2] - r[0], r[3] - r[1]); + let enc = self.enc.get_or_insert_with(|| self.gpu.encoder()); + for y in 0..ch { + let to = (((r[1] + y) * img_w + r[0]) * 3 * 4) as u64; + enc.copy_buffer_to_buffer(src.raw(), (y * cw * 3 * 4) as u64, dst.raw(), to, (cw * 3 * 4) as u64); + } + } + pub fn read_rgb(&mut self, b: &Buf, w: usize, h: usize) -> Rgb32f { Rgb32f { width: w, height: h, data: self.read(b, w * h * 3) } } @@ -1093,17 +1117,35 @@ fn defringe(cx: &mut Cx<'_>, img: Buf, plan: &Plan<'_>) -> Buf { } /// Spot removal (`spots::apply`), spot by spot on `img` in place: each spot reads the image as -/// the earlier ones left it. +/// the earlier ones left it. Process V14's heal (a membrane solve per spot) has no kernel yet: each +/// of its spots runs on the CPU on the rectangle it reads, the only part of the image that crosses +/// to the host and back; the rest of the render stays on the device. fn spots(cx: &mut Cx<'_>, img: Buf, plan: &Plan<'_>) -> Buf { use lightcraft_pipeline::spots; let (w, h) = (plan.w, plan.h); let method = spots::HealMethod::of(&plan.settings); - if method == spots::HealMethod::Pinned && !plan.settings.spots.is_empty() { - // process V14's heal (a membrane solve per spot) has no kernel yet: the spots run on the CPU - // between the device stages, the rest of the render stays on the device - let mut host = cx.read_rgb(&img, w, h); - spots::apply(&mut host, &plan.settings.spots, &plan.frame, plan.px_per_long, method); - return cx.gpu.upload(rgb_words(&host)); + if method == spots::HealMethod::Pinned { + for spot in &plan.settings.spots { + let Some(l) = spots::layout(spot, &plan.frame, w, h, plan.px_per_long) else { continue }; + let Some(&first) = l.pts.first() else { continue }; + let offset = match l.offset { + Some(o) => o, + None => auto_source(cx, &img, w, h, first, l.r), + }; + let r = spots::spot_reads(&l, offset, method, w, h); + let mut crop = cx.read_rect(&img, w, r); + let (bx, by, bw, bh) = (l.bx, l.by, l.bw, l.bh); + spots::apply_spot(&mut crop, (r[0], r[1]), l, offset, method); + // only the spot's box changed + let mut words = Vec::with_capacity(bw * bh * 3); + for y in by..by + bh { + let row = ((y - r[1]) * crop.width + (bx - r[0])) * 3; + words.extend_from_slice(&rgb_words(&crop)[row..row + bw * 3]); + } + let up = cx.gpu.upload(&words); + cx.write_rect(&up, &img, w, [bx, by, bx + bw, by + bh]); + } + return img; } for spot in &plan.settings.spots { let Some(l) = spots::layout(spot, &plan.frame, w, h, plan.px_per_long) else { continue }; diff --git a/crates/gpu/tests/it/equivalence.rs b/crates/gpu/tests/it/equivalence.rs index a36bff5def..cb7707caef 100644 --- a/crates/gpu/tests/it/equivalence.rs +++ b/crates/gpu/tests/it/equivalence.rs @@ -1527,8 +1527,8 @@ fn soft_proofs_match() { /// Spot removal on the device: Clone, Heal and Remove (automatic source, scored on the device), /// brushed strokes, overlapping spots (each reads what the earlier ones left), feather 0 and -/// spots cut by the image edge; on process V13 by the device kernels, on V14 (the pinned heal) on the -/// CPU between the device stages. +/// spots cut by the image edge and sources past it; on process V13 by the device kernels, on V14 (the +/// pinned heal) by each spot's box read back, healed on the CPU and written back. #[test] fn spots_match() { if !gpu() { @@ -1552,6 +1552,7 @@ fn spots_match() { ("remove near the edge (auto)", vec![spot(SpotMode::Remove, &[(0.04, 0.5)], 0.03, 50.0, None)]), ("brushed heal stroke", vec![spot(SpotMode::Heal, &[(0.2, 0.7), (0.3, 0.72), (0.4, 0.69)], 0.02, 30.0, Some((0.0, -0.15)))]), ("feather 0, half opacity", vec![Spot { opacity: 50.0, ..spot(SpotMode::Clone, &[(0.7, 0.3)], 0.04, 0.0, Some((-0.2, 0.0))) }]), + ("source past the edge", vec![spot(SpotMode::Heal, &[(0.1, 0.5)], 0.04, 50.0, Some((-0.2, 0.0)))]), ("cut by the edge", vec![spot(SpotMode::Heal, &[(0.99, 0.02)], 0.05, 50.0, Some((-0.2, 0.2)))]), ( "overlapping, auto after manual", diff --git a/crates/pipeline/src/spots.rs b/crates/pipeline/src/spots.rs index 80acb439a5..1f31d782ea 100644 --- a/crates/pipeline/src/spots.rs +++ b/crates/pipeline/src/spots.rs @@ -436,84 +436,120 @@ fn pinned_distances(l: &SpotLayout, method: HealMethod) -> Vec { /// is [`HealMethod::of`] the photo's settings. pub fn apply(img: &mut Rgb32f, spots: &[Spot], frame: &Frame, ppl: f64, method: HealMethod) { let (w, h) = (img.width, img.height); - let pinned = method == HealMethod::Pinned; for spot in spots { let Some(l) = layout(spot, frame, w, h, ppl) else { continue; }; - // (empty unless the pinned heal will use it: a box too big for its working memory gets the - // averaged heal without the plane being built) - let dist = pinned_distances(&l, method); - let pinned_heal = !dist.is_empty(); - let SpotLayout { r, pts, offset, bx: bx0, by: by0, bw, bh, inner, opacity, heal, fill } = l; - let Some(&first) = pts.first() else { continue }; - let offset = offset.unwrap_or_else(|| auto_source(img, first, r)); - // (V14 reads whole pixels: between them, bilinear sampling averages the source's grain away) - let offset = if pinned { (offset.0.round(), offset.1.round()) } else { offset }; - // alpha of the stroke and the source patch in the box - let mut alpha = vec![0.0f32; bw * bh]; - let mut src = vec![[0.0f32; 3]; bw * bh]; - let mut tgt = vec![[0.0f32; 3]; bw * bh]; - for y in 0..bh { - for x in 0..bw { - let (px, py) = ((bx0 + x) as f32 + 0.5, (by0 + y) as f32 + 0.5); - let d = dist.get(y * bw + x).copied().unwrap_or_else(|| distance(&pts, px, py)); - alpha[y * bw + x] = (1.0 - smooth(inner, r, d)) * opacity; - src[y * bw + x] = img.sample_bilinear(px + offset.0, py + offset.1); - tgt[y * bw + x] = img.get(bx0 + x, by0 + y); - } + let Some(&first) = l.pts.first() else { continue }; + let offset = l.offset.unwrap_or_else(|| auto_source(img, first, l.r)); + apply_spot(img, (0, 0), l, offset, method); + } +} + +/// The pixels [`apply_spot`] reads for `l` with source `offset` in a `w × h` output: the spot's box +/// and its source patch (whole pixels under [`HealMethod::Pinned`], also the bilinear neighbour +/// otherwise), clamped to the image, as [x0, y0, x1, y1). A source past the image's edge reads the +/// edge pixel, which the clamped rectangle holds, so a crop of it renders as the whole image does. +pub fn spot_reads(l: &SpotLayout, offset: (f32, f32), method: HealMethod, w: usize, h: usize) -> [usize; 4] { + let whole = [0, 0, w, h]; + let t = [l.bx, l.by, l.bx + l.bw, l.by + l.bh].map(|v| v as f64); + let reach = |d: f32| { + let d = f64::from(d); + match method { + HealMethod::Pinned => (d.round(), d.round()), + HealMethod::Averaged => (d.floor(), d.ceil() + 1.0), } - if fill { - fill_box(&mut src, &tgt, &alpha, bw, bh); + }; + let ((x0, x1), (y0, y1)) = (reach(offset.0), reach(offset.1)); + let s = [t[0] + x0, t[1] + y0, t[2] + x1, t[3] + y1]; + if !s.iter().all(|v| v.is_finite()) { + return whole; + } + // (a pixel more on every side) + let r = [t[0].min(s[0]) - 1.0, t[1].min(s[1]) - 1.0, t[2].max(s[2]) + 1.0, t[3].max(s[3]) + 1.0]; + // Where the source lies past the image's edge, this clamps to the edge itself: `sample_bilinear` + // clamps its coordinate to the image and reads the edge pixel there, and so does a crop that + // starts or ends on that edge. + let clamp = |v: f64, hi: usize| v.clamp(0.0, hi as f64) as usize; + [clamp(r[0], w), clamp(r[1], h), clamp(r[2], w), clamp(r[3], h)] +} + +/// One spot of [`apply`] on `img`, a crop of the output whose pixel (0, 0) is output pixel `origin`; +/// `l` is in output pixels and `offset` is the resolved source offset (auto-chosen already when the +/// spot's is `None`). The crop must hold [`spot_reads`] of the spot. +pub fn apply_spot(img: &mut Rgb32f, origin: (usize, usize), l: SpotLayout, offset: (f32, f32), method: HealMethod) { + let pinned = method == HealMethod::Pinned; + // (empty unless the pinned heal will use it: a box too big for its working memory gets the + // averaged heal without the plane being built) + let dist = pinned_distances(&l, method); + let pinned_heal = !dist.is_empty(); + let SpotLayout { r, pts, bx: bx0, by: by0, bw, bh, inner, opacity, heal, fill, .. } = l; + // (V14 reads whole pixels: between them, bilinear sampling averages the source's grain away) + let offset = if pinned { (offset.0.round(), offset.1.round()) } else { offset }; + let (ox, oy) = origin; + // alpha of the stroke and the source patch in the box + let mut alpha = vec![0.0f32; bw * bh]; + let mut src = vec![[0.0f32; 3]; bw * bh]; + let mut tgt = vec![[0.0f32; 3]; bw * bh]; + for y in 0..bh { + for x in 0..bw { + let (px, py) = ((bx0 + x) as f32 + 0.5, (by0 + y) as f32 + 0.5); + let d = dist.get(y * bw + x).copied().unwrap_or_else(|| distance(&pts, px, py)); + alpha[y * bw + x] = (1.0 - smooth(inner, r, d)) * opacity; + src[y * bw + x] = img.sample_bilinear(px + offset.0 - ox as f32, py + offset.1 - oy as f32); + tgt[y * bw + x] = img.get(bx0 + x - ox, by0 + y - oy); } - let healed = if pinned_heal { pinned::heal(&pinned::Patch { w: bw, h: bh, src: &src, tgt: &tgt, dist: &dist, r }) } else { None }; - let pinned_here = healed.is_some(); - if let Some(healed) = healed { - src = healed; - } - let low = if heal && !pinned_here { - // Tone correction from the spot's *surroundings* only: normalized convolution of - // (target − source) over pixels outside the stroke (a membrane-like interpolation). - let outside: Vec = alpha.iter().map(|a| if *a < 0.02 { 1.0 } else { 0.0 }).collect(); - let diff = Rgb32f { - width: bw, - height: bh, - data: tgt.iter().zip(&src).zip(&outside).map(|((t, s), m)| [(t[0] - s[0]) * m, (t[1] - s[1]) * m, (t[2] - s[2]) * m]).collect(), - }; - let wts = lightcraft_raster::Plane { width: bw, height: bh, data: outside }; - let sigma = (r * 0.6).max(1.0); - let (bd, bm) = (lightcraft_raster::blur::gaussian(&diff, sigma), lightcraft_raster::blur::gaussian(&wts, sigma)); - Some(Rgb32f { - width: bw, - height: bh, - data: bd - .data - .iter() - .zip(&bm.data) - .map(|(d, m)| { - let m = m.max(1e-4); - [d[0] / m, d[1] / m, d[2] / m] - }) - .collect(), - }) - } else { - None + } + if fill { + fill_box(&mut src, &tgt, &alpha, bw, bh); + } + let healed = if pinned_heal { pinned::heal(&pinned::Patch { w: bw, h: bh, src: &src, tgt: &tgt, dist: &dist, r }) } else { None }; + let pinned_here = healed.is_some(); + if let Some(healed) = healed { + src = healed; + } + let low = if heal && !pinned_here { + // Tone correction from the spot's *surroundings* only: normalized convolution of + // (target − source) over pixels outside the stroke (a membrane-like interpolation). + let outside: Vec = alpha.iter().map(|a| if *a < 0.02 { 1.0 } else { 0.0 }).collect(); + let diff = Rgb32f { + width: bw, + height: bh, + data: tgt.iter().zip(&src).zip(&outside).map(|((t, s), m)| [(t[0] - s[0]) * m, (t[1] - s[1]) * m, (t[2] - s[2]) * m]).collect(), }; - for y in 0..bh { - for x in 0..bw { - let i = y * bw + x; - let a = alpha[i]; - if a <= 0.0 { - continue; - } - let mut v = src[i]; - if let Some(l) = &low { - let d = l.data[i]; - v = [v[0] + d[0], v[1] + d[1], v[2] + d[2]]; - } - let t = tgt[i]; - img.set(bx0 + x, by0 + y, [t[0] + (v[0] - t[0]) * a, t[1] + (v[1] - t[1]) * a, t[2] + (v[2] - t[2]) * a].map(|c| c.max(0.0))); + let wts = lightcraft_raster::Plane { width: bw, height: bh, data: outside }; + let sigma = (r * 0.6).max(1.0); + let (bd, bm) = (lightcraft_raster::blur::gaussian(&diff, sigma), lightcraft_raster::blur::gaussian(&wts, sigma)); + Some(Rgb32f { + width: bw, + height: bh, + data: bd + .data + .iter() + .zip(&bm.data) + .map(|(d, m)| { + let m = m.max(1e-4); + [d[0] / m, d[1] / m, d[2] / m] + }) + .collect(), + }) + } else { + None + }; + for y in 0..bh { + for x in 0..bw { + let i = y * bw + x; + let a = alpha[i]; + if a <= 0.0 { + continue; } + let mut v = src[i]; + if let Some(l) = &low { + let d = l.data[i]; + v = [v[0] + d[0], v[1] + d[1], v[2] + d[2]]; + } + let t = tgt[i]; + img.set(bx0 + x - ox, by0 + y - oy, [t[0] + (v[0] - t[0]) * a, t[1] + (v[1] - t[1]) * a, t[2] + (v[2] - t[2]) * a].map(|c| c.max(0.0))); } } } @@ -595,6 +631,52 @@ mod tests { } } + /// Each spot on a crop of what [`spot_reads`] says it reads gives the same pixels in its box as + /// [`apply`] on the whole image: Heal and Clone, either heal, and a spot cut by the edge whose + /// source lies past it. + #[test] + fn a_spot_on_its_reads_matches_the_whole_image() { + let (w, h) = (96, 64); + let frame = Frame::new(w, h, &DevelopSettings::default(), true); + let ppl = frame.px_per_long(w); + let spot = |mode, x: f64, y: f64, off: (f64, f64)| Spot { + mode, + points: vec![Point::new(x, y)], + size: 6.0 / w as f64, + feather: 50.0, + opacity: 100.0, + source_offset: Some(Point::new(off.0, off.1)), + }; + let spots = [ + spot(SpotMode::Heal, 0.5, 0.5, (0.17, 0.06)), + spot(SpotMode::Clone, 0.3, 0.4, (-0.11, 0.13)), + spot(SpotMode::Heal, 0.99, 0.02, (-0.2, 0.2)), + spot(SpotMode::Heal, 0.03, 0.9, (-0.4, 0.3)), + ]; + for method in BOTH { + for spot in &spots { + let original = Rgb32f::from_fn(w, h, |x, y| { + [0.2 + (x * 7 % 13) as f32 / 40.0, 0.1 + (y * 5 % 11) as f32 / 30.0, 0.3 + ((x + y) % 5) as f32 / 20.0] + }); + let mut whole = original.clone(); + apply(&mut whole, std::slice::from_ref(spot), &frame, ppl, method); + let l = layout(spot, &frame, w, h, ppl).expect("on the image"); + let offset = l.offset.expect("manual source"); + let [x0, y0, x1, y1] = spot_reads(&l, offset, method, w, h); + let mut crop = Rgb32f::from_fn(x1 - x0, y1 - y0, |x, y| original.get(x0 + x, y0 + y)); + let (bx, by, bw, bh) = (l.bx, l.by, l.bw, l.bh); + apply_spot(&mut crop, (x0, y0), l, offset, method); + let mut pasted = original.clone(); + for y in by..by + bh { + for x in bx..bx + bw { + pasted.set(x, y, crop.get(x - x0, y - y0)); + } + } + assert_eq!(pasted.data, whole.data, "{:?} spot at {:?} ({method:?})", spot.mode, spot.points[0]); + } + } + } + /// Vertical stripes (period `period` px) with a black blot over the middle. fn striped_with_blot(w: usize, h: usize, period: usize) -> Rgb32f { let mut img = Rgb32f::from_fn(w, h, |x, _| if (x / period).is_multiple_of(2) { [0.2; 3] } else { [0.7; 3] });