PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Preserve document depth when splitting vector shapes (#1495)
Harrison O'Connor-Hoover5355221f81e3
diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rsindex 9a986dbf3..c929246fb 100644--- a/crates/compose/src/lib.rs+++ b/crates/compose/src/lib.rs@@ -1245,7 +1245,7 @@ fn shape_parts(layer: &Layer, clipped: &[Layer], rect: Rect, cx: &Ctx) -> Optionfn split_parts(layer: &Layer, rect: Rect, cx: &Ctx) -> Option<(Buffer, Buffer, Option<Vec<f32>>)> {let LayerContent::Shape(sh) = &layer.content else { return None };sh.stroke.as_ref()?;- let (fs, ss) = shape_split::split(sh, cx.canvas)?;+ let (fs, ss) = shape_split::split(sh, cx.canvas, cx.depth)?;Some((surface_to_buffer(&fs, rect), surface_to_buffer(&ss, rect), mask_vals(layer, rect, cx)))}diff --git a/crates/compose/src/shape_split.rs b/crates/compose/src/shape_split.rsindex 3c90249a6..3c1a4b106 100644--- a/crates/compose/src/shape_split.rs+++ b/crates/compose/src/shape_split.rs@@ -6,7 +6,7 @@ use std::collections::HashMap;use std::hash::{Hash, Hasher};use std::sync::{Mutex, OnceLock};-use photocraft_color::PixelFormat;+use photocraft_color::{PixelFormat, SampleType};use photocraft_doc::vector::ShapeLayer;use photocraft_geom::Rect;use photocraft_raster::Surface;@@ -22,14 +22,15 @@ fn cache() -> &'static Mutex<(HashMap<u64, Entry>, u64)> {const CAPACITY: usize = 32;-/// (fill only, stroke only) of a stroked shape, rendered over `canvas` (RGBA8, as the CPU-/// compositor's split always was). `None` without a stroke. Where the shape's pixels+/// (fill only, stroke only) of a stroked shape, rendered over `canvas` in RGBA at `depth`.+/// `None` without a stroke. Where the shape's pixels/// (Photoshop's rendering, `sh.cache`) reach past our fill, the part the fill doesn't explain is/// stroke: the stroke follows Photoshop's coverage (psd-tools double-stroke-effects).-pub fn split(sh: &ShapeLayer, canvas: Rect) -> Option<(Surface, Surface)> {+pub fn split(sh: &ShapeLayer, canvas: Rect, depth: SampleType) -> Option<(Surface, Surface)> {sh.stroke.as_ref()?;let mut h = std::collections::hash_map::DefaultHasher::new();(canvas.x0, canvas.y0, canvas.x1, canvas.y1).hash(&mut h);+ depth.hash(&mut h);format!("{:?}{:?}{:?}{:?}", sh.path, sh.fill, sh.stroke, sh.live).hash(&mut h);if let Some(c) = &sh.cache {format!("{:?}{:?}", c.format(), c.default_pixel()).hash(&mut h);@@ -47,7 +48,7 @@ pub fn split(sh: &ShapeLayer, canvas: Rect) -> Option<(Surface, Surface)> {return Some(e.0.clone());}}- let fmt = PixelFormat::RGBA8;+ let fmt = PixelFormat::RGBA8.with_sample(depth);let fill_only = ShapeLayer { stroke: None, cache: None, ..sh.clone() };let stroke_only = ShapeLayer { fill: None, cache: None, ..sh.clone() };let mut parts = (photocraft_vector::render_shape(&fill_only, fmt, canvas), photocraft_vector::render_shape(&stroke_only, fmt, canvas));@@ -92,6 +93,7 @@ fn fit_stroke(fill: &Surface, stroke: &mut Surface, cache: &Surface, canvas: Recstroke.read_rgba_into(r, &mut s);cache.read_rgba_into(r, &mut c);let mut out = Vec::with_capacity(n * 4);+ let float = stroke.format().sample == SampleType::F32;for ((fp, sp), cp) in f.iter().zip(&s).zip(&c) {let mut p = *sp;if fp[3] < 1.0 - 1e-3 {@@ -101,7 +103,11 @@ fn fit_stroke(fill: &Surface, stroke: &mut Surface, cache: &Surface, canvas: Rec} else if a > 1e-3 {// Normal over the fill: a·p + f·(1 - a)·fill = pixels (premultiplied).let k = fp[3] * (1.0 - a);- let un = |i: usize| ((cp[3] * cp[i] - k * fp[i]) / a).clamp(0.0, 1.0);+ let un = |i: usize| {+ let v = (cp[3] * cp[i] - k * fp[i]) / a;+ // Float RGB retains HDR values; integer samples use the normalized range.+ if float { v } else { v.clamp(0.0, 1.0) }+ };[un(0), un(1), un(2), a]} else {[sp[0], sp[1], sp[2], a]diff --git a/crates/compose/src/stroke_tests.rs b/crates/compose/src/stroke_tests.rsindex eaa4a619c..ab265fa20 100644--- a/crates/compose/src/stroke_tests.rs+++ b/crates/compose/src/stroke_tests.rs@@ -36,6 +36,56 @@ fn shape(x0: f64, x1: f64, fill: Fill, stroke: Option<ShapeStroke>) -> Layer {Layer::new("shape", LayerContent::Shape(sh))}+fn gradient_shape(width: u32, height: u32) -> ShapeLayer {+ let (w, h) = (f64::from(width), f64::from(height));+ ShapeLayer {+ path: Path::new(vec![Subpath::polygon(&[(0.0, 0.0), (w, 0.0), (w, h), (0.0, h)])]),+ fill: Some(Fill::gradient(vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], 0.0, 1.0, GradientStyle::Linear, false)),+ stroke: Some(ShapeStroke { width: 4.0, ..ShapeStroke::default() }),+ live: None,+ cache: None,+ psd_raw: None,+ }+}++#[test]+fn split_stroked_gradient_with_effect_keeps_document_precision() {+ for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {+ let mut d = Document::with_background("t", Size::new(4000, 40), ColorMode::Rgb, depth, Color::WHITE);+ let mut sh = gradient_shape(4000, 40);+ sh.cache = Some(photocraft_vector::render_shape(&sh, d.pixel_format(), d.bounds()));+ let mut layer = Layer::new("gradient shape", LayerContent::Shape(sh));+ layer.effects.items = vec![stroke(1.0, StrokePosition::Outside, blue())];+ d.layers.push(layer);+ let row = render(&d, Rect::from_xywh(0, 20, 4000, 1));+ let mut levels: Vec<u32> = row.px.iter().map(|p| (p[0] * 65535.0).round() as u32).collect();+ levels.sort_unstable();+ levels.dedup();+ if depth == SampleType::U8 {+ assert!(levels.len() <= 256, "8-bit control: {} levels", levels.len());+ } else {+ assert!(levels.len() > 3000, "{depth:?}: split gradient has only {} levels", levels.len());+ }+ }+}++#[test]+fn split_cache_keeps_same_shape_separate_at_each_document_depth() {+ let canvas = Rect::new(0, 0, 64, 8);+ let mut sh = gradient_shape(64, 8);+ // Keep the shape and cached tile identities identical while only the document depth changes.+ sh.cache = Some(photocraft_vector::render_shape(&sh, PixelFormat::RGBA32F, canvas));+ let mut layer = Layer::new("same shape", LayerContent::Shape(sh.clone()));+ layer.effects.items = vec![stroke(1.0, StrokePosition::Outside, blue())];+ for depth in [SampleType::U8, SampleType::U16, SampleType::F32, SampleType::U8] {+ let mut d = Document::with_background("t", Size::new(64, 8), ColorMode::Rgb, depth, Color::WHITE);+ d.layers.push(layer.clone());+ let expected = photocraft_vector::render_shape(&sh, PixelFormat::RGBA8.with_sample(depth), canvas).pixel(17, 4)[0];+ let actual = px(&d, 17, 4)[0];+ assert!((actual - expected).abs() < 1e-6, "{depth:?}: got {actual}, expected {expected}; split cache must include document depth");+ }+}+#[test]fn outline_share_treats_stroke_and_shape_as_disjoint_areas() {// Outside the shape the stroke covers the pixel; inside it nothing.@@ -172,15 +222,19 @@ fn hairline_vector_stroke_keeps_the_files_edge_pixel_colour() {// pixels are opaque and mostly fill. Our path sits off the pixel grid, so our fill covers only// part of an edge pixel; fitting the stroke to the file's pixels must keep their colour there,// not paint the edge in the stroke's full colour. At every depth.- for (sample, fmt) in [(SampleType::U8, PixelFormat::RGBA8), (SampleType::U16, PixelFormat::RGBA16), (SampleType::F32, PixelFormat::RGBA32F)] {+ for (sample, fmt, edge, fill) in [+ (SampleType::U8, PixelFormat::RGBA8, 0.86, 1.0),+ (SampleType::U16, PixelFormat::RGBA16, 0.86, 1.0),+ (SampleType::F32, PixelFormat::RGBA32F, 0.86, 1.0),+ (SampleType::F32, PixelFormat::RGBA32F, 2.0, 2.0),+ ] {let mut d = Document::with_background("t", Size::new(40, 40), ColorMode::Rgb, sample, Color::WHITE);- let edge = 0.86;let vs = ShapeStroke { width: 0.25, paint: Fill::Solid(Color::rgb(0.48, 0.48, 0.48)), ..ShapeStroke::default() };let path = Path::new(vec![Subpath::polygon(&[(10.3, 10.3), (29.7, 10.3), (29.7, 29.7), (10.3, 29.7)])]);let mut cache = photocraft_raster::Surface::new(fmt);cache.fill_rect(Rect::new(10, 10, 30, 30), &[edge, edge, edge, 1.0]);- cache.fill_rect(Rect::new(11, 11, 29, 29), &[1.0, 1.0, 1.0, 1.0]);- let sh = ShapeLayer { path, fill: Some(Fill::Solid(Color::WHITE)), stroke: Some(vs), live: None, cache: Some(cache), psd_raw: None };+ cache.fill_rect(Rect::new(11, 11, 29, 29), &[fill, fill, fill, 1.0]);+ let sh = ShapeLayer { path, fill: Some(Fill::Solid(Color::rgb(fill, fill, fill))), stroke: Some(vs), live: None, cache: Some(cache), psd_raw: None };let mut l = Layer::new("shape", LayerContent::Shape(sh));// Any layer effect sends the shape through the fill/stroke split.l.effects.items = vec![Effect::default_drop_shadow()];@@ -190,6 +244,6 @@ fn hairline_vector_stroke_keeps_the_files_edge_pixel_colour() {assert!(close4(p, [edge, edge, edge, 1.0]), "{sample:?} edge pixel ({x}, {y}): {p:?}");}// The interior keeps the fill.- assert!(close4(px(&d, 20, 20), [1.0, 1.0, 1.0, 1.0]), "{sample:?} {:?}", px(&d, 20, 20));+ assert!(close4(px(&d, 20, 20), [fill, fill, fill, 1.0]), "{sample:?} {:?}", px(&d, 20, 20));}}diff --git a/crates/gpu/src/plan.rs b/crates/gpu/src/plan.rsindex ea9df089c..b320ea938 100644--- a/crates/gpu/src/plan.rs+++ b/crates/gpu/src/plan.rs@@ -641,7 +641,7 @@ impl<'a> Planner<'a> {if let LayerContent::Shape(sh) = &layer.content&& !visible_clipped.is_empty()- && let Some((fill, stroke)) = photocraft_compose::shape_split::split(sh, self.cx.canvas)+ && let Some((fill, stroke)) = photocraft_compose::shape_split::split(sh, self.cx.canvas, self.cx.depth){// The vector stroke goes above the clipped layers: the fill is the clipping base,// the stroke is laid over the clipped result, then the masks apply to both@@ -912,7 +912,7 @@ impl<'a> Planner<'a> {// A stroked shape's vector stroke goes above its clipped layers and interior effects// (compose::split_parts): the fill and the stroke unmasked, the masks applied after.let split = match &layer.content {- LayerContent::Shape(sh) if sh.stroke.is_some() => photocraft_compose::shape_split::split(sh, canvas),+ LayerContent::Shape(sh) if sh.stroke.is_some() => photocraft_compose::shape_split::split(sh, canvas, self.cx.depth),_ => None,};let (mut content, vstroke) = match split {diff --git a/crates/gpu/tests/parity.rs b/crates/gpu/tests/parity.rsindex 45d741fb2..05d13a666 100644--- a/crates/gpu/tests/parity.rs+++ b/crates/gpu/tests/parity.rs@@ -1056,40 +1056,42 @@ fn stroke_effects_on_filled_and_stroked_shapes() {// clipped layers and a mask.let Some(mut g) = gpu() else { return };use photocraft_doc::vector::{Path, ShapeLayer, ShapeStroke, StrokeAlign, Subpath};- for (fill_kind, vector_stroke, masked) in [(0, false, false), (1, false, true), (0, true, false), (1, true, true)] {- let mut d = fx_doc(90, 70, SampleType::U8);- let path = Path::new(vec![Subpath::polygon(&[(14.3, 12.6), (70.2, 18.1), (60.7, 58.4), (24.9, 50.2)])]);- let mut clear = Color::rgb(0.9, 0.3, 0.1);- clear.alpha = 0.0;- let fill = if fill_kind == 0 {- Fill::Solid(Color::rgb(0.3, 0.6, 0.9))- } else {- Fill::gradient(vec![(0.0, Color::rgb(0.9, 0.3, 0.1)), (1.0, clear)], 20.0, 1.0, GradientStyle::Linear, false)- };- let stroke_v = vector_stroke.then(|| ShapeStroke {- width: 3.0,- align: StrokeAlign::Inside,- paint: Fill::Solid(Color::rgb(0.1, 0.8, 0.2)),- ..ShapeStroke::default()- });- let mut sh = ShapeLayer { path, fill: Some(fill), stroke: stroke_v, live: None, cache: None, psd_raw: None };- sh.cache = Some(photocraft_vector::render_shape(&sh, d.pixel_format(), d.bounds()));- let mut l = Layer::new("shape", LayerContent::Shape(sh));- if masked {- l.mask = Some(mask(Rect::new(0, 0, 90, 70), 7, 0.6));+ for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {+ for (fill_kind, vector_stroke, masked) in [(0, false, false), (1, false, true), (0, true, false), (1, true, true)] {+ let mut d = fx_doc(90, 70, depth);+ let path = Path::new(vec![Subpath::polygon(&[(14.3, 12.6), (70.2, 18.1), (60.7, 58.4), (24.9, 50.2)])]);+ let mut clear = Color::rgb(0.9, 0.3, 0.1);+ clear.alpha = 0.0;+ let fill = if fill_kind == 0 {+ Fill::Solid(Color::rgb(0.3, 0.6, 0.9))+ } else {+ Fill::gradient(vec![(0.0, Color::rgb(0.9, 0.3, 0.1)), (1.0, clear)], 20.0, 1.0, GradientStyle::Linear, false)+ };+ let stroke_v = vector_stroke.then(|| ShapeStroke {+ width: 3.0,+ align: StrokeAlign::Inside,+ paint: Fill::Solid(Color::rgb(0.1, 0.8, 0.2)),+ ..ShapeStroke::default()+ });+ let mut sh = ShapeLayer { path, fill: Some(fill), stroke: stroke_v, live: None, cache: None, psd_raw: None };+ sh.cache = Some(photocraft_vector::render_shape(&sh, d.pixel_format(), d.bounds()));+ let mut l = Layer::new("shape", LayerContent::Shape(sh));+ if masked {+ l.mask = Some(mask(Rect::new(0, 0, 90, 70), 7, 0.6));+ }+ l.effects.items = vec![+ Effect::Stroke(stroke(2.0, StrokePosition::Outside, FxPaint::Color(Color::rgb(1.0, 1.0, 1.0)))),+ Effect::Stroke(stroke(5.0, StrokePosition::Outside, FxPaint::Gradient(gradient()))),+ Effect::Stroke(stroke(3.0, StrokePosition::Inside, FxPaint::Gradient(gradient()))),+ Effect::ColorOverlay { common: photocraft_doc::FxCommon::new(BlendMode::Multiply, 0.7), color: Color::rgb(0.2, 0.2, 0.9) },+ Effect::DropShadow(shadow(BlendMode::Multiply, 0.7, 120.0, 4.0, 5.0, 0.0)),+ ];+ d.layers.push(l);+ let mut c = noise_layer("clip", d.pixel_format(), Rect::new(30, 0, 60, 70), 9, 0.5);+ c.clipped = true;+ d.layers.push(c);+ fx_check(&mut g, &d, &format!("{depth:?} fill {fill_kind} vector stroke {vector_stroke} masked {masked}"));}- l.effects.items = vec![- Effect::Stroke(stroke(2.0, StrokePosition::Outside, FxPaint::Color(Color::rgb(1.0, 1.0, 1.0)))),- Effect::Stroke(stroke(5.0, StrokePosition::Outside, FxPaint::Gradient(gradient()))),- Effect::Stroke(stroke(3.0, StrokePosition::Inside, FxPaint::Gradient(gradient()))),- Effect::ColorOverlay { common: photocraft_doc::FxCommon::new(BlendMode::Multiply, 0.7), color: Color::rgb(0.2, 0.2, 0.9) },- Effect::DropShadow(shadow(BlendMode::Multiply, 0.7, 120.0, 4.0, 5.0, 0.0)),- ];- d.layers.push(l);- let mut c = noise_layer("clip", PixelFormat::RGBA8, Rect::new(30, 0, 60, 70), 9, 0.5);- c.clipped = true;- d.layers.push(c);- fx_check(&mut g, &d, &format!("fill {fill_kind} vector stroke {vector_stroke} masked {masked}"));}}@@ -1246,25 +1248,28 @@ fn blend_mode_extremes() {fn stroked_shapes_with_clipped_layers() {let Some(mut g) = gpu() else { return };use photocraft_doc::vector::{Path, ShapeLayer, ShapeStroke, Subpath};- for (blend, masked) in [(BlendMode::Normal, false), (BlendMode::Multiply, true)] {- let mut d = base_doc(80, 64);- let path = Path::new(vec![Subpath::polygon(&[(10.3, 8.6), (66.2, 12.1), (58.7, 54.4), (16.9, 48.2)])]);- let stroke = ShapeStroke { width: 5.0, paint: Fill::Solid(Color::rgb(0.9, 0.9, 0.1)), ..Default::default() };- let mut sh = ShapeLayer { path, fill: Some(Fill::Solid(Color::rgb(0.2, 0.3, 0.8))), stroke: Some(stroke), live: None, cache: None, psd_raw: None };- sh.cache = Some(photocraft_vector::render_shape(&sh, d.pixel_format(), d.bounds()));- let mut l = Layer::new("shape", LayerContent::Shape(sh));- l.blend = blend;- l.opacity = 0.9;- if masked {- l.mask = Some(mask(Rect::new(0, 0, 80, 64), 41, 1.0));+ for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {+ for (blend, masked) in [(BlendMode::Normal, false), (BlendMode::Multiply, true)] {+ let mut d = Document::new("t", Size::new(80, 64), ColorMode::Rgb, depth);+ d.layers.push(noise_layer("bg", d.pixel_format(), Rect::from_xywh(0, 0, 80, 64), 1, 0.3));+ let path = Path::new(vec![Subpath::polygon(&[(10.3, 8.6), (66.2, 12.1), (58.7, 54.4), (16.9, 48.2)])]);+ let stroke = ShapeStroke { width: 5.0, paint: Fill::Solid(Color::rgb(0.9, 0.9, 0.1)), ..Default::default() };+ let mut sh = ShapeLayer { path, fill: Some(Fill::Solid(Color::rgb(0.2, 0.3, 0.8))), stroke: Some(stroke), live: None, cache: None, psd_raw: None };+ sh.cache = Some(photocraft_vector::render_shape(&sh, d.pixel_format(), d.bounds()));+ let mut l = Layer::new("shape", LayerContent::Shape(sh));+ l.blend = blend;+ l.opacity = 0.9;+ if masked {+ l.mask = Some(mask(Rect::new(0, 0, 80, 64), 41, 1.0));+ }+ let mut c = noise_layer("clip", d.pixel_format(), Rect::new(0, 0, 80, 64), 42, 0.5);+ c.clipped = true;+ c.blend = BlendMode::Screen;+ d.layers.extend([l, c]);+ let st = photocraft_gpu::render_to_vec_stats(&mut g.comp, &g.device, &g.queue, &d, d.bounds());+ assert!(st.is_ok(), "planned on the GPU");+ check(&mut g, &d, &format!("{depth:?} stroked shape + clipped {blend:?} masked {masked}"));}- let mut c = noise_layer("clip", PixelFormat::RGBA8, Rect::new(0, 0, 80, 64), 42, 0.5);- c.clipped = true;- c.blend = BlendMode::Screen;- d.layers.extend([l, c]);- let st = photocraft_gpu::render_to_vec_stats(&mut g.comp, &g.device, &g.queue, &d, d.bounds());- assert!(st.is_ok(), "planned on the GPU");- check(&mut g, &d, &format!("stroked shape + clipped {blend:?} masked {masked}"));}}