Skip to content

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

Scripts: Flatten All Layer Effects bakes with the document's Global Light and patterns (#5719) (#5720)

David Mannbc4f2a783d15
diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs
index 3cf2f1dc1..e35d5ad40 100644
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@ -349,6 +349,31 @@ pub fn render_layer(layer: &Layer, rect: Rect) -> Buffer {
buf
}
+/// [`render_layer`] in `doc`'s context: the layer alone over `rect`, with the document's patterns,
+/// Global Light, colour mode, depth and canvas (fill layers and gradients are laid out on it), as
+/// the canvas composites it. Bakes (Scripts › Flatten All Layer Effects) render through this so
+/// the pixels match what was on screen (#5719). Rects past [`MAX_RENDER_PIXELS`] give an empty
+/// buffer.
+pub fn render_layer_in(doc: &Document, layer: &Layer, rect: Rect) -> Buffer {
+ if rect.is_empty() {
+ return Buffer::transparent(rect);
+ }
+ if u64::from(rect.width()) * u64::from(rect.height()) > MAX_RENDER_PIXELS {
+ return Buffer::transparent(Rect::EMPTY);
+ }
+ let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode);
+ // A lone layer: a deep knockout reveals transparency, not the document's Background.
+ let cx = Ctx { doc: None, ..Ctx::for_doc(doc, &patterns) };
+ let lab = doc.mode == photocraft_color::ColorMode::Lab;
+ let hdr = doc.depth == photocraft_color::SampleType::F32;
+ let cmyk = cmyk_space(doc);
+ photocraft_color::convert::with_cmyk_space(cmyk.as_ref(), || {
+ let mut buf = Buffer::transparent(rect);
+ in_blend_space(lab, hdr, || composite_stack_at(std::slice::from_ref(layer), &mut buf, &cx, advanced::Scope::ROOT));
+ buf
+ })
+}
+
/// Documents above this many pixels get thumbnails from a proxy (see [`proxy`]) when that is
/// faithful; smaller ones are reduced from the exact composite.
pub const PROXY_THUMBNAIL_PIXELS: u64 = 16 << 20;
diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs
index 1fb3fcf30..2299aa3e4 100644
--- a/crates/engine/src/file_cmds.rs
+++ b/crates/engine/src/file_cmds.rs
@@ -1293,10 +1293,12 @@ fn has_live_effects(l: &Layer) -> bool {
l.effects.enabled && l.effects.items.iter().any(|e| e.enabled())
}
-/// The layer rendered alone (keeping what `keep` says), as a surface in `fmt`. With `apply_mask`
-/// off the layer's pixel and vector masks are left out of the render, so a caller that keeps them
-/// live on the baked raster does not mask the pixels twice.
-fn bake(l: &Layer, canvas: Rect, fmt: PixelFormat, keep_effects: bool, apply_mask: bool) -> Surface {
+/// The layer of `doc` rendered alone (keeping what `keep` says) with the document's Global Light,
+/// patterns and canvas, as a surface in the document's format. With `apply_mask` off the layer's
+/// pixel and vector masks are left out of the render, so a caller that keeps them live on the
+/// baked raster does not mask the pixels twice.
+fn bake(doc: &Document, l: &Layer, keep_effects: bool, apply_mask: bool) -> Surface {
+ let canvas = doc.bounds();
let mut tmp = l.clone();
tmp.opacity = 1.0;
tmp.blend = photocraft_color::BlendMode::Normal;
@@ -1313,7 +1315,7 @@ fn bake(l: &Layer, canvas: Rect, fmt: PixelFormat, keep_effects: bool, apply_mas
// Render over the union of the canvas and the content so off-canvas pixels survive.
let area = l.surface().map_or(canvas, |s| s.content_bounds().union(&canvas));
let area = if keep_effects { area.inflate(256) } else { area };
- buffer_surface(&photocraft_compose::render_layer(&tmp, area), fmt)
+ buffer_surface(&photocraft_compose::render_layer_in(doc, &tmp, area), doc.pixel_format())
}
fn walk_ids(doc: &Document) -> Vec<LayerId> {
@@ -1323,8 +1325,6 @@ fn walk_ids(doc: &Document) -> Vec<LayerId> {
fn flatten_all_effects(s: &mut Session) -> Result<Value> {
let mut n = 0;
s.edit("Flatten All Layer Effects", |doc, _| {
- let canvas = doc.bounds();
- let fmt = doc.pixel_format();
for id in walk_ids(doc) {
let Some(l) = doc.layer(id) else { continue };
if !has_live_effects(l) || matches!(l.content, LayerContent::Group(_) | LayerContent::Adjustment(_)) {
@@ -1332,7 +1332,7 @@ fn flatten_all_effects(s: &mut Session) -> Result<Value> {
}
// The pixel and vector masks stay on the layer (baking must not destroy them), so the
// pixels are baked without them and each mask then applies once to the baked raster.
- let px = bake(l, canvas, fmt, true, false);
+ let px = bake(doc, l, true, false);
let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
l.content = LayerContent::Raster(px);
l.effects = Default::default();
@@ -1349,8 +1349,6 @@ fn flatten_all_effects(s: &mut Session) -> Result<Value> {
fn flatten_all_masks(s: &mut Session) -> Result<Value> {
let (mut n, mut skipped) = (0, 0);
s.edit("Flatten All Masks", |doc, _| {
- let canvas = doc.bounds();
- let fmt = doc.pixel_format();
for id in walk_ids(doc) {
let Some(l) = doc.layer(id) else { continue };
let masked = l.mask.as_ref().is_some_and(|m| m.enabled) || l.vector_mask.is_some();
@@ -1363,7 +1361,7 @@ fn flatten_all_masks(s: &mut Session) -> Result<Value> {
skipped += 1;
continue;
}
- let px = bake(l, canvas, fmt, false, true);
+ let px = bake(doc, l, false, true);
let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
l.content = LayerContent::Raster(px);
l.mask = None;
diff --git a/crates/engine/src/file_cmds/tests.rs b/crates/engine/src/file_cmds/tests.rs
index 3ab50c4a7..b07c64985 100644
--- a/crates/engine/src/file_cmds/tests.rs
+++ b/crates/engine/src/file_cmds/tests.rs
@@ -747,6 +747,74 @@ fn flatten_all_layer_effects_keeps_masks() {
}
}
+/// Flattens all layer effects on a red square carrying `fx` (in a document prepared by `setup`)
+/// and asserts the composite did not change: the bake uses the document's own context (#5719).
+fn assert_flatten_effects_is_a_no_op(depth: u32, setup: impl FnOnce(&mut Document), fx: photocraft_doc::Effect) {
+ let mut s = session(40, 40, depth);
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s.execute("select.rect", json!({"x": 14, "y": 14, "width": 12, "height": 12})).unwrap();
+ s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap();
+ s.execute("select.deselect", json!({})).unwrap();
+ let id = s.active().unwrap().active_layer.unwrap();
+ s.edit("fx", |doc, _| {
+ setup(doc);
+ let l = doc.layer_mut(id).unwrap();
+ l.effects.enabled = true;
+ l.effects.items.push(fx);
+ Ok(())
+ })
+ .unwrap();
+ let before = photocraft_compose::flatten(doc(&s));
+ assert_eq!(s.execute("file.scripts.flattenAllLayerEffects", json!({})).unwrap()["flattened"], 1);
+ let after = photocraft_compose::flatten(doc(&s));
+ for (i, (a, b)) in after.px.iter().zip(&before.px).enumerate() {
+ for k in 0..4 {
+ assert!((a[k] - b[k]).abs() < 0.02, "depth {depth}: pixel ({}, {}) changed: {b:?} -> {a:?}", i % 40, i / 40);
+ }
+ }
+}
+
+/// A Drop Shadow that uses Global Light is baked at the document's angle, not the default 120°.
+#[test]
+fn flatten_all_layer_effects_uses_the_documents_global_light() {
+ for depth in [8, 16, 32] {
+ let shadow = photocraft_doc::Effect::DropShadow(photocraft_doc::effects::Shadow {
+ common: photocraft_doc::effects::FxCommon::new(photocraft_color::BlendMode::Normal, 1.0),
+ color: photocraft_color::Color::rgb(0.0, 0.0, 1.0),
+ angle: 120.0,
+ use_global_light: true,
+ distance: 10.0,
+ spread: 0.0,
+ size: 0.0,
+ contour: photocraft_doc::effects::Contour::Linear,
+ anti_alias: false,
+ noise: 0.0,
+ knocks_out: true,
+ });
+ assert_flatten_effects_is_a_no_op(depth, |d| d.global_light.angle = 0.0, shadow);
+ }
+}
+
+/// A Pattern Overlay of a document pattern survives the bake instead of vanishing.
+#[test]
+fn flatten_all_layer_effects_keeps_a_pattern_overlay() {
+ for depth in [8, 16, 32] {
+ let mut tile = photocraft_raster::Surface::new(PixelFormat::new(ColorMode::Rgb, photocraft_color::SampleType::U8, true));
+ tile.fill_rect(Rect::new(0, 0, 2, 2), &[0.0, 1.0, 0.0, 1.0]);
+ let pat = photocraft_doc::Pattern::new("green", tile, 2, 2);
+ let overlay = photocraft_doc::Effect::PatternOverlay {
+ common: photocraft_doc::effects::FxCommon::new(photocraft_color::BlendMode::Normal, 1.0),
+ name: pat.name.clone(),
+ id: pat.id.clone(),
+ scale: 1.0,
+ angle: 0.0,
+ link: true,
+ phase: (0.0, 0.0),
+ };
+ assert_flatten_effects_is_a_no_op(depth, |d| d.patterns.push(pat), overlay);
+ }
+}
+
#[test]
fn layers_to_files_writes_each_visible_layer() {
let dir = tmp("layers");