mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Merge pull request #15095 from yoriswind/codex/define-brush-visible-source-14271
Define brush presets from the visible document composite
This commit is contained in:
24 files changed
+2112
-300
No files matched your search
@@ -6,7 +6,10 @@ use std::sync::{Arc, Mutex, MutexGuard};
|
||||
use photocraft_engine::{
|
||||
Session,
|
||||
actions_cmds::{ActionState, ActionsFile, is_action_key},
|
||||
preset_store::{self, PresetBackend, *},
|
||||
preset_store::{
|
||||
self, ACTIONS_FILE, INDEX_FILE, MAX_ACTIONS_BYTES, MAX_GROUP_BYTES, MAX_GROUPS, MAX_INDEX_BYTES, MAX_PATTERNS_BYTES, MAX_PRESETS_PER_GROUP,
|
||||
MAX_STORE_BYTES, MAX_TIP_BYTES, PATTERNS_FILE, PresetBackend,
|
||||
},
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
|
||||
@@ -32,8 +32,9 @@ use std::borrow::Cow;
|
||||
use photocraft_doc::{Knockout, Layer, LayerContent};
|
||||
use photocraft_geom::Rect;
|
||||
|
||||
use crate::content::render_content_with;
|
||||
use crate::extents::recycle_mask;
|
||||
use crate::{Buffer, Ctx, composite_atop, composite_layer, effects, mask_vals, render_content};
|
||||
use crate::{Buffer, BufferAlloc, Ctx, effects, mask_vals};
|
||||
|
||||
/// Where a layer stack sits, for knockouts: at the document's top level, and/or inside an
|
||||
/// isolated (non-pass-through) group. Photoshop stops a deep knockout at the bottom of the
|
||||
@@ -99,26 +100,31 @@ pub fn is_background(l: &Layer) -> bool {
|
||||
l.has_background_traits()
|
||||
}
|
||||
|
||||
/// What a deep knockout reveals over `rect`: the document's initial backdrop with its Background
|
||||
/// layer (transparency when it has none, or when it is hidden).
|
||||
pub(crate) fn deep_target(cx: &Ctx, rect: Rect) -> Buffer {
|
||||
let Some(doc) = cx.doc else { return Buffer::transparent(rect) };
|
||||
let mut b = crate::multichannel::backdrop(doc, rect);
|
||||
fn deep_target_with<A: BufferAlloc>(cx: &Ctx, rect: Rect, alloc: &A) -> Result<Buffer, A::Error> {
|
||||
let Some(doc) = cx.doc else { return alloc.filled(rect, [0.0; 4]) };
|
||||
let mut b = crate::multichannel::backdrop_with(doc, rect, alloc)?;
|
||||
if let Some(bg) = doc.layers.first().filter(|l| l.visible && is_background(l)) {
|
||||
composite_layer(bg, &[], &mut b, cx, None, Scope::ROOT);
|
||||
crate::composite::composite_layer_with(bg, &[], &mut b, cx, None, Scope::ROOT, alloc)?;
|
||||
}
|
||||
b
|
||||
Ok(b)
|
||||
}
|
||||
|
||||
/// The knockout target of a layer of a stack in `scope`, if it knocks out. `floor` is the
|
||||
/// stack's starting backdrop (`None` at the top level, where a shallow knockout reaches the
|
||||
/// Background too).
|
||||
pub(crate) fn knockout_target<'b>(layer: &Layer, floor: Option<&'b Buffer>, rect: Rect, cx: &Ctx, scope: Scope) -> Option<Cow<'b, Buffer>> {
|
||||
let deep = || if scope.isolated { Buffer::transparent(rect) } else { deep_target(cx, rect) };
|
||||
pub(crate) fn knockout_target_with<'b, A: BufferAlloc>(
|
||||
layer: &Layer,
|
||||
floor: Option<&'b Buffer>,
|
||||
rect: Rect,
|
||||
cx: &Ctx,
|
||||
scope: Scope,
|
||||
alloc: &A,
|
||||
) -> Result<Option<Cow<'b, Buffer>>, A::Error> {
|
||||
let deep = || if scope.isolated { alloc.filled(rect, [0.0; 4]) } else { deep_target_with(cx, rect, alloc) };
|
||||
match layer.advanced.knockout {
|
||||
Knockout::None => None,
|
||||
Knockout::Shallow => Some(floor.map_or_else(|| Cow::Owned(deep()), Cow::Borrowed)),
|
||||
Knockout::Deep => Some(Cow::Owned(deep())),
|
||||
Knockout::None => Ok(None),
|
||||
Knockout::Shallow => match floor {
|
||||
Some(floor) => Ok(Some(Cow::Borrowed(floor))),
|
||||
None => Ok(Some(Cow::Owned(deep()?))),
|
||||
},
|
||||
Knockout::Deep => Ok(Some(Cow::Owned(deep()?))),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -128,17 +134,15 @@ pub(crate) fn needs_floor(layers: &[Layer]) -> bool {
|
||||
layers.iter().any(|l| l.visible && !l.clipped && l.advanced.knockout == Knockout::Shallow)
|
||||
}
|
||||
|
||||
/// The shape a layer knocks out over `rect` (row-major): its content's alpha with its masks;
|
||||
/// with Transparency Shapes Layer off (and for adjustment layers) just the masks.
|
||||
fn knockout_shape(layer: &Layer, rect: Rect, cx: &Ctx) -> Vec<f32> {
|
||||
fn knockout_shape_with<A: BufferAlloc>(layer: &Layer, rect: Rect, cx: &Ctx, alloc: &A) -> Result<Vec<f32>, A::Error> {
|
||||
let n = rect.width() as usize * rect.height() as usize;
|
||||
let masks = || mask_vals(layer, rect, cx).unwrap_or_else(|| vec![1.0; n]);
|
||||
if !layer.advanced.transparency_shapes {
|
||||
return masks();
|
||||
return Ok(masks());
|
||||
}
|
||||
match render_content(layer, rect, cx) {
|
||||
Some(b) => b.px.iter().map(|p| p[3]).collect(),
|
||||
None => masks(),
|
||||
match render_content_with(layer, rect, cx, alloc)? {
|
||||
Some(b) => Ok(b.px.iter().map(|p| p[3]).collect()),
|
||||
None => Ok(masks()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,19 +154,27 @@ fn knockout_shape(layer: &Layer, rect: Rect, cx: &Ctx) -> Vec<f32> {
|
||||
///
|
||||
/// `clip_alpha` keeps alpha from growing (clipped layers stay inside their base's alpha; a
|
||||
/// knockout to transparency may still lower it).
|
||||
pub(crate) fn knockout(layer: &Layer, backdrop: &mut Buffer, target: &Buffer, clip_alpha: bool, cx: &Ctx, draw: impl FnOnce(&mut Buffer)) {
|
||||
pub(crate) fn knockout_with<A: BufferAlloc>(
|
||||
layer: &Layer,
|
||||
backdrop: &mut Buffer,
|
||||
target: &Buffer,
|
||||
clip_alpha: bool,
|
||||
cx: &Ctx,
|
||||
alloc: &A,
|
||||
draw: impl FnOnce(&mut Buffer) -> Result<(), A::Error>,
|
||||
) -> Result<(), A::Error> {
|
||||
// Coverage knocks out proportionally. (Photoshop knocks out a little more at anti-aliased
|
||||
// shape edges: psd-tools knockout-isolated-groups differs on 0.45 % of its pixels, along
|
||||
// ellipse edges; a binary shape matched worse.)
|
||||
let shape = knockout_shape(layer, backdrop.rect, cx);
|
||||
let shape = knockout_shape_with(layer, backdrop.rect, cx, alloc)?;
|
||||
if target.rect != backdrop.rect || shape.len() != backdrop.px.len() {
|
||||
// Never reached (targets are built over the backdrop's rect); compositing without the
|
||||
// knockout beats a wrong pixel or a panic.
|
||||
recycle_mask(Some(shape));
|
||||
draw(backdrop);
|
||||
return;
|
||||
draw(backdrop)?;
|
||||
return Ok(());
|
||||
}
|
||||
let before = backdrop.clone();
|
||||
let before = alloc.clone(backdrop)?;
|
||||
for ((p, t), k) in backdrop.px.iter_mut().zip(&target.px).zip(&shape) {
|
||||
if *k > 0.0 {
|
||||
let a = p[3];
|
||||
@@ -172,11 +184,11 @@ pub(crate) fn knockout(layer: &Layer, backdrop: &mut Buffer, target: &Buffer, cl
|
||||
}
|
||||
}
|
||||
}
|
||||
let knocked = (layer.opacity < 1.0).then(|| backdrop.clone());
|
||||
draw(backdrop);
|
||||
let knocked = if layer.opacity < 1.0 { Some(alloc.clone(backdrop)?) } else { None };
|
||||
draw(backdrop)?;
|
||||
let Some(knocked) = knocked else {
|
||||
recycle_mask(Some(shape));
|
||||
return;
|
||||
return Ok(());
|
||||
};
|
||||
let rest = 1.0 - layer.opacity.clamp(0.0, 1.0);
|
||||
for (((p, b), k), s) in backdrop.px.iter_mut().zip(&before.px).zip(&knocked.px).zip(&shape) {
|
||||
@@ -192,20 +204,20 @@ pub(crate) fn knockout(layer: &Layer, backdrop: &mut Buffer, target: &Buffer, cl
|
||||
*p = if a > 0.0 { [(pm[0] / a).clamp(0.0, 1.0), (pm[1] / a).clamp(0.0, 1.0), (pm[2] / a).clamp(0.0, 1.0), a] } else { [0.0; 4] };
|
||||
}
|
||||
recycle_mask(Some(shape));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Composite a clipping group's clipped layers atop `base` (the base's isolated content, Blend
|
||||
/// Clipped Layers as Group on). The grouped clipping layers composite in isolation, like an
|
||||
/// isolated group, so a clipped layer's knockout (shallow or deep) stops at the bottom of the
|
||||
/// clipping group: the base's content.
|
||||
pub(crate) fn composite_clipped(clipped: &[Layer], base: &mut Buffer, cx: &Ctx) {
|
||||
let floor = clipped.iter().any(|c| c.visible && c.advanced.knockout != Knockout::None).then(|| base.clone());
|
||||
pub(crate) fn composite_clipped_with<A: BufferAlloc>(clipped: &[Layer], base: &mut Buffer, cx: &Ctx, alloc: &A) -> Result<(), A::Error> {
|
||||
let floor = if clipped.iter().any(|c| c.visible && c.advanced.knockout != Knockout::None) { Some(alloc.clone(base)?) } else { None };
|
||||
for c in clipped.iter().filter(|c| c.visible) {
|
||||
match &floor {
|
||||
Some(f) if c.advanced.knockout != Knockout::None => knockout(c, base, f, true, cx, |b| composite_atop(c, b, cx)),
|
||||
_ => composite_atop(c, base, cx),
|
||||
Some(f) if c.advanced.knockout != Knockout::None => {
|
||||
knockout_with(c, base, f, true, cx, alloc, |b| crate::composite::composite_atop_with(c, b, cx, alloc))?
|
||||
}
|
||||
_ => crate::composite::composite_atop_with(c, base, cx, alloc)?,
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether `layer`'s clipped layers blend one by one (Blend Clipped Layers as Group off).
|
||||
@@ -218,14 +230,22 @@ pub(crate) fn clips_individually(layer: &Layer, clipped: &[Layer]) -> bool {
|
||||
/// clipped layer composited in its own mode onto the result, inside the base's shape (its alpha
|
||||
/// with masks, times its opacity). A clipped layer's shallow knockout stops at the backdrop
|
||||
/// beneath the base (the bottom of the clipping group).
|
||||
pub(crate) fn composite_clipped_individually(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx, ko: Option<&Buffer>, scope: Scope) {
|
||||
pub(crate) fn composite_clipped_individually_with<A: BufferAlloc>(
|
||||
layer: &Layer,
|
||||
clipped: &[Layer],
|
||||
backdrop: &mut Buffer,
|
||||
cx: &Ctx,
|
||||
ko: Option<&Buffer>,
|
||||
scope: Scope,
|
||||
alloc: &A,
|
||||
) -> Result<(), A::Error> {
|
||||
let rect = backdrop.rect;
|
||||
let n = backdrop.px.len();
|
||||
let floor = clipped.iter().any(|c| c.visible && c.advanced.knockout == Knockout::Shallow).then(|| backdrop.clone());
|
||||
composite_layer(layer, &[], backdrop, cx, ko, scope);
|
||||
let floor = if clipped.iter().any(|c| c.visible && c.advanced.knockout == Knockout::Shallow) { Some(alloc.clone(backdrop)?) } else { None };
|
||||
crate::composite::composite_layer_with(layer, &[], backdrop, cx, ko, scope, alloc)?;
|
||||
let op = layer.opacity.clamp(0.0, 1.0);
|
||||
let clip: Vec<f32> = match render_content(layer, rect, cx) {
|
||||
Some(b) => b.px.iter().map(|p| p[3] * op).collect(),
|
||||
let clip = match render_content_with(layer, rect, cx, alloc)? {
|
||||
Some(b) => b.px.iter().map(|p| p[3] * op).collect::<Vec<_>>(),
|
||||
None => {
|
||||
let mv = mask_vals(layer, rect, cx);
|
||||
let clip = mv.as_ref().map_or_else(|| vec![op; n], |m| m.iter().map(|m| m * op).collect());
|
||||
@@ -234,18 +254,19 @@ pub(crate) fn composite_clipped_individually(layer: &Layer, clipped: &[Layer], b
|
||||
}
|
||||
};
|
||||
if clip.len() != n {
|
||||
return;
|
||||
return Ok(());
|
||||
}
|
||||
for c in clipped.iter().filter(|c| c.visible) {
|
||||
let before = backdrop.clone();
|
||||
let t = knockout_target(c, floor.as_ref(), rect, cx, Scope { root: false, ..scope });
|
||||
composite_layer(c, &[], backdrop, cx, t.as_deref(), scope);
|
||||
let before = alloc.clone(backdrop)?;
|
||||
let t = knockout_target_with(c, floor.as_ref(), rect, cx, Scope { root: false, ..scope }, alloc)?;
|
||||
crate::composite::composite_layer_with(c, &[], backdrop, cx, t.as_deref(), scope, alloc)?;
|
||||
for ((p, b), k) in backdrop.px.iter_mut().zip(&before.px).zip(&clip) {
|
||||
if *k < 1.0 {
|
||||
*p = mix(*b, *p, k.max(0.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether a mask of `layer` hides its effects instead of shaping them (Layer / Vector Mask
|
||||
|
||||
+152
-87
@@ -1,19 +1,27 @@
|
||||
use super::content::{channel_weights, empty_in, render_content, restore_channels, surface_to_buffer};
|
||||
use super::content::{channel_weights, empty_in, render_content_with, restore_channels, surface_to_buffer_with};
|
||||
use super::ctx::Ctx;
|
||||
use super::extents::{effects_frame, mask_k, mask_vals, recycle_mask, shapeless_stroke_bounds};
|
||||
use super::fx_cache::effect_maps;
|
||||
use super::{BlendMode, Buffer, Fill, Layer, LayerContent, Rect, Surface, advanced, blend, effects, psblend, shape_split};
|
||||
|
||||
/// Composite an isolated group's sibling list (bottom→top) onto `backdrop` (its own buffer).
|
||||
pub(crate) fn composite_stack(layers: &[Layer], backdrop: &mut Buffer, cx: &Ctx) {
|
||||
composite_stack_at(layers, backdrop, cx, advanced::Scope::ISOLATED);
|
||||
}
|
||||
use super::fx_cache::effect_maps_with;
|
||||
use super::{BlendMode, Buffer, BufferAlloc, Fill, InfallibleBufferAlloc, Layer, LayerContent, Rect, Surface, advanced, blend, effects, psblend, shape_split};
|
||||
|
||||
/// Composite a sibling list (bottom→top) onto `backdrop`; `scope` says where the stack sits (see
|
||||
/// [`advanced::Scope`]: it decides what knockouts reveal).
|
||||
pub(crate) fn composite_stack_at(layers: &[Layer], backdrop: &mut Buffer, cx: &Ctx, scope: advanced::Scope) {
|
||||
match composite_stack_at_with(layers, backdrop, cx, scope, &InfallibleBufferAlloc) {
|
||||
Ok(()) => {}
|
||||
Err(never) => match never {},
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn composite_stack_at_with<A: BufferAlloc>(
|
||||
layers: &[Layer],
|
||||
backdrop: &mut Buffer,
|
||||
cx: &Ctx,
|
||||
scope: advanced::Scope,
|
||||
alloc: &A,
|
||||
) -> Result<(), A::Error> {
|
||||
// Shallow knockouts stop at the bottom of this stack: the backdrop it starts from.
|
||||
let floor = (!scope.root && advanced::needs_floor(layers)).then(|| backdrop.clone());
|
||||
let floor = if !scope.root && advanced::needs_floor(layers) { Some(alloc.clone(backdrop)?) } else { None };
|
||||
let mut i = 0;
|
||||
while i < layers.len() {
|
||||
let base = &layers[i];
|
||||
@@ -24,14 +32,15 @@ pub(crate) fn composite_stack_at(layers: &[Layer], backdrop: &mut Buffer, cx: &C
|
||||
}
|
||||
let clipped = &layers[i + 1..j];
|
||||
if base.visible {
|
||||
let ko = advanced::knockout_target(base, floor.as_ref(), backdrop.rect, cx, scope);
|
||||
composite_layer(base, clipped, backdrop, cx, ko.as_deref(), scope);
|
||||
let ko = advanced::knockout_target_with(base, floor.as_ref(), backdrop.rect, cx, scope, alloc)?;
|
||||
composite_layer_with(base, clipped, backdrop, cx, ko.as_deref(), scope, alloc)?;
|
||||
if let (LayerContent::Adjustment(_), Some(q)) = (&base.content, adjustment_quantum(cx.depth)) {
|
||||
quantize(backdrop, q);
|
||||
}
|
||||
}
|
||||
i = j.max(i + 1);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Steps per unit of an integer document's samples: Photoshop applies adjustment layers to
|
||||
@@ -208,7 +217,7 @@ thread_local! {
|
||||
/// is mixed back towards `before` (the backdrop without it) where the ranges hide the layer.
|
||||
/// Mixing premultiplied colour by `k` equals compositing the layer at `k` × its alpha, since
|
||||
/// every blend mode's source-over result is linear in the source alpha.
|
||||
fn apply_blend_if(layer: &Layer, before: &Buffer, out: &mut Buffer, cx: &Ctx) {
|
||||
fn apply_blend_if_with<A: BufferAlloc>(layer: &Layer, before: &Buffer, out: &mut Buffer, cx: &Ctx, alloc: &A) -> Result<(), A::Error> {
|
||||
// "This Layer" is the layer's own colour. An adjustment layer (no content of its own) is
|
||||
// judged by its result at full strength, before Opacity and its mask mix it in, as Photoshop
|
||||
// does (#9542). Groups nested deeper than `MAX_BLEND_IF_GROUP_DEPTH` Blend Ifs are judged by
|
||||
@@ -217,16 +226,16 @@ fn apply_blend_if(layer: &Layer, before: &Buffer, out: &mut Buffer, cx: &Ctx) {
|
||||
let is_group = matches!(layer.content, LayerContent::Group(_));
|
||||
let nested = BLEND_IF_GROUPS.with(std::cell::Cell::get);
|
||||
let own = if let LayerContent::Adjustment(adj) = &layer.content {
|
||||
let mut result = before.clone();
|
||||
let mut result = alloc.clone(before)?;
|
||||
cx.apply_adjustment(adj, &mut result);
|
||||
Some(result)
|
||||
} else if is_group && nested >= MAX_BLEND_IF_GROUP_DEPTH {
|
||||
None
|
||||
} else {
|
||||
BLEND_IF_GROUPS.with(|d| d.set(nested + u32::from(is_group)));
|
||||
let own = render_content(layer, out.rect, cx);
|
||||
let own = render_content_with(layer, out.rect, cx, alloc);
|
||||
BLEND_IF_GROUPS.with(|d| d.set(nested));
|
||||
own
|
||||
own?
|
||||
};
|
||||
for (i, (p, b)) in out.px.iter_mut().zip(&before.px).enumerate() {
|
||||
let this = match &own {
|
||||
@@ -246,67 +255,94 @@ fn apply_blend_if(layer: &Layer, before: &Buffer, out: &mut Buffer, cx: &Ctx) {
|
||||
[0.0; 4]
|
||||
};
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Composite `layer` (plus its clipping group) onto `backdrop`, honouring its channel restrictions
|
||||
/// and Blend If, and knocking out to `ko` when it has a knockout (see [`advanced`]).
|
||||
pub(crate) fn composite_layer(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx, ko: Option<&Buffer>, scope: advanced::Scope) {
|
||||
pub(crate) fn composite_layer_with<A: BufferAlloc>(
|
||||
layer: &Layer,
|
||||
clipped: &[Layer],
|
||||
backdrop: &mut Buffer,
|
||||
cx: &Ctx,
|
||||
ko: Option<&Buffer>,
|
||||
scope: advanced::Scope,
|
||||
alloc: &A,
|
||||
) -> Result<(), A::Error> {
|
||||
// Blend Clipped Layers as Group off: the base alone, then each clipped layer in its own mode.
|
||||
if advanced::clips_individually(layer, clipped) {
|
||||
advanced::composite_clipped_individually(layer, clipped, backdrop, cx, ko, scope);
|
||||
return;
|
||||
advanced::composite_clipped_individually_with(layer, clipped, backdrop, cx, ko, scope, alloc)?;
|
||||
return Ok(());
|
||||
}
|
||||
let w = channel_weights(layer, cx.mode);
|
||||
let blend_if = blend_if_active(layer, cx.mode);
|
||||
let before = (w.is_some() || blend_if).then(|| backdrop.clone());
|
||||
let before = if w.is_some() || blend_if { Some(alloc.clone(backdrop)?) } else { None };
|
||||
match ko {
|
||||
Some(target) => advanced::knockout(layer, backdrop, target, false, cx, |b| composite_layer_any(layer, clipped, b, cx, scope)),
|
||||
None => composite_layer_any(layer, clipped, backdrop, cx, scope),
|
||||
Some(target) => advanced::knockout_with(layer, backdrop, target, false, cx, alloc, |b| composite_layer_any_with(layer, clipped, b, cx, scope, alloc))?,
|
||||
None => composite_layer_any_with(layer, clipped, backdrop, cx, scope, alloc)?,
|
||||
}
|
||||
if let Some(before) = &before {
|
||||
if let Some(w) = w {
|
||||
restore_channels(backdrop, before, w);
|
||||
}
|
||||
if blend_if {
|
||||
apply_blend_if(layer, before, backdrop, cx);
|
||||
apply_blend_if_with(layer, before, backdrop, cx, alloc)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn composite_layer_any(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx, scope: advanced::Scope) {
|
||||
fn composite_layer_any_with<A: BufferAlloc>(
|
||||
layer: &Layer,
|
||||
clipped: &[Layer],
|
||||
backdrop: &mut Buffer,
|
||||
cx: &Ctx,
|
||||
scope: advanced::Scope,
|
||||
alloc: &A,
|
||||
) -> Result<(), A::Error> {
|
||||
if let LayerContent::Group(g) = &layer.content
|
||||
&& let Some(ab) = &g.artboard
|
||||
{
|
||||
composite_artboard(layer, ab, clipped, backdrop, cx, scope);
|
||||
return;
|
||||
composite_artboard_with(layer, ab, clipped, backdrop, cx, scope, alloc)?;
|
||||
return Ok(());
|
||||
}
|
||||
composite_layer_plain(layer, clipped, backdrop, cx, scope);
|
||||
composite_layer_plain_with(layer, clipped, backdrop, cx, scope, alloc)
|
||||
}
|
||||
|
||||
/// An artboard: its background and the group, composited only inside the board (contents and
|
||||
/// effects outside it are clipped away; the backdrop there is untouched).
|
||||
fn composite_artboard(layer: &Layer, ab: &photocraft_doc::Artboard, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx, scope: advanced::Scope) {
|
||||
fn composite_artboard_with<A: BufferAlloc>(
|
||||
layer: &Layer,
|
||||
ab: &photocraft_doc::Artboard,
|
||||
clipped: &[Layer],
|
||||
backdrop: &mut Buffer,
|
||||
cx: &Ctx,
|
||||
scope: advanced::Scope,
|
||||
alloc: &A,
|
||||
) -> Result<(), A::Error> {
|
||||
let board = ab.rect.intersect(&backdrop.rect);
|
||||
if board.is_empty() {
|
||||
return;
|
||||
return Ok(());
|
||||
}
|
||||
let (bw, w) = (board.width() as usize, backdrop.rect.width() as usize);
|
||||
let row0 = |y: i32| (y - backdrop.rect.y0) as usize * w + (board.x0 - backdrop.rect.x0) as usize;
|
||||
let mut sub = Buffer::transparent(board);
|
||||
let mut sub = alloc.filled(board, [0.0; 4])?;
|
||||
for y in board.y0..board.y1 {
|
||||
let o = row0(y);
|
||||
let so = (y - board.y0) as usize * bw;
|
||||
sub.px[so..so + bw].copy_from_slice(&backdrop.px[o..o + bw]);
|
||||
}
|
||||
if let Some(bg) = ab.background.rgba() {
|
||||
blend_into(&mut sub, &Buffer::filled(board, bg), BlendMode::Normal, 1.0);
|
||||
let background = alloc.filled(board, bg)?;
|
||||
blend_into(&mut sub, &background, BlendMode::Normal, 1.0);
|
||||
}
|
||||
composite_layer_plain(layer, clipped, &mut sub, cx, scope);
|
||||
composite_layer_plain_with(layer, clipped, &mut sub, cx, scope, alloc)?;
|
||||
for y in board.y0..board.y1 {
|
||||
let o = row0(y);
|
||||
let so = (y - board.y0) as usize * bw;
|
||||
backdrop.px[o..o + bw].copy_from_slice(&sub.px[so..so + bw]);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The surface `render_content` reads `layer`'s pixels from, when that is all it draws.
|
||||
@@ -342,13 +378,28 @@ pub(crate) fn composite_pixel_layer(layer: &Layer, surf: &Surface, backdrop: &mu
|
||||
recycle_mask(mv);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx, scope: advanced::Scope) {
|
||||
match composite_layer_plain_with(layer, clipped, backdrop, cx, scope, &InfallibleBufferAlloc) {
|
||||
Ok(()) => {}
|
||||
Err(never) => match never {},
|
||||
}
|
||||
}
|
||||
|
||||
fn composite_layer_plain_with<A: BufferAlloc>(
|
||||
layer: &Layer,
|
||||
clipped: &[Layer],
|
||||
backdrop: &mut Buffer,
|
||||
cx: &Ctx,
|
||||
scope: advanced::Scope,
|
||||
alloc: &A,
|
||||
) -> Result<(), A::Error> {
|
||||
let rect = backdrop.rect;
|
||||
// A TSL-off stroke base that is transparent here can still have visible clipped siblings;
|
||||
// keep the full clipping path for it instead of the stroke-bounds shortcut. Other bases keep
|
||||
// the usual skip (their clipped layers vanish with them).
|
||||
if (clipped.is_empty() || shapeless_stroke_bounds(layer).is_none()) && empty_in(layer, rect) {
|
||||
return;
|
||||
return Ok(());
|
||||
}
|
||||
let opacity = layer.opacity * layer.fill_opacity;
|
||||
|
||||
@@ -373,8 +424,8 @@ pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop:
|
||||
let needs_mix = opacity < 1.0 || layer.mask.is_some() || layer.vector_mask.is_some();
|
||||
let has_clipped = clipped.iter().any(|c| c.visible);
|
||||
// Children can draw directly unless mixing or clipping needs the original backdrop.
|
||||
let before = (needs_mix || has_clipped).then(|| backdrop.clone());
|
||||
composite_stack_at(&g.children, backdrop, cx, scope.pass_through());
|
||||
let before = if needs_mix || has_clipped { Some(alloc.clone(backdrop)?) } else { None };
|
||||
composite_stack_at_with(&g.children, backdrop, cx, scope.pass_through(), alloc)?;
|
||||
if needs_mix && let Some(before) = &before {
|
||||
let mv = mask_vals(layer, rect, cx);
|
||||
for (i, (p, a)) in backdrop.px.iter_mut().zip(&before.px).enumerate() {
|
||||
@@ -395,22 +446,21 @@ pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop:
|
||||
}
|
||||
// A Frame's stroke over the frame's content, at the group's opacity.
|
||||
if let Some(stroke) = shape_split::frame_stroke(layer, cx.canvas, cx.depth) {
|
||||
blend_into(backdrop, &surface_to_buffer(&stroke, rect), BlendMode::Normal, opacity);
|
||||
blend_into(backdrop, &surface_to_buffer_with(&stroke, rect, alloc)?, BlendMode::Normal, opacity);
|
||||
}
|
||||
// Layers clipped to a pass-through group sit atop the group's
|
||||
// isolated rendering; their effect (isolated result with vs. without
|
||||
// them, each placed over the original backdrop) is added to the
|
||||
// pass-through result. Exact when the children blend Normal, close
|
||||
// otherwise (matches psd-tools clipping-mask3/4/5).
|
||||
if has_clipped && let (Some(before), Some(iso)) = (before, render_content(layer, rect, cx)) {
|
||||
let mut clipped_iso = iso.clone();
|
||||
advanced::composite_clipped(clipped, &mut clipped_iso, cx);
|
||||
let mut without = before.clone();
|
||||
if has_clipped && let (Some(before), Some(iso)) = (before, render_content_with(layer, rect, cx, alloc)?) {
|
||||
let mut clipped_iso = alloc.clone(&iso)?;
|
||||
advanced::composite_clipped_with(clipped, &mut clipped_iso, cx, alloc)?;
|
||||
let mut without = alloc.clone(&before)?;
|
||||
blend_into(&mut without, &iso, BlendMode::Normal, opacity);
|
||||
let mut with = before;
|
||||
blend_into(&mut with, &clipped_iso, BlendMode::Normal, opacity);
|
||||
for ((p, w), wo) in backdrop.px.iter_mut().zip(&with.px).zip(&without.px) {
|
||||
// Work premultiplied so transparent areas stay consistent.
|
||||
let pa = p[3];
|
||||
let mut pm = [p[0] * pa, p[1] * pa, p[2] * pa, pa];
|
||||
for c in 0..3 {
|
||||
@@ -421,7 +471,7 @@ pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop:
|
||||
*p = if a > 0.0 { [(pm[0] / a).clamp(0.0, 1.0), (pm[1] / a).clamp(0.0, 1.0), (pm[2] / a).clamp(0.0, 1.0), a] } else { [0.0; 4] };
|
||||
}
|
||||
}
|
||||
return;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Adjustment layers transform the backdrop, then blend the result back in.
|
||||
@@ -429,13 +479,13 @@ pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop:
|
||||
let mv = mask_vals(layer, rect, cx);
|
||||
if mv.as_ref().is_some_and(|values| values.iter().all(|&value| opacity * value <= 0.0)) {
|
||||
recycle_mask(mv);
|
||||
return;
|
||||
return Ok(());
|
||||
}
|
||||
let mut adjusted = Buffer::transparent(rect);
|
||||
let mut adjusted = alloc.filled(rect, [0.0; 4])?;
|
||||
adjusted.px.copy_from_slice(&backdrop.px);
|
||||
cx.apply_adjustment(adj, &mut adjusted);
|
||||
// Clipped layers onto an adjustment are uncommon; they composite atop the adjusted result.
|
||||
advanced::composite_clipped(clipped, &mut adjusted, cx);
|
||||
advanced::composite_clipped_with(clipped, &mut adjusted, cx, alloc)?;
|
||||
if layer.blend == BlendMode::Dissolve {
|
||||
// An adjustment has no standalone source alpha. Its effective coverage comes from its
|
||||
// own opacity and mask, not a continuous RGB mix (#3050).
|
||||
@@ -460,7 +510,7 @@ pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop:
|
||||
}
|
||||
}
|
||||
recycle_mask(mv);
|
||||
return;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if effects::has_effects(layer) {
|
||||
@@ -468,23 +518,23 @@ pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop:
|
||||
// hides the finished layer and effects.
|
||||
let src = advanced::effects_source(layer);
|
||||
let hide = advanced::hiding_mask(layer, rect, cx);
|
||||
let before = hide.as_ref().map(|_| backdrop.clone());
|
||||
composite_layer_effects(&src, clipped, backdrop, cx);
|
||||
let before = if hide.is_some() { Some(alloc.clone(backdrop)?) } else { None };
|
||||
composite_layer_effects_with(&src, clipped, backdrop, cx, alloc)?;
|
||||
if let (Some(m), Some(b)) = (&hide, &before) {
|
||||
advanced::apply_hiding_mask(backdrop, b, m);
|
||||
}
|
||||
recycle_mask(hide);
|
||||
return;
|
||||
return Ok(());
|
||||
}
|
||||
if let Some((mut content, stroke, mask)) = shape_parts(layer, clipped, rect, cx) {
|
||||
advanced::composite_clipped(clipped, &mut content, cx);
|
||||
if let Some((mut content, stroke, mask)) = shape_parts_with(layer, clipped, rect, cx, alloc)? {
|
||||
advanced::composite_clipped_with(clipped, &mut content, cx, alloc)?;
|
||||
for (i, (p, s)) in content.px.iter_mut().zip(&stroke.px).enumerate() {
|
||||
*p = psblend::composite(BlendMode::Normal, *p, *s, 1.0);
|
||||
p[3] *= mask_k(&mask, i);
|
||||
}
|
||||
blend_layer_into(backdrop, &content, layer, cx, 1.0);
|
||||
recycle_mask(mask);
|
||||
return;
|
||||
return Ok(());
|
||||
}
|
||||
if !matches!(layer.content, LayerContent::Group(_) | LayerContent::Fill(_) | LayerContent::Adjustment(_))
|
||||
&& let Some(s) = layer.surface()
|
||||
@@ -505,7 +555,7 @@ pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop:
|
||||
*p = psblend::composite_normal_rgb([0.0; 4], *p, 1.0);
|
||||
}
|
||||
}
|
||||
return;
|
||||
return Ok(());
|
||||
}
|
||||
// The row-at-a-time fast path blends like `blend_into_fill`; Transparency Shapes Layer off
|
||||
// with one of the special eight needs `blend_layer_into`'s per-pixel mask split.
|
||||
@@ -513,33 +563,35 @@ pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop:
|
||||
&& (layer.advanced.transparency_shapes || !psblend::fill_is_special(layer.blend))
|
||||
&& let Some(surf) = pixel_surface(layer)
|
||||
{
|
||||
return composite_pixel_layer(layer, surf, backdrop, cx);
|
||||
composite_pixel_layer(layer, surf, backdrop, cx);
|
||||
return Ok(());
|
||||
}
|
||||
let Some(mut content) = render_content(layer, rect, cx) else { return };
|
||||
advanced::composite_clipped(clipped, &mut content, cx);
|
||||
let Some(mut content) = render_content_with(layer, rect, cx, alloc)? else { return Ok(()) };
|
||||
advanced::composite_clipped_with(clipped, &mut content, cx, alloc)?;
|
||||
blend_layer_into(backdrop, &content, layer, cx, text_gamma(layer));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A layer with effects (and its clipping group) onto `backdrop`.
|
||||
fn composite_layer_effects(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx) {
|
||||
fn composite_layer_effects_with<A: BufferAlloc>(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx, alloc: &A) -> Result<(), A::Error> {
|
||||
let rect = backdrop.rect;
|
||||
// Neighbourhoods are already captured by the full-region effect maps;
|
||||
// content and effect application only need the output rectangle.
|
||||
// A stroked shape's vector stroke stays above its clipped layers and interior effects.
|
||||
let (mut content, parts) = match split_parts(layer, rect, cx) {
|
||||
let (mut content, parts) = match split_parts_with(layer, rect, cx, alloc)? {
|
||||
Some((fill, stroke, mask)) => (fill, Some((stroke, mask))),
|
||||
None => {
|
||||
let Some(content) = render_content(layer, rect, cx) else { return };
|
||||
let Some(content) = render_content_with(layer, rect, cx, alloc)? else { return Ok(()) };
|
||||
(content, None)
|
||||
}
|
||||
};
|
||||
advanced::composite_clipped(clipped, &mut content, cx);
|
||||
advanced::composite_clipped_with(clipped, &mut content, cx, alloc)?;
|
||||
let vstroke = parts.as_ref().map(|(s, m)| effects::VectorStroke { stroke: s, mask: m.as_deref() });
|
||||
let maps = effect_maps(layer, rect, cx);
|
||||
effects::composite_with_effects_prepared(layer, &content, backdrop, &maps, effects_frame(layer, cx.canvas), cx.patterns, vstroke);
|
||||
let maps = effect_maps_with(layer, rect, cx, alloc)?;
|
||||
effects::composite_with_effects_prepared_with(layer, &content, backdrop, (&maps, vstroke), effects_frame(layer, cx.canvas), cx.patterns, alloc)?;
|
||||
if let Some((_, mask)) = parts {
|
||||
recycle_mask(mask);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The coverage-mixing gamma of a layer: the text blending gamma
|
||||
@@ -548,25 +600,30 @@ pub fn text_gamma(layer: &Layer) -> f32 {
|
||||
if matches!(layer.content, LayerContent::Text(_)) { psblend::text_gamma() } else { 1.0 }
|
||||
}
|
||||
|
||||
/// Unmasked shape fill, vector stroke and shared mask values.
|
||||
type ShapeParts = (Buffer, Buffer, Option<Vec<f32>>);
|
||||
|
||||
/// A stroked shape layer with visible clipped layers: Photoshop draws the shape's vector stroke
|
||||
/// above the clipped layers, so the base content is the fill alone and the stroke is laid on top
|
||||
/// after clipping. See [`split_parts`].
|
||||
fn shape_parts(layer: &Layer, clipped: &[Layer], rect: Rect, cx: &Ctx) -> Option<(Buffer, Buffer, Option<Vec<f32>>)> {
|
||||
/// after clipping. See [`split_parts_with`].
|
||||
fn shape_parts_with<A: BufferAlloc>(layer: &Layer, clipped: &[Layer], rect: Rect, cx: &Ctx, alloc: &A) -> Result<Option<ShapeParts>, A::Error> {
|
||||
if !clipped.iter().any(|c| c.visible) {
|
||||
return None;
|
||||
return Ok(None);
|
||||
}
|
||||
split_parts(layer, rect, cx)
|
||||
split_parts_with(layer, rect, cx, alloc)
|
||||
}
|
||||
|
||||
/// A stroked shape layer's (fill, vector stroke, mask values) over `rect`; `None` for other
|
||||
/// layers. Fill and stroke are unmasked: the mask applies to them together. Layer effects paint
|
||||
/// the fill's interior effects beneath the vector stroke (psd-tools stroke-composite: a colour
|
||||
/// overlay leaves the stroke, the stroke effect covers it).
|
||||
fn 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, cx.depth)?;
|
||||
Some((surface_to_buffer(&fs, rect), surface_to_buffer(&ss, rect), mask_vals(layer, rect, cx)))
|
||||
fn split_parts_with<A: BufferAlloc>(layer: &Layer, rect: Rect, cx: &Ctx, alloc: &A) -> Result<Option<ShapeParts>, A::Error> {
|
||||
let LayerContent::Shape(sh) = &layer.content else { return Ok(None) };
|
||||
if sh.stroke.is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
let Some((fs, ss)) = shape_split::split(sh, cx.canvas, cx.depth) else { return Ok(None) };
|
||||
Ok(Some((surface_to_buffer_with(&fs, rect, alloc)?, surface_to_buffer_with(&ss, rect, alloc)?, mask_vals(layer, rect, cx))))
|
||||
}
|
||||
|
||||
pub(crate) fn texture_ctx<'a>(layer: &Layer, region: Rect, cx: &Ctx<'a>) -> effects::TextureCtx<'a> {
|
||||
@@ -576,25 +633,26 @@ pub(crate) fn texture_ctx<'a>(layer: &Layer, region: Rect, cx: &Ctx<'a>) -> effe
|
||||
|
||||
/// Composite `layer` onto `base` restricted to the base's alpha (clipping mask semantics),
|
||||
/// honouring its channel restrictions and Blend If.
|
||||
pub(crate) fn composite_atop(layer: &Layer, base: &mut Buffer, cx: &Ctx) {
|
||||
pub(crate) fn composite_atop_with<A: BufferAlloc>(layer: &Layer, base: &mut Buffer, cx: &Ctx, alloc: &A) -> Result<(), A::Error> {
|
||||
let w = channel_weights(layer, cx.mode);
|
||||
let blend_if = blend_if_active(layer, cx.mode);
|
||||
let before = (w.is_some() || blend_if).then(|| base.clone());
|
||||
composite_atop_any(layer, base, cx);
|
||||
let before = if w.is_some() || blend_if { Some(alloc.clone(base)?) } else { None };
|
||||
composite_atop_any_with(layer, base, cx, alloc)?;
|
||||
if let Some(before) = &before {
|
||||
if let Some(w) = w {
|
||||
restore_channels(base, before, w);
|
||||
}
|
||||
if blend_if {
|
||||
apply_blend_if(layer, before, base, cx);
|
||||
apply_blend_if_with(layer, before, base, cx, alloc)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn composite_atop_any(layer: &Layer, base: &mut Buffer, cx: &Ctx) {
|
||||
fn composite_atop_any_with<A: BufferAlloc>(layer: &Layer, base: &mut Buffer, cx: &Ctx, alloc: &A) -> Result<(), A::Error> {
|
||||
let rect = base.rect;
|
||||
if let LayerContent::Adjustment(adj) = &layer.content {
|
||||
let mut adjusted = base.clone();
|
||||
let mut adjusted = alloc.clone(base)?;
|
||||
cx.apply_adjustment(adj, &mut adjusted);
|
||||
let mv = mask_vals(layer, rect, cx);
|
||||
for (i, p) in base.px.iter_mut().enumerate() {
|
||||
@@ -614,7 +672,7 @@ fn composite_atop_any(layer: &Layer, base: &mut Buffer, cx: &Ctx) {
|
||||
}
|
||||
}
|
||||
recycle_mask(mv);
|
||||
return;
|
||||
return Ok(());
|
||||
}
|
||||
if effects::has_effects(layer) {
|
||||
// Effects of a clipped layer are clipped to the base too: render
|
||||
@@ -624,25 +682,31 @@ fn composite_atop_any(layer: &Layer, base: &mut Buffer, cx: &Ctx) {
|
||||
let hide = advanced::hiding_mask(layer, rect, cx);
|
||||
let src = advanced::effects_source(layer);
|
||||
let layer = src.as_ref();
|
||||
let (content, parts) = match split_parts(layer, rect, cx) {
|
||||
let (content, parts) = match split_parts_with(layer, rect, cx, alloc)? {
|
||||
Some((fill, stroke, mask)) => (fill, Some((stroke, mask))),
|
||||
None => {
|
||||
let Some(content) = render_content(layer, rect, cx) else {
|
||||
let Some(content) = render_content_with(layer, rect, cx, alloc)? else {
|
||||
recycle_mask(hide);
|
||||
return;
|
||||
return Ok(());
|
||||
};
|
||||
(content, None)
|
||||
}
|
||||
};
|
||||
let vstroke = parts.as_ref().map(|(s, m)| effects::VectorStroke { stroke: s, mask: m.as_deref() });
|
||||
let mut opaque = Buffer { rect, px: base.px.iter().map(|p| [p[0], p[1], p[2], 1.0]).collect() };
|
||||
let maps = effect_maps(layer, rect, cx);
|
||||
effects::composite_with_effects_prepared(layer, &content, &mut opaque, &maps, effects_frame(layer, cx.canvas), cx.patterns, vstroke);
|
||||
let mut opaque = alloc.clone(base)?;
|
||||
for p in &mut opaque.px {
|
||||
p[3] = 1.0;
|
||||
}
|
||||
let maps = effect_maps_with(layer, rect, cx, alloc)?;
|
||||
effects::composite_with_effects_prepared_with(layer, &content, &mut opaque, (&maps, vstroke), effects_frame(layer, cx.canvas), cx.patterns, alloc)?;
|
||||
if let Some((_, mask)) = parts {
|
||||
recycle_mask(mask);
|
||||
}
|
||||
if let Some(m) = &hide {
|
||||
let plain = Buffer { rect, px: base.px.iter().map(|p| [p[0], p[1], p[2], 1.0]).collect() };
|
||||
let mut plain = alloc.clone(base)?;
|
||||
for p in &mut plain.px {
|
||||
p[3] = 1.0;
|
||||
}
|
||||
advanced::apply_hiding_mask(&mut opaque, &plain, m);
|
||||
}
|
||||
recycle_mask(hide);
|
||||
@@ -651,9 +715,9 @@ fn composite_atop_any(layer: &Layer, base: &mut Buffer, cx: &Ctx) {
|
||||
*p = [o[0], o[1], o[2], p[3]];
|
||||
}
|
||||
}
|
||||
return;
|
||||
return Ok(());
|
||||
}
|
||||
let Some(content) = render_content(layer, rect, cx) else { return };
|
||||
let Some(content) = render_content_with(layer, rect, cx, alloc)? else { return Ok(()) };
|
||||
let opacity = layer.opacity * layer.fill_opacity;
|
||||
let gamma = text_gamma(layer);
|
||||
for (i, p) in base.px.iter_mut().enumerate() {
|
||||
@@ -676,6 +740,7 @@ fn composite_atop_any(layer: &Layer, base: &mut Buffer, cx: &Ctx) {
|
||||
let r = blend::composite_gamma(layer.blend, [p[0], p[1], p[2], 1.0], s, opacity, gamma);
|
||||
*p = [r[0], r[1], r[2], alpha];
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Blend an isolated layer buffer into the backdrop.
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
use super::composite::{adjustment_quantum, blend_into, composite_stack};
|
||||
use super::composite::{adjustment_quantum, blend_into};
|
||||
use super::ctx::Ctx;
|
||||
use super::extents::{effect_shape, effect_source_bounds, mask_vals, recycle_mask, shapeless_stroke_bounds, transparent_outside};
|
||||
use super::fx_cache::effect_maps;
|
||||
use super::{BlendMode, Buffer, Document, Fill, Layer, LayerContent, Pattern, Rect, Surface, bounds, effects, gradient_fill, pattern, shape_split};
|
||||
use super::{
|
||||
BlendMode, Buffer, BufferAlloc, Document, Fill, InfallibleBufferAlloc, Layer, LayerContent, Pattern, Rect, Surface, bounds, effects, gradient_fill,
|
||||
pattern, shape_split,
|
||||
};
|
||||
|
||||
/// Tile size for parallel rendering (tile results are independent).
|
||||
pub const RENDER_TILE: i32 = 256;
|
||||
@@ -28,31 +31,39 @@ fn scratch_reuse_preserves_pixels() {
|
||||
|
||||
/// Render a layer's own content (no blending into the backdrop yet) into an isolated buffer.
|
||||
/// Returns None for layers that operate on the backdrop (adjustments, pass-through groups).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn render_content(layer: &Layer, rect: Rect, cx: &Ctx) -> Option<Buffer> {
|
||||
match render_content_with(layer, rect, cx, &InfallibleBufferAlloc) {
|
||||
Ok(buffer) => buffer,
|
||||
Err(never) => match never {},
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn render_content_with<A: BufferAlloc>(layer: &Layer, rect: Rect, cx: &Ctx, alloc: &A) -> Result<Option<Buffer>, A::Error> {
|
||||
let mut buf = match &layer.content {
|
||||
LayerContent::Group(g) => {
|
||||
let mut b = Buffer::transparent(rect);
|
||||
composite_stack(&g.children, &mut b, cx);
|
||||
let mut b = alloc.filled(rect, [0.0; 4])?;
|
||||
super::composite::composite_stack_at_with(&g.children, &mut b, cx, super::advanced::Scope::ISOLATED, alloc)?;
|
||||
b
|
||||
}
|
||||
LayerContent::Fill(f) => match &layer.fill_cache {
|
||||
// Photoshop's own rendering, valid while the fill is unchanged.
|
||||
Some(c) if c.fill == *f => surface_to_scratch(&c.surface, rect),
|
||||
Some(c) if c.fill == *f => surface_to_scratch_with(&c.surface, rect, alloc)?,
|
||||
_ if cx.mode == photocraft_color::ColorMode::Cmyk => {
|
||||
let frame = fill_frame(layer, cx.canvas);
|
||||
let native_rect = if matches!(f, Fill::Solid(_)) { Rect::new(0, 0, 1, 1) } else { rect };
|
||||
match gradient_fill::render_cmyk_fill(f, native_rect, frame, cx.depth) {
|
||||
Some(s) if matches!(f, Fill::Solid(_)) => Buffer::filled(rect, s.rgba(0, 0)),
|
||||
Some(s) => surface_to_buffer(&s, rect),
|
||||
None => render_fill(f, rect, frame, cx.patterns, adjustment_quantum(cx.depth)),
|
||||
Some(s) if matches!(f, Fill::Solid(_)) => alloc.filled(rect, s.rgba(0, 0))?,
|
||||
Some(s) => surface_to_buffer_with(&s, rect, alloc)?,
|
||||
None => render_fill_with(f, rect, frame, cx.patterns, adjustment_quantum(cx.depth), alloc)?,
|
||||
}
|
||||
}
|
||||
_ => render_fill(f, rect, fill_frame(layer, cx.canvas), cx.patterns, adjustment_quantum(cx.depth)),
|
||||
_ => render_fill_with(f, rect, fill_frame(layer, cx.canvas), cx.patterns, adjustment_quantum(cx.depth), alloc)?,
|
||||
},
|
||||
LayerContent::Adjustment(_) => return None,
|
||||
LayerContent::Adjustment(_) => return Ok(None),
|
||||
_ => match layer.surface() {
|
||||
Some(s) => surface_to_scratch(s, rect),
|
||||
None => Buffer::transparent(rect),
|
||||
Some(s) => surface_to_scratch_with(s, rect, alloc)?,
|
||||
None => alloc.filled(rect, [0.0; 4])?,
|
||||
},
|
||||
};
|
||||
if let Some(m) = mask_vals(layer, rect, cx) {
|
||||
@@ -63,9 +74,9 @@ pub(crate) fn render_content(layer: &Layer, rect: Rect, cx: &Ctx) -> Option<Buff
|
||||
}
|
||||
// A Frame's stroke lies over its masked content; the frame doesn't clip it.
|
||||
if let Some(stroke) = shape_split::frame_stroke(layer, cx.canvas, cx.depth) {
|
||||
blend_into(&mut buf, &surface_to_buffer(&stroke, rect), BlendMode::Normal, 1.0);
|
||||
blend_into(&mut buf, &surface_to_buffer_with(&stroke, rect, alloc)?, BlendMode::Normal, 1.0);
|
||||
}
|
||||
Some(buf)
|
||||
Ok(Some(buf))
|
||||
}
|
||||
|
||||
/// The shape `layer`'s effect maps are built from over `rect` (row-major; for the GPU
|
||||
@@ -97,12 +108,53 @@ pub fn surface_to_buffer(s: &Surface, rect: Rect) -> Buffer {
|
||||
buf
|
||||
}
|
||||
|
||||
pub(crate) fn surface_to_buffer_with<A: BufferAlloc>(s: &Surface, rect: Rect, alloc: &A) -> Result<Buffer, A::Error> {
|
||||
let mut buf = alloc.filled(rect, [0.0; 4])?;
|
||||
s.read_rgba_into(rect, &mut buf.px);
|
||||
Ok(buf)
|
||||
}
|
||||
|
||||
fn render_fill_with<A: BufferAlloc>(
|
||||
fill: &Fill,
|
||||
rect: Rect,
|
||||
frame: Rect,
|
||||
patterns: &pattern::PreparedPatterns<'_>,
|
||||
quantum: Option<f32>,
|
||||
alloc: &A,
|
||||
) -> Result<Buffer, A::Error> {
|
||||
match fill {
|
||||
Fill::Solid(c) => {
|
||||
let rgb = c.to_rgb();
|
||||
alloc.filled(rect, [rgb[0], rgb[1], rgb[2], c.alpha])
|
||||
}
|
||||
Fill::Gradient { .. } => {
|
||||
let mut buffer = alloc.filled(rect, [0.0; 4])?;
|
||||
gradient_fill::render_quantized_into(fill, rect, frame, quantum, &mut buffer.px);
|
||||
Ok(buffer)
|
||||
}
|
||||
Fill::Pattern { name, id, scale, angle, link, phase } => {
|
||||
let mut buffer = alloc.filled(rect, [0.0; 4])?;
|
||||
if let Some(tile) = patterns.get(id, name) {
|
||||
pattern::render_into(&tile, &pattern::Placement::new(frame, *link, *phase, *scale, *angle), rect, &mut buffer.px);
|
||||
}
|
||||
Ok(buffer)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn surface_to_scratch(s: &Surface, rect: Rect) -> Buffer {
|
||||
let mut buf = Buffer::transparent(rect);
|
||||
s.read_rgba_into(rect, &mut buf.px);
|
||||
buf
|
||||
}
|
||||
|
||||
fn surface_to_scratch_with<A: BufferAlloc>(s: &Surface, rect: Rect, alloc: &A) -> Result<Buffer, A::Error> {
|
||||
let mut buf = alloc.filled(rect, [0.0; 4])?;
|
||||
s.read_rgba_into(rect, &mut buf.px);
|
||||
Ok(buf)
|
||||
}
|
||||
|
||||
/// The frame a fill layer's gradient is laid out in ("Align with layer", Photoshop's default):
|
||||
/// the layer's bounds, i.e. the area its masks reveal: a hide-all pixel mask's painted area, or
|
||||
/// the vector mask's path; otherwise the canvas.
|
||||
@@ -144,18 +196,9 @@ pub fn render_fill_content(layer: &Layer, f: &Fill, canvas: Rect, patterns: &[Pa
|
||||
/// `quantum`: the document depth's levels, which a dithered gradient is rounded to
|
||||
/// ([`gradient_fill::render_quantized`]); `None` keeps it in float.
|
||||
pub(crate) fn render_fill(f: &Fill, rect: Rect, canvas: Rect, patterns: &pattern::PreparedPatterns<'_>, quantum: Option<f32>) -> Buffer {
|
||||
match f {
|
||||
Fill::Solid(c) => {
|
||||
let rgb = c.to_rgb();
|
||||
Buffer::filled(rect, [rgb[0], rgb[1], rgb[2], c.alpha])
|
||||
}
|
||||
// Gradient geometry relative to the layer's frame, independent of the render rect.
|
||||
Fill::Gradient { .. } => Buffer { rect, px: gradient_fill::render_quantized(f, rect, canvas, quantum) },
|
||||
// Laid out from the layer's frame when linked; transparent if the pattern is missing.
|
||||
Fill::Pattern { name, scale, id, angle, link, phase } => match patterns.get(id, name) {
|
||||
Some(tile) => Buffer { rect, px: pattern::render(&tile, &pattern::Placement::new(canvas, *link, *phase, *scale, *angle), rect) },
|
||||
None => Buffer::transparent(rect),
|
||||
},
|
||||
match render_fill_with(f, rect, canvas, patterns, quantum, &InfallibleBufferAlloc) {
|
||||
Ok(buffer) => buffer,
|
||||
Err(never) => match never {},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+22
-11
@@ -1,6 +1,6 @@
|
||||
use super::content::empty_in;
|
||||
use super::fx_cache::{effect_maps, fx_over_budget, layer_identity};
|
||||
use super::{Buffer, Document, Layer, LayerContent, Rect, adjust, advanced, effects, pattern};
|
||||
use super::fx_cache::{effect_maps_with, fx_over_budget, layer_identity};
|
||||
use super::{Buffer, BufferAlloc, Document, InfallibleBufferAlloc, Layer, LayerContent, Rect, adjust, advanced, effects, pattern};
|
||||
|
||||
type VectorMaskSlot = std::sync::Arc<std::sync::OnceLock<photocraft_vector::CompiledVectorMask>>;
|
||||
|
||||
@@ -183,22 +183,33 @@ pub(crate) const PREPARE_DEPTH: u32 = 64;
|
||||
/// `rect` before tiles render in parallel, layers concurrently on native targets, each build
|
||||
/// inside `setting` (the tiles' thread-local colour setting). Tiles then only read finished maps:
|
||||
/// none builds one while others need it (#276), and none duplicates another's build. Builds never
|
||||
/// wait on each other (`cached_effect_maps`), so building them in parallel can't deadlock.
|
||||
/// wait on each other (`cached_effect_maps_with`), so building them in parallel can't deadlock.
|
||||
pub(crate) fn prepare_effects(layers: &[Layer], rect: Rect, cx: &Ctx, setting: impl Fn(&mut dyn FnMut()) + Sync) {
|
||||
let _ = prepare_effects_with(layers, rect, cx, &InfallibleBufferAlloc, |build| {
|
||||
let mut infallible = || match build() {
|
||||
Ok(()) => (),
|
||||
Err(never) => match never {},
|
||||
};
|
||||
setting(&mut infallible);
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
|
||||
/// Fallible counterpart of [`prepare_effects`], used by the compositor before it starts tiles.
|
||||
pub(crate) fn prepare_effects_with<A, F>(layers: &[Layer], rect: Rect, cx: &Ctx, alloc: &A, setting: F) -> Result<(), A::Error>
|
||||
where
|
||||
A: BufferAlloc + Sync,
|
||||
F: Fn(&mut dyn FnMut() -> Result<(), A::Error>) -> Result<(), A::Error> + Sync,
|
||||
{
|
||||
let mut todo = Vec::new();
|
||||
effect_layers(layers, rect, 0, &mut todo);
|
||||
let build = |l: &std::borrow::Cow<Layer>| {
|
||||
setting(&mut || {
|
||||
let _ = effect_maps(l, rect, cx);
|
||||
});
|
||||
};
|
||||
let build = |l: &std::borrow::Cow<Layer>| setting(&mut || effect_maps_with(l, rect, cx, alloc).map(|_| ()));
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if todo.len() > 1 {
|
||||
use rayon::prelude::*;
|
||||
todo.par_iter().for_each(build);
|
||||
return;
|
||||
return todo.par_iter().try_for_each(build);
|
||||
}
|
||||
todo.iter().for_each(build);
|
||||
todo.iter().try_for_each(build)
|
||||
}
|
||||
|
||||
/// The visible layers of `layers` (groups included) with effects that can reach `rect`.
|
||||
|
||||
@@ -44,7 +44,7 @@ use bevel::{bevel_maps, satin_map};
|
||||
#[cfg(test)]
|
||||
use blur::{blur, box_line, dilate, tent, tent_direct};
|
||||
pub use blur::{size_one_kernel, tent_kernel};
|
||||
pub(crate) use composite::{VectorStroke, build_maps_prepared, composite_with_effects_prepared, map_count};
|
||||
pub(crate) use composite::{VectorStroke, build_maps_prepared, composite_with_effects_prepared_with, map_count};
|
||||
pub use composite::{build_maps, composite_with_effects, outline_share, premerges_layer, shadow_see_through, stroke_widths};
|
||||
pub use distance::{FieldKind, STROKE_CHAMFER_MAX, bevel_distance_fields, distance_field, stroke_outside_exact};
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -5,6 +5,7 @@ use super::{
|
||||
Bevel, BevelStyle, BlendMode, Buffer, Effect, FxMaps, FxPaint, GlobalLight, Layer, MAX_REACH, Map, PREPARED_PATTERN_BYTES, Pattern, Placement,
|
||||
PreparedPatterns, Rect, StrokePosition, psblend,
|
||||
};
|
||||
use crate::{BufferAlloc, InfallibleBufferAlloc};
|
||||
|
||||
/// Build every effect map for `layer` from its alpha `shape` over `rect`.
|
||||
pub fn build_maps(layer: &Layer, shape: Vec<f32>, rect: Rect, light: &GlobalLight, tex: &TextureCtx) -> FxMaps {
|
||||
@@ -242,13 +243,29 @@ pub(crate) fn composite_with_effects_prepared(
|
||||
patterns: &PreparedPatterns<'_>,
|
||||
vstroke: Option<VectorStroke<'_>>,
|
||||
) {
|
||||
match composite_with_effects_prepared_with(layer, content, backdrop, (maps, vstroke), layer_bounds, patterns, &InfallibleBufferAlloc) {
|
||||
Ok(()) => {}
|
||||
Err(never) => match never {},
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn composite_with_effects_prepared_with<A: BufferAlloc>(
|
||||
layer: &Layer,
|
||||
content: &Buffer,
|
||||
backdrop: &mut Buffer,
|
||||
prepared: (&FxMaps, Option<VectorStroke<'_>>),
|
||||
layer_bounds: Rect,
|
||||
patterns: &PreparedPatterns<'_>,
|
||||
alloc: &A,
|
||||
) -> Result<(), A::Error> {
|
||||
let (maps, vstroke) = prepared;
|
||||
let pass = EffectPass::new(layer, maps, content.rect, layer_bounds, patterns, vstroke.as_ref());
|
||||
let big = pass.big;
|
||||
let shape = pass.effect_shape(content);
|
||||
let rect = backdrop.rect;
|
||||
let before = backdrop.clone();
|
||||
let before = alloc.clone(backdrop)?;
|
||||
// Exterior effects are painted on a backdrop copy extended to `big`.
|
||||
let mut work = Buffer::transparent(big);
|
||||
let mut work = alloc.filled(big, [0.0; 4])?;
|
||||
for y in rect.y0.max(big.y0)..rect.y1.min(big.y1) {
|
||||
for x in rect.x0.max(big.x0)..rect.x1.min(big.x1) {
|
||||
work.px[((y - big.y0) as usize) * pass.w + (x - big.x0) as usize] = before.get(x, y);
|
||||
@@ -262,7 +279,7 @@ pub(crate) fn composite_with_effects_prepared(
|
||||
// keeps its alpha, as in Photoshop.
|
||||
let gamma = crate::text_gamma(layer);
|
||||
let premerge = premerges_layer(layer);
|
||||
let mut lay = pass.layer_pixels(content, &shape);
|
||||
let mut lay = pass.layer_pixels_with(content, &shape, alloc)?;
|
||||
if premerge {
|
||||
for (lp, wp) in lay.px.iter_mut().zip(&work.px) {
|
||||
*lp = psblend::composite_gamma(layer.blend, *wp, *lp, 1.0, gamma);
|
||||
@@ -272,13 +289,13 @@ pub(crate) fn composite_with_effects_prepared(
|
||||
let fields = pass.stroke_fields(!strokes.is_empty());
|
||||
pass.paint_interior(&mut lay, &shape);
|
||||
pass.paint_vector_stroke(&mut lay, &shape);
|
||||
pass.paint_inside_strokes(&mut lay, &shape, &strokes, &fields);
|
||||
pass.paint_inside_strokes_with(&mut lay, &shape, &strokes, &fields, alloc)?;
|
||||
pass.paint_bevel(&mut lay, BevelPaint::Inner, Some(&shape));
|
||||
// The shape's own alpha.
|
||||
for (p, a) in lay.px.iter_mut().zip(&shape.v) {
|
||||
p[3] *= a.min(1.0);
|
||||
}
|
||||
pass.paint_outside_strokes(&mut work, &lay, &shape, &strokes, &fields);
|
||||
pass.paint_outside_strokes_with(&mut work, &lay, &shape, &strokes, &fields, alloc)?;
|
||||
pass.paint_bevel(&mut work, BevelPaint::Outer, None);
|
||||
|
||||
// Layer (with interior effects) onto the exterior result, in the layer's mode.
|
||||
@@ -293,6 +310,7 @@ pub(crate) fn composite_with_effects_prepared(
|
||||
// to 6/255 dark (psd-tools layer_effects Emboss: 7.8 → 5.7/255).
|
||||
pass.paint_bevel(&mut work, BevelPaint::Both, None);
|
||||
pass.write_back(backdrop, &before, &work);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `true` where the effect shape covers a pixel enough for interior effects to paint.
|
||||
@@ -435,7 +453,7 @@ impl<'a> EffectPass<'a> {
|
||||
}
|
||||
|
||||
/// The layer's own pixels at fill opacity, with their alpha made relative to `shape`.
|
||||
fn layer_pixels(&self, content: &Buffer, shape: &Map) -> Buffer {
|
||||
fn layer_pixels_with<A: BufferAlloc>(&self, content: &Buffer, shape: &Map, alloc: &A) -> Result<Buffer, A::Error> {
|
||||
let content_fill = if self.interior_group() { 1.0 } else { self.layer.fill_opacity };
|
||||
let relative = self.relative();
|
||||
let lay_alpha = |i: usize, p: &[f32; 4], a: f32| {
|
||||
@@ -447,7 +465,11 @@ impl<'a> EffectPass<'a> {
|
||||
content_fill
|
||||
}
|
||||
};
|
||||
Buffer { rect: self.big, px: content.px.iter().zip(&shape.v).enumerate().map(|(i, (p, a))| [p[0], p[1], p[2], lay_alpha(i, p, *a)]).collect() }
|
||||
let mut lay = alloc.filled(self.big, [0.0; 4])?;
|
||||
for (i, (out, (p, a))) in lay.px.iter_mut().zip(content.px.iter().zip(&shape.v)).enumerate() {
|
||||
*out = [p[0], p[1], p[2], lay_alpha(i, p, *a)];
|
||||
}
|
||||
Ok(lay)
|
||||
}
|
||||
|
||||
/// Paints the interior effects other than strokes and bevels: overlays, satin, inner glow
|
||||
@@ -535,7 +557,14 @@ impl<'a> EffectPass<'a> {
|
||||
|
||||
/// Strokes. Inside parts are painted over the layer (bottom instance first); outside parts
|
||||
/// are slid beneath it, so the first listed (top) instance is processed first.
|
||||
fn paint_inside_strokes(&self, lay: &mut Buffer, shape: &Map, strokes: &[&photocraft_doc::StrokeFx], fields: &StrokeFields) {
|
||||
fn paint_inside_strokes_with<A: BufferAlloc>(
|
||||
&self,
|
||||
lay: &mut Buffer,
|
||||
shape: &Map,
|
||||
strokes: &[&photocraft_doc::StrokeFx],
|
||||
fields: &StrokeFields,
|
||||
alloc: &A,
|
||||
) -> Result<(), A::Error> {
|
||||
for st in strokes.iter().rev().copied() {
|
||||
let (in_w, _) = stroke_widths(st);
|
||||
if in_w <= 0.0 {
|
||||
@@ -549,7 +578,7 @@ impl<'a> EffectPass<'a> {
|
||||
// A Normal stroke replaces the layer under it instead of blending with it
|
||||
// (Photoshop): at 50 % opacity an opaque pixel under the stroke turns into the
|
||||
// stroke colour at 50 % alpha, not a 50/50 mix.
|
||||
let mut stroke_px = Buffer { rect: self.big, px: vec![[0.0; 4]; lay.px.len()] };
|
||||
let mut stroke_px = alloc.filled(self.big, [0.0; 4])?;
|
||||
paint_fx(&mut stroke_px, &m, &st.paint, self.stroke_frame(st), self.anchor, self.big, BlendMode::Normal, st.common.opacity, self.patterns);
|
||||
for ((p, s), cov) in lay.px.iter_mut().zip(&stroke_px.px).zip(&m.v) {
|
||||
if s[3] <= 0.0 {
|
||||
@@ -565,6 +594,7 @@ impl<'a> EffectPass<'a> {
|
||||
paint_fx(lay, &m, &st.paint, self.stroke_frame(st), self.anchor, self.big, st.common.blend, st.common.opacity, self.patterns);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Bevel and emboss effects whose paint is `kind`. Inner ones paint into the layer relative
|
||||
@@ -589,27 +619,41 @@ impl<'a> EffectPass<'a> {
|
||||
/// above a wider Normal stroke multiplies the backdrop, not the lower stroke). Each stroke's
|
||||
/// share is its coverage × opacity not yet taken by strokes above; for Normal strokes this
|
||||
/// equals stacking them top over bottom.
|
||||
fn paint_outside_strokes(&self, work: &mut Buffer, lay: &Buffer, shape: &Map, strokes: &[&photocraft_doc::StrokeFx], fields: &StrokeFields) {
|
||||
fn paint_outside_strokes_with<A: BufferAlloc>(
|
||||
&self,
|
||||
work: &mut Buffer,
|
||||
lay: &Buffer,
|
||||
shape: &Map,
|
||||
strokes: &[&photocraft_doc::StrokeFx],
|
||||
fields: &StrokeFields,
|
||||
alloc: &A,
|
||||
) -> Result<(), A::Error> {
|
||||
if !strokes.iter().any(|st| stroke_widths(st).1 > 0.0) {
|
||||
return;
|
||||
return Ok(());
|
||||
}
|
||||
let (w, h) = (self.w, self.h);
|
||||
let base = work.clone();
|
||||
let mut acc = vec![[0.0f32; 4]; w * h]; // premultiplied Σ share·blended
|
||||
let mut cover = vec![0.0f32; w * h];
|
||||
let base = alloc.clone(work)?;
|
||||
let mut acc = alloc.filled(self.big, [0.0; 4])?; // premultiplied Σ share·blended
|
||||
let mut cover = alloc.scalar_filled(self.big, 0.0)?;
|
||||
for st in strokes.iter().copied() {
|
||||
let (_, out_w) = stroke_widths(st);
|
||||
if out_w <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let share = self.outside_share(st, out_w, shape, lay, fields, &mut cover);
|
||||
let share = self.outside_share(st, shape, lay, fields, &mut cover, alloc)?;
|
||||
// The stroke blended over the backdrop at full coverage.
|
||||
let mut blended = base.clone();
|
||||
let ones = Map { w, h, v: share.iter().map(|&s| if s > 0.0 { 1.0 } else { 0.0 }).collect() };
|
||||
let mut blended = alloc.clone(&base)?;
|
||||
let mut ones = alloc.scalar_filled(self.big, 0.0)?;
|
||||
for (one, &s) in ones.iter_mut().zip(&share) {
|
||||
if s > 0.0 {
|
||||
*one = 1.0;
|
||||
}
|
||||
}
|
||||
let ones = Map { w, h, v: ones };
|
||||
// The share already carries the Dissolve choice, so the paint itself composites as Normal.
|
||||
let paint_blend = if st.common.blend == BlendMode::Dissolve { BlendMode::Normal } else { st.common.blend };
|
||||
paint_fx(&mut blended, &ones, &st.paint, self.stroke_frame(st), self.anchor, self.big, paint_blend, 1.0, self.patterns);
|
||||
for ((a, b), s) in acc.iter_mut().zip(&blended.px).zip(&share) {
|
||||
for ((a, b), s) in acc.px.iter_mut().zip(&blended.px).zip(&share) {
|
||||
if *s > 0.0 {
|
||||
for c in 0..3 {
|
||||
a[c] += s * b[c] * b[3];
|
||||
@@ -618,7 +662,7 @@ impl<'a> EffectPass<'a> {
|
||||
}
|
||||
}
|
||||
}
|
||||
for ((p, a), c) in work.px.iter_mut().zip(&acc).zip(&cover) {
|
||||
for ((p, a), c) in work.px.iter_mut().zip(&acc.px).zip(&cover) {
|
||||
if *c <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
@@ -628,11 +672,21 @@ impl<'a> EffectPass<'a> {
|
||||
*p = [(p[0] * p[3] * k + a[0]) / alpha, (p[1] * p[3] * k + a[1]) / alpha, (p[2] * p[3] * k + a[2]) / alpha, alpha.min(1.0)];
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The share of each pixel an outside stroke `st` (outside width `out_w`) takes: its coverage
|
||||
/// × opacity not yet taken by the strokes above, which `cover` accumulates.
|
||||
fn outside_share(&self, st: &photocraft_doc::StrokeFx, out_w: f32, shape: &Map, lay: &Buffer, fields: &StrokeFields, cover: &mut [f32]) -> Vec<f32> {
|
||||
fn outside_share<A: BufferAlloc>(
|
||||
&self,
|
||||
st: &photocraft_doc::StrokeFx,
|
||||
shape: &Map,
|
||||
lay: &Buffer,
|
||||
fields: &StrokeFields,
|
||||
cover: &mut [f32],
|
||||
alloc: &A,
|
||||
) -> Result<Vec<f32>, A::Error> {
|
||||
let (_, out_w) = stroke_widths(st);
|
||||
let (w, big) = (self.w, self.big);
|
||||
// Shape layers without a filled outline stroke their vector outline, estimated from local
|
||||
// coverage; every other layer strokes its shape. The width then picks the field.
|
||||
@@ -649,7 +703,7 @@ impl<'a> EffectPass<'a> {
|
||||
(false, false) => fields.dout.as_deref(),
|
||||
}
|
||||
.unwrap_or_default();
|
||||
let mut share = vec![0.0f32; w * self.h];
|
||||
let mut share = alloc.scalar_filled(self.big, 0.0)?;
|
||||
for (i, sh) in share.iter_mut().enumerate() {
|
||||
let band = (out_w + 0.5 - d[i]).clamp(0.0, 1.0);
|
||||
let k = if inside(shape.v[i]) { if vector_outline { 0.0 } else { band * outline_share(shape.v[i], lay.px[i][3]) } } else { band };
|
||||
@@ -661,7 +715,7 @@ impl<'a> EffectPass<'a> {
|
||||
*sh = k * (1.0 - cover[i]);
|
||||
cover[i] += *sh;
|
||||
}
|
||||
share
|
||||
Ok(share)
|
||||
}
|
||||
|
||||
/// Writes the finished stack `work` into `backdrop` (over `before`) at layer opacity.
|
||||
@@ -751,3 +805,135 @@ fn mix_premul(a: [f32; 4], b: [f32; 4], k: f32) -> [f32; 4] {
|
||||
out[3] = alpha;
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod outside_stroke_allocation_tests {
|
||||
use super::*;
|
||||
use photocraft_color::{Color, PixelFormat};
|
||||
use photocraft_doc::{FxCommon, StrokeFx};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
struct RejectFilled;
|
||||
|
||||
impl BufferAlloc for RejectFilled {
|
||||
type Error = &'static str;
|
||||
|
||||
fn filled(&self, _rect: Rect, _color: [f32; 4]) -> Result<Buffer, Self::Error> {
|
||||
Err("outside stroke accumulator")
|
||||
}
|
||||
|
||||
fn clone(&self, buffer: &Buffer) -> Result<Buffer, Self::Error> {
|
||||
buffer.try_clone().map_err(|_| "clone allocation")
|
||||
}
|
||||
|
||||
fn scalar_filled(&self, _rect: Rect, _value: f32) -> Result<Vec<f32>, Self::Error> {
|
||||
Err("outside stroke scalar allocation")
|
||||
}
|
||||
}
|
||||
|
||||
struct FailScalarAt {
|
||||
fail_at: usize,
|
||||
attempts: AtomicUsize,
|
||||
}
|
||||
|
||||
impl BufferAlloc for FailScalarAt {
|
||||
type Error = usize;
|
||||
|
||||
fn filled(&self, rect: Rect, color: [f32; 4]) -> Result<Buffer, Self::Error> {
|
||||
Ok(Buffer::filled(rect, color))
|
||||
}
|
||||
|
||||
fn clone(&self, buffer: &Buffer) -> Result<Buffer, Self::Error> {
|
||||
Ok(buffer.clone())
|
||||
}
|
||||
|
||||
fn scalar_filled(&self, rect: Rect, value: f32) -> Result<Vec<f32>, Self::Error> {
|
||||
let attempt = self.attempts.fetch_add(1, Ordering::Relaxed) + 1;
|
||||
if attempt == self.fail_at {
|
||||
return Err(attempt);
|
||||
}
|
||||
Ok(photocraft_raster::scratch::take(rect.width() as usize * rect.height() as usize, value))
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enabled_outside_stroke_scalar_allocation_failures_preserve_pixels() {
|
||||
let rect = Rect::new(0, 0, 4, 4);
|
||||
let mut layer = Layer::raster("outside stroke", PixelFormat::RGBA8);
|
||||
layer.effects.items.push(Effect::Stroke(StrokeFx {
|
||||
common: FxCommon::new(BlendMode::Normal, 1.0),
|
||||
size: 1.0,
|
||||
position: StrokePosition::Outside,
|
||||
paint: FxPaint::Color(Color::rgb(0.0, 0.0, 1.0)),
|
||||
overprint: false,
|
||||
}));
|
||||
let mut shape = Map::new(4, 4, 0.0);
|
||||
for (index, value) in shape.v.iter_mut().enumerate() {
|
||||
if matches!(index, 5 | 6 | 9 | 10) {
|
||||
*value = 1.0;
|
||||
}
|
||||
}
|
||||
let patterns = PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES);
|
||||
let texture = TextureCtx { rect, patterns: &[], anchor: (0.0, 0.0) };
|
||||
let maps = build_maps(&layer, shape.v.clone(), rect, &GlobalLight::default(), &texture);
|
||||
let pass = EffectPass::new(&layer, &maps, rect, rect, &patterns, None);
|
||||
let strokes: Vec<_> = layer.effects.items.iter().filter_map(|effect| if let Effect::Stroke(stroke) = effect { Some(stroke) } else { None }).collect();
|
||||
assert!(strokes.iter().any(|stroke| stroke_widths(stroke).1 > 0.0));
|
||||
let fields = pass.stroke_fields(true);
|
||||
let mut lay = Buffer::filled(rect, [0.0; 4]);
|
||||
for (pixel, alpha) in lay.px.iter_mut().zip(&shape.v) {
|
||||
pixel[3] = *alpha;
|
||||
}
|
||||
let original = Buffer::filled(rect, [1.0; 4]);
|
||||
|
||||
// The three scalar allocations are the accumulated cover, this stroke's share, and the
|
||||
// paint-coverage map. Each failure is returned before any work pixels are written back.
|
||||
for fail_at in 1..=3 {
|
||||
let allocator = FailScalarAt { fail_at, attempts: AtomicUsize::new(0) };
|
||||
let mut work = original.clone();
|
||||
assert_eq!(pass.paint_outside_strokes_with(&mut work, &lay, &shape, &strokes, &fields, &allocator), Err(fail_at),);
|
||||
assert_eq!(allocator.attempts.load(Ordering::Relaxed), fail_at);
|
||||
assert_eq!(work, original, "a rejected scalar scratch buffer cannot publish partial stroke pixels");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enabled_outside_stroke_accumulator_propagates_allocation_failure_and_preserves_pixels() {
|
||||
let rect = Rect::new(0, 0, 4, 4);
|
||||
let mut layer = Layer::raster("outside stroke", PixelFormat::RGBA8);
|
||||
layer.effects.items.push(Effect::Stroke(StrokeFx {
|
||||
common: FxCommon::new(BlendMode::Normal, 1.0),
|
||||
size: 1.0,
|
||||
position: StrokePosition::Outside,
|
||||
paint: FxPaint::Color(Color::rgb(0.0, 0.0, 1.0)),
|
||||
overprint: false,
|
||||
}));
|
||||
let mut shape = Map::new(4, 4, 0.0);
|
||||
for (index, value) in shape.v.iter_mut().enumerate() {
|
||||
if matches!(index, 5 | 6 | 9 | 10) {
|
||||
*value = 1.0;
|
||||
}
|
||||
}
|
||||
let patterns = PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES);
|
||||
let texture = TextureCtx { rect, patterns: &[], anchor: (0.0, 0.0) };
|
||||
let maps = build_maps(&layer, shape.v.clone(), rect, &GlobalLight::default(), &texture);
|
||||
let pass = EffectPass::new(&layer, &maps, rect, rect, &patterns, None);
|
||||
let strokes: Vec<_> = layer.effects.items.iter().filter_map(|effect| if let Effect::Stroke(stroke) = effect { Some(stroke) } else { None }).collect();
|
||||
assert!(strokes.iter().any(|stroke| stroke_widths(stroke).1 > 0.0));
|
||||
let fields = pass.stroke_fields(true);
|
||||
let mut lay = Buffer::filled(rect, [0.0; 4]);
|
||||
for (pixel, alpha) in lay.px.iter_mut().zip(&shape.v) {
|
||||
pixel[3] = *alpha;
|
||||
}
|
||||
let original = Buffer::filled(rect, [1.0; 4]);
|
||||
let mut failed = original.clone();
|
||||
assert_eq!(pass.paint_outside_strokes_with(&mut failed, &lay, &shape, &strokes, &fields, &RejectFilled), Err("outside stroke accumulator"));
|
||||
assert_eq!(failed, original, "a rejected accumulator cannot publish partial stroke pixels");
|
||||
let mut legacy = original.clone();
|
||||
pass.paint_outside_strokes_with(&mut legacy, &lay, &shape, &strokes, &fields, &InfallibleBufferAlloc).unwrap();
|
||||
let mut fallible = original.clone();
|
||||
pass.paint_outside_strokes_with(&mut fallible, &lay, &shape, &strokes, &fields, &crate::FallibleBufferAlloc).unwrap();
|
||||
assert_ne!(legacy, original, "the enabled outside stroke must actually paint");
|
||||
assert_eq!(fallible, legacy);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
use super::content::{render_content, surface_to_buffer};
|
||||
use super::content::{render_content_with, surface_to_buffer_with};
|
||||
use super::ctx::Ctx;
|
||||
use super::{BlendMode, Document, Layer, LayerContent, Rect, adjustment_quantum, advanced, bounds, effects, masks, shape_split};
|
||||
use super::{
|
||||
BlendMode, BufferAlloc, Document, InfallibleBufferAlloc, Layer, LayerContent, Rect, adjustment_quantum, advanced, bounds, effects, masks, shape_split,
|
||||
};
|
||||
|
||||
/// Bounds of a layer's own pixels (union over group children; the canvas
|
||||
/// for fill layers; an artboard's board).
|
||||
@@ -114,17 +116,27 @@ pub fn effect_outline(layer: &Layer) -> Option<&photocraft_doc::vector::Path> {
|
||||
/// fill is opaque (it can differ from ours by a fraction of a pixel: psd-tools shape-fx2), the
|
||||
/// path where the fill fades out (psd-tools stroke-effects).
|
||||
pub(crate) fn effect_shape(layer: &Layer, rect: Rect, cx: &Ctx) -> Vec<f32> {
|
||||
match effect_shape_with(layer, rect, cx, &InfallibleBufferAlloc) {
|
||||
Ok(shape) => shape,
|
||||
Err(never) => match never {},
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn effect_shape_with<A: BufferAlloc>(layer: &Layer, rect: Rect, cx: &Ctx, alloc: &A) -> Result<Vec<f32>, A::Error> {
|
||||
let n = rect.width() as usize * rect.height() as usize;
|
||||
// Transparency Shapes Layer off: the effects take the whole layer as their shape (its masks
|
||||
// still apply).
|
||||
if !layer.advanced.transparency_shapes {
|
||||
return mask_vals(layer, rect, cx).unwrap_or_else(|| vec![1.0; n]);
|
||||
return Ok(mask_vals(layer, rect, cx).unwrap_or_else(|| vec![1.0; n]));
|
||||
}
|
||||
let Some(path) = effect_outline(layer).filter(|_| n > 0) else {
|
||||
return render_content(layer, rect, cx).map(|b| b.px.iter().map(|p| p[3]).collect()).unwrap_or_else(|| vec![0.0; n]);
|
||||
return Ok(render_content_with(layer, rect, cx, alloc)?.map(|b| b.px.iter().map(|p| p[3]).collect()).unwrap_or_else(|| vec![0.0; n]));
|
||||
};
|
||||
// Unmasked: the masks scale the shape, they aren't the fill's transparency.
|
||||
let a: Vec<f32> = layer.surface().map(|s| surface_to_buffer(s, rect).px.iter().map(|p| p[3]).collect()).unwrap_or_else(|| vec![0.0; n]);
|
||||
let a: Vec<f32> = match layer.surface() {
|
||||
Some(s) => surface_to_buffer_with(s, rect, alloc)?.px.iter().map(|p| p[3]).collect(),
|
||||
None => vec![0.0; n],
|
||||
};
|
||||
let cov = photocraft_vector::path_coverage(path, rect);
|
||||
let mv = mask_vals(layer, rect, cx);
|
||||
let (w, h) = (rect.width() as usize, rect.height() as usize);
|
||||
@@ -148,7 +160,7 @@ pub(crate) fn effect_shape(layer: &Layer, rect: Rect, cx: &Ctx) -> Vec<f32> {
|
||||
}
|
||||
}
|
||||
recycle_mask(mv);
|
||||
out
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The frame layer-effect gradients and linked patterns are laid out in, when it isn't the
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::composite::texture_ctx;
|
||||
use super::ctx::{Ctx, PREPARE_DEPTH};
|
||||
use super::extents::{effect_shape, effect_source_bounds};
|
||||
use super::{Layer, LayerContent, Rect, Surface, advanced, effects};
|
||||
use super::extents::{effect_shape_with, effect_source_bounds};
|
||||
use super::{BufferAlloc, InfallibleBufferAlloc, Layer, LayerContent, Rect, Surface, advanced, effects};
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Layer-effect map cache
|
||||
@@ -207,6 +207,13 @@ const MAX_FX_BUILD_BYTES: u64 = if cfg!(target_pointer_width = "64") { 4 << 30 }
|
||||
/// canvas grown likewise; see [`effect_region`]), built once per layer state and shared by every
|
||||
/// tile. `rect` is what the caller composites the layer over (see [`effect_region`]).
|
||||
pub(crate) fn effect_maps(layer: &Layer, rect: Rect, cx: &Ctx) -> std::sync::Arc<effects::FxMaps> {
|
||||
match effect_maps_with(layer, rect, cx, &InfallibleBufferAlloc) {
|
||||
Ok(maps) => maps,
|
||||
Err(never) => match never {},
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn effect_maps_with<A: BufferAlloc>(layer: &Layer, rect: Rect, cx: &Ctx, alloc: &A) -> Result<std::sync::Arc<effects::FxMaps>, A::Error> {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let (mut region, clipped) = effect_region(layer, rect, cx);
|
||||
// Non-local effects keep their whole source region, which a few distant pixels stretch over
|
||||
@@ -217,8 +224,8 @@ pub(crate) fn effect_maps(layer: &Layer, rect: Rect, cx: &Ctx) -> std::sync::Arc
|
||||
}
|
||||
static NO_CACHE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
if *NO_CACHE.get_or_init(|| std::env::var_os("PHOTOCRAFT_FX_NOCACHE").is_some()) {
|
||||
let shape = if region.is_empty() { Vec::new() } else { effect_shape(layer, region, cx) };
|
||||
return std::sync::Arc::new(effects::build_maps_prepared(layer, shape, region, &cx.light, &texture_ctx(layer, region, cx), cx.patterns));
|
||||
let shape = if region.is_empty() { Vec::new() } else { effect_shape_with(layer, region, cx, alloc)? };
|
||||
return Ok(std::sync::Arc::new(effects::build_maps_prepared(layer, shape, region, &cx.light, &texture_ctx(layer, region, cx), cx.patterns)));
|
||||
}
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
cx.layer_keys.identity(layer, cx.doc).hash(&mut h);
|
||||
@@ -227,15 +234,22 @@ pub(crate) fn effect_maps(layer: &Layer, rect: Rect, cx: &Ctx) -> std::sync::Arc
|
||||
let key = h.finish();
|
||||
// Prepared for this render (see `prepare_effects`): no global lookup, no build.
|
||||
if let Some((m, _)) = cx.fx_maps.lock().unwrap_or_else(|e| e.into_inner()).get(&key) {
|
||||
return m.clone();
|
||||
return Ok(m.clone());
|
||||
}
|
||||
let maps = cached_effect_maps(layer, region, key, cx);
|
||||
cx.fx_maps.lock().unwrap_or_else(|e| e.into_inner()).entry(key).or_insert((maps, clipped)).0.clone()
|
||||
let maps = cached_effect_maps_with(layer, region, key, cx, alloc)?;
|
||||
Ok(cx.fx_maps.lock().unwrap_or_else(|e| e.into_inner()).entry(key).or_insert((maps, clipped)).0.clone())
|
||||
}
|
||||
|
||||
fn build_fx_slot_maps(layer: &Layer, region: Rect, key: u64, cx: &Ctx, slot: &FxSlot) -> std::sync::Arc<effects::FxMaps> {
|
||||
fn build_fx_slot_maps_with<A: BufferAlloc>(
|
||||
layer: &Layer,
|
||||
region: Rect,
|
||||
key: u64,
|
||||
cx: &Ctx,
|
||||
slot: &FxSlot,
|
||||
alloc: &A,
|
||||
) -> Result<std::sync::Arc<effects::FxMaps>, A::Error> {
|
||||
let generation = photocraft_raster::spill::read_error_generation();
|
||||
let shape: Vec<f32> = if region.is_empty() { Vec::new() } else { effect_shape(layer, region, cx) };
|
||||
let shape: Vec<f32> = if region.is_empty() { Vec::new() } else { effect_shape_with(layer, region, cx, alloc)? };
|
||||
let maps = effects::build_maps_prepared(layer, shape, region, &cx.light, &texture_ctx(layer, region, cx), cx.patterns);
|
||||
let mut pin = Vec::new();
|
||||
let mut readable = true;
|
||||
@@ -248,7 +262,7 @@ fn build_fx_slot_maps(layer: &Layer, region: Rect, key: u64, cx: &Ctx, slot: &Fx
|
||||
let maps = std::sync::Arc::new(maps);
|
||||
if !readable || photocraft_raster::spill::check_since(generation).is_err() {
|
||||
// Built from a scratch placeholder: use it for this frame, never cache it.
|
||||
return maps;
|
||||
return Ok(maps);
|
||||
}
|
||||
if slot.set(FxEntry { maps: maps.clone(), _pin: pin, bytes }).is_ok() {
|
||||
// Counted exactly once, by the build that filled the slot, and only while the
|
||||
@@ -259,7 +273,7 @@ fn build_fx_slot_maps(layer: &Layer, region: Rect, key: u64, cx: &Ctx, slot: &Fx
|
||||
}
|
||||
}
|
||||
// A concurrent build that finished first wins, so every tile shares one map.
|
||||
slot.get().map_or(maps, |e| e.maps.clone())
|
||||
Ok(slot.get().map_or(maps, |e| e.maps.clone()))
|
||||
}
|
||||
|
||||
fn evict_fx_cache_over_budget(key: u64) {
|
||||
@@ -291,7 +305,7 @@ fn evict_fx_cache_over_budget(key: u64) {
|
||||
/// the same layer; had it blocked on a once-init held further up its own stack, it would deadlock.
|
||||
/// Instead a miss builds the maps here and the first finished build is kept. Renders build every
|
||||
/// layer's maps before their parallel tiles (`prepare_effects`), so tiles rarely miss.
|
||||
fn cached_effect_maps(layer: &Layer, region: Rect, key: u64, cx: &Ctx) -> std::sync::Arc<effects::FxMaps> {
|
||||
fn cached_effect_maps_with<A: BufferAlloc>(layer: &Layer, region: Rect, key: u64, cx: &Ctx, alloc: &A) -> Result<std::sync::Arc<effects::FxMaps>, A::Error> {
|
||||
let slot = {
|
||||
let mut c = fx_cache().lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(s) = c.map.get(&key) {
|
||||
@@ -305,9 +319,25 @@ fn cached_effect_maps(layer: &Layer, region: Rect, key: u64, cx: &Ctx) -> std::s
|
||||
};
|
||||
let maps = match slot.get() {
|
||||
Some(e) => e.maps.clone(),
|
||||
None => build_fx_slot_maps(layer, region, key, cx, &slot),
|
||||
None => match build_fx_slot_maps_with(layer, region, key, cx, &slot, alloc) {
|
||||
Ok(maps) => maps,
|
||||
Err(error) => {
|
||||
// Allocation failures never publish a partial cache entry. If another renderer
|
||||
// finished the same slot while this one failed, use that complete result.
|
||||
let mut c = fx_cache().lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(entry) = slot.get() {
|
||||
entry.maps.clone()
|
||||
} else {
|
||||
if c.map.get(&key).is_some_and(|current| std::sync::Arc::ptr_eq(current, &slot)) {
|
||||
c.map.remove(&key);
|
||||
c.order.retain(|candidate| *candidate != key);
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
// Evict the oldest entries over budget (never the one just used).
|
||||
evict_fx_cache_over_budget(key);
|
||||
maps
|
||||
Ok(maps)
|
||||
}
|
||||
@@ -130,7 +130,14 @@ pub fn render(f: &Fill, rect: Rect, frame: Rect) -> Vec<[f32; 4]> {
|
||||
/// [`render`] with dithered pixels rounded to `quantum` steps (the document depth's levels, see
|
||||
/// [`crate::adjustment_quantum`]), as a gradient painted into a layer of that depth stores them.
|
||||
pub fn render_quantized(f: &Fill, rect: Rect, frame: Rect, quantum: Option<f32>) -> Vec<[f32; 4]> {
|
||||
render_ramp(f, rect, frame, Ramp::new(f), quantum)
|
||||
let mut px = vec![[0.0f32; 4]; rect.width() as usize * rect.height() as usize];
|
||||
render_quantized_into(f, rect, frame, quantum, &mut px);
|
||||
px
|
||||
}
|
||||
|
||||
/// Render into caller-owned pixels so compositor paths can use fallible pooled storage.
|
||||
pub(crate) fn render_quantized_into(f: &Fill, rect: Rect, frame: Rect, quantum: Option<f32>, px: &mut [[f32; 4]]) {
|
||||
render_ramp_into(f, rect, frame, Ramp::new(f), quantum, px);
|
||||
}
|
||||
|
||||
/// Native CMYK solid/gradient pixels at document depth; patterns return `None`.
|
||||
@@ -155,10 +162,18 @@ pub fn render_cmyk_fill(f: &Fill, rect: Rect, frame: Rect, depth: photocraft_col
|
||||
|
||||
fn render_ramp<const N: usize>(f: &Fill, rect: Rect, frame: Rect, ramp: Option<Ramp<N>>, quantum: Option<f32>) -> Vec<[f32; N]> {
|
||||
let mut px = vec![[0.0f32; N]; rect.width() as usize * rect.height() as usize];
|
||||
let (Some(ramp), Fill::Gradient { angle, scale, style, reverse, offset, dither: dith, .. }) = (ramp, f) else { return px };
|
||||
render_ramp_into(f, rect, frame, ramp, quantum, &mut px);
|
||||
px
|
||||
}
|
||||
|
||||
fn render_ramp_into<const N: usize>(f: &Fill, rect: Rect, frame: Rect, ramp: Option<Ramp<N>>, quantum: Option<f32>, px: &mut [[f32; N]]) {
|
||||
let (Some(ramp), Fill::Gradient { angle, scale, style, reverse, offset, dither: dith, .. }) = (ramp, f) else {
|
||||
px.fill([0.0; N]);
|
||||
return;
|
||||
};
|
||||
let w = rect.width() as usize;
|
||||
if w == 0 {
|
||||
return px;
|
||||
return;
|
||||
}
|
||||
// Linear and Reflected end points on whole pixels, as Photoshop (crate::fill_layout).
|
||||
let (angle, scale, offset) = &crate::fill_layout::gradient_layout(*style, *angle, *scale, *offset, frame);
|
||||
@@ -181,7 +196,6 @@ fn render_ramp<const N: usize>(f: &Fill, rect: Rect, frame: Rect, ramp: Option<R
|
||||
for (j, out) in px.chunks_mut(w).enumerate() {
|
||||
row(rect.y0 + j as i32, out);
|
||||
}
|
||||
px
|
||||
}
|
||||
|
||||
fn frame_dims(frame: Rect) -> (f32, f32) {
|
||||
|
||||
@@ -56,11 +56,13 @@ mod render;
|
||||
pub use composite::{adjustment_quantum, blend_if_active, occludes_below, text_gamma};
|
||||
#[cfg(test)]
|
||||
use composite::{blend_into_fill, blend_into_g, branchless_floor, composite_layer_plain, composite_pixel_layer, pixel_surface, quantize};
|
||||
use composite::{composite_atop, composite_layer, composite_stack_at, dissolve_noise};
|
||||
use composite::{composite_stack_at, dissolve_noise};
|
||||
use content::empty_in;
|
||||
#[cfg(test)]
|
||||
use content::render_content;
|
||||
#[cfg(test)]
|
||||
use content::render_fill;
|
||||
pub use content::{RENDER_TILE, channel_weights, fill_frame, layer_shape, render_fill_content, stroke_frame, surface_to_buffer};
|
||||
use content::{empty_in, render_content};
|
||||
use ctx::{Ctx, prepare_effects};
|
||||
#[cfg(test)]
|
||||
use ctx::{LayerKeys, PREPARE_DEPTH, effect_layers, prepare_tones};
|
||||
@@ -87,8 +89,8 @@ use render::in_blend_space;
|
||||
use render::render_tiled_with;
|
||||
pub(crate) use render::visible_layers;
|
||||
pub use render::{
|
||||
BAND_PIXELS, MAX_RENDER_PIXELS, band_rows_for, cmyk_space, composite_to_surface, composite_to_surface_with_interrupt, flatten, flatten_to_surface, render,
|
||||
render_bands, render_layer, render_layer_in, render_tiled,
|
||||
BAND_PIXELS, MAX_RENDER_PIXELS, RenderBandsError, band_rows_for, cmyk_space, composite_to_surface, composite_to_surface_with_interrupt, flatten,
|
||||
flatten_to_surface, render, render_bands, render_layer, render_layer_in, render_tiled, try_render_bands,
|
||||
};
|
||||
|
||||
/// Straight-alpha RGBA float buffer covering a rectangle.
|
||||
@@ -121,6 +123,26 @@ impl Buffer {
|
||||
pub fn filled(rect: Rect, c: [f32; 4]) -> Self {
|
||||
Self { rect, px: photocraft_raster::scratch::take(rect.width() as usize * rect.height() as usize, c) }
|
||||
}
|
||||
/// Fallibly allocate a transparent RGBA buffer, preserving `filled`'s scratch-pool slack.
|
||||
pub fn try_transparent(rect: Rect) -> Result<Self, photocraft_raster::AllocationError> {
|
||||
Self::try_filled(rect, [0.0; 4])
|
||||
}
|
||||
/// Fallibly allocate and fill an RGBA buffer.
|
||||
pub fn try_filled(rect: Rect, c: [f32; 4]) -> Result<Self, photocraft_raster::AllocationError> {
|
||||
let width = usize::try_from(rect.width()).map_err(|_| photocraft_raster::AllocationError::SizeOverflow)?;
|
||||
let height = usize::try_from(rect.height()).map_err(|_| photocraft_raster::AllocationError::SizeOverflow)?;
|
||||
let len = width.checked_mul(height).ok_or(photocraft_raster::AllocationError::SizeOverflow)?;
|
||||
let bytes = len.checked_mul(std::mem::size_of::<[f32; 4]>()).ok_or(photocraft_raster::AllocationError::SizeOverflow)?;
|
||||
let px = photocraft_raster::scratch::try_take(len, c).ok_or(photocraft_raster::AllocationError::NotEnoughMemory { bytes })?;
|
||||
Ok(Self { rect, px })
|
||||
}
|
||||
/// Fallibly clone the pixel storage while keeping the same rectangle.
|
||||
pub fn try_clone(&self) -> Result<Self, photocraft_raster::AllocationError> {
|
||||
let bytes = self.px.len().checked_mul(std::mem::size_of::<[f32; 4]>()).ok_or(photocraft_raster::AllocationError::SizeOverflow)?;
|
||||
let mut px = photocraft_raster::scratch::try_take(self.px.len(), [0.0; 4]).ok_or(photocraft_raster::AllocationError::NotEnoughMemory { bytes })?;
|
||||
px.copy_from_slice(&self.px);
|
||||
Ok(Self { rect: self.rect, px })
|
||||
}
|
||||
/// The pixels, taken out of the buffer (it can't be destructured: it returns them to the
|
||||
/// pool on drop).
|
||||
pub fn into_px(mut self) -> Vec<[f32; 4]> {
|
||||
@@ -165,6 +187,47 @@ impl Buffer {
|
||||
}
|
||||
}
|
||||
|
||||
/// Selects infallible compatibility behavior or propagating buffer allocation errors in the
|
||||
/// shared compositor core.
|
||||
pub(crate) trait BufferAlloc {
|
||||
type Error: Send;
|
||||
fn filled(&self, rect: Rect, color: [f32; 4]) -> Result<Buffer, Self::Error>;
|
||||
fn clone(&self, buffer: &Buffer) -> Result<Buffer, Self::Error>;
|
||||
fn scalar_filled(&self, rect: Rect, value: f32) -> Result<Vec<f32>, Self::Error>;
|
||||
}
|
||||
|
||||
pub(crate) struct InfallibleBufferAlloc;
|
||||
impl BufferAlloc for InfallibleBufferAlloc {
|
||||
type Error = std::convert::Infallible;
|
||||
fn filled(&self, rect: Rect, color: [f32; 4]) -> Result<Buffer, Self::Error> {
|
||||
Ok(Buffer::filled(rect, color))
|
||||
}
|
||||
fn clone(&self, buffer: &Buffer) -> Result<Buffer, Self::Error> {
|
||||
Ok(buffer.clone())
|
||||
}
|
||||
fn scalar_filled(&self, rect: Rect, value: f32) -> Result<Vec<f32>, Self::Error> {
|
||||
Ok(photocraft_raster::scratch::take(rect.width() as usize * rect.height() as usize, value))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct FallibleBufferAlloc;
|
||||
impl BufferAlloc for FallibleBufferAlloc {
|
||||
type Error = photocraft_raster::AllocationError;
|
||||
fn filled(&self, rect: Rect, color: [f32; 4]) -> Result<Buffer, Self::Error> {
|
||||
Buffer::try_filled(rect, color)
|
||||
}
|
||||
fn clone(&self, buffer: &Buffer) -> Result<Buffer, Self::Error> {
|
||||
buffer.try_clone()
|
||||
}
|
||||
fn scalar_filled(&self, rect: Rect, value: f32) -> Result<Vec<f32>, Self::Error> {
|
||||
let width = usize::try_from(rect.width()).map_err(|_| photocraft_raster::AllocationError::SizeOverflow)?;
|
||||
let height = usize::try_from(rect.height()).map_err(|_| photocraft_raster::AllocationError::SizeOverflow)?;
|
||||
let len = width.checked_mul(height).ok_or(photocraft_raster::AllocationError::SizeOverflow)?;
|
||||
let bytes = len.checked_mul(std::mem::size_of::<f32>()).ok_or(photocraft_raster::AllocationError::SizeOverflow)?;
|
||||
photocraft_raster::scratch::try_take(len, value).ok_or(photocraft_raster::AllocationError::NotEnoughMemory { bytes })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod soft_shape_tests;
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -191,9 +191,14 @@ pub fn inks(doc: &Document, rect: Rect) -> Buffer {
|
||||
buf
|
||||
}
|
||||
|
||||
/// The starting backdrop of a document render: the inks for Multichannel, else transparent.
|
||||
pub(crate) fn backdrop(doc: &Document, rect: Rect) -> Buffer {
|
||||
if doc.mode == ColorMode::Multichannel { inks(doc, rect) } else { Buffer::transparent(rect) }
|
||||
pub(crate) fn backdrop_with<A: crate::BufferAlloc>(doc: &Document, rect: Rect, alloc: &A) -> Result<Buffer, A::Error> {
|
||||
if doc.mode == ColorMode::Multichannel {
|
||||
let mut buf = alloc.filled(rect, [1.0; 4])?;
|
||||
overprint(&mut buf, doc, |_| true);
|
||||
Ok(buf)
|
||||
} else {
|
||||
alloc.filled(rect, [0.0; 4])
|
||||
}
|
||||
}
|
||||
|
||||
/// [`crate::thumbnail_buffer`] of an RGB or CMYK document with its spot channels printed over it
|
||||
|
||||
@@ -286,12 +286,19 @@ pub fn flatten_cmyk(doc: &Document, rect: Rect, fmt: PixelFormat, paper: bool) -
|
||||
/// whose stack has adjustment layers the inks carry exactly, worked out on the inks; `None` for
|
||||
/// any other document, which the RGB compositor renders. Rows of `tile` render in parallel.
|
||||
pub fn render_cmyk(doc: &Document, rect: Rect, tile: i32) -> Option<Buffer> {
|
||||
let stack = InkStack::new(doc).filter(InkStack::adjusts)?;
|
||||
match render_cmyk_with(doc, rect, tile, &crate::InfallibleBufferAlloc) {
|
||||
Ok(result) => result,
|
||||
Err(never) => match never {},
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn render_cmyk_with<A: crate::BufferAlloc>(doc: &Document, rect: Rect, tile: i32, alloc: &A) -> Result<Option<Buffer>, A::Error> {
|
||||
let Some(stack) = InkStack::new(doc).filter(InkStack::adjusts) else { return Ok(None) };
|
||||
let cmyk = crate::cmyk_space(doc);
|
||||
let w = rect.width() as usize;
|
||||
let mut out = Buffer::transparent(rect);
|
||||
let mut out = alloc.filled(rect, [0.0; 4])?;
|
||||
if w == 0 || rect.is_empty() {
|
||||
return Some(out);
|
||||
return Ok(Some(out));
|
||||
}
|
||||
let rows = tile.max(1) as usize;
|
||||
let band = |i: usize, px: &mut [[f32; 4]]| {
|
||||
@@ -311,11 +318,15 @@ pub fn render_cmyk(doc: &Document, rect: Rect, tile: i32) -> Option<Buffer> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
use rayon::prelude::*;
|
||||
out.px.par_chunks_mut(w * rows).enumerate().for_each(|(i, px)| band(i, px));
|
||||
let chunk_len = w.saturating_mul(rows).min(out.px.len()).max(1);
|
||||
out.px.par_chunks_mut(chunk_len).enumerate().for_each(|(i, px)| band(i, px));
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
for (i, px) in out.px.chunks_mut(w * rows).enumerate() {
|
||||
band(i, px);
|
||||
{
|
||||
let chunk_len = w.saturating_mul(rows).min(out.px.len()).max(1);
|
||||
for (i, px) in out.px.chunks_mut(chunk_len).enumerate() {
|
||||
band(i, px);
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
Ok(Some(out))
|
||||
}
|
||||
@@ -227,11 +227,18 @@ pub fn flatten_lab(doc: &Document, rect: Rect, fmt: PixelFormat, white: bool) ->
|
||||
/// work on L, a and b, worked out on the stored values; `None` for any other document, which the
|
||||
/// RGB compositor renders. Rows of `tile` render in parallel.
|
||||
pub fn render_lab(doc: &Document, rect: Rect, tile: i32) -> Option<Buffer> {
|
||||
let stack = LabStack::new(doc).filter(LabStack::adjusts)?;
|
||||
match render_lab_with(doc, rect, tile, &crate::InfallibleBufferAlloc) {
|
||||
Ok(result) => result,
|
||||
Err(never) => match never {},
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn render_lab_with<A: crate::BufferAlloc>(doc: &Document, rect: Rect, tile: i32, alloc: &A) -> Result<Option<Buffer>, A::Error> {
|
||||
let Some(stack) = LabStack::new(doc).filter(LabStack::adjusts) else { return Ok(None) };
|
||||
let w = rect.width() as usize;
|
||||
let mut out = Buffer::transparent(rect);
|
||||
let mut out = alloc.filled(rect, [0.0; 4])?;
|
||||
if w == 0 || rect.is_empty() {
|
||||
return Some(out);
|
||||
return Ok(Some(out));
|
||||
}
|
||||
let rows = tile.max(1) as usize;
|
||||
let band = |i: usize, px: &mut [[f32; 4]]| {
|
||||
@@ -249,11 +256,15 @@ pub fn render_lab(doc: &Document, rect: Rect, tile: i32) -> Option<Buffer> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
use rayon::prelude::*;
|
||||
out.px.par_chunks_mut(w * rows).enumerate().for_each(|(i, px)| band(i, px));
|
||||
let chunk_len = w.saturating_mul(rows).min(out.px.len()).max(1);
|
||||
out.px.par_chunks_mut(chunk_len).enumerate().for_each(|(i, px)| band(i, px));
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
for (i, px) in out.px.chunks_mut(w * rows).enumerate() {
|
||||
band(i, px);
|
||||
{
|
||||
let chunk_len = w.saturating_mul(rows).min(out.px.len()).max(1);
|
||||
for (i, px) in out.px.chunks_mut(chunk_len).enumerate() {
|
||||
band(i, px);
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
Ok(Some(out))
|
||||
}
|
||||
@@ -449,12 +449,24 @@ impl Placement {
|
||||
/// Renders `tile` over `rect` (row-major straight RGBA).
|
||||
pub fn render(tile: &Tile, place: &Placement, rect: Rect) -> Vec<[f32; 4]> {
|
||||
let mut out = Vec::with_capacity(rect.width() as usize * rect.height() as usize);
|
||||
render_into(tile, place, rect, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// Render into caller-owned storage for fallible compositor allocations.
|
||||
pub(crate) fn render_into(tile: &Tile, place: &Placement, rect: Rect, out: &mut Vec<[f32; 4]>) {
|
||||
let len = rect.width() as usize * rect.height() as usize;
|
||||
if out.len() != len {
|
||||
out.clear();
|
||||
out.resize(len, [0.0; 4]);
|
||||
}
|
||||
let mut i = 0;
|
||||
for y in rect.y0..rect.y1 {
|
||||
for x in rect.x0..rect.x1 {
|
||||
out.push(tile.sample_area(place, f64::from(x) + 0.5, f64::from(y) + 0.5));
|
||||
out[i] = tile.sample_area(place, f64::from(x) + 0.5, f64::from(y) + 0.5);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
+262
-34
@@ -1,7 +1,10 @@
|
||||
use super::composite::composite_stack_at;
|
||||
use super::composite::{composite_stack_at, composite_stack_at_with};
|
||||
use super::content::RENDER_TILE;
|
||||
use super::ctx::{Ctx, RenderVectorMasks, prepare_effects, prepare_tones};
|
||||
use super::{Buffer, Document, Layer, Rect, Surface, adjust, advanced, cmyk, multichannel, native, native_lab, pattern, psblend};
|
||||
use super::ctx::{Ctx, RenderVectorMasks, prepare_effects_with, prepare_tones};
|
||||
use super::{
|
||||
Buffer, BufferAlloc, Document, FallibleBufferAlloc, InfallibleBufferAlloc, Layer, Rect, Surface, adjust, advanced, cmyk, multichannel, native, native_lab,
|
||||
pattern, psblend,
|
||||
};
|
||||
|
||||
/// Every layer the compositor draws, groups before their children: hidden layers and everything
|
||||
/// inside hidden groups are left out.
|
||||
@@ -38,6 +41,13 @@ pub fn render_tiled(doc: &Document, rect: Rect, tile: i32) -> Buffer {
|
||||
}
|
||||
|
||||
pub(crate) fn render_tiled_with(doc: &Document, rect: Rect, tile: i32, cx: &Ctx) -> Buffer {
|
||||
match render_tiled_with_alloc(doc, rect, tile, cx, &InfallibleBufferAlloc) {
|
||||
Ok(buffer) => buffer,
|
||||
Err(never) => match never {},
|
||||
}
|
||||
}
|
||||
|
||||
fn render_tiled_with_alloc<A: BufferAlloc + Sync>(doc: &Document, rect: Rect, tile: i32, cx: &Ctx, alloc: &A) -> Result<Buffer, A::Error> {
|
||||
let tile = tile.max(1);
|
||||
// Lab documents mix Normal blending in CIELAB, as Photoshop does (psblend::LAB_MIX); 32-bit
|
||||
// documents don't clip Add / Divide or Hue / Saturation / Color / Luminosity at 1 (psblend::HDR).
|
||||
@@ -47,43 +57,41 @@ pub(crate) fn render_tiled_with(doc: &Document, rect: Rect, tile: i32, cx: &Ctx)
|
||||
let cmyk = cmyk_space(doc);
|
||||
let cmyk = cmyk.as_ref();
|
||||
if rect.is_empty() {
|
||||
return Buffer::transparent(rect);
|
||||
return alloc.filled(rect, [0.0; 4]);
|
||||
}
|
||||
// Refuse rects too large to hold: an empty buffer, not an allocation failure.
|
||||
if u64::from(rect.width()) * u64::from(rect.height()) > MAX_RENDER_PIXELS {
|
||||
return Buffer::transparent(Rect::EMPTY);
|
||||
return alloc.filled(Rect::EMPTY, [0.0; 4]);
|
||||
}
|
||||
// A CMYK stack with adjustment layers the inks carry exactly composites on its inks.
|
||||
if let Some(buf) = native::render_cmyk(doc, rect, tile) {
|
||||
return buf;
|
||||
// A CMYK stack with adjustment layers the inks carry exactly composites on the inks.
|
||||
if let Some(buf) = native::render_cmyk_with(doc, rect, tile, alloc)? {
|
||||
return Ok(buf);
|
||||
}
|
||||
// A Lab stack with adjustment layers that work on L, a and b composites on its stored values.
|
||||
if let Some(buf) = native_lab::render_lab(doc, rect, tile) {
|
||||
return buf;
|
||||
if let Some(buf) = native_lab::render_lab_with(doc, rect, tile, alloc)? {
|
||||
return Ok(buf);
|
||||
}
|
||||
cx.set_fx_clip(rect);
|
||||
if i64::from(rect.width()) <= i64::from(tile) && i64::from(rect.height()) <= i64::from(tile) {
|
||||
return photocraft_color::convert::with_cmyk_space(cmyk, || {
|
||||
let mut buf = multichannel::backdrop(doc, rect);
|
||||
in_blend_space(lab, hdr, || composite_stack_at(&doc.layers, &mut buf, cx, advanced::Scope::ROOT));
|
||||
buf
|
||||
return photocraft_color::convert::with_cmyk_space(cmyk, || -> Result<_, A::Error> {
|
||||
let mut buf = multichannel::backdrop_with(doc, rect, alloc)?;
|
||||
in_blend_space(lab, hdr, || composite_stack_at_with(&doc.layers, &mut buf, cx, advanced::Scope::ROOT, alloc))?;
|
||||
Ok(buf)
|
||||
});
|
||||
}
|
||||
// Effect maps are built once, here, before any tile needs them (#276).
|
||||
prepare_effects(&doc.layers, rect, cx, |f| {
|
||||
photocraft_color::convert::with_cmyk_space(cmyk, || in_blend_space(lab, hdr, f));
|
||||
});
|
||||
prepare_effects_with(&doc.layers, rect, cx, alloc, |f| photocraft_color::convert::with_cmyk_space(cmyk, || in_blend_space(lab, hdr, f)))?;
|
||||
let run = |t: Rect| {
|
||||
photocraft_color::convert::with_cmyk_space(cmyk, || {
|
||||
let mut b = multichannel::backdrop(doc, t);
|
||||
in_blend_space(lab, hdr, || composite_stack_at(&doc.layers, &mut b, cx, advanced::Scope::ROOT));
|
||||
b
|
||||
photocraft_color::convert::with_cmyk_space(cmyk, || -> Result<_, A::Error> {
|
||||
let mut b = multichannel::backdrop_with(doc, t, alloc)?;
|
||||
in_blend_space(lab, hdr, || composite_stack_at_with(&doc.layers, &mut b, cx, advanced::Scope::ROOT, alloc))?;
|
||||
Ok(b)
|
||||
})
|
||||
};
|
||||
// Tiles are written straight into the output, one row of tiles (a band) at a time, so the
|
||||
// peak is the output plus the tiles in flight, not a second full-size copy.
|
||||
let w = rect.width() as usize;
|
||||
let mut out = Buffer::transparent(rect);
|
||||
let mut out = alloc.filled(rect, [0.0; 4])?;
|
||||
let band_tiles = |y0: i32| {
|
||||
let y1 = y0.saturating_add(tile).min(rect.y1);
|
||||
let mut v = Vec::new();
|
||||
@@ -102,42 +110,46 @@ pub(crate) fn render_tiled_with(doc: &Document, rect: Rect, tile: i32, cx: &Ctx)
|
||||
band[o..o + pw].copy_from_slice(src);
|
||||
}
|
||||
};
|
||||
let band_len = w * tile as usize;
|
||||
let band_len = w.saturating_mul(tile as usize).min(out.px.len()).max(1);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
use rayon::prelude::*;
|
||||
let bands = rect.height().div_ceil(tile as u32) as usize;
|
||||
if bands >= 2 * rayon::current_num_threads() {
|
||||
// Enough bands to keep every core busy: one band per task, its tiles in turn.
|
||||
out.px.par_chunks_mut(band_len).enumerate().for_each(|(i, band)| {
|
||||
out.px.par_chunks_mut(band_len).enumerate().try_for_each(|(i, band)| {
|
||||
let y0 = rect.y0 + i as i32 * tile;
|
||||
for t in band_tiles(y0) {
|
||||
put(band, y0, &run(t));
|
||||
let part = run(t)?;
|
||||
put(band, y0, &part);
|
||||
}
|
||||
});
|
||||
Ok::<(), A::Error>(())
|
||||
})?;
|
||||
} else {
|
||||
// Few, wide bands: the tiles of each band in parallel, and the bands too, so a band's
|
||||
// slowest tile doesn't leave the other cores idle until the next band starts. Each
|
||||
// tile is written as soon as it is done, so only the tiles in flight are held.
|
||||
out.px.par_chunks_mut(band_len).enumerate().for_each(|(i, band)| {
|
||||
out.px.par_chunks_mut(band_len).enumerate().try_for_each(|(i, band)| {
|
||||
let y0 = rect.y0 + i as i32 * tile;
|
||||
let band = std::sync::Mutex::new(band);
|
||||
band_tiles(y0).into_par_iter().for_each(|t| {
|
||||
let part = run(t);
|
||||
band_tiles(y0).into_par_iter().try_for_each(|t| {
|
||||
let part = run(t)?;
|
||||
let mut band = band.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
put(&mut band, y0, &part);
|
||||
});
|
||||
});
|
||||
Ok::<(), A::Error>(())
|
||||
})
|
||||
})?;
|
||||
}
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
for (i, band) in out.px.chunks_mut(band_len).enumerate() {
|
||||
let y0 = rect.y0 + i as i32 * tile;
|
||||
for t in band_tiles(y0) {
|
||||
put(band, y0, &run(t));
|
||||
let part = run(t)?;
|
||||
put(band, y0, &part);
|
||||
}
|
||||
}
|
||||
out
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Runs `f` with this thread's document blend flags set ([`psblend::LAB_MIX`], [`psblend::HDR`]),
|
||||
@@ -160,11 +172,51 @@ pub fn cmyk_space(doc: &Document) -> Option<std::sync::Arc<photocraft_color::con
|
||||
/// Pixels per band of [`render_bands`] (a 14000 px wide band is ~600 rows, ~130 MB of f32).
|
||||
pub const BAND_PIXELS: u64 = 8 << 20;
|
||||
|
||||
/// Errors reported by [`try_render_bands`]. Allocation errors cover RGBA `Buffer` storage used by
|
||||
/// compositing and effect-shape construction; non-Buffer temporaries such as masks and effect-map
|
||||
/// arrays remain infallible.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum RenderBandsError<E> {
|
||||
/// The compositor could not reserve or size one of its RGBA buffers. Earlier complete bands
|
||||
/// may already have been delivered to the sink.
|
||||
Allocation(photocraft_raster::AllocationError),
|
||||
/// The caller's sink rejected a completed band.
|
||||
Sink(E),
|
||||
}
|
||||
|
||||
enum RenderBandsCoreError<E, A> {
|
||||
Allocation(A),
|
||||
Sink(E),
|
||||
}
|
||||
|
||||
/// Composite `rect` in horizontal bands, top to bottom, handing each band to `sink` (tiles inside
|
||||
/// a band render in parallel). Peak memory is one band instead of the whole composite, so huge
|
||||
/// documents can be exported or displayed without a full-size float copy. `band_rows` of 0 picks
|
||||
/// about [`BAND_PIXELS`] per band; bands are whole multiples of [`RENDER_TILE`] rows.
|
||||
pub fn render_bands<E>(doc: &Document, rect: Rect, band_rows: i32, mut sink: impl FnMut(Buffer) -> Result<(), E>) -> Result<(), E> {
|
||||
match render_bands_with_alloc(doc, rect, band_rows, &InfallibleBufferAlloc, &mut sink) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(RenderBandsCoreError::Sink(error)) => Err(error),
|
||||
Err(RenderBandsCoreError::Allocation(never)) => match never {},
|
||||
}
|
||||
}
|
||||
|
||||
/// Fallible `render_bands` variant that reports compositor-owned RGBA buffer allocation failures.
|
||||
pub fn try_render_bands<E>(doc: &Document, rect: Rect, band_rows: i32, mut sink: impl FnMut(Buffer) -> Result<(), E>) -> Result<(), RenderBandsError<E>> {
|
||||
match render_bands_with_alloc(doc, rect, band_rows, &FallibleBufferAlloc, &mut sink) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(RenderBandsCoreError::Allocation(error)) => Err(RenderBandsError::Allocation(error)),
|
||||
Err(RenderBandsCoreError::Sink(error)) => Err(RenderBandsError::Sink(error)),
|
||||
}
|
||||
}
|
||||
|
||||
fn render_bands_with_alloc<A: BufferAlloc + Sync, E>(
|
||||
doc: &Document,
|
||||
rect: Rect,
|
||||
band_rows: i32,
|
||||
alloc: &A,
|
||||
sink: &mut impl FnMut(Buffer) -> Result<(), E>,
|
||||
) -> Result<(), RenderBandsCoreError<E, A::Error>> {
|
||||
if rect.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -175,7 +227,8 @@ pub fn render_bands<E>(doc: &Document, rect: Rect, band_rows: i32, mut sink: imp
|
||||
let mut y = rect.y0;
|
||||
while y < rect.y1 {
|
||||
let y1 = y.saturating_add(rows).min(rect.y1);
|
||||
sink(render_tiled_with(doc, Rect::new(rect.x0, y, rect.x1, y1), RENDER_TILE, &cx))?;
|
||||
let band = render_tiled_with_alloc(doc, Rect::new(rect.x0, y, rect.x1, y1), RENDER_TILE, &cx, alloc).map_err(RenderBandsCoreError::Allocation)?;
|
||||
sink(band).map_err(RenderBandsCoreError::Sink)?;
|
||||
y = y1;
|
||||
}
|
||||
Ok(())
|
||||
@@ -384,3 +437,178 @@ pub fn composite_to_surface_with_interrupt(
|
||||
out.prune();
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod fallible_bands_tests {
|
||||
use super::*;
|
||||
use photocraft_color::{Color, ColorMode, SampleType};
|
||||
use photocraft_doc::{Document, Fill, Knockout, Layer, LayerContent};
|
||||
use photocraft_geom::Size;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
struct FailBufferAt {
|
||||
fail_at: usize,
|
||||
attempts: AtomicUsize,
|
||||
}
|
||||
|
||||
impl FailBufferAt {
|
||||
fn attempt(&self) -> Result<(), usize> {
|
||||
let n = self.attempts.fetch_add(1, Ordering::Relaxed) + 1;
|
||||
if n == self.fail_at { Err(n) } else { Ok(()) }
|
||||
}
|
||||
}
|
||||
|
||||
impl BufferAlloc for FailBufferAt {
|
||||
type Error = usize;
|
||||
|
||||
fn filled(&self, rect: Rect, color: [f32; 4]) -> Result<Buffer, Self::Error> {
|
||||
self.attempt()?;
|
||||
Buffer::try_filled(rect, color).map_err(|_| usize::MAX)
|
||||
}
|
||||
|
||||
fn clone(&self, buffer: &Buffer) -> Result<Buffer, Self::Error> {
|
||||
self.attempt()?;
|
||||
buffer.try_clone().map_err(|_| usize::MAX)
|
||||
}
|
||||
|
||||
fn scalar_filled(&self, rect: Rect, value: f32) -> Result<Vec<f32>, Self::Error> {
|
||||
self.attempt()?;
|
||||
let len = (rect.width() as usize).checked_mul(rect.height() as usize).ok_or(usize::MAX)?;
|
||||
photocraft_raster::scratch::try_take(len, value).ok_or(usize::MAX)
|
||||
}
|
||||
}
|
||||
|
||||
fn nested_document() -> Document {
|
||||
let mut doc = Document::new("fallible bands", Size::new(8, 8), ColorMode::Rgb, SampleType::U8);
|
||||
let mut fill = Layer::new("fill", LayerContent::Fill(Fill::Solid(Color::BLACK)));
|
||||
fill.advanced.knockout = Knockout::Shallow;
|
||||
doc.layers.push(Layer::group("nested", vec![fill]));
|
||||
doc
|
||||
}
|
||||
|
||||
fn outlined_effect_document() -> Document {
|
||||
let mut doc = Document::new("fallible outlined effect", Size::new(512, 256), ColorMode::Rgb, SampleType::U8);
|
||||
let path = photocraft_doc::vector::Path {
|
||||
subpaths: vec![photocraft_doc::vector::Subpath::polygon(&[(12.0, 12.0), (60.0, 12.0), (60.0, 60.0), (12.0, 60.0)])],
|
||||
..Default::default()
|
||||
};
|
||||
let mut cache = photocraft_doc::Surface::new(photocraft_color::PixelFormat::RGBA8);
|
||||
cache.fill_rect(Rect::new(12, 12, 60, 60), &[0.0, 0.0, 0.0, 1.0]);
|
||||
let shape = photocraft_doc::vector::ShapeLayer { path, fill: Some(Fill::Solid(Color::BLACK)), cache: Some(cache), ..Default::default() };
|
||||
let mut layer = Layer::new("outlined shape", LayerContent::Shape(shape));
|
||||
layer.effects.items.push(photocraft_doc::Effect::default_drop_shadow());
|
||||
doc.layers.push(layer);
|
||||
doc
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fail_nth_buffer_constructor_propagates_through_nested_rendering() {
|
||||
let doc = nested_document();
|
||||
let rect = doc.bounds();
|
||||
let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode);
|
||||
let ctx = Ctx::for_doc(&doc, &patterns);
|
||||
let count = {
|
||||
let mut backdrop = Buffer::filled(rect, [0.0; 4]);
|
||||
let alloc = FailBufferAt { fail_at: usize::MAX, attempts: AtomicUsize::new(0) };
|
||||
composite_stack_at_with(&doc.layers, &mut backdrop, &ctx, advanced::Scope::ROOT, &alloc).unwrap();
|
||||
alloc.attempts.load(Ordering::Relaxed)
|
||||
};
|
||||
assert!(count >= 4, "nested shallow knockout exercises buffers and clones");
|
||||
for fail_at in 1..=count {
|
||||
let mut backdrop = Buffer::filled(rect, [0.0; 4]);
|
||||
let alloc = FailBufferAt { fail_at, attempts: AtomicUsize::new(0) };
|
||||
assert!(composite_stack_at_with(&doc.layers, &mut backdrop, &ctx, advanced::Scope::ROOT, &alloc).is_err());
|
||||
assert_eq!(alloc.attempts.load(Ordering::Relaxed), fail_at);
|
||||
}
|
||||
let regular = render_tiled(&doc, rect, 8);
|
||||
let mut composited = Buffer::filled(rect, [0.0; 4]);
|
||||
composite_stack_at_with(&doc.layers, &mut composited, &ctx, advanced::Scope::ROOT, &InfallibleBufferAlloc).unwrap();
|
||||
assert_eq!(composited, regular);
|
||||
let alloc = FallibleBufferAlloc;
|
||||
assert_eq!(render_tiled_with_alloc(&doc, rect, 8, &ctx, &alloc).unwrap(), regular);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_bands_with_alloc_reports_outer_and_tile_allocations_before_the_sink() {
|
||||
let doc = Document::new("fallible tile", Size::new(512, 256), ColorMode::Rgb, SampleType::U8);
|
||||
for fail_at in [1, 2] {
|
||||
let alloc = FailBufferAt { fail_at, attempts: AtomicUsize::new(0) };
|
||||
let mut delivered = 0;
|
||||
let result = render_bands_with_alloc(&doc, doc.bounds(), RENDER_TILE, &alloc, &mut |_| {
|
||||
delivered += 1;
|
||||
Ok::<(), ()>(())
|
||||
});
|
||||
assert!(matches!(result, Err(RenderBandsCoreError::Allocation(error)) if error == fail_at));
|
||||
assert_eq!(delivered, 0, "failed output or tile allocation must not deliver a partial band");
|
||||
if fail_at == 1 {
|
||||
assert_eq!(alloc.attempts.load(Ordering::Relaxed), 1, "the output allocation is sequential");
|
||||
} else {
|
||||
assert!(alloc.attempts.load(Ordering::Relaxed) >= 2, "parallel tile allocation may have other in-flight attempts");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effect_shape_buffer_failure_is_not_cached_and_retry_uses_the_successful_cache() {
|
||||
let mut doc = Document::new("fallible effect shape", Size::new(512, 256), ColorMode::Rgb, SampleType::U8);
|
||||
let fill = Layer::new("group fill", LayerContent::Fill(Fill::Solid(Color::BLACK)));
|
||||
let mut layer = Layer::group("styled group", vec![fill]);
|
||||
layer.effects.items.push(photocraft_doc::Effect::default_drop_shadow());
|
||||
doc.layers.push(layer);
|
||||
let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode);
|
||||
let cx = Ctx::for_doc(&doc, &patterns);
|
||||
|
||||
for _ in 0..2 {
|
||||
let alloc = FailBufferAt { fail_at: 1, attempts: AtomicUsize::new(0) };
|
||||
let mut delivered = 0;
|
||||
let result = render_bands_with_alloc(&doc, doc.bounds(), RENDER_TILE, &alloc, &mut |_| {
|
||||
delivered += 1;
|
||||
Ok::<(), ()>(())
|
||||
});
|
||||
assert!(matches!(result, Err(RenderBandsCoreError::Allocation(1))));
|
||||
assert_eq!(delivered, 0, "failed effect-shape allocation must happen before the sink");
|
||||
assert_eq!(alloc.attempts.load(Ordering::Relaxed), 1, "the cold effect shape requests an RGBA buffer before output");
|
||||
}
|
||||
|
||||
let alloc = FallibleBufferAlloc;
|
||||
render_tiled_with_alloc(&doc, doc.bounds(), RENDER_TILE, &cx, &alloc).unwrap();
|
||||
let cache_hit_alloc = FailBufferAt { fail_at: 1, attempts: AtomicUsize::new(0) };
|
||||
crate::fx_cache::effect_maps_with(&doc.layers[0], doc.bounds(), &cx, &cache_hit_alloc).unwrap();
|
||||
assert_eq!(cache_hit_alloc.attempts.load(Ordering::Relaxed), 0, "the successful render-context cache avoids rebuilding its RGBA shape");
|
||||
|
||||
let outlined = outlined_effect_document();
|
||||
let alloc = FailBufferAt { fail_at: 1, attempts: AtomicUsize::new(0) };
|
||||
let mut delivered = 0;
|
||||
let result = render_bands_with_alloc(&outlined, outlined.bounds(), RENDER_TILE, &alloc, &mut |_| {
|
||||
delivered += 1;
|
||||
Ok::<(), ()>(())
|
||||
});
|
||||
assert!(matches!(result, Err(RenderBandsCoreError::Allocation(1))));
|
||||
assert_eq!(delivered, 0, "outline alpha extraction must use the fallible surface buffer path");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fallible_bands_preserves_sink_errors_as_a_separate_variant() {
|
||||
let doc = nested_document();
|
||||
let result = try_render_bands(&doc, doc.bounds(), 4, |_| Err::<(), _>("sink stopped"));
|
||||
assert_eq!(result, Err(RenderBandsError::Sink("sink stopped")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_and_fallible_band_apis_deliver_the_same_pixels() {
|
||||
let doc = nested_document();
|
||||
let mut legacy = Vec::new();
|
||||
render_bands(&doc, doc.bounds(), 8, |band| {
|
||||
legacy.push(band);
|
||||
Ok::<(), ()>(())
|
||||
})
|
||||
.unwrap();
|
||||
let mut fallible = Vec::new();
|
||||
try_render_bands(&doc, doc.bounds(), 8, |band| {
|
||||
fallible.push(band);
|
||||
Ok::<(), ()>(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(legacy, fallible);
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,6 @@
|
||||
//! (`{"scattering": {"enabled": true}}`). Strokes are deterministic: the jitter seed is the `seed`
|
||||
//! param or a hash of the points, so a journaled command replays to identical pixels.
|
||||
|
||||
use photocraft_doc::LayerContent;
|
||||
use photocraft_geom::Rect;
|
||||
use photocraft_paint::mixer::{MixerSettings, MixerState};
|
||||
use photocraft_paint::replace::{Limits, ReplaceMode, ReplaceSettings, Sampling, apply_color_replacement, color_replacement_effect};
|
||||
@@ -1067,45 +1066,109 @@ fn presets_set_current(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn has_selection_and_pixels(s: &Session) -> std::result::Result<(), String> {
|
||||
let d = s.active().ok_or("no document")?;
|
||||
if d.doc.selection.is_none() {
|
||||
return Err("no selection".into());
|
||||
}
|
||||
let l = d.active_layer.and_then(|id| d.doc.layer(id)).ok_or("no active layer")?;
|
||||
if matches!(l.content, LayerContent::Raster(_)) { Ok(()) } else { Err("active layer is not a pixel layer".into()) }
|
||||
s.active().ok_or("no document")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Largest sampled tip side (like Photoshop's 5000 px limit, kept smaller for preset size).
|
||||
pub const MAX_TIP: u32 = 2500;
|
||||
|
||||
fn define_from_selection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
define_from_selection_with_renderer(s, p, |doc, area, sink| photocraft_compose::try_render_bands(doc, area, 0, sink))
|
||||
}
|
||||
|
||||
fn define_from_selection_with_renderer(
|
||||
s: &mut Session,
|
||||
p: &Value,
|
||||
render: impl FnOnce(
|
||||
&photocraft_doc::Document,
|
||||
photocraft_geom::Rect,
|
||||
&mut dyn FnMut(photocraft_compose::Buffer) -> Result<()>,
|
||||
) -> std::result::Result<(), photocraft_compose::RenderBandsError<EngineError>>,
|
||||
) -> Result<Value> {
|
||||
let cmd = "brush.defineFromSelection";
|
||||
let name = name_param(p, cmd)?;
|
||||
let d = s.active().ok_or(EngineError::NoDocument)?;
|
||||
let sel = d.doc.selection.as_ref().ok_or_else(|| bad(cmd, "no selection"))?;
|
||||
let id = d.active_layer.ok_or(EngineError::Other("no active layer".into()))?;
|
||||
let surf = d.doc.layer(id).and_then(|l| l.surface()).ok_or_else(|| bad(cmd, "not a pixel layer"))?;
|
||||
let area = sel.content_bounds().intersect(&d.doc.bounds());
|
||||
let sel = d.doc.selection.as_ref();
|
||||
let area = sel.map_or_else(|| d.doc.bounds(), |sel| sel.content_bounds().intersect(&d.doc.bounds()));
|
||||
if area.is_empty() {
|
||||
return Err(bad(cmd, "the selection is empty"));
|
||||
}
|
||||
// Paint amount = darkness × alpha × selection (black = full paint, like Photoshop).
|
||||
let (w, h) = (area.width() as usize, area.height() as usize);
|
||||
// The sampled tip is one f32 buffer over the whole selection; a large selection must fail
|
||||
// The sampled tip is one f32 buffer over the source area; a large area must fail
|
||||
// gracefully instead of aborting the process on allocation, so reserve it fallibly. The
|
||||
// multiply is checked too: on a 32-bit target (wasm32) it can overflow where the rest of
|
||||
// this command is already fallible.
|
||||
let len = w.checked_mul(h).ok_or_else(|| crate::allocation::error("defining a brush from the selection", "requested size overflowed"))?;
|
||||
// Sparse canvases can span huge areas. Density and selection remain live while the
|
||||
// compositor holds one RGBA band, not a full-canvas RGBA plane; account for that
|
||||
// actual maximum band before allocating any sampling buffers.
|
||||
let mask_bytes = sel.map_or(0, |sel| (sel.channels() as u64).saturating_mul(4));
|
||||
let band_rows = area.height().min(photocraft_compose::band_rows_for(area.width(), 0) as u32);
|
||||
let band_bytes = u64::from(area.width()).saturating_mul(u64::from(band_rows)).saturating_mul(16);
|
||||
let dense_bytes = (len as u64).saturating_mul(4u64.saturating_add(mask_bytes)).saturating_add(band_bytes);
|
||||
if dense_bytes > crate::allocation::MAX_DENSE_BYTES {
|
||||
return Err(EngineError::Other(format!(
|
||||
"defining a brush from the selection would need {} MB of working memory for a {} x {} px area (limit {} MB); the document was not changed",
|
||||
dense_bytes >> 20,
|
||||
area.width(),
|
||||
area.height(),
|
||||
crate::allocation::MAX_DENSE_BYTES >> 20
|
||||
)));
|
||||
}
|
||||
let mut v = crate::allocation::filled(len, 0.0, "defining a brush from the selection")?;
|
||||
let sc = sel.channels();
|
||||
// The selection mask is a second buffer of the same size; it must fail gracefully too
|
||||
let sc = sel.map_or(1, |sel| sel.channels());
|
||||
// A selection mask, when present, is a second buffer of the same size; it must fail gracefully too
|
||||
// (review of #5469), so read it through the fallible allocator.
|
||||
let sv = crate::allocation::read_region(sel, area, "defining a brush from the selection")?;
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let c = surf.rgba(area.x0 + x as i32, area.y0 + y as i32);
|
||||
let l = photocraft_color::blend::lum([c[0], c[1], c[2]]);
|
||||
v[y * w + x] = ((1.0 - l) * c[3] * sv[(y * w + x) * sc]).clamp(0.0, 1.0);
|
||||
let sv = sel.map(|sel| crate::allocation::read_region(sel, area, "defining a brush from the selection")).transpose()?;
|
||||
// The compositor keeps RGB document encoding; other document models produce
|
||||
// the existing RGB numeric view (including the document-profile CMYK conversion).
|
||||
let source = if d.doc.mode == photocraft_color::ColorMode::Rgb {
|
||||
crate::color_cmds::document_profile(&d.doc)
|
||||
} else {
|
||||
crate::color_cmds::working_profile(photocraft_color::ColorMode::Rgb)
|
||||
};
|
||||
let options = craft_cms::TransformOptions { intent: craft_cms::Intent::RelativeColorimetric, bpc: true, ..Default::default() };
|
||||
let gray =
|
||||
craft_cms::cached(&source, craft_cms::Builtin::SGray.profile(), options).map_err(|e| bad(cmd, format!("cannot convert brush source to gray: {e}")))?;
|
||||
let mut converted = [0.0f32; 16];
|
||||
// Keep the allocation boundary fallible before entering compositor-owned scratch storage.
|
||||
crate::allocation::checkpoint("defining a brush from the selection")?;
|
||||
let rendered = render(&d.doc, area, &mut |band| -> Result<()> {
|
||||
for (row, pixels) in band.px.chunks_exact(w).enumerate() {
|
||||
let y = (band.rect.y0 - area.y0) as usize + row;
|
||||
for (x, c) in pixels.iter().enumerate() {
|
||||
let selected = sv.as_ref().map_or(1.0, |sv| sv[(y * w + x) * sc]);
|
||||
// Known-zero contributions leave the freshly zeroed density alone.
|
||||
if selected == 0.0 {
|
||||
continue;
|
||||
}
|
||||
if c[3] == 0.0 {
|
||||
continue;
|
||||
}
|
||||
// A sampled profile curve can clamp infinity to a finite endpoint;
|
||||
// reject contributing invalid source values before the CMS can hide them.
|
||||
if c.iter().any(|channel| !channel.is_finite()) {
|
||||
return Err(bad(cmd, "brush source contains a non-finite colour channel"));
|
||||
}
|
||||
// Composite over white before the nonlinear gray conversion. The
|
||||
// selection scales the resulting density once; alpha is already in it.
|
||||
let over_white = [c[0], c[1], c[2]].map(|channel| channel * c[3] + (1.0 - c[3]));
|
||||
gray.eval(&over_white, &mut converted).map_err(|e| bad(cmd, format!("cannot convert brush source to gray: {e}")))?;
|
||||
if !converted[0].is_finite() {
|
||||
return Err(bad(cmd, "brush source converted to a non-finite gray value"));
|
||||
}
|
||||
v[y * w + x] = ((1.0 - converted[0]) * selected).clamp(0.0, 1.0);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
match rendered {
|
||||
Ok(()) => {}
|
||||
Err(photocraft_compose::RenderBandsError::Sink(error)) => return Err(error),
|
||||
Err(photocraft_compose::RenderBandsError::Allocation(error)) => {
|
||||
return Err(crate::allocation::error("defining a brush from the selection", &error.to_string()));
|
||||
}
|
||||
}
|
||||
let (brush, tw, th) = sampled_brush(cmd, &v, w, h)?;
|
||||
@@ -1489,3 +1552,12 @@ mod mixer_live_tests;
|
||||
#[cfg(test)]
|
||||
#[path = "color_replacement_history_name_tests.rs"]
|
||||
mod color_replacement_history_name_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod define_brush_merged_source_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod define_brush_no_selection_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod define_brush_color_density_tests;
|
||||
@@ -0,0 +1,327 @@
|
||||
//! Numeric falsifier for issue #14273; this does not change brush capture.
|
||||
//!
|
||||
//! Inputs are encoded sRGB RGB8 samples, composited over encoded white before
|
||||
//! the cached sRGB -> sGray transform. Density is one minus encoded gray, then
|
||||
//! multiplied by selection coverage exactly once. Arbitrary document profiles,
|
||||
//! HDR/non-RGB sources and actual stamping remain outside this probe.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_cms::{Builtin, Intent, TransformOptions};
|
||||
|
||||
#[test]
|
||||
fn sgray_matches_six_literal_density_targets_and_alpha_selection_controls() {
|
||||
let source = Arc::new(Builtin::Srgb.profile().clone());
|
||||
let gray = Arc::new(Builtin::SGray.profile().clone());
|
||||
let options = TransformOptions { intent: Intent::RelativeColorimetric, bpc: true, ..Default::default() };
|
||||
let transform = craft_cms::cached(&source, &gray, options).unwrap();
|
||||
let gray_value = |rgb: [f32; 3]| {
|
||||
// Same public API and output scratch size as color_cmds::swatch_in_doc.
|
||||
let mut output = [0.0f32; 16];
|
||||
transform.eval(&rgb, &mut output).unwrap();
|
||||
assert!(output[0].is_finite(), "the CMS must return a finite gray value");
|
||||
output[0].clamp(0.0, 1.0)
|
||||
};
|
||||
let density = |rgb: [f32; 3], alpha: f32, selection: f32| {
|
||||
let over_white = rgb.map(|channel| channel * alpha + (1.0 - alpha));
|
||||
(1.0 - gray_value(over_white)) * selection
|
||||
};
|
||||
|
||||
// Independent measured targets from #14273, not values derived from the
|
||||
// candidate transform or the command's existing fixed luminance weights.
|
||||
let mut mismatches = Vec::new();
|
||||
for (name, rgb, expected, tolerance) in [
|
||||
("red", [255u8, 0, 0], 0.49f32, 0.03f32),
|
||||
("green", [0, 255, 0], 0.14, 0.03),
|
||||
("blue", [0, 0, 255], 0.72, 0.03),
|
||||
("gray 128", [128, 128, 128], 0.50, 0.01),
|
||||
("gray 200", [200, 200, 200], 0.22, 0.01),
|
||||
("black", [0, 0, 0], 1.0, 0.0001),
|
||||
] {
|
||||
let actual = density(rgb.map(|value| f32::from(value) / 255.0), 1.0, 1.0);
|
||||
eprintln!("{name}: density {actual:.6}, target {expected:.6} +/- {tolerance:.6}");
|
||||
if (actual - expected).abs() > tolerance {
|
||||
mismatches.push(format!("{name}: {actual:.6}, expected {expected:.6} +/- {tolerance:.6}"));
|
||||
}
|
||||
}
|
||||
assert!(mismatches.is_empty(), "sGray candidate fails measured targets:\n{}", mismatches.join("\n"));
|
||||
|
||||
// Transparency is white, not an extra multiplier applied after the CMS.
|
||||
assert!(density([0.0, 0.0, 1.0], 0.0, 1.0).abs() <= 0.0001);
|
||||
assert!((density([0.0; 3], 0.5, 1.0) - 0.5).abs() <= 0.01);
|
||||
assert!((density([0.0; 3], 1.0, 0.25) - 0.25).abs() <= 0.0001);
|
||||
assert!((density([0.0; 3], 0.5, 0.5) - 0.25).abs() <= 0.01, "alpha or selection must not be applied twice");
|
||||
assert_eq!(density([1.0, 0.0, 0.0], 1.0, 0.0), 0.0);
|
||||
|
||||
// This is an ordering control, not a new measured coloured-alpha target:
|
||||
// half-transparent red is the explicit RGB sample [1, .5, .5] over white.
|
||||
let half_red = density([1.0, 0.0, 0.0], 0.5, 1.0);
|
||||
let explicit_over_white = 1.0 - gray_value([1.0, 0.5, 0.5]);
|
||||
assert_eq!(half_red, explicit_over_white);
|
||||
}
|
||||
|
||||
use super::{GrayTile, Session, TipShape, json};
|
||||
|
||||
const COMMANDS: [&str; 2] = ["brush.defineFromSelection", "edit.defineBrushPreset"];
|
||||
|
||||
fn rgb_source(depth: u32, rgba: [f32; 4]) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 40, "height": 40, "depth": depth, "background": "#ffffff"})).unwrap();
|
||||
s.edit("Colour square", |doc, active| {
|
||||
doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(10, 10, 30, 30), &rgba);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn tip(s: &Session) -> &GrayTile {
|
||||
let TipShape::Sampled(tip) = &s.tools.brush.tip else { panic!("expected a sampled tip") };
|
||||
tip
|
||||
}
|
||||
|
||||
fn define_square(s: &mut Session, command: &str, selected: bool) -> f32 {
|
||||
if selected {
|
||||
s.execute("select.rect", json!({"x": 8, "y": 8, "width": 24, "height": 24})).unwrap();
|
||||
}
|
||||
let doc = s.active().unwrap().doc.clone();
|
||||
let history = s.active().unwrap().history.past_len();
|
||||
let presets = s.tools.presets.len();
|
||||
let result = s.execute(command, json!({"name": "Colour density"})).unwrap();
|
||||
assert_eq!((result["width"].as_u64(), result["height"].as_u64()), (Some(20), Some(20)));
|
||||
assert_eq!((tip(s).width, tip(s).height), (20, 20));
|
||||
assert_eq!(s.tools.presets.len(), presets + 1);
|
||||
assert_eq!(s.tools.current_preset.as_deref(), Some("Colour density"));
|
||||
assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc));
|
||||
assert_eq!(s.active().unwrap().history.past_len(), history);
|
||||
assert_eq!(s.active().unwrap().doc.selection.is_some(), selected);
|
||||
tip(s).get(10, 10)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn defined_tips_match_the_six_measured_density_targets_at_all_depths() {
|
||||
for command in COMMANDS {
|
||||
for depth in [8, 16, 32] {
|
||||
for selected in [false, true] {
|
||||
for (name, rgb, expected, tolerance) in [
|
||||
("red", [255u8, 0, 0], 0.49f32, 0.03f32),
|
||||
("green", [0, 255, 0], 0.14, 0.03),
|
||||
("blue", [0, 0, 255], 0.72, 0.03),
|
||||
("gray 128", [128, 128, 128], 0.50, 0.01),
|
||||
("gray 200", [200, 200, 200], 0.22, 0.01),
|
||||
("black", [0, 0, 0], 1.0, 0.0001),
|
||||
] {
|
||||
let [r, g, b] = rgb.map(|v| f32::from(v) / 255.0);
|
||||
let mut s = rgb_source(depth, [r, g, b, 1.0]);
|
||||
let actual = define_square(&mut s, command, selected);
|
||||
assert!((actual - expected).abs() <= tolerance, "{command}, {name}, depth {depth}, selected {selected}: {actual}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_density_applies_alpha_before_gray_and_selection_once() {
|
||||
for command in COMMANDS {
|
||||
for (alpha, coverage, expected) in [(0.5, 1.0, 0.5), (1.0, 0.25, 0.25), (0.5, 0.5, 0.25)] {
|
||||
let mut s = rgb_source(32, [0.0, 0.0, 0.0, alpha]);
|
||||
s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
|
||||
s.edit("Selection coverage", |doc, _| {
|
||||
doc.selection.as_mut().unwrap().fill_rect(photocraft_geom::Rect::new(10, 10, 30, 30), &[coverage]);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute(command, json!({"name": "Coverage"})).unwrap();
|
||||
assert!((tip(&s).get(10, 10) - expected).abs() <= 0.01, "{command}, alpha {alpha}, coverage {coverage}");
|
||||
}
|
||||
|
||||
// An explicit over-white RGB square is an independent way to provide the
|
||||
// same colour; this is an ordering control, not a new reference target.
|
||||
let mut half_red = rgb_source(32, [1.0, 0.0, 0.0, 0.5]);
|
||||
let mut over_white = rgb_source(32, [1.0, 0.5, 0.5, 1.0]);
|
||||
let half = define_square(&mut half_red, command, false);
|
||||
let opaque = define_square(&mut over_white, command, false);
|
||||
assert!((half - opaque).abs() <= 1.0 / 65535.0);
|
||||
|
||||
let mut transparent = rgb_source(32, [0.0, 0.0, 1.0, 0.0]);
|
||||
let brush = transparent.tools.brush.clone();
|
||||
let presets = transparent.tools.presets.clone();
|
||||
let err = transparent.execute(command, json!({"name": "Transparent colour"})).unwrap_err();
|
||||
assert!(err.to_string().contains("contain no paint"), "{err}");
|
||||
assert_eq!(transparent.tools.brush, brush);
|
||||
assert_eq!(transparent.tools.presets, presets);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tagged_rgb_uses_the_document_encoding() {
|
||||
for command in COMMANDS {
|
||||
let mut tagged = rgb_source(32, [0.5, 0.5, 0.5, 1.0]);
|
||||
tagged
|
||||
.edit("Assign linear RGB", |doc, _| {
|
||||
doc.icc_profile = Some(Builtin::LinearSrgb.profile().to_bytes());
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let explicit = craft_cms::cached(Builtin::LinearSrgb.profile(), Builtin::SGray.profile(), TransformOptions::default()).unwrap();
|
||||
let mut gray = [0.0f32; 16];
|
||||
explicit.eval(&[0.5, 0.5, 0.5], &mut gray).unwrap();
|
||||
let actual = define_square(&mut tagged, command, false);
|
||||
assert!((actual - (1.0 - gray[0])).abs() <= 1.0 / 65535.0);
|
||||
|
||||
let mut srgb = rgb_source(32, [0.5, 0.5, 0.5, 1.0]);
|
||||
let untagged = define_square(&mut srgb, command, false);
|
||||
assert!((actual - untagged).abs() > 0.1, "the fixture must distinguish profile encoding");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_gray_keeps_numeric_density_in_its_existing_rgb_view() {
|
||||
for command in COMMANDS {
|
||||
for depth in [8, 16, 32] {
|
||||
for profile in [None, Some(Builtin::DotGain20Compat), Some(Builtin::GrayGamma22)] {
|
||||
for value in [128.0 / 255.0, 200.0 / 255.0, 0.0] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 40, "height": 40, "mode": "gray", "depth": depth, "background": "white"})).unwrap();
|
||||
s.edit("Native gray square", |doc, active| {
|
||||
doc.icc_profile = profile.map(|p| p.profile().to_bytes());
|
||||
doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(10, 10, 30, 30), &[value, 1.0]);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let actual = define_square(&mut s, command, false);
|
||||
assert!((actual - (1.0 - value)).abs() <= 0.0001, "{command}, depth {depth}, profile {profile:?}, value {value}: {actual}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_alpha_and_zero_selection_skip_hidden_colour() {
|
||||
for command in COMMANDS {
|
||||
for transparent in [true, false] {
|
||||
for rgb in [[0.0, 0.0, 1.0], [f32::NAN, f32::INFINITY, f32::NEG_INFINITY]] {
|
||||
let mut s = rgb_source(32, [0.0, 0.0, 0.0, 1.0]);
|
||||
let hole = photocraft_geom::Rect::new(15, 15, 25, 25);
|
||||
s.edit("Hidden colour", |doc, active| {
|
||||
let alpha = if transparent { 0.0 } else { 1.0 };
|
||||
doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(hole, &[rgb[0], rgb[1], rgb[2], alpha]);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let st = s.active().unwrap();
|
||||
let stored = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(20, 20);
|
||||
assert_eq!(stored[3], if transparent { 0.0 } else { 1.0 });
|
||||
for channel in 0..3 {
|
||||
if rgb[channel].is_nan() {
|
||||
assert!(stored[channel].is_nan(), "the non-finite fixture must reach the source read");
|
||||
} else {
|
||||
assert_eq!(stored[channel], rgb[channel]);
|
||||
}
|
||||
}
|
||||
if !transparent {
|
||||
s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
|
||||
s.edit("Zero coverage hole", |doc, _| {
|
||||
doc.selection.as_mut().unwrap().fill_rect(hole, &[0.0]);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
// The hole stays inside the sampled area, rather than being
|
||||
// removed by selection bounds before the per-pixel check.
|
||||
assert_eq!(s.active().unwrap().doc.selection.as_ref().unwrap().content_bounds(), photocraft_geom::Rect::new(10, 10, 30, 30));
|
||||
}
|
||||
let doc = s.active().unwrap().doc.clone();
|
||||
let history = s.active().unwrap().history.past_len();
|
||||
let presets = s.tools.presets.len();
|
||||
|
||||
let made = s.execute(command, json!({"name": "Visible black border"})).unwrap();
|
||||
|
||||
assert_eq!((made["width"].as_u64(), made["height"].as_u64()), (Some(20), Some(20)));
|
||||
assert_eq!(tip(&s).get(0, 0), 1.0);
|
||||
assert_eq!(tip(&s).get(19, 19), 1.0);
|
||||
assert_eq!(tip(&s).get(5, 5), 0.0, "hidden colour contributes no paint");
|
||||
assert_eq!(tip(&s).get(14, 14), 0.0);
|
||||
assert_eq!(s.tools.presets.len(), presets + 1);
|
||||
assert_eq!(s.tools.current_preset.as_deref(), Some("Visible black border"));
|
||||
assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc));
|
||||
assert_eq!(s.active().unwrap().history.past_len(), history);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sampled_trcs_cannot_hide_non_finite_contributing_channels() {
|
||||
let mut profile = Builtin::Srgb.profile().clone();
|
||||
profile.trc = profile.trc.take().map(|curves| curves.map(|curve| craft_cms::Curve::Table(curve.sample(256))));
|
||||
// Reset the built-in's encoded bytes and cache key after replacing its curves.
|
||||
let icc = profile.with_encoded_bytes().to_bytes();
|
||||
let parsed = craft_cms::Profile::parse(&icc).unwrap();
|
||||
assert!(parsed.trc.as_ref().unwrap().iter().all(|curve| matches!(curve, craft_cms::Curve::Table(_))));
|
||||
let options = TransformOptions { intent: Intent::RelativeColorimetric, bpc: true, ..Default::default() };
|
||||
let gray = craft_cms::cached(&parsed, Builtin::SGray.profile(), options).unwrap();
|
||||
let mut converted = [0.0f32; 16];
|
||||
gray.eval(&[f32::INFINITY, 0.0, 0.0], &mut converted).unwrap();
|
||||
assert!(converted[0].is_finite(), "the sampled-TRC fixture must expose clamping before the command's gray check");
|
||||
|
||||
for command in COMMANDS {
|
||||
for selected in [false, true] {
|
||||
let mut finite = rgb_source(32, [1.0, 0.0, 0.0, 1.0]);
|
||||
finite
|
||||
.edit("Assign sampled sRGB", |doc, _| {
|
||||
doc.icc_profile = Some(icc.clone());
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert!((define_square(&mut finite, command, selected) - 0.49).abs() <= 0.03);
|
||||
|
||||
for rgba in [
|
||||
[f32::INFINITY, 0.0, 0.0, 1.0],
|
||||
[0.0, f32::INFINITY, 0.0, 1.0],
|
||||
[0.0, 0.0, f32::INFINITY, 1.0],
|
||||
[0.0, 0.0, 0.0, f32::INFINITY],
|
||||
[f32::NAN, 0.0, 0.0, 1.0],
|
||||
[f32::NEG_INFINITY, 0.0, 0.0, 1.0],
|
||||
] {
|
||||
let mut s = rgb_source(32, rgba);
|
||||
s.edit("Assign sampled sRGB", |doc, _| {
|
||||
doc.icc_profile = Some(icc.clone());
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
if selected {
|
||||
s.execute("select.rect", json!({"x": 8, "y": 8, "width": 24, "height": 24})).unwrap();
|
||||
}
|
||||
// An accepted invalid source would replace this existing preset.
|
||||
s.execute("brush.presets.save", json!({"name": "Kept preset"})).unwrap();
|
||||
let active = s.active().unwrap().active_layer.unwrap();
|
||||
let stored = s.active().unwrap().doc.layer(active).unwrap().surface().unwrap().rgba(20, 20).map(f32::to_bits);
|
||||
assert_eq!(stored, rgba.map(f32::to_bits), "non-finite values must reach the source read unchanged");
|
||||
let doc = s.active().unwrap().doc.clone();
|
||||
let history = s.active().unwrap().history.past_len();
|
||||
let brush = s.tools.brush.clone();
|
||||
let presets = s.tools.presets.clone();
|
||||
let current = s.tools.current_preset.clone();
|
||||
let revision = s.tools.brush_rev;
|
||||
let journal = s.journal.clone();
|
||||
|
||||
let error = s.execute(command, json!({"name": "Kept preset"})).unwrap_err();
|
||||
|
||||
assert!(error.to_string().contains("non-finite"), "{command}: {error}");
|
||||
assert!(Arc::ptr_eq(&doc, &s.active().unwrap().doc));
|
||||
assert_eq!(s.active().unwrap().history.past_len(), history);
|
||||
assert_eq!(s.active().unwrap().active_layer, Some(active));
|
||||
assert_eq!(s.active().unwrap().doc.selection.is_some(), selected);
|
||||
assert_eq!(s.active().unwrap().doc.icc_profile.as_ref(), Some(&icc));
|
||||
assert_eq!(s.active().unwrap().doc.layer(active).unwrap().surface().unwrap().rgba(20, 20).map(f32::to_bits), stored);
|
||||
assert_eq!(s.tools.brush, brush);
|
||||
assert_eq!(s.tools.presets, presets);
|
||||
assert_eq!(s.tools.current_preset, current);
|
||||
assert_eq!(s.tools.brush_rev, revision);
|
||||
assert_eq!(s.journal, journal);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,403 @@
|
||||
use super::*;
|
||||
use photocraft_doc::Layer;
|
||||
|
||||
const COMMANDS: [&str; 2] = ["edit.defineBrushPreset", "brush.defineFromSelection"];
|
||||
|
||||
fn tip(s: &Session) -> &GrayTile {
|
||||
let TipShape::Sampled(tip) = &s.tools.brush.tip else { panic!("expected a sampled tip") };
|
||||
tip
|
||||
}
|
||||
|
||||
fn source(depth: u32) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 200, "height": 150, "depth": depth, "background": "#ffffff"})).unwrap();
|
||||
s.execute("layer.new.layer", json!({"name": "Tip"})).unwrap();
|
||||
s.edit("Two visible squares", |doc, active| {
|
||||
let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();
|
||||
surf.fill_rect(Rect::new(50, 40, 90, 70), &[0.0, 0.0, 0.0, 1.0]);
|
||||
surf.fill_rect(Rect::new(120, 60, 150, 90), &[128.0 / 255.0, 128.0 / 255.0, 128.0 / 255.0, 1.0]);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visible_capture_is_identical_with_background_tip_group_or_no_active_layer() {
|
||||
for command in COMMANDS {
|
||||
for depth in [8, 16, 32] {
|
||||
let mut s = source(depth);
|
||||
let background = s.active().unwrap().doc.layers[0].id;
|
||||
let painted = s.active().unwrap().active_layer.unwrap();
|
||||
s.execute("layer.new.group", json!({"name": "Empty active group"})).unwrap();
|
||||
let group = s.active().unwrap().active_layer.unwrap();
|
||||
let mut expected = None;
|
||||
for active in [Some(background), Some(painted), Some(group), None] {
|
||||
s.edit("Choose capture-independent active layer", |_, current| {
|
||||
*current = active;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let doc = s.active().unwrap().doc.clone();
|
||||
let history = s.active().unwrap().history.past_len();
|
||||
assert!(s.is_enabled(command));
|
||||
let made = s.execute(command, json!({"name": "Merged tip"})).unwrap();
|
||||
assert_eq!((made["width"].as_u64(), made["height"].as_u64()), (Some(100), Some(50)));
|
||||
assert_eq!(s.tools.brush.size, 100.0);
|
||||
assert_eq!(tip(&s).get(0, 0), 1.0);
|
||||
assert_eq!(tip(&s).get(60, 0), 0.0);
|
||||
assert!((tip(&s).get(70, 20) - 127.0 / 255.0).abs() < 0.003);
|
||||
let pixels: Vec<_> = (0..50).flat_map(|y| (0..100).map(move |x| (x, y))).map(|(x, y)| tip(&s).get(x, y)).collect();
|
||||
if let Some(expected) = &expected {
|
||||
assert_eq!(&pixels, expected);
|
||||
} else {
|
||||
expected = Some(pixels);
|
||||
}
|
||||
assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc));
|
||||
assert_eq!(s.active().unwrap().active_layer, active);
|
||||
assert_eq!(s.active().unwrap().history.past_len(), history);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_limits_the_visible_composite_even_with_background_active() {
|
||||
for command in COMMANDS {
|
||||
let mut s = source(8);
|
||||
s.edit("Activate background", |doc, active| {
|
||||
*active = Some(doc.layers[0].id);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.rect", json!({"x": 115, "y": 55, "width": 40, "height": 40})).unwrap();
|
||||
let mask = s.active().unwrap().doc.selection.clone();
|
||||
s.execute(command, json!({"name": "Selected composite"})).unwrap();
|
||||
assert_eq!((tip(&s).width, tip(&s).height), (30, 30));
|
||||
assert!((tip(&s).get(0, 0) - 127.0 / 255.0).abs() < 0.003);
|
||||
assert_eq!(s.active().unwrap().doc.selection, mask);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visible_group_children_and_occlusion_count_but_hidden_layers_and_groups_do_not() {
|
||||
for command in COMMANDS {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap();
|
||||
s.edit("Visible and hidden composite contributors", |doc, active| {
|
||||
let mut black = Layer::raster("Nested visible black", doc.pixel_format());
|
||||
black.surface_mut().unwrap().fill_rect(Rect::new(1, 1, 5, 5), &[0.0, 0.0, 0.0, 1.0]);
|
||||
let visible = Layer::group("Visible group", vec![black]);
|
||||
let mut hidden_black = Layer::raster("Hidden black", doc.pixel_format());
|
||||
hidden_black.surface_mut().unwrap().fill_rect(doc.bounds(), &[0.0, 0.0, 0.0, 1.0]);
|
||||
hidden_black.visible = false;
|
||||
let mut hidden_group = Layer::group("Hidden ancestor", vec![hidden_black.duplicate()]);
|
||||
hidden_group.children_mut().unwrap()[0].visible = true;
|
||||
hidden_group.visible = false;
|
||||
let mut white = Layer::raster("Visible white occlusion", doc.pixel_format());
|
||||
white.surface_mut().unwrap().fill_rect(Rect::new(1, 1, 3, 5), &[1.0, 1.0, 1.0, 1.0]);
|
||||
*active = Some(hidden_black.id);
|
||||
doc.layers.extend([visible, hidden_black, hidden_group, white]);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute(command, json!({"name": "Only visible ink"})).unwrap();
|
||||
assert_eq!((tip(&s).width, tip(&s).height), (2, 4));
|
||||
for y in 0..4 {
|
||||
for x in 0..2 {
|
||||
assert_eq!(tip(&s).get(x, y), 1.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn composite_transparency_and_selection_coverage_are_applied_once() {
|
||||
for command in COMMANDS {
|
||||
for depth in [8, 16, 32] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 8, "height": 8, "depth": depth, "background": "transparent"})).unwrap();
|
||||
s.edit("Nested translucent source", |doc, active| {
|
||||
let mut black = Layer::raster("Half black", doc.pixel_format());
|
||||
black.surface_mut().unwrap().fill_rect(Rect::new(1, 1, 6, 7), &[0.0, 0.0, 0.0, 0.5]);
|
||||
let group = Layer::group("Active group", vec![black]);
|
||||
*active = Some(group.id);
|
||||
doc.layers.push(group);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
for selected in [false, true] {
|
||||
if selected {
|
||||
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap();
|
||||
s.edit("Quarter coverage", |doc, _| {
|
||||
doc.selection.as_mut().unwrap().fill_rect(Rect::new(0, 0, 8, 8), &[0.25]);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
s.execute(command, json!({"name": "Translucent composite"})).unwrap();
|
||||
assert_eq!((tip(&s).width, tip(&s).height), (5, 6));
|
||||
let expected = if selected { 0.125 } else { 0.5 };
|
||||
for y in 0..6 {
|
||||
for x in 0..5 {
|
||||
assert!((tip(&s).get(x, y) - expected).abs() < 0.003);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hidden_black_source_over_white_or_transparency_is_empty_and_does_not_replace_a_preset() {
|
||||
for command in COMMANDS {
|
||||
for background in ["white", "transparent"] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 8, "height": 8, "background": background})).unwrap();
|
||||
s.execute("layer.new.layer", json!({"name": "Hidden ink"})).unwrap();
|
||||
s.edit("Hide all ink", |doc, active| {
|
||||
let bounds = doc.bounds();
|
||||
let layer = doc.layer_mut(active.unwrap()).unwrap();
|
||||
layer.surface_mut().unwrap().fill_rect(bounds, &[0.0, 0.0, 0.0, 1.0]);
|
||||
layer.visible = false;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("brush.presets.save", json!({"name": "Kept"})).unwrap();
|
||||
let brush = s.tools.brush.clone();
|
||||
let presets = s.tools.presets.clone();
|
||||
let current = s.tools.current_preset.clone();
|
||||
let doc = s.active().unwrap().doc.clone();
|
||||
let history = s.active().unwrap().history.past_len();
|
||||
let err = s.execute(command, json!({"name": "Kept"})).unwrap_err();
|
||||
assert!(err.to_string().contains("contain no paint"), "{err}");
|
||||
assert_eq!(s.tools.brush, brush);
|
||||
assert_eq!(s.tools.presets, presets);
|
||||
assert_eq!(s.tools.current_preset, current);
|
||||
assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc));
|
||||
assert_eq!(s.active().unwrap().history.past_len(), history);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merged_rgb_retains_the_document_profile_before_gray_conversion() {
|
||||
for command in COMMANDS {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 8, "height": 8, "depth": 32, "background": "transparent"})).unwrap();
|
||||
s.edit("Linear gray nested under active group", |doc, active| {
|
||||
doc.icc_profile = Some(craft_cms::Builtin::LinearSrgb.profile().to_bytes());
|
||||
let mut layer = Layer::raster("Linear half gray", doc.pixel_format());
|
||||
layer.surface_mut().unwrap().fill_rect(Rect::new(1, 1, 5, 5), &[0.5, 0.5, 0.5, 1.0]);
|
||||
let group = Layer::group("Active group", vec![layer]);
|
||||
*active = Some(group.id);
|
||||
doc.layers.push(group);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute(command, json!({"name": "Profiled merged tip"})).unwrap();
|
||||
assert_eq!((tip(&s).width, tip(&s).height), (4, 4));
|
||||
// Encoded sGray for linear RGB 0.5 is about 0.735, not encoded RGB 0.5.
|
||||
assert!((tip(&s).get(0, 0) - 0.265).abs() < 0.01);
|
||||
}
|
||||
}
|
||||
|
||||
fn sparse_budget_source(width: u32, height: u32, selected: bool) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": width, "height": height, "background": "transparent"})).unwrap();
|
||||
s.edit("Sparse composite budget fixture", |doc, active| {
|
||||
let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();
|
||||
surf.fill_rect(Rect::new(0, 0, 1, 1), &[0.0, 0.0, 0.0, 1.0]);
|
||||
assert_eq!(surf.tile_count(), 1);
|
||||
if selected {
|
||||
let mut mask = Surface::new(photocraft_color::PixelFormat::GRAY8);
|
||||
mask.fill_rect(Rect::new(0, 0, 1, 1), &[1.0]);
|
||||
mask.fill_rect(Rect::new(width as i32 - 1, height as i32 - 1, width as i32, height as i32), &[1.0]);
|
||||
assert_eq!(mask.tile_count(), 2);
|
||||
assert_eq!(mask.content_bounds(), doc.bounds());
|
||||
doc.selection = Some(mask);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn composite_storage_is_counted_with_density_and_mask_before_any_allocation() {
|
||||
const WIDTH: u32 = 32768;
|
||||
for command in COMMANDS {
|
||||
for selected in [false, true] {
|
||||
// Density plus optional mask fit exactly; the simultaneously live RGBA band
|
||||
// must also count, even though the document itself is sparse.
|
||||
let bytes = if selected { 8 } else { 4 };
|
||||
let height = (crate::allocation::MAX_DENSE_BYTES / (bytes * u64::from(WIDTH))) as u32;
|
||||
let mut s = sparse_budget_source(WIDTH, height, selected);
|
||||
let doc = s.active().unwrap().doc.clone();
|
||||
let brush = s.tools.brush.clone();
|
||||
let presets = s.tools.presets.clone();
|
||||
let current = s.tools.current_preset.clone();
|
||||
let history = s.active().unwrap().history.past_len();
|
||||
crate::allocation::fail_next_for_test();
|
||||
let result = s.execute(command, json!({"name": "Composite over budget"}));
|
||||
let unspent = crate::allocation::capacity::<u8>(0, "consume composite budget failpoint");
|
||||
let err = result.unwrap_err();
|
||||
assert!(err.to_string().contains("working memory"), "{err}");
|
||||
assert!(unspent.is_err(), "budget refusal must precede the first allocation");
|
||||
assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc));
|
||||
assert_eq!(s.active().unwrap().history.past_len(), history);
|
||||
assert_eq!(s.tools.brush, brush);
|
||||
assert_eq!(s.tools.presets, presets);
|
||||
assert_eq!(s.tools.current_preset, current);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compositor_allocation_boundary_failure_preserves_source_and_preset_state() {
|
||||
for command in COMMANDS {
|
||||
for selected in [false, true] {
|
||||
let mut s = source(8);
|
||||
if selected {
|
||||
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 200, "height": 150})).unwrap();
|
||||
}
|
||||
let doc = s.active().unwrap().doc.clone();
|
||||
let history = s.active().unwrap().history.past_len();
|
||||
let brush = s.tools.brush.clone();
|
||||
let presets = s.tools.presets.clone();
|
||||
let current = s.tools.current_preset.clone();
|
||||
crate::allocation::fail_after_for_test(if selected { 2 } else { 1 });
|
||||
let result = s.execute(command, json!({"name": "Compositor allocation failure"}));
|
||||
let _ = crate::allocation::capacity::<u8>(0, "reset compositor failpoint");
|
||||
let err = result.unwrap_err();
|
||||
assert!(err.to_string().contains("not enough memory"), "{err}");
|
||||
assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc));
|
||||
assert_eq!(s.active().unwrap().history.past_len(), history);
|
||||
assert_eq!(s.tools.brush, brush);
|
||||
assert_eq!(s.tools.presets, presets);
|
||||
assert_eq!(s.tools.current_preset, current);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_banded_capture_that_fits_the_budget_is_not_charged_for_a_full_rgba_canvas() {
|
||||
const WIDTH: u32 = 32768;
|
||||
let band_rows = photocraft_compose::band_rows_for(WIDTH, 0) as u64;
|
||||
let band_bytes = u64::from(WIDTH) * band_rows * 16;
|
||||
for command in COMMANDS {
|
||||
for selected in [false, true] {
|
||||
let sample_bytes = if selected { 8 } else { 4 };
|
||||
let height = ((crate::allocation::MAX_DENSE_BYTES - band_bytes) / (sample_bytes * u64::from(WIDTH))) as u32;
|
||||
let pixels = u64::from(WIDTH) * u64::from(height);
|
||||
assert!(pixels * sample_bytes + band_bytes <= crate::allocation::MAX_DENSE_BYTES);
|
||||
assert!(pixels * (sample_bytes + 16) > crate::allocation::MAX_DENSE_BYTES, "a full-plane estimate would incorrectly reject this fixture");
|
||||
let mut s = sparse_budget_source(WIDTH, height, selected);
|
||||
let doc = s.active().unwrap().doc.clone();
|
||||
let brush = s.tools.brush.clone();
|
||||
let presets = s.tools.presets.clone();
|
||||
// Refuse the first real allocation, after verifying that the budget allowed it.
|
||||
crate::allocation::fail_next_for_test();
|
||||
let result = s.execute(command, json!({"name": "Fits with bands"}));
|
||||
let unspent = crate::allocation::capacity::<u8>(0, "consume band acceptance failpoint");
|
||||
let err = result.unwrap_err().to_string();
|
||||
assert!(err.contains("not enough memory") && !err.contains("working memory"), "{err}");
|
||||
assert!(unspent.is_ok(), "the accepted budget must reach the first allocation");
|
||||
assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc));
|
||||
assert_eq!(s.tools.brush, brush);
|
||||
assert_eq!(s.tools.presets, presets);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_visible_capture_is_identical_with_background_tip_group() {
|
||||
for command in COMMANDS {
|
||||
for depth in [8, 16, 32] {
|
||||
let mut s = source(depth);
|
||||
let background = s.active().unwrap().doc.layers[0].id;
|
||||
let painted = s.active().unwrap().active_layer.unwrap();
|
||||
s.execute("layer.new.group", json!({"name": "Empty active group"})).unwrap();
|
||||
let group = s.active().unwrap().active_layer.unwrap();
|
||||
s.execute("select.rect", json!({"x": 50, "y": 40, "width": 100, "height": 50})).unwrap();
|
||||
let mut expected = None;
|
||||
for active in [Some(background), Some(painted), Some(group)] {
|
||||
s.edit("Choose capture-independent active layer", |_, current| {
|
||||
*current = active;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let doc = s.active().unwrap().doc.clone();
|
||||
let history = s.active().unwrap().history.past_len();
|
||||
assert!(s.is_enabled(command));
|
||||
let made = s.execute(command, json!({"name": "Merged tip"})).unwrap();
|
||||
assert_eq!((made["width"].as_u64(), made["height"].as_u64()), (Some(100), Some(50)));
|
||||
assert_eq!(s.tools.brush.size, 100.0);
|
||||
assert_eq!(tip(&s).get(0, 0), 1.0);
|
||||
assert_eq!(tip(&s).get(60, 0), 0.0);
|
||||
assert!((tip(&s).get(70, 20) - 127.0 / 255.0).abs() < 0.003);
|
||||
let pixels: Vec<_> = (0..50).flat_map(|y| (0..100).map(move |x| (x, y))).map(|(x, y)| tip(&s).get(x, y)).collect();
|
||||
if let Some(expected) = &expected {
|
||||
assert_eq!(&pixels, expected);
|
||||
} else {
|
||||
expected = Some(pixels);
|
||||
}
|
||||
assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc));
|
||||
assert_eq!(s.active().unwrap().active_layer, active);
|
||||
assert_eq!(s.active().unwrap().history.past_len(), history);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visible_composite_keeps_occlusion_and_ignores_hidden_source() {
|
||||
for command in COMMANDS {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap();
|
||||
s.edit("Visible composite with hidden source", |doc, active| {
|
||||
let mut black = Layer::raster("Visible black", doc.pixel_format());
|
||||
black.surface_mut().unwrap().fill_rect(Rect::new(1, 1, 5, 5), &[0.0, 0.0, 0.0, 1.0]);
|
||||
let mut hidden_black = Layer::raster("Hidden black", doc.pixel_format());
|
||||
hidden_black.surface_mut().unwrap().fill_rect(doc.bounds(), &[0.0, 0.0, 0.0, 1.0]);
|
||||
hidden_black.visible = false;
|
||||
let mut white = Layer::raster("Visible white occlusion", doc.pixel_format());
|
||||
white.surface_mut().unwrap().fill_rect(Rect::new(1, 1, 3, 5), &[1.0, 1.0, 1.0, 1.0]);
|
||||
*active = Some(hidden_black.id);
|
||||
doc.layers.extend([black, hidden_black, white]);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap();
|
||||
s.execute(command, json!({"name": "Only visible ink"})).unwrap();
|
||||
assert_eq!((tip(&s).width, tip(&s).height), (2, 4));
|
||||
for y in 0..4 {
|
||||
for x in 0..2 {
|
||||
assert_eq!(tip(&s).get(x, y), 1.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_buffer_failure_preserves_source_and_preset_state() {
|
||||
for command in COMMANDS {
|
||||
let mut s = source(8);
|
||||
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 200, "height": 150})).unwrap();
|
||||
let doc = s.active().unwrap().doc.clone();
|
||||
let history = s.active().unwrap().history.past_len();
|
||||
let brush = s.tools.brush.clone();
|
||||
let presets = s.tools.presets.clone();
|
||||
let current = s.tools.current_preset.clone();
|
||||
crate::allocation::fail_after_for_test(1);
|
||||
let result = s.execute(command, json!({"name": "Selection buffer failure"}));
|
||||
let _ = crate::allocation::capacity::<u8>(0, "reset selection failpoint");
|
||||
let err = result.unwrap_err();
|
||||
assert!(err.to_string().contains("not enough memory"), "{err}");
|
||||
assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc));
|
||||
assert_eq!(s.active().unwrap().history.past_len(), history);
|
||||
assert_eq!(s.tools.brush, brush);
|
||||
assert_eq!(s.tools.presets, presets);
|
||||
assert_eq!(s.tools.current_preset, current);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
use super::*;
|
||||
|
||||
const COMMANDS: [&str; 2] = ["edit.defineBrushPreset", "brush.defineFromSelection"];
|
||||
|
||||
fn source(depth: u32) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 200, "height": 150, "depth": depth, "background": "#ffffff"})).unwrap();
|
||||
s.execute("layer.new.layer", json!({"name": "Tip"})).unwrap();
|
||||
s.edit("BrushSrc", |doc, active| {
|
||||
let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();
|
||||
surf.fill_rect(Rect::new(50, 40, 90, 70), &[0.0, 0.0, 0.0, 1.0]);
|
||||
surf.fill_rect(Rect::new(120, 60, 150, 90), &[128.0 / 255.0, 128.0 / 255.0, 128.0 / 255.0, 1.0]);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn tip(s: &Session) -> &GrayTile {
|
||||
let TipShape::Sampled(tip) = &s.tools.brush.tip else { panic!("expected a sampled tip") };
|
||||
tip
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_selection_the_canvas_is_trimmed_to_the_measured_content() {
|
||||
for command in COMMANDS {
|
||||
for depth in [8, 16, 32] {
|
||||
let mut s = source(depth);
|
||||
assert!(s.active().unwrap().doc.selection.is_none());
|
||||
assert!(s.is_enabled(command), "{command}, depth {depth}");
|
||||
let doc = s.active().unwrap().doc.clone();
|
||||
let history = s.active().unwrap().history.past_len();
|
||||
let presets = s.tools.presets.len();
|
||||
|
||||
let result = s.execute(command, json!({"name": "Canvas tip"})).unwrap();
|
||||
|
||||
assert_eq!((result["width"].as_u64(), result["height"].as_u64()), (Some(100), Some(50)));
|
||||
assert_eq!(s.tools.brush.size, 100.0);
|
||||
assert_eq!((tip(&s).width, tip(&s).height), (100, 50));
|
||||
assert_eq!(tip(&s).get(0, 0), 1.0);
|
||||
assert_eq!(tip(&s).get(60, 0), 0.0, "transparent gap contributes no paint");
|
||||
assert!((tip(&s).get(70, 20) - 127.0 / 255.0).abs() < 0.003);
|
||||
assert_eq!(s.tools.presets.len(), presets + 1);
|
||||
assert_eq!(s.tools.current_preset.as_deref(), Some("Canvas tip"));
|
||||
assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc), "source document is untouched");
|
||||
assert_eq!(s.active().unwrap().history.past_len(), history);
|
||||
assert!(s.active().unwrap().doc.selection.is_none(), "no synthetic selection is left behind");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_existing_selection_still_limits_the_tip_to_the_grey_square() {
|
||||
for command in COMMANDS {
|
||||
let mut s = source(8);
|
||||
s.execute("select.rect", json!({"x": 115, "y": 55, "width": 40, "height": 40})).unwrap();
|
||||
let result = s.execute(command, json!({"name": "Selected tip"})).unwrap();
|
||||
assert_eq!((result["width"].as_u64(), result["height"].as_u64()), (Some(30), Some(30)));
|
||||
assert_eq!(s.tools.brush.size, 30.0);
|
||||
assert!((tip(&s).get(0, 0) - 127.0 / 255.0).abs() < 0.003);
|
||||
assert!(s.active().unwrap().doc.selection.is_some());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_partial_selection_keeps_coverage_alpha_and_canvas_clipping() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 8, "height": 8, "background": "transparent"})).unwrap();
|
||||
s.edit("Half opaque source", |doc, active| {
|
||||
let bounds = doc.bounds();
|
||||
doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(bounds, &[0.0, 0.0, 0.0, 0.5]);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.rect", json!({"x": -3, "y": -2, "width": 8, "height": 8})).unwrap();
|
||||
s.edit("Partial coverage", |doc, _| {
|
||||
doc.selection.as_mut().unwrap().fill_rect(Rect::new(0, 0, 5, 6), &[0.25]);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
s.execute("brush.defineFromSelection", json!({"name": "Masked tip"})).unwrap();
|
||||
|
||||
assert_eq!((tip(&s).width, tip(&s).height), (5, 6));
|
||||
assert!((tip(&s).get(0, 0) - 0.125).abs() < 0.003, "density includes source alpha and selection coverage");
|
||||
assert!((tip(&s).get(4, 5) - 0.125).abs() < 0.003);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_document_is_disabled_and_a_group_active_capture_uses_visible_pixels() {
|
||||
let mut s = Session::new();
|
||||
for command in COMMANDS {
|
||||
assert!(!s.is_enabled(command));
|
||||
assert!(s.execute(command, json!({"name": "No document"})).is_err());
|
||||
}
|
||||
s = source(8);
|
||||
s.execute("layer.new.group", json!({"name": "Not pixels"})).unwrap();
|
||||
for command in COMMANDS {
|
||||
assert!(s.is_enabled(command));
|
||||
s.execute(command, json!({"name": "Visible pixels"})).unwrap();
|
||||
assert_eq!((tip(&s).width, tip(&s).height), (100, 50));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_large_canvas_is_trimmed_before_the_existing_tip_side_limit() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": MAX_TIP + 1, "height": 2, "background": "#ffffff"})).unwrap();
|
||||
s.edit("One black pixel", |doc, active| {
|
||||
doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(MAX_TIP as i32, 0, MAX_TIP as i32 + 1, 1), &[0.0, 0.0, 0.0, 1.0]);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let made = s.execute("edit.defineBrushPreset", json!({"name": "One pixel"})).unwrap();
|
||||
assert_eq!((made["width"].as_u64(), made["height"].as_u64()), (Some(1), Some(1)));
|
||||
assert_eq!(tip(&s).get(0, 0), 1.0);
|
||||
|
||||
s.edit("Too wide painted area", |doc, active| {
|
||||
let bounds = doc.bounds();
|
||||
doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(bounds, &[0.0, 0.0, 0.0, 1.0]);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let brush = s.tools.brush.clone();
|
||||
let presets = s.tools.presets.clone();
|
||||
let err = s.execute("edit.defineBrushPreset", json!({"name": "Too wide"})).unwrap_err();
|
||||
assert!(err.to_string().contains("too large for a brush tip"), "{err}");
|
||||
assert_eq!(s.tools.brush, brush);
|
||||
assert_eq!(s.tools.presets, presets);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_canvas_capture_allocation_failure_leaves_the_source_and_presets_unchanged() {
|
||||
let mut s = source(8);
|
||||
let brush = s.tools.brush.clone();
|
||||
let presets = s.tools.presets.clone();
|
||||
let current = s.tools.current_preset.clone();
|
||||
let doc = s.active().unwrap().doc.clone();
|
||||
let history = s.active().unwrap().history.past_len();
|
||||
crate::allocation::fail_next_for_test();
|
||||
let result = s.execute("brush.defineFromSelection", json!({"name": "Allocation failure"}));
|
||||
let _ = crate::allocation::capacity::<u8>(0, "reset failpoint");
|
||||
let err = result.unwrap_err().to_string();
|
||||
assert!(err.contains("not enough memory") && err.contains("defining a brush from the selection"), "{err}");
|
||||
assert_eq!(s.tools.brush, brush);
|
||||
assert_eq!(s.tools.presets, presets);
|
||||
assert_eq!(s.tools.current_preset, current);
|
||||
assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc));
|
||||
assert_eq!(s.active().unwrap().history.past_len(), history);
|
||||
}
|
||||
|
||||
// Sparse source and mask fixtures keep just one or two tiles, even when their
|
||||
// bounds would require gigabytes of dense sampling buffers.
|
||||
fn budget_source(width: u32, height: u32, selected: bool) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": width, "height": height, "background": "transparent"})).unwrap();
|
||||
s.edit("Sparse budget source", |doc, active| {
|
||||
let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();
|
||||
surf.fill_rect(Rect::new(0, 0, 1, 1), &[0.0, 0.0, 0.0, 1.0]);
|
||||
assert_eq!(surf.tile_count(), 1);
|
||||
if selected {
|
||||
let mut mask = photocraft_raster::Surface::new(photocraft_color::PixelFormat::GRAY8);
|
||||
mask.fill_rect(Rect::new(0, 0, 1, 1), &[1.0]);
|
||||
mask.fill_rect(Rect::new(width as i32 - 1, height as i32 - 1, width as i32, height as i32), &[1.0]);
|
||||
assert_eq!(mask.tile_count(), 2);
|
||||
assert_eq!(mask.content_bounds(), doc.bounds());
|
||||
doc.selection = Some(mask);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn assert_budget_refusal(s: &mut Session, command: &str) {
|
||||
let brush = s.tools.brush.clone();
|
||||
let presets = s.tools.presets.clone();
|
||||
let current = s.tools.current_preset.clone();
|
||||
let doc = s.active().unwrap().doc.clone();
|
||||
let history = s.active().unwrap().history.past_len();
|
||||
let revision = s.active().unwrap().revision;
|
||||
// This also makes the regression safe on the unfixed code: its first dense
|
||||
// allocation fails instead of trying to fill the enormous buffer.
|
||||
crate::allocation::fail_next_for_test();
|
||||
let result = s.execute(command, json!({"name": "Over budget"}));
|
||||
let unspent = crate::allocation::capacity::<u8>(0, "consume budget test failpoint");
|
||||
let err = result.unwrap_err().to_string();
|
||||
assert!(err.contains("working memory") && err.contains("defining a brush from the selection"), "{err}");
|
||||
assert!(unspent.is_err(), "the budget refusal must precede the first fallible allocation");
|
||||
assert_eq!(s.tools.brush, brush);
|
||||
assert_eq!(s.tools.presets, presets);
|
||||
assert_eq!(s.tools.current_preset, current);
|
||||
assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc));
|
||||
assert_eq!(s.active().unwrap().history.past_len(), history);
|
||||
assert_eq!(s.active().unwrap().revision, revision);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_over_budget_canvas_is_refused_before_sampling() {
|
||||
const WIDTH: u32 = 32768;
|
||||
// The pixel count fits usize on both targets, while its f32 density buffer
|
||||
// alone is just over that target's dense-memory budget.
|
||||
let height = (crate::allocation::MAX_DENSE_BYTES / (4 * u64::from(WIDTH))) as u32 + 1;
|
||||
for command in COMMANDS {
|
||||
let mut s = budget_source(WIDTH, height, false);
|
||||
assert!(s.active().unwrap().doc.selection.is_none());
|
||||
assert_budget_refusal(&mut s, command);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_capture_counts_density_and_mask_buffers_together() {
|
||||
const WIDTH: u32 = 32768;
|
||||
let height = (crate::allocation::MAX_DENSE_BYTES / (4 * u64::from(WIDTH))) as u32;
|
||||
let density_bytes = u64::from(WIDTH) * u64::from(height) * 4;
|
||||
assert_eq!(density_bytes, crate::allocation::MAX_DENSE_BYTES, "density alone would fit; the live mask must also count");
|
||||
for command in COMMANDS {
|
||||
let mut s = budget_source(WIDTH, height, true);
|
||||
assert_eq!(s.active().unwrap().doc.selection.as_ref().unwrap().channels(), 1);
|
||||
assert_budget_refusal(&mut s, command);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_small_selection_on_an_over_budget_canvas_still_defines_a_tip() {
|
||||
const WIDTH: u32 = 32768;
|
||||
let height = (crate::allocation::MAX_DENSE_BYTES / (4 * u64::from(WIDTH))) as u32 + 1;
|
||||
for command in COMMANDS {
|
||||
let mut s = budget_source(WIDTH, height, false);
|
||||
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 1, "height": 1})).unwrap();
|
||||
let result = s.execute(command, json!({"name": "Small selected tip"})).unwrap();
|
||||
assert_eq!((result["width"].as_u64(), result["height"].as_u64()), (Some(1), Some(1)));
|
||||
assert_eq!(tip(&s).get(0, 0), 1.0);
|
||||
}
|
||||
}
|
||||
@@ -687,6 +687,24 @@ fn define_brush_from_selection_survives_failure_of_the_second_allocation() {
|
||||
assert!(same_pixels(&pixels_before, &surface(&s), s.active().unwrap().doc.bounds()), "the document pixels are unchanged");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn define_brush_from_selection_propagates_compositor_allocation_error_transactionally() {
|
||||
let mut s = session(40, 40);
|
||||
s.execute("select.rect", json!({"x": 5, "y": 5, "width": 20, "height": 20})).unwrap();
|
||||
let doc = s.active().unwrap().doc.clone();
|
||||
let brush_before = s.tools.brush.clone();
|
||||
let presets_before = s.tools.presets.clone();
|
||||
let history_before = s.active().unwrap().history.past_len();
|
||||
let result = define_from_selection_with_renderer(&mut s, &json!({"name": "Blob"}), |_, _, _| {
|
||||
Err(photocraft_compose::RenderBandsError::Allocation(photocraft_raster::AllocationError::NotEnoughMemory { bytes: 64 }))
|
||||
});
|
||||
assert!(result.is_err_and(|e| e.to_string().contains("defining a brush from the selection")));
|
||||
assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc));
|
||||
assert_eq!(s.tools.brush, brush_before);
|
||||
assert_eq!(s.tools.presets, presets_before);
|
||||
assert_eq!(s.active().unwrap().history.past_len(), history_before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn works_on_cmyk_and_16_bit() {
|
||||
for (mode, depth) in [("cmyk", 8), ("rgb", 16), ("grayscale", 32)] {
|
||||
|
||||
@@ -756,7 +756,7 @@ fn preset_manager_brush_delete_clears_current_preset() {
|
||||
#[test]
|
||||
fn define_brush_preset_wraps_define_from_selection() {
|
||||
let mut s = session(8);
|
||||
assert!(!s.is_enabled("edit.defineBrushPreset"));
|
||||
assert!(s.is_enabled("edit.defineBrushPreset"));
|
||||
s.execute("edit.fill", json!({"color": "#000000"})).unwrap();
|
||||
s.execute("select.rect", json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap();
|
||||
s.execute("edit.defineBrushPreset", json!({})).unwrap();
|
||||
|
||||
@@ -255,11 +255,21 @@ fn take_with<T: Pooled>(len: usize, fill: T, slack: usize) -> Vec<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Fallible [`take`]: on a pool miss the heap allocation is `try_reserve_exact`, so `None` means
|
||||
/// the allocation failed rather than aborting. The pool lookup keeps `take`'s existing 2x slack.
|
||||
pub fn try_take<T: Pooled>(len: usize, fill: T) -> Option<Vec<T>> {
|
||||
try_take_with_slack(len, fill, 2)
|
||||
}
|
||||
|
||||
/// Fallible [`take_exact`]: on a pool miss the heap allocation is `try_reserve_exact`, so
|
||||
/// `None` means the allocation failed rather than aborting.
|
||||
/// `None` means the allocation failed rather than aborting. Only exact-capacity buffers are reused.
|
||||
pub fn try_take_exact<T: Pooled>(len: usize, fill: T) -> Option<Vec<T>> {
|
||||
try_take_with_slack(len, fill, 1)
|
||||
}
|
||||
|
||||
fn try_take_with_slack<T: Pooled>(len: usize, fill: T, slack: usize) -> Option<Vec<T>> {
|
||||
USES.fetch_add(1, Ordering::Relaxed);
|
||||
let mut v = match pop::<T>(len, 1) {
|
||||
let mut v = match pop::<T>(len, slack) {
|
||||
Some(v) => v,
|
||||
None => {
|
||||
let mut v = Vec::new();
|
||||
|
||||
@@ -100,6 +100,38 @@ fn try_take_exact_reuses_and_allocates() {
|
||||
release();
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Verifies fallible takes preserve the slack policy of their infallible counterparts.
|
||||
fn try_take_preserves_slack_and_exact_variant_stays_exact() {
|
||||
let _g = serial();
|
||||
release();
|
||||
let pooled = Vec::<f32>::with_capacity(150_000);
|
||||
let pooled_ptr = pooled.as_ptr();
|
||||
give(pooled);
|
||||
let slack = try_take(100_000, 1.0f32);
|
||||
assert_eq!(slack.as_ref().map(|v| v.as_ptr()), Some(pooled_ptr));
|
||||
assert!(slack.is_some_and(|v| v.len() == 100_000 && v.iter().all(|&sample| sample == 1.0)));
|
||||
release();
|
||||
|
||||
let pooled = Vec::<f32>::with_capacity(150_000);
|
||||
let pooled_ptr = pooled.as_ptr();
|
||||
give(pooled);
|
||||
let exact = try_take_exact(100_000, 2.0f32);
|
||||
assert!(exact.is_some());
|
||||
assert_ne!(exact.as_ref().map(|v| v.as_ptr()), Some(pooled_ptr));
|
||||
assert!(exact.is_some_and(|v| v.iter().all(|&sample| sample == 2.0)));
|
||||
release();
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// A request beyond Vec's representable capacity returns an allocation failure, not a panic.
|
||||
fn fallible_take_reports_capacity_overflow() {
|
||||
let _g = serial();
|
||||
release();
|
||||
assert!(try_take::<[f32; 4]>(usize::MAX, [0.0; 4]).is_none());
|
||||
release();
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Verifies buffers below the pooling threshold are not retained.
|
||||
fn small_buffers_are_not_retained() {
|
||||
|
||||
Reference in new issue
Block a user