Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

refactor(gpu): bevel fields are asked for, windowed and checked as one pair

xsvm900968367138
diff --git a/crates/compose/src/effects.rs b/crates/compose/src/effects.rs
index d4f65dcb4..650651e96 100644
--- a/crates/compose/src/effects.rs
+++ b/crates/compose/src/effects.rs
@@ -1509,8 +1509,7 @@ fn bevel_height(shape: &Map, b: &Bevel, g: &BevelGeom, tex: &TextureCtx, pattern
tent(&mut h, g.width);
h
} else {
- let sharp = sharp_edges(shape);
- let (din, dout) = (bevel_dist_inside(shape, &sharp, size), bevel_dist_outside(shape, &sharp, size));
+ let [din, dout] = bevel_dists(shape, size);
let soft = g.chisel_soft > 0.0;
let w = shape.w;
let v = par_fill(w, shape.h, 0.0, |y, row| {
@@ -2322,9 +2321,13 @@ pub fn distance_field(kind: FieldKind, alpha: Vec<f32>, w: usize, h: usize, reac
/// Both chiselled bevel fields of `alpha`, `[BevelInside, BevelOutside]`: each is its
/// [`distance_field`], with the sharp edges they both start from found once.
pub fn bevel_distance_fields(alpha: Vec<f32>, w: usize, h: usize, reach: f32) -> [Vec<f32>; 2] {
- let s = Map { w, h, v: alpha };
- let sharp = sharp_edges(&s);
- [bevel_dist_inside(&s, &sharp, reach), bevel_dist_outside(&s, &sharp, reach)]
+ bevel_dists(&Map { w, h, v: alpha }, reach)
+}
+
+/// The inside and outside bevel distances of `s`, from one set of sharp edges.
+fn bevel_dists(s: &Map, reach: f32) -> [Vec<f32>; 2] {
+ let sharp = sharp_edges(s);
+ [bevel_dist_inside(s, &sharp, reach), bevel_dist_outside(s, &sharp, reach)]
}
#[cfg(test)]
diff --git a/crates/gpu/src/fx.rs b/crates/gpu/src/fx.rs
index 4b4ae5d57..35691c211 100644
--- a/crates/gpu/src/fx.rs
+++ b/crates/gpu/src/fx.rs
@@ -203,6 +203,11 @@ impl B {
self.fields.push((kind, reach_for(width)));
In::Field(kind)
}
+ /// A chiselled bevel's inside and outside fields, always asked for together ([`bevel_fields`]
+ /// computes them as one).
+ fn bevel_fields(&mut self, width: f32) -> [In; 2] {
+ [FieldKind::BevelInside, FieldKind::BevelOutside].map(|k| self.field(k, width))
+ }
/// `Map::shifted` by whole pixels (`invert`: of `1 - a`); identity shifts of the plain map
/// are skipped.
fn shift(&mut self, src: In, dx: f32, dy: f32, outside: f32, invert: bool) -> In {
@@ -374,8 +379,7 @@ pub(crate) fn program_with(e: &Effect, light: &GlobalLight, vector_shape: bool,
let mut h = if bv.technique == BevelTechnique::Smooth {
b.conv(In::Shape, photocraft_compose::effects::tent_kernel(g.width))
} else {
- let din = b.field(FieldKind::BevelInside, size);
- let dout = b.field(FieldKind::BevelOutside, size);
+ let [din, dout] = b.bevel_fields(size);
let soft = g.chisel_soft > 0.0;
let h = b.push(stage(Kernel::MBevelH, Some(din), Some(dout), [paint(g.paint), size, f32::from(u8::from(soft)), 0.0], 0));
// As `effects::bevel_height`: only emboss styles blur a Chisel Soft ramp.
@@ -542,35 +546,51 @@ fn threaded_inside(kind: FieldKind) -> bool {
/// fields run on all threads inside `distance_field`, from one window. That is also the window the CPU
/// compositor computes them from, so a rebuilt field is exactly the one it gives.
fn field_banded(kind: FieldKind, reach: i32, shape: &[f32], region: Rect, out: Rect, halo: i32) -> Vec<f32> {
- if threaded_inside(kind) {
- let win = out.inflate(halo).intersect(&region);
- if win.is_empty() {
- return Vec::new();
- }
- let f = photocraft_compose::effects::distance_field(kind, crop(shape, region, win), win.width() as usize, win.height() as usize, reach as f32);
- return if win == out { f } else { crop(&f, win, out) };
- }
- let parts = par_map(bands(out, BAND.max(halo)), |band| {
- let win = band.inflate(halo).intersect(&region);
- let f = photocraft_compose::effects::distance_field(kind, crop(shape, region, win), win.width() as usize, win.height() as usize, reach as f32);
- crop(&f, win, band)
+ let [f] = fields_in_windows(threaded_inside(kind), shape, region, out, halo, |s, w, h| {
+ [photocraft_compose::effects::distance_field(kind, s, w, h, reach as f32)]
});
- parts.concat()
+ f
}
-/// [`field`] of both bevel fields over the same `out`, `[BevelInside, BevelOutside]`: one window,
-/// whose sharp edges are found once instead of once per field.
+/// [`field`] of both bevel fields over the same `out`, `[BevelInside, BevelOutside]`, with the
+/// sharp edges of each window found once (the two kinds have the same radius and threading).
pub(crate) fn bevel_fields(reach: i32, shape: &[f32], region: Rect, out: Rect) -> [Vec<f32>; 2] {
- let [inside, outside] = [FieldKind::BevelInside, FieldKind::BevelOutside];
- if !threaded_inside(inside) {
- return [inside, outside].map(|k| field(k, reach, shape, region, out));
- }
- let win = out.inflate(field_radius(inside, reach) + 1).intersect(&region);
- if win.is_empty() {
- return [Vec::new(), Vec::new()];
+ let kind = FieldKind::BevelInside;
+ fields_in_windows(threaded_inside(kind), shape, region, out, field_radius(kind, reach) + 1, |s, w, h| {
+ photocraft_compose::effects::bevel_distance_fields(s, w, h, reach as f32)
+ })
+}
+
+/// The fields `compute` gives for a `w × h` window of the region-sized `shape`, over `out` (inside
+/// `region`), each window grown by `halo`: `out` as one window when `whole` (the field spreads over
+/// threads itself), else bands of it in parallel.
+fn fields_in_windows<const N: usize>(
+ whole: bool,
+ shape: &[f32],
+ region: Rect,
+ out: Rect,
+ halo: i32,
+ compute: impl Fn(Vec<f32>, usize, usize) -> [Vec<f32>; N] + Sync + Send,
+) -> [Vec<f32>; N] {
+ let part = |r: Rect| -> [Vec<f32>; N] {
+ let win = r.inflate(halo).intersect(&region);
+ if win.is_empty() {
+ return std::array::from_fn(|_| Vec::new());
+ }
+ let f = compute(crop(shape, region, win), win.width() as usize, win.height() as usize);
+ if win == r { f } else { f.map(|f| crop(&f, win, r)) }
+ };
+ if whole {
+ return part(out);
}
- let f = photocraft_compose::effects::bevel_distance_fields(crop(shape, region, win), win.width() as usize, win.height() as usize, reach as f32);
- if win == out { f } else { f.map(|f| crop(&f, win, out)) }
+ let parts = par_map(bands(out, BAND.max(halo)), part);
+ std::array::from_fn(|k| {
+ let mut f = Vec::with_capacity(parts.iter().map(|p| p[k].len()).sum());
+ for p in &parts {
+ f.extend_from_slice(&p[k]);
+ }
+ f
+ })
}
/// The layer's shape (`compose::layer_shape`) over `r`, in parallel bands.
@@ -877,6 +897,16 @@ mod tests {
let [inside, outside] = bevel_fields(reach, &shape, region, out);
assert_eq!(bits(&inside), bits(&field(FieldKind::BevelInside, reach, &shape, region, out)), "inside, reach {reach}, {out:?}");
assert_eq!(bits(&outside), bits(&field(FieldKind::BevelOutside, reach, &shape, region, out)), "outside, reach {reach}, {out:?}");
+ // The banded path (wasm) pairs them per band the same way.
+ let halo = field_radius(FieldKind::BevelInside, reach) + 1;
+ let banded =
+ fields_in_windows(false, &shape, region, out, halo, |s, w, h| photocraft_compose::effects::bevel_distance_fields(s, w, h, reach as f32));
+ for (k, kind) in [FieldKind::BevelInside, FieldKind::BevelOutside].into_iter().enumerate() {
+ let [one] = fields_in_windows(false, &shape, region, out, halo, |s, w, h| {
+ [photocraft_compose::effects::distance_field(kind, s, w, h, reach as f32)]
+ });
+ assert_eq!(bits(&banded[k]), bits(&one), "banded {kind:?}, reach {reach}, {out:?}");
+ }
}
}
}
diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs
index a90258b4b..87e7963d7 100644
--- a/crates/gpu/src/lib.rs
+++ b/crates/gpu/src/lib.rs
@@ -1073,7 +1073,7 @@ impl Compositor {
let aprons: Vec<i32> = plan.fx.iter().zip(&paged).map(|(f, &pg)| if pg { Self::fx_apron(doc, f) } else { 0 }).collect();
for (f, &pg) in plan.fx.iter().zip(&paged) {
if !pg {
- self.sync_fx(device, queue, encoder, doc, f, (f.layer.id, None), f.region, &mut stats);
+ self.sync_fx(device, queue, encoder, doc, f, (f.layer.id, None), f.region, &mut stats)?;
}
}
let fr = self.frame_res(device, queue, canvas, &plan);
@@ -1104,7 +1104,7 @@ impl Compositor {
continue;
}
let window = pf.inflate(aprons.get(i).copied().unwrap_or(0)).intersect(&f.region);
- self.sync_fx(device, queue, encoder, doc, f, (f.layer.id, Some(cell)), window, &mut stats);
+ self.sync_fx(device, queue, encoder, doc, f, (f.layer.id, Some(cell)), window, &mut stats)?;
}
let chunks = grid_rects(part, self.chunk);
stats.chunks += chunks.len();
@@ -1715,7 +1715,7 @@ impl Compositor {
key: FxKey,
region: Rect,
stats: &mut Stats,
- ) {
+ ) -> Result<(), Unsupported> {
let layer = f.layer;
let canvas = doc.bounds();
let is_group = matches!(layer.content, LayerContent::Group(_));
@@ -1786,13 +1786,13 @@ impl Compositor {
}
// Present: kept or (re)inserted above.
let stamp = self.stamp;
- let Some(e) = self.fx.get_mut(&key) else { return };
+ let Some(e) = self.fx.get_mut(&key) else { return Ok(()) };
e.last_used = frame;
e.stamp = stamp;
e.doc = doc.id;
e.tiles = [content_src.map(fx::snapshot), mask_src.map(fx::snapshot)];
if region.is_empty() {
- return;
+ return Ok(());
}
let t_trace = web_time_now();
@@ -1822,28 +1822,33 @@ impl Compositor {
_ => Some((kind, region, reach)),
})
.collect();
- // A chiselled bevel's two fields over the same rectangle share their window's sharp edges.
+ // A chiselled bevel's two fields are asked for and kept together (`fx::bevel_fields`), so they
+ // are recomputed together, over one rectangle at one reach.
let job = |k: FieldKind| jobs.iter().find(|j| j.0 == k).map(|j| (j.1, j.2));
- let mut bevel = match (job(FieldKind::BevelInside), job(FieldKind::BevelOutside)) {
- (Some((out, reach)), b) if b == Some((out, reach)) => fx::bevel_fields(reach, &e.shape_cpu, region, out).map(Some),
- _ => [None, None],
- };
+ let (bevel_in, bevel_out) = (job(FieldKind::BevelInside), job(FieldKind::BevelOutside));
+ if bevel_in != bevel_out {
+ return Err(Unsupported(format!("bevel fields of `{}` out of step: inside {bevel_in:?}, outside {bevel_out:?}", layer.name)));
+ }
for (kind, out, reach) in jobs {
- let have = e.fields.get(&kind).map(|(r, _)| *r);
- let pair = match kind {
- FieldKind::BevelInside => bevel[0].take(),
- FieldKind::BevelOutside => bevel[1].take(),
- _ => None,
+ let fields = match kind {
+ FieldKind::BevelInside => {
+ let [inside, outside] = fx::bevel_fields(reach, &e.shape_cpu, region, out);
+ vec![(FieldKind::BevelInside, inside), (FieldKind::BevelOutside, outside)]
+ }
+ // Computed with BevelInside, over the same rectangle at the same reach (checked above).
+ FieldKind::BevelOutside => continue,
+ _ => vec![(kind, fx::field(kind, reach, &e.shape_cpu, region, out))],
};
- let v = pair.unwrap_or_else(|| fx::field(kind, reach, &e.shape_cpu, region, out));
- if have.is_none_or(|r| r < reach) {
- e.fields.insert(kind, (reach, Tex::map(device, "pc_fx_field", region, MAP32)));
- }
- if let Some((_, t)) = e.fields.get(&kind) {
- t.write_r32(queue, region, out, &v);
+ for (kind, v) in fields {
+ if e.fields.get(&kind).is_none_or(|(r, _)| *r < reach) {
+ e.fields.insert(kind, (reach, Tex::map(device, "pc_fx_field", region, MAP32)));
+ }
+ if let Some((_, t)) = e.fields.get(&kind) {
+ t.write_r32(queue, region, out, &v);
+ }
+ staged += v.len() as u64 * 4;
+ stats.fx_pixels += out.width() as u64 * out.height() as u64;
}
- staged += v.len() as u64 * 4;
- stats.fx_pixels += out.width() as u64 * out.height() as u64;
}
if let Some(t) = t_trace.filter(|_| !damage.is_empty()) {
@@ -1858,7 +1863,7 @@ impl Compositor {
if prog.maps == 0 {
continue;
}
- let Some(e) = self.fx.get_mut(&key) else { return };
+ let Some(e) = self.fx.get_mut(&key) else { return Ok(()) };
let same = e.progs[i].key == prog.key && e.progs[i].maps.len() == prog.maps;
let d = if same { damage } else { region };
if d.is_empty() {
@@ -1873,6 +1878,7 @@ impl Compositor {
stats.fx_programs += 1;
self.run_program(device, queue, encoder, key, i, prog, d, stats);
}
+ Ok(())
}
/// Record the passes of `prog` (maps of item `item` of `layer`) recomputing damage `d`.