mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Preserve clone canvas coverage for sources without alpha
This commit is contained in:
1 parent
9e74e79d5b
commit
967e987edd
12 files changed
+386
-27
No files matched your search
@@ -17,6 +17,9 @@
|
||||
[people.brianblakely]
|
||||
sync_github_name = true
|
||||
|
||||
[people.mlo0352]
|
||||
sync_github_name = true
|
||||
|
||||
[people.abdul-karim-mia]
|
||||
real_name = "Abdul karim mia"
|
||||
sync_github_name = false
|
||||
@@ -329,6 +332,3 @@ sync_github_name = false
|
||||
[people.tomgardenart]
|
||||
display_name = "Nostella"
|
||||
sync_github_name = false
|
||||
|
||||
[people.mlo0352]
|
||||
sync_github_name = true
|
||||
@@ -48,7 +48,63 @@ pub(super) fn clone_sample(
|
||||
return Err(bad(cmd, "transformed clone source exceeds the sampling budget; increase source scale or reduce the brush"));
|
||||
}
|
||||
let src = read(source_rect)?;
|
||||
Ok(crate::presets::clone_source::resample(&src, rect, map, alpha_index(&surf.format())))
|
||||
Ok(crate::presets::clone_source::resample(&src, rect, map, alpha_index(&source.sample_format(surf))))
|
||||
}
|
||||
|
||||
/// Composite explicit source coverage onto a destination that may store no alpha channel.
|
||||
/// Small working patches keep temporary allocations bounded and preserve native colours/depth.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn apply_clone_coverage(
|
||||
target: &mut Surface,
|
||||
rect: Rect,
|
||||
cov: &[f32],
|
||||
opacity: f32,
|
||||
selection: Option<&Surface>,
|
||||
lock: bool,
|
||||
paint: &Region,
|
||||
mode: BlendMode,
|
||||
) -> Rect {
|
||||
let fmt = target.format();
|
||||
let n = fmt.channels();
|
||||
if fmt.alpha || paint.ch == n || rect.is_empty() {
|
||||
return apply_coverage(target, rect, cov, opacity, selection, lock, paint, mode);
|
||||
}
|
||||
let full_width = rect.width() as usize;
|
||||
let mut y = rect.y0;
|
||||
while y < rect.y1 {
|
||||
let y1 = y.saturating_add(64).min(rect.y1);
|
||||
let mut x = rect.x0;
|
||||
while x < rect.x1 {
|
||||
let x1 = x.saturating_add(64).min(rect.x1);
|
||||
let block = Rect::new(x, y, x1, y1);
|
||||
let width = block.width() as usize;
|
||||
let mut block_cov = vec![0.0; width * block.height() as usize];
|
||||
for (row, values) in block_cov.chunks_exact_mut(width).enumerate() {
|
||||
let offset = (y.abs_diff(rect.y0) as usize + row).saturating_mul(full_width).saturating_add(x.abs_diff(rect.x0) as usize);
|
||||
if let Some(source) = cov.get(offset..offset.saturating_add(width)) {
|
||||
values.copy_from_slice(source);
|
||||
}
|
||||
}
|
||||
// Transparent source spans cannot change an opaque target. Skip them by alpha,
|
||||
// never by colour: an all-zero black source pixel is still valid opaque paint.
|
||||
let covered = block_cov.iter().any(|value| *value > 0.0);
|
||||
let sampled = covered && (y..y1).any(|py| (x..x1).any(|px| paint.px(px, py).get(n).is_some_and(|alpha| *alpha > 0.0)));
|
||||
if !sampled {
|
||||
x = x1;
|
||||
continue;
|
||||
}
|
||||
let working = clone_sampling::opaque_alpha(Region::read(target, block), fmt);
|
||||
// Quantize only when writing back to the real target, not before blending.
|
||||
let mut patch = Surface::new(PixelFormat::new(fmt.mode, SampleType::F32, true));
|
||||
working.write(&mut patch);
|
||||
apply_coverage(&mut patch, block, &block_cov, opacity, selection, lock, paint, mode);
|
||||
let native: Vec<_> = patch.read_region(block).chunks_exact(n + 1).flat_map(|px| px.iter().take(n).copied()).collect();
|
||||
target.write_region(block, &native);
|
||||
x = x1;
|
||||
}
|
||||
y = y1;
|
||||
}
|
||||
rect
|
||||
}
|
||||
|
||||
/// Read-only clone overlay. Shares the stroke sampler without anchoring a source or editing history.
|
||||
@@ -122,7 +178,8 @@ fn preview_periodic(
|
||||
}
|
||||
};
|
||||
let region = clone_sample(&d.doc, Some(id), surf, which, &source, rect, map, wrap, "clone.preview")?;
|
||||
let px = region.data.chunks_exact(surf.format().channels()).map(|p| to_rgba(&surf.format(), p)).collect();
|
||||
let fmt = source.sample_format(surf);
|
||||
let px = region.data.chunks_exact(fmt.channels()).map(|p| to_rgba(&fmt, p)).collect();
|
||||
Ok(photocraft_compose::Buffer { rect, px })
|
||||
}
|
||||
|
||||
@@ -160,6 +217,7 @@ pub(super) fn clamp_samples(fmt: &PixelFormat, data: &mut [f32]) {
|
||||
// Clone Stamp / Healing Brush / History Brush
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/// Paint from a frozen source and record its pairing only after the destination edit succeeds.
|
||||
pub(super) fn clone_stamp(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "paint.cloneStamp";
|
||||
let (stroke, id) = parse_brush(s, p, CMD)?;
|
||||
@@ -180,12 +238,15 @@ pub(super) fn clone_stamp(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Ok(l.bounds);
|
||||
}
|
||||
if flag(p, "wrap", false) {
|
||||
return periodic::stroke(pre, surf, &stroke, sel, lock, mode, CMD, |before, r| clone_sample(pre, id, before, which, &source, r, &map, true, CMD));
|
||||
let fmt = source.sample_format(surf);
|
||||
return periodic::stroke(pre, surf, &stroke, sel, lock, mode, CMD, fmt, |before, r| {
|
||||
clone_sample(pre, id, before, which, &source, r, &map, true, CMD)
|
||||
});
|
||||
}
|
||||
let (bounds, cov) = coverage(CMD, &stroke)?;
|
||||
// Samples come from the pre-stroke state, so pixels painted earlier in the stroke are never re-cloned.
|
||||
let paint = clone_sample(pre, id, surf, which, &source, bounds, &map, flag(p, "wrap", false), CMD)?;
|
||||
Ok(apply_coverage(surf, bounds, &cov, stroke.brush.opacity, sel, lock, &paint, mode))
|
||||
Ok(apply_clone_coverage(surf, bounds, &cov, stroke.brush.opacity, sel, lock, &paint, mode))
|
||||
})?;
|
||||
crate::presets::clone_source::remember_mapping(s, p, &map);
|
||||
let mut r = clone_result(dmg, off, aligned, p, &stroke);
|
||||
@@ -415,6 +476,7 @@ impl LiveRetouch {
|
||||
lock: self.lock,
|
||||
mode: self.mode,
|
||||
cmd: live_cmd,
|
||||
paint_format: source.sample_format(pre_surf),
|
||||
}
|
||||
.draw(dirty, &self.brush, &self.points, paint)
|
||||
}
|
||||
@@ -433,8 +495,14 @@ impl LiveRetouch {
|
||||
};
|
||||
// The Pattern Stamp's Behind goes beneath the pixels, as its commit lays it.
|
||||
let behind = matches!(self.paint, LivePaint::Pattern { behind: true, .. });
|
||||
let clone = matches!(self.paint, LivePaint::Clone { .. });
|
||||
let (surf, _) = crate::channel_cmds::target_surface(std::sync::Arc::make_mut(&mut self.doc), self.id, &self.params)?;
|
||||
surf.write_region(r, &self.pre_surf.read_region(r));
|
||||
Ok(pattern_stamp::lay_coverage(surf, r, cov, self.opacity, self.sel.as_ref(), self.lock, &paint, self.mode, behind).union(&r))
|
||||
let damage = if clone {
|
||||
apply_clone_coverage(surf, r, cov, self.opacity, self.sel.as_ref(), self.lock, &paint, self.mode)
|
||||
} else {
|
||||
pattern_stamp::lay_coverage(surf, r, cov, self.opacity, self.sel.as_ref(), self.lock, &paint, self.mode, behind)
|
||||
};
|
||||
Ok(damage.union(&r))
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ pub(super) struct CloneFrom {
|
||||
other: Option<(Arc<Document>, u64)>,
|
||||
layer: Option<LayerId>,
|
||||
transform: Option<Arc<Transform>>,
|
||||
pixels: bool,
|
||||
}
|
||||
|
||||
impl CloneFrom {
|
||||
@@ -29,7 +30,14 @@ impl CloneFrom {
|
||||
(None, None) => true,
|
||||
_ => false,
|
||||
};
|
||||
document && self.layer == other.layer && colors
|
||||
document && self.layer == other.layer && colors && self.pixels == other.pixels
|
||||
}
|
||||
|
||||
/// Pixel cloning carries coverage independently of the destination's stored alpha flag.
|
||||
/// Masks and channels retain their existing scalar sampling semantics.
|
||||
pub(super) fn sample_format(&self, surf: &Surface) -> PixelFormat {
|
||||
let fmt = surf.format();
|
||||
if self.pixels { alpha_format(fmt) } else { fmt }
|
||||
}
|
||||
|
||||
/// Read a source region into the destination's native channels, optionally wrapping its canvas.
|
||||
@@ -45,7 +53,7 @@ impl CloneFrom {
|
||||
cmd: &str,
|
||||
) -> Result<Region> {
|
||||
let doc = self.other.as_ref().map_or(pre, |(doc, _)| doc.as_ref());
|
||||
let fmt = surf.format();
|
||||
let fmt = self.sample_format(surf);
|
||||
if self.other.is_some() && fmt.mode != pre.mode {
|
||||
return Err(bad(cmd, "the destination layer color model does not match its document"));
|
||||
}
|
||||
@@ -63,24 +71,88 @@ impl CloneFrom {
|
||||
}
|
||||
(sample(doc, target, sampled, which, rect), sampled.format())
|
||||
};
|
||||
convert_region(region, from, fmt, self.transform.as_deref(), cmd)
|
||||
convert_region(region, from, fmt, self.transform.as_deref(), self.pixels.then(|| doc.bounds()), cmd)
|
||||
};
|
||||
if wrap { periodic::sample_with(doc.bounds(), fmt.channels(), rect, cmd, read) } else { read(rect) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Native colour/depth with an explicit coverage channel for intermediate paint pixels.
|
||||
pub(super) fn alpha_format(fmt: PixelFormat) -> PixelFormat {
|
||||
PixelFormat::new(fmt.mode, fmt.sample, true)
|
||||
}
|
||||
|
||||
/// Lift opaque native pixels into an alpha-bearing working region without a colour conversion.
|
||||
pub(super) fn opaque_alpha(region: Region, fmt: PixelFormat) -> Region {
|
||||
if fmt.alpha {
|
||||
return region;
|
||||
}
|
||||
let n = fmt.channels();
|
||||
let mut out = Region::new(region.rect, n + 1);
|
||||
for (src, dst) in region.data.chunks_exact(n).zip(out.data.chunks_exact_mut(n + 1)) {
|
||||
if let Some(colors) = dst.get_mut(..n) {
|
||||
colors.copy_from_slice(src);
|
||||
}
|
||||
if let Some(alpha) = dst.last_mut() {
|
||||
*alpha = 1.0;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Clear only sampled rows/spans outside the source canvas, without another full pixel buffer.
|
||||
fn clip_canvas(region: &mut Region, bounds: Rect) {
|
||||
let n = region.ch;
|
||||
let row_values = region.width().saturating_mul(n);
|
||||
if row_values == 0 {
|
||||
return;
|
||||
}
|
||||
let x0 = i64::from(region.rect.x0);
|
||||
let x1 = i64::from(region.rect.x1);
|
||||
let left = (i64::from(bounds.x0).clamp(x0, x1) - x0) as usize;
|
||||
let right = (i64::from(bounds.x1).clamp(x0, x1) - x0) as usize;
|
||||
for (row_index, row) in region.data.chunks_exact_mut(row_values).enumerate() {
|
||||
let y = i64::from(region.rect.y0) + row_index as i64;
|
||||
if y < i64::from(bounds.y0) || y >= i64::from(bounds.y1) {
|
||||
row.fill(0.0);
|
||||
} else {
|
||||
if let Some(span) = row.get_mut(..left.saturating_mul(n)) {
|
||||
span.fill(0.0);
|
||||
}
|
||||
if let Some(span) = row.get_mut(right.saturating_mul(n)..) {
|
||||
span.fill(0.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert only the sampled region; preserve alpha and skip identical-profile HDR conversion.
|
||||
fn convert_region(region: Region, from: PixelFormat, to: PixelFormat, transform: Option<&Transform>, cmd: &str) -> Result<Region> {
|
||||
fn convert_region(mut region: Region, from: PixelFormat, to: PixelFormat, transform: Option<&Transform>, canvas: Option<Rect>, cmd: &str) -> Result<Region> {
|
||||
// A malformed document can contain a surface whose model disagrees with its ICC profile.
|
||||
// Check the native strides before the transform indexes them or its bounded scratch buffer.
|
||||
if transform.is_some_and(|t| t.inputs() != from.mode.color_channels() || t.outputs() != to.mode.color_channels() || t.outputs() > 16) {
|
||||
return Err(bad(cmd, "clone source color channels do not match the document profiles"));
|
||||
}
|
||||
let inside_canvas = canvas.is_none_or(|bounds| region.rect.intersect(&bounds) == region.rect);
|
||||
if transform.is_none() && from.mode == to.mode && from.alpha == to.alpha {
|
||||
if !inside_canvas && let Some(bounds) = canvas {
|
||||
clip_canvas(&mut region, bounds);
|
||||
}
|
||||
return Ok(region);
|
||||
}
|
||||
let mut out = Region::new(region.rect, to.channels());
|
||||
for (src, dst) in region.data.chunks_exact(from.channels()).zip(out.data.chunks_exact_mut(to.channels())) {
|
||||
let width = region.width();
|
||||
let canvas = canvas.filter(|_| !inside_canvas);
|
||||
for (i, (src, dst)) in region.data.chunks_exact(from.channels()).zip(out.data.chunks_exact_mut(to.channels())).enumerate() {
|
||||
// A surface without alpha is opaque inside its document canvas, including black
|
||||
// default pixels. Outside that canvas it has no sample, regardless of stored defaults.
|
||||
if let Some(bounds) = canvas {
|
||||
let x = i64::from(region.rect.x0) + (i % width) as i64;
|
||||
let y = i64::from(region.rect.y0) + (i / width) as i64;
|
||||
if x < i64::from(bounds.x0) || y < i64::from(bounds.y0) || x >= i64::from(bounds.x1) || y >= i64::from(bounds.y1) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if let Some(transform) = transform {
|
||||
let colors = to.mode.color_channels();
|
||||
let mut converted = [0.0; 16];
|
||||
@@ -147,7 +219,7 @@ pub(super) fn resolve(s: &Session, p: &Value, cmd: &str) -> Result<CloneFrom> {
|
||||
}
|
||||
}
|
||||
let transform = if external { color_transform(s, &st.doc, which, cmd)? } else { None };
|
||||
Ok(CloneFrom { other: external.then(|| (st.doc.clone(), st.revision)), layer, transform })
|
||||
Ok(CloneFrom { other: external.then(|| (st.doc.clone(), st.revision)), layer, transform, pixels: true })
|
||||
}
|
||||
|
||||
/// Choose the sampled pixel/composite profile and cache its conversion to the destination profile.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use super::*;
|
||||
use crate::presets::clone_source::Mapping;
|
||||
|
||||
/// Create a native colour-gradient source and an empty destination without re-picking.
|
||||
fn setup(depth: u64, mode: &str) -> (Session, LayerId, LayerId) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 64, "height": 64, "depth": depth, "mode": mode})).unwrap();
|
||||
@@ -25,14 +26,17 @@ fn setup(depth: u64, mode: &str) -> (Session, LayerId, LayerId) {
|
||||
(s, source, target)
|
||||
}
|
||||
|
||||
/// Read a layer as RGBA so assertions can compare different native depths and models.
|
||||
fn pixel(s: &Session, id: LayerId, x: i32, y: i32) -> [f32; 4] {
|
||||
s.active().unwrap().doc.layer(id).unwrap().surface().unwrap().rgba(x, y)
|
||||
}
|
||||
|
||||
/// Use one hard dab whose opacity and flow give twenty-percent centre coverage.
|
||||
fn params(wrap: bool) -> Value {
|
||||
json!({"points": [[48, 48]], "size": 12, "hardness": 100, "opacity": 50, "flow": 40, "wrap": wrap})
|
||||
}
|
||||
|
||||
/// A picked layer must remain the source through target switches and every rendering path.
|
||||
#[test]
|
||||
fn clone_current_layer_keeps_the_picked_source_for_preview_live_commit_and_undo() {
|
||||
for depth in [8, 16, 32] {
|
||||
@@ -68,6 +72,7 @@ fn clone_current_layer_keeps_the_picked_source_for_preview_live_commit_and_undo(
|
||||
}
|
||||
}
|
||||
|
||||
/// Missing source identities must fail atomically instead of sampling another layer.
|
||||
#[test]
|
||||
fn clone_deleted_source_and_invalid_source_layer_fail_without_edits() {
|
||||
let (mut s, source, target) = setup(8, "rgb");
|
||||
@@ -85,6 +90,7 @@ fn clone_deleted_source_and_invalid_source_layer_fail_without_edits() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Transparency is valid source data, and an explicit source-layer override takes precedence.
|
||||
#[test]
|
||||
fn clone_transparent_source_and_explicit_source_layer_are_respected() {
|
||||
let (mut s, source, target) = setup(16, "rgb");
|
||||
@@ -97,6 +103,7 @@ fn clone_transparent_source_and_explicit_source_layer_are_respected() {
|
||||
assert!((pixel(&s, target, 48, 48)[3] - 0.2).abs() < 0.01);
|
||||
}
|
||||
|
||||
/// Retaining Current Layer sources must preserve existing same-document composite sampling.
|
||||
#[test]
|
||||
fn clone_source_layer_does_not_change_composite_sampling_modes() {
|
||||
for which in ["currentAndBelow", "all"] {
|
||||
@@ -110,6 +117,7 @@ fn clone_source_layer_does_not_change_composite_sampling_modes() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Matching coordinates alone cannot authorize cached pixels from another sampled layer.
|
||||
#[test]
|
||||
fn clone_live_commit_rejects_a_changed_source_layer_with_the_same_coordinates() {
|
||||
let (mut s, _, target) = setup(8, "rgb");
|
||||
@@ -118,6 +126,7 @@ fn clone_live_commit_rejects_a_changed_source_layer_with_the_same_coordinates()
|
||||
assert!(s.offer_live_retouch(live).is_err());
|
||||
}
|
||||
|
||||
/// Re-picking after a return to the original layer updates local and cross-layer painting.
|
||||
#[test]
|
||||
fn clone_repicking_on_the_original_layer_updates_both_layers() {
|
||||
for depth in [8, 16, 32] {
|
||||
@@ -140,6 +149,7 @@ fn clone_repicking_on_the_original_layer_updates_both_layers() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Cross-document sampling must agree across previews, live pixels, replay and history.
|
||||
#[test]
|
||||
fn clone_sources_work_between_documents_with_preview_live_commit_and_undo() {
|
||||
for depth in [8, 16, 32] {
|
||||
@@ -174,6 +184,7 @@ fn clone_sources_work_between_documents_with_preview_live_commit_and_undo() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Compatible profiles convert through CMS while identical profiles preserve native ink values.
|
||||
#[test]
|
||||
fn clone_cross_document_matching_color_modes_and_profiles_use_cms() {
|
||||
use photocraft_cms::{Builtin, TransformOptions};
|
||||
@@ -213,6 +224,7 @@ fn clone_cross_document_matching_color_modes_and_profiles_use_cms() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Preview, live and committed painting must enforce the same documented mode compatibility.
|
||||
#[test]
|
||||
fn clone_and_heal_cross_document_mode_compatibility_matches_preview_live_and_commit() {
|
||||
for from in ["rgb", "gray", "cmyk", "lab"] {
|
||||
@@ -241,6 +253,7 @@ fn clone_and_heal_cross_document_mode_compatibility_matches_preview_live_and_com
|
||||
}
|
||||
}
|
||||
|
||||
/// Frozen pixels cannot survive source edits or closure; fresh replay must sample current data.
|
||||
#[test]
|
||||
fn clone_closed_source_document_and_stale_live_pixels_fail_gracefully() {
|
||||
let (mut s, source, _) = setup(8, "rgb");
|
||||
@@ -272,6 +285,7 @@ fn clone_closed_source_document_and_stale_live_pixels_fail_gracefully() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A persisted document ID must not accidentally revive an already-closed clone source.
|
||||
#[test]
|
||||
fn clone_closed_source_cannot_be_revived_by_reopening_a_saved_copy() {
|
||||
let (mut s, source, _) = setup(8, "rgb");
|
||||
@@ -298,6 +312,7 @@ fn clone_closed_source_cannot_be_revived_by_reopening_a_saved_copy() {
|
||||
assert!((got[3] - 0.2).abs() < 0.01);
|
||||
}
|
||||
|
||||
/// New source identities must coexist with older slots that never stored a document ID.
|
||||
#[test]
|
||||
fn clone_source_document_json_and_legacy_slots_are_compatible() {
|
||||
let (mut s, _, _) = setup(8, "rgb");
|
||||
@@ -310,6 +325,7 @@ fn clone_source_document_json_and_legacy_slots_are_compatible() {
|
||||
assert!(old.document.is_none());
|
||||
}
|
||||
|
||||
/// Every slot reply keeps stable identity while open-tab indexes may change.
|
||||
#[test]
|
||||
fn clone_source_replies_keep_document_identity_when_resetting_transforms() {
|
||||
let (mut s, _, _) = setup(8, "rgb");
|
||||
@@ -336,6 +352,7 @@ fn clone_source_replies_keep_document_identity_when_resetting_transforms() {
|
||||
assert_eq!(reset["documentId"], json!(document_id));
|
||||
}
|
||||
|
||||
/// Source conversion must preserve float light above white and distinguish absent/stored alpha.
|
||||
#[test]
|
||||
fn clone_between_documents_preserves_float_hdr_and_source_alpha() {
|
||||
for alpha in [false, true] {
|
||||
@@ -355,6 +372,7 @@ fn clone_between_documents_preserves_float_hdr_and_source_alpha() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Unsupported external mask destinations must refuse without modifying their document.
|
||||
#[test]
|
||||
fn clone_cross_document_mask_targets_refuse_instead_of_sampling_the_wrong_document() {
|
||||
let (mut s, _, _) = setup(8, "rgb");
|
||||
@@ -368,6 +386,7 @@ fn clone_cross_document_mask_targets_refuse_instead_of_sampling_the_wrong_docume
|
||||
assert_eq!(s.active().unwrap().doc, before);
|
||||
}
|
||||
|
||||
/// Malformed document/layer colour models must produce ordinary errors before pixel edits.
|
||||
#[test]
|
||||
fn clone_cross_document_mismatched_surface_models_fail_without_panicking_or_editing() {
|
||||
for change_source in [true, false] {
|
||||
@@ -390,6 +409,7 @@ fn clone_cross_document_mismatched_surface_models_fail_without_panicking_or_edit
|
||||
}
|
||||
}
|
||||
|
||||
/// All four finite canvas edges must agree across sampling modes, depths and rendering paths.
|
||||
#[test]
|
||||
fn clone_source_edges_clip_preview_live_and_committed_stamps() {
|
||||
for depth in [8, 16, 32] {
|
||||
@@ -441,6 +461,7 @@ fn clone_source_edges_clip_preview_live_and_committed_stamps() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Missing source pixels must leave previously painted destination colours intact.
|
||||
#[test]
|
||||
fn clone_clipped_source_preserves_existing_destination_pixels_on_the_original_layer() {
|
||||
let (mut s, source, _) = setup(16, "rgb");
|
||||
@@ -461,6 +482,7 @@ fn clone_clipped_source_preserves_existing_destination_pixels_on_the_original_la
|
||||
}
|
||||
}
|
||||
|
||||
/// Periodic sampling uses source dimensions even when the destination canvas is larger.
|
||||
#[test]
|
||||
fn clone_pattern_preview_wraps_at_the_source_document_edges() {
|
||||
let (mut s, source, _) = setup(16, "rgb");
|
||||
@@ -476,6 +498,7 @@ fn clone_pattern_preview_wraps_at_the_source_document_edges() {
|
||||
assert_eq!(pixel(&s, target, 50, 48), want, "wrapping uses the 64 px source canvas, not the 80 px destination");
|
||||
}
|
||||
|
||||
/// Exercise the real five-thousand-pixel limit on a twenty-four-megapixel destination.
|
||||
#[test]
|
||||
#[ignore = "allocates full 5,000 px clone coverage and pixel buffers; run explicitly with one test thread"]
|
||||
fn clone_maximum_size_stamp_keeps_straight_source_edges() {
|
||||
@@ -499,6 +522,7 @@ fn clone_maximum_size_stamp_keeps_straight_source_edges() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Unaligned strokes update their readout without turning that report into an aligned origin.
|
||||
#[test]
|
||||
fn clone_offsets_report_each_unaligned_stroke_without_persisting_its_alignment() {
|
||||
for depth in [8, 16, 32] {
|
||||
@@ -515,6 +539,7 @@ fn clone_offsets_report_each_unaligned_stroke_without_persisting_its_alignment()
|
||||
}
|
||||
}
|
||||
|
||||
/// Mode changes preserve aligned sampling while numeric edits use the pairing being reported.
|
||||
#[test]
|
||||
fn clone_offsets_follow_mode_toggles_and_manual_edits_use_the_reported_pairing() {
|
||||
for depth in [8, 16, 32] {
|
||||
@@ -539,6 +564,7 @@ fn clone_offsets_follow_mode_toggles_and_manual_edits_use_the_reported_pairing()
|
||||
}
|
||||
}
|
||||
|
||||
/// An offset edit has an explicit reference and cannot partially mutate slots on invalid input.
|
||||
#[test]
|
||||
fn clone_offsets_accept_a_preview_reference_and_reject_invalid_points_atomically() {
|
||||
let (mut s, _, _) = setup(16, "rgb");
|
||||
@@ -559,6 +585,7 @@ fn clone_offsets_accept_a_preview_reference_and_reject_invalid_points_atomically
|
||||
}
|
||||
}
|
||||
|
||||
/// Only successful slot-based painting may record a source pairing.
|
||||
#[test]
|
||||
fn clone_offsets_do_not_record_previews_failed_strokes_or_explicit_command_sources() {
|
||||
for cmd in ["paint.cloneStamp", "paint.healingBrush"] {
|
||||
@@ -591,6 +618,7 @@ fn clone_offsets_do_not_record_previews_failed_strokes_or_explicit_command_sourc
|
||||
}
|
||||
}
|
||||
|
||||
/// Old slots remain readable; re-picking clears pairings and invalid slot indexes fail safely.
|
||||
#[test]
|
||||
fn clone_offsets_keep_legacy_pairings_and_clear_readouts_when_a_source_is_repicked() {
|
||||
let (mut s, source, _) = setup(16, "rgb");
|
||||
@@ -617,6 +645,7 @@ fn clone_offsets_keep_legacy_pairings_and_clear_readouts_when_a_source_is_repick
|
||||
assert!(matches!(s.execute("cloneSource.resetTransform", json!({})), Err(EngineError::BadParams { .. })));
|
||||
}
|
||||
|
||||
/// A small destination dab must not request an unbounded transformed source buffer.
|
||||
#[test]
|
||||
fn clone_offsets_scaled_source_reads_are_bounded_before_allocation() {
|
||||
for cmd in ["paint.cloneStamp", "paint.healingBrush"] {
|
||||
@@ -630,6 +659,7 @@ fn clone_offsets_scaled_source_reads_are_bounded_before_allocation() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Null optional fields must not silently change document selection or source transforms.
|
||||
#[test]
|
||||
fn clone_offsets_null_optional_coordinates_keep_the_picked_source_document() {
|
||||
for depth in [8, 16, 32] {
|
||||
@@ -648,6 +678,7 @@ fn clone_offsets_null_optional_coordinates_keep_the_picked_source_document() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Extreme affine source coordinates must resolve to missing pixels without overflow or NaN.
|
||||
#[test]
|
||||
fn clone_and_heal_transformed_far_sources_are_finite_and_preserve_the_destination() {
|
||||
for depth in [8, 16, 32] {
|
||||
@@ -669,3 +700,164 @@ fn clone_and_heal_transformed_far_sources_are_finite_and_preserve_the_destinatio
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Build equivalent opaque sources with/without stored alpha, using quantized fixture colours.
|
||||
fn no_alpha_scene(depth: u64, mode: &str, source_alpha: bool, target_alpha: bool, external: bool, at: [i32; 2], color: [f32; 4]) -> (Session, LayerId) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 64, "height": 64, "depth": depth, "mode": mode})).unwrap();
|
||||
let source = s.active().unwrap().active_layer.unwrap();
|
||||
s.edit("opaque source", |doc, _| {
|
||||
let bounds = doc.bounds();
|
||||
let surf = doc.layer_mut(source).unwrap().surface_mut().unwrap();
|
||||
let fmt = PixelFormat::new(surf.format().mode, surf.format().sample, source_alpha);
|
||||
let mut quantized = Surface::new(fmt);
|
||||
quantized.write_region(Rect::new(0, 0, 1, 1), &photocraft_raster::from_rgba(&fmt, color));
|
||||
let values = quantized.read_region(Rect::new(0, 0, 1, 1));
|
||||
*surf = if source_alpha {
|
||||
let mut finite = Surface::new(fmt);
|
||||
finite.fill_rect(bounds, &values);
|
||||
finite
|
||||
} else {
|
||||
Surface::with_default(fmt, &values)
|
||||
};
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("cloneSource.set", json!({"source": at})).unwrap();
|
||||
if external {
|
||||
s.execute("file.new", json!({"width": 80, "height": 80, "depth": depth, "mode": mode})).unwrap();
|
||||
}
|
||||
s.execute("layer.new.layer", json!({})).unwrap();
|
||||
let target = s.active().unwrap().active_layer.unwrap();
|
||||
s.edit("blue destination", |doc, _| {
|
||||
let surf = doc.layer_mut(target).unwrap().surface_mut().unwrap();
|
||||
let fmt = PixelFormat::new(surf.format().mode, surf.format().sample, target_alpha);
|
||||
let mut quantized = Surface::new(fmt);
|
||||
quantized.write_region(Rect::new(0, 0, 1, 1), &photocraft_raster::from_rgba(&fmt, [0.0, 0.0, 1.0, 1.0]));
|
||||
*surf = Surface::with_default(fmt, &quantized.read_region(Rect::new(0, 0, 1, 1)));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
(s, target)
|
||||
}
|
||||
|
||||
/// Compare native values with an opaque alpha-bearing reference at the same colour/depth.
|
||||
fn assert_opaque_reference(actual: &Surface, expected: &Surface, rect: Rect) {
|
||||
let (n, en) = (actual.channels(), expected.channels());
|
||||
for (i, (a, e)) in actual.read_region(rect).chunks_exact(n).zip(expected.read_region(rect).chunks_exact(en)).enumerate() {
|
||||
assert_eq!(a, &e[..n], "native pixel {i}, {:?}", actual.format());
|
||||
}
|
||||
}
|
||||
|
||||
/// Canvas coverage is independent of stored alpha, including opaque black and wrapped sources.
|
||||
#[test]
|
||||
fn clone_no_alpha_sources_clip_preview_live_and_commit_at_all_canvas_corners() {
|
||||
for depth in [8, 16, 32] {
|
||||
for mode in ["rgb", "gray", "cmyk", "lab"] {
|
||||
for target_alpha in [false, true] {
|
||||
for external in [false, true] {
|
||||
for wrap in [false, true] {
|
||||
for at in [[0, 0], [63, 0], [0, 63], [63, 63]] {
|
||||
let color = if at[0] == at[1] { [0.0, 0.0, 0.0, 1.0] } else { [1.0, 0.0, 0.0, 1.0] };
|
||||
let (mut actual, target) = no_alpha_scene(depth, mode, false, target_alpha, external, at, color);
|
||||
let (mut reference, expected) = no_alpha_scene(depth, mode, true, true, external, at, color);
|
||||
let initial = actual.active().unwrap().doc.layer(target).unwrap().surface().unwrap().clone();
|
||||
let fmt = initial.format();
|
||||
let map = Mapping { source: (at[0] as f64, at[1] as f64), anchor: (32.0, 32.0), m: [1.0, 0.0, 0.0, 1.0] };
|
||||
let roi = Rect::new(24, 24, 40, 40);
|
||||
let shown = clone_preview_periodic(&actual, roi, &map, "current", wrap).unwrap();
|
||||
let wanted = clone_preview_periodic(&reference, roi, &map, "current", wrap).unwrap();
|
||||
for (i, (a, e)) in shown.px.iter().zip(&wanted.px).enumerate() {
|
||||
assert_eq!(a, e, "preview {i}: {depth}/{mode}/{target_alpha}/{external}/{wrap}/{at:?}");
|
||||
}
|
||||
let p = json!({"points": [[32,32]], "size": 12, "hardness": 100, "opacity": 50, "flow": 40, "wrap": wrap});
|
||||
reference.execute("paint.cloneStamp", p.clone()).unwrap();
|
||||
let expected_surf = reference.active().unwrap().doc.layer(expected).unwrap().surface().unwrap();
|
||||
let live = LiveRetouch::begin(&actual, "paint.cloneStamp", &p).unwrap();
|
||||
assert_opaque_reference(live.doc.layer(target).unwrap().surface().unwrap(), expected_surf, roi);
|
||||
actual.offer_live_retouch(live).unwrap();
|
||||
assert_eq!(actual.execute("paint.cloneStamp", p.clone()).unwrap()["fromLive"], true);
|
||||
assert_opaque_reference(actual.active().unwrap().doc.layer(target).unwrap().surface().unwrap(), expected_surf, roi);
|
||||
assert!(actual.undo());
|
||||
actual.execute("paint.cloneStamp", p).unwrap();
|
||||
let surf = actual.active().unwrap().doc.layer(target).unwrap().surface().unwrap();
|
||||
assert_eq!(surf.format(), fmt, "cloning must retain the destination's native format");
|
||||
assert_opaque_reference(surf, expected_surf, roi);
|
||||
if !wrap {
|
||||
let x = if at[0] == 0 { 31 } else { 33 };
|
||||
let y = if at[1] == 0 { 31 } else { 33 };
|
||||
let outside = Rect::new(x, y, x + 1, y + 1);
|
||||
assert_eq!(surf.read_region(outside), initial.read_region(outside), "missing source leaves destination pixels intact");
|
||||
assert_eq!(shown.px[((y - 24) * 16 + x - 24) as usize][3], 0.0);
|
||||
}
|
||||
let inside = Rect::new(32, 32, 33, 33);
|
||||
assert_ne!(surf.read_region(inside), initial.read_region(inside), "opaque black must paint inside the source canvas");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Affine filtering, blend modes and source composites retain alpha-bearing source coverage.
|
||||
#[test]
|
||||
fn clone_no_alpha_sources_match_alpha_sources_with_transforms_and_composites() {
|
||||
for mode in ["rgb", "cmyk"] {
|
||||
for which in ["current", "currentAndBelow", "all"] {
|
||||
for blend in ["normal", "multiply", "lighten"] {
|
||||
for wrap in [false, true] {
|
||||
let color = if blend == "normal" { [0.0, 0.0, 0.0, 1.0] } else { [1.0, 0.25, 0.75, 1.0] };
|
||||
let (mut actual, target) = no_alpha_scene(32, mode, false, false, true, [0, 0], color);
|
||||
let (mut reference, expected) = no_alpha_scene(32, mode, true, true, true, [0, 0], color);
|
||||
for session in [&mut actual, &mut reference] {
|
||||
session.execute("cloneSource.set", json!({"width": 150, "height": 75, "rotation": 30, "flipH": true})).unwrap();
|
||||
}
|
||||
let p =
|
||||
json!({"points": [[32,32]], "size": 12, "hardness": 100, "opacity": 50, "flow": 40, "sampleLayer": which, "mode": blend, "wrap": wrap});
|
||||
let (map, _) = crate::presets::clone_source::resolve(&actual, &p, (32.0, 32.0), "paint.cloneStamp").unwrap();
|
||||
let roi = Rect::new(24, 24, 40, 40);
|
||||
let preview = clone_preview_periodic(&actual, roi, &map, which, wrap).unwrap();
|
||||
let wanted = clone_preview_periodic(&reference, roi, &map, which, wrap).unwrap();
|
||||
for (a, e) in preview.px.iter().zip(&wanted.px) {
|
||||
assert_eq!(a, e, "{mode}/{which}/{blend}/{wrap}");
|
||||
}
|
||||
reference.execute("paint.cloneStamp", p.clone()).unwrap();
|
||||
let expected_surf = reference.active().unwrap().doc.layer(expected).unwrap().surface().unwrap();
|
||||
let live = LiveRetouch::begin(&actual, "paint.cloneStamp", &p).unwrap();
|
||||
assert_opaque_reference(live.doc.layer(target).unwrap().surface().unwrap(), expected_surf, roi);
|
||||
actual.offer_live_retouch(live).unwrap();
|
||||
assert_eq!(actual.execute("paint.cloneStamp", p.clone()).unwrap()["fromLive"], true);
|
||||
assert!(actual.undo());
|
||||
actual.execute("paint.cloneStamp", p).unwrap();
|
||||
assert_opaque_reference(actual.active().unwrap().doc.layer(target).unwrap().surface().unwrap(), expected_surf, roi);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The shared Healing Brush sampler keeps opaque destinations equivalent to alpha-bearing ones.
|
||||
#[test]
|
||||
fn clone_no_alpha_healing_sources_match_alpha_sources_in_preview_and_commit() {
|
||||
for depth in [16, 32] {
|
||||
for which in ["current", "currentAndBelow", "all"] {
|
||||
for wrap in [false, true] {
|
||||
let (mut actual, target) = no_alpha_scene(depth, "rgb", false, false, true, [0, 0], [0.5, 0.5, 0.5, 1.0]);
|
||||
let (mut reference, expected) = no_alpha_scene(depth, "rgb", true, true, true, [0, 0], [0.5, 0.5, 0.5, 1.0]);
|
||||
let p = json!({"points": [[32,32]], "size": 12, "hardness": 100, "sampleLayer": which, "wrap": wrap});
|
||||
let roi = Rect::new(24, 24, 40, 40);
|
||||
let live = LiveRetouch::begin(&actual, "paint.healingBrush", &p).unwrap();
|
||||
let expected_live = LiveRetouch::begin(&reference, "paint.healingBrush", &p).unwrap();
|
||||
assert_opaque_reference(live.doc.layer(target).unwrap().surface().unwrap(), expected_live.doc.layer(expected).unwrap().surface().unwrap(), roi);
|
||||
actual.execute("paint.healingBrush", p.clone()).unwrap();
|
||||
reference.execute("paint.healingBrush", p).unwrap();
|
||||
assert_opaque_reference(
|
||||
actual.active().unwrap().doc.layer(target).unwrap().surface().unwrap(),
|
||||
reference.active().unwrap().doc.layer(expected).unwrap().surface().unwrap(),
|
||||
roi,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::clone::{blend_param, clamp_samples, clone_mapping, clone_result, clone_sample};
|
||||
use super::clone::{apply_clone_coverage, blend_param, clamp_samples, clone_mapping, clone_result, clone_sample};
|
||||
use super::periodic;
|
||||
use super::sampling::{SampleLayers, composite_region, sample_all_layers, sample_layers};
|
||||
use super::{
|
||||
@@ -44,6 +44,7 @@ pub(super) fn heal_region(fmt: &PixelFormat, src: &Region, dst: &Region, mask: &
|
||||
out
|
||||
}
|
||||
|
||||
/// Fit the sampled texture to the destination using matching native channels and source coverage.
|
||||
pub(super) fn healing_brush(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "paint.healingBrush";
|
||||
let (stroke, id) = parse_brush(s, p, CMD)?;
|
||||
@@ -60,7 +61,7 @@ pub(super) fn healing_brush(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let wrap = flag(p, "wrap", false);
|
||||
let (bounds, cov) = coverage(CMD, &stroke)?;
|
||||
let (g, cov) = pad_coverage(bounds, &cov, 2);
|
||||
let fmt = surf.format();
|
||||
let fmt = source.sample_format(surf);
|
||||
let src = clone_sample(pre, id, surf, which, &source, g, &map, wrap, CMD)?;
|
||||
// The destination the texture is fitted to: the layer itself, or what the user sees when
|
||||
// sampling several layers (so healing onto an empty layer matches the composite).
|
||||
@@ -69,17 +70,18 @@ pub(super) fn healing_brush(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else if which == SampleLayers::Current {
|
||||
Region::read(surf, g)
|
||||
} else {
|
||||
composite_region(pre, id, which, g, fmt)
|
||||
composite_region(pre, id, which, g, surf.format())
|
||||
};
|
||||
let dst = if fmt.alpha && !surf.format().alpha { super::clone_sampling::opaque_alpha(dst, surf.format()) } else { dst };
|
||||
let mask: Vec<bool> = cov.iter().map(|c| *c > 0.0).collect();
|
||||
let healed = heal_region(&fmt, &src, &dst, &mask);
|
||||
if wrap {
|
||||
return periodic::stroke(pre, surf, &stroke, sel, lock, mode, CMD, |_, r| {
|
||||
return periodic::stroke(pre, surf, &stroke, sel, lock, mode, CMD, fmt, |_, r| {
|
||||
let part = healed.crop(r);
|
||||
if part.rect == r { Ok(part) } else { Err(bad(CMD, "the healed patch does not cover the stroke")) }
|
||||
});
|
||||
}
|
||||
Ok(apply_coverage(surf, g, &cov, stroke.brush.opacity, sel, lock, &healed, mode))
|
||||
Ok(apply_clone_coverage(surf, g, &cov, stroke.brush.opacity, sel, lock, &healed, mode))
|
||||
})?;
|
||||
crate::presets::clone_source::remember_mapping(s, p, &map);
|
||||
Ok(clone_result(dmg, off, aligned, p, &stroke))
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Bounded reads from the repeating document tile used by Pattern Preview.
|
||||
|
||||
use super::{BlendMode, BrushSettings, Document, LayerId, Rect, Region, Result, SampleLayers, Stroke, StrokePoint, Surface, alpha_index, apply_coverage, bad};
|
||||
use super::clone::apply_clone_coverage;
|
||||
use super::{BlendMode, BrushSettings, Document, LayerId, PixelFormat, Rect, Region, Result, SampleLayers, Stroke, StrokePoint, Surface, alpha_index, bad};
|
||||
|
||||
/// At most four disjoint rectangles in the document tile. Projecting the dirty area separately
|
||||
/// from the stroke bounds avoids scanning the whole document when a small dab crosses a seam.
|
||||
@@ -35,6 +36,7 @@ pub(super) fn stroke(
|
||||
lock: bool,
|
||||
mode: BlendMode,
|
||||
cmd: &str,
|
||||
paint_format: PixelFormat,
|
||||
mut paint: impl FnMut(&Surface, Rect) -> Result<Region>,
|
||||
) -> Result<Rect> {
|
||||
let mut renderer = photocraft_paint::StrokeRenderer::new(&stroke.brush, None, 1.0);
|
||||
@@ -42,7 +44,7 @@ pub(super) fn stroke(
|
||||
renderer.finish();
|
||||
let before = target.clone();
|
||||
let bounds = renderer.bounds();
|
||||
Composite { target, before: &before, tile: pre.bounds(), opacity: stroke.brush.opacity, selection, lock, mode, cmd }.draw(
|
||||
Composite { target, before: &before, tile: pre.bounds(), opacity: stroke.brush.opacity, selection, lock, mode, cmd, paint_format }.draw(
|
||||
bounds,
|
||||
&stroke.brush,
|
||||
&stroke.points,
|
||||
@@ -63,9 +65,12 @@ pub(super) struct Composite<'a> {
|
||||
pub mode: BlendMode,
|
||||
/// The command an over-budget stroke's error names.
|
||||
pub cmd: &'a str,
|
||||
/// The sampled native channels, including temporary coverage for opaque pixel layers.
|
||||
pub paint_format: PixelFormat,
|
||||
}
|
||||
|
||||
impl Composite<'_> {
|
||||
/// Fold dabs into bounded destination patches before applying selection, opacity and blending.
|
||||
pub fn draw(&mut self, dirty: Rect, brush: &BrushSettings, points: &[StrokePoint], mut paint: impl FnMut(Rect) -> Result<Region>) -> Result<Rect> {
|
||||
let ctx = photocraft_paint::BrushContext::new(brush);
|
||||
let mut generator = photocraft_paint::dynamics::DabGenerator::new(brush, 1.0);
|
||||
@@ -96,9 +101,9 @@ impl Composite<'_> {
|
||||
while x < rect.x1 {
|
||||
let x1 = x.saturating_add(64).min(rect.x1);
|
||||
let dst = Rect::new(x, y, x1, y1);
|
||||
let mut stroke = PatchStroke::new(dst, self.target.channels());
|
||||
let mut stroke = PatchStroke::new(dst, self.paint_format.channels());
|
||||
let mut dual_stroke = PatchStroke::new(dst, 1);
|
||||
let alpha = alpha_index(&self.target.format());
|
||||
let alpha = alpha_index(&self.paint_format);
|
||||
for (dab, bounds) in &primary {
|
||||
if !project(*bounds, self.tile).iter().any(|r| !r.intersect(&dst).is_empty()) {
|
||||
continue;
|
||||
@@ -127,7 +132,7 @@ impl Composite<'_> {
|
||||
}
|
||||
}
|
||||
self.target.write_region(dst, &self.before.read_region(dst));
|
||||
apply_coverage(self.target, dst, &stroke.coverage, self.opacity, self.selection, self.lock, &stroke.paint, self.mode);
|
||||
apply_clone_coverage(self.target, dst, &stroke.coverage, self.opacity, self.selection, self.lock, &stroke.paint, self.mode);
|
||||
damage = damage.union(&dst);
|
||||
x = x1;
|
||||
}
|
||||
@@ -138,6 +143,7 @@ impl Composite<'_> {
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
/// Gather one dab's periodic copies using its strongest coverage at each destination pixel.
|
||||
fn fold_dab(
|
||||
&self,
|
||||
ctx: &photocraft_paint::BrushContext,
|
||||
@@ -148,7 +154,7 @@ impl Composite<'_> {
|
||||
paint: &mut impl FnMut(Rect) -> Result<Region>,
|
||||
work: &mut u64,
|
||||
) -> Result<PatchStroke> {
|
||||
let mut result = PatchStroke::new(dst, if dual { 1 } else { self.target.channels() });
|
||||
let mut result = PatchStroke::new(dst, if dual { 1 } else { self.paint_format.channels() });
|
||||
let (w, h) = (i64::from(self.tile.width()), i64::from(self.tile.height()));
|
||||
let nx0 = (i64::from(bounds.x0) - i64::from(dst.x1)).div_euclid(w) + 1;
|
||||
let nx1 = (i64::from(bounds.x1) - 1 - i64::from(dst.x0)).div_euclid(w);
|
||||
@@ -217,6 +223,7 @@ impl PatchStroke {
|
||||
Self { coverage: vec![0.0; len], depth: vec![0.0; len], paint: Region::new(rect, channels) }
|
||||
}
|
||||
|
||||
/// Accumulate flow-weighted, premultiplied native colours and independent source alpha.
|
||||
fn accumulate(&mut self, dab: &photocraft_paint::Dab, footprint: &PatchStroke, alpha: Option<usize>) {
|
||||
let rect = self.paint.rect;
|
||||
for y in rect.y0..rect.y1 {
|
||||
@@ -245,6 +252,7 @@ impl PatchStroke {
|
||||
}
|
||||
}
|
||||
|
||||
/// Recover straight colours while keeping stroke coverage separate from source alpha.
|
||||
fn normalize(&mut self, alpha: Option<usize>) {
|
||||
let rect = self.paint.rect;
|
||||
for y in rect.y0..rect.y1 {
|
||||
|
||||
@@ -355,6 +355,7 @@ fn slot_json(s: &Session, i: usize) -> Value {
|
||||
result
|
||||
}
|
||||
|
||||
/// Report all slot geometry and stable identities with their current open-document indexes.
|
||||
fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let c = &s.presets.clone;
|
||||
Ok(
|
||||
@@ -362,6 +363,7 @@ fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
)
|
||||
}
|
||||
|
||||
/// Select a validated slot without changing its source, pairing or transform.
|
||||
fn select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "cloneSource.select";
|
||||
p.get("index").filter(|v| !v.is_null()).ok_or_else(|| bad(CMD, "missing `index`"))?;
|
||||
@@ -370,6 +372,7 @@ fn select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(slot_json(s, i))
|
||||
}
|
||||
|
||||
/// Validate a source/transform edit atomically, using the displayed reference for numeric offsets.
|
||||
fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "cloneSource.set";
|
||||
let i = index(s, p, CMD)?;
|
||||
@@ -457,6 +460,7 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(slot_json(s, i))
|
||||
}
|
||||
|
||||
/// Reset scale/rotation/flips while retaining source identity and established pairings.
|
||||
fn reset_transform(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let i = index(s, p, "cloneSource.resetTransform")?;
|
||||
let slot = &mut s.presets.clone.slots[i];
|
||||
@@ -464,6 +468,7 @@ fn reset_transform(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(slot_json(s, i))
|
||||
}
|
||||
|
||||
/// Update transient overlay appearance without editing image pixels or source geometry.
|
||||
fn overlay(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let o = &mut s.presets.clone.overlay;
|
||||
let flag = |k: &str| p.get(k).and_then(Value::as_bool);
|
||||
|
||||
@@ -2,6 +2,7 @@ use super::*;
|
||||
use crate::canvas::{Drag, ToolEvent, tool_event};
|
||||
use photocraft_engine::Session;
|
||||
|
||||
/// Create two distinguishable source colours and an empty layer for real mouse strokes.
|
||||
fn app() -> PhotocraftApp {
|
||||
let mut app = PhotocraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 64, "height": 64})).unwrap();
|
||||
@@ -15,6 +16,7 @@ fn app() -> PhotocraftApp {
|
||||
app
|
||||
}
|
||||
|
||||
/// Exercise the same Down/Up path used by canvas interaction.
|
||||
fn stamp(app: &mut PhotocraftApp, at: [f64; 2]) {
|
||||
remember_clone_cursor(app, at);
|
||||
tool_event(app, ToolEvent::Down { x: at[0], y: at[1], pressure: 1.0 }, egui::Modifiers::NONE);
|
||||
@@ -22,6 +24,7 @@ fn stamp(app: &mut PhotocraftApp, at: [f64; 2]) {
|
||||
assert!(!app.ui.status_error, "{}", app.ui.status);
|
||||
}
|
||||
|
||||
/// Hover may change a displayed pairing but cannot alter source state or document revision.
|
||||
#[test]
|
||||
fn clone_offset_hover_readout_does_not_establish_a_painting_anchor() {
|
||||
for aligned in [false, true] {
|
||||
@@ -38,6 +41,7 @@ fn clone_offset_hover_readout_does_not_establish_a_painting_anchor() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Entering the panel must retain the last canvas reference for a numeric offset edit.
|
||||
#[test]
|
||||
fn clone_offset_edit_before_painting_uses_the_preview_reference_and_matches_pixels() {
|
||||
for aligned in [false, true] {
|
||||
@@ -56,6 +60,7 @@ fn clone_offset_edit_before_painting_uses_the_preview_reference_and_matches_pixe
|
||||
}
|
||||
}
|
||||
|
||||
/// Reporting an unaligned stroke must not discard the established aligned sampling origin.
|
||||
#[test]
|
||||
fn clone_offset_readout_tracks_aligned_mode_without_replacing_its_saved_anchor() {
|
||||
let mut app = app();
|
||||
@@ -73,6 +78,7 @@ fn clone_offset_readout_tracks_aligned_mode_without_replacing_its_saved_anchor()
|
||||
assert_eq!(app.session.presets.clone.active().anchor, original_anchor);
|
||||
}
|
||||
|
||||
/// A slot switch changes the source; a cursor from another destination cannot set its reference.
|
||||
#[test]
|
||||
fn clone_offset_readout_uses_the_selected_slot_and_destination_document() {
|
||||
let mut app = app();
|
||||
@@ -94,6 +100,7 @@ fn clone_offset_readout_uses_the_selected_slot_and_destination_document() {
|
||||
assert_eq!(clone_offset_readout(&app), Some([0.0, 0.0]), "a cursor from another document cannot become this one's reference");
|
||||
}
|
||||
|
||||
/// The marker and readout use the same scaled, rotated or flipped mapping as sampling.
|
||||
#[test]
|
||||
fn clone_offsets_share_transformed_sampling_geometry_during_a_stroke() {
|
||||
for (transform, want) in [
|
||||
@@ -116,6 +123,7 @@ fn clone_offsets_share_transformed_sampling_geometry_during_a_stroke() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Invalid cursor positions and restored UI state must not invent a preview reference.
|
||||
#[test]
|
||||
fn clone_offset_cursor_is_transient_and_rejects_nonfinite_positions() {
|
||||
let mut app = app();
|
||||
@@ -131,6 +139,7 @@ fn clone_offset_cursor_is_transient_and_rejects_nonfinite_positions() {
|
||||
assert!(restored.clone_cursor.is_none());
|
||||
}
|
||||
|
||||
/// View zoom changes screen geometry while document-space displacement remains constant.
|
||||
#[test]
|
||||
fn clone_offset_readout_is_in_document_pixels_at_different_canvas_zooms() {
|
||||
let mut app = app();
|
||||
|
||||
@@ -549,6 +549,7 @@ pub fn tool_presets_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
|
||||
// ------------------------------------------------------------------ Clone Source
|
||||
|
||||
/// Display source identity and edit the resolved pairing/transform through engine commands.
|
||||
pub fn clone_source_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let cs = app.session.presets.clone.clone();
|
||||
|
||||
@@ -124,7 +124,7 @@ tablets against Photoshop side by side.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-11 | minor | Clone sources retain their document/layer across target switches, including a return to re-pick on the original layer; ICC conversion between documents, source-aware preview caching and closed-source errors. Hover previews respect Clone Stamp opacity and flow. Source-edge regressions cover all four corners, 8/16/32-bit, same/cross-document sampling and Pattern Preview; an explicit 5,000 px hard stamp passes. Recorded the remaining 5,000 px soft-brush mouse/replay inconsistency. Clone Source X/Y now report the preview or last successful pairing independently of Aligned state; numeric edits use the same reference, with slot/document/transform and failure regressions. Invalid/null coordinate handling and bounded transformed reads are covered. Cross-document mode compatibility follows the Adobe reference, including the Healing Brush Grayscale exception. Far affine samples no longer overflow bilinear neighbour coordinates or introduce NaN alpha. No estimate or parity percentage changed. |
|
||||
| 2026-11-11 | minor | Clone sources retain their document/layer across target switches, including a return to re-pick on the original layer; ICC conversion between documents, source-aware preview caching and closed-source errors. Hover previews respect Clone Stamp opacity and flow. Source-edge regressions cover all four corners, 8/16/32-bit, same/cross-document sampling and Pattern Preview; an explicit 5,000 px hard stamp passes. Recorded the remaining 5,000 px soft-brush mouse/replay inconsistency. Clone Source X/Y now report the preview or last successful pairing independently of Aligned state; numeric edits use the same reference, with slot/document/transform and failure regressions. Invalid/null coordinate handling and bounded transformed reads are covered. Cross-document mode compatibility follows the Adobe reference, including the Healing Brush Grayscale exception. Far affine samples no longer overflow bilinear neighbour coordinates or introduce NaN alpha. Source canvas coverage is preserved for no-alpha sources and destinations across preview, live and committed painting; native storage formats remain unchanged. No estimate or parity percentage changed. |
|
||||
| 2026-11-06 | minor | Eraser end of the pen switches to the Eraser on Windows with Windows Ink on (#2285); row stays partial (X11, web); no estimate changed |
|
||||
| 2026-10-30 | minor | Art History Brush Opacity on the options bar, #10263; no estimate changed |
|
||||
| 2026-10-25 | minor | Art History Brush row added as partial (8 of 10 styles, TOOL-213-20, #1610). No brush-feel estimate changed. |
|
||||
|
||||
@@ -59,7 +59,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i
|
||||
- `select.findLayers` (#10884, Select › Find Layers) filters the Layers panel by Name and selects none of the matches; as with any filter, a selected layer the filter hides is deselected (#10879). With `name` it sets the Name text; without it the text is kept. Through `engine.execute` or an action step that is all; through the menu, the shortcut or `ui.menu.invoke` without `name`, the Layers panel is also shown and its Name field takes the keyboard focus with the text selected (unless Filter Options › Hide hid the filter row, which stays hidden). The reply lists the ids of the layers the Name text matches in `selected` (trimmed, ignoring case: a blank text lists every layer, a text nothing matches none) and the Name filter applied in `layerFilter` (`{by: "name", name}`).
|
||||
- `ui.set` also accepts the Histogram panel: `histogramPanel` `{view?, channel?, showChannelsInColor?, showStatistics?, source?}` (any subset, kept with the preferences): `view` is `compact`, `expanded` or `allChannels`; `channel` is `composite`, `red`, `green`, `blue`, `cyan`, `magenta`, `yellow`, `black`, `a`, `b`, `luminosity` or `colors` (one the document's mode lacks shows as its composite); `source` is `entireImage`, `selectedLayer` or `adjustmentComposite` (Entire Image is counted in Compact View, when the document has one layer, or when no adjustment layer is selected for Adjustment Composite). `histogramRange` is `[from, to]` (levels 0..255) or `null`: the dragged tonal range whose Count and Percentile the statistics show. `histogramRefresh: true` is Uncached Refresh: the current state is recounted at cache level 1. `ui.inspect` › `histogram` reports the options, the channel and source as they apply, the channels the document offers, whether the shown histogram is `current` (counted for the document's revision, source and cache level the panel wants now), its `cacheLevel`, `maxCacheLevel` (Preferences › Performance › Cache Levels), `preview` (an adjustment's preview is counted) and `stats` (`mean`, `stdDev`, `median`, `pixels`, `level`, `count`, `percentile`, `clipped` percent at 0 and 255). Histograms are counted while the panel is shown.
|
||||
- Each painting tool keeps its own brush, as in Photoshop: `tools.setBrush` and `ui.set {brushSize}` change the active tool's brush, and switching tools swaps in that tool's own (size, hardness, mode, opacity, flow, dynamics, smoothing). A tool used for the first time starts from the brush in hand. The colours, the erase flag and the stroke seed stay shared. So `ui.set {tool: "eraser", brushSize: 12}` sets the Eraser's size, and `ui.set {tool: "brush"}` afterwards brings the Brush's own size back.
|
||||
- For pixel-layer destinations, Clone Stamp and Healing Brush source slots remember the picked document and layer. Alt-click in one open document, switch tabs, and paint in another; Current Layer reads the picked layer, Current & Below reads its source stack, and All Layers reads its source document composite. Clone Stamp requires matching document color modes; Healing Brush additionally allows Grayscale on either side. Compatible cross-document colors use the document ICC profiles through the CMS. `cloneSource.set {"source":[x,y],"document":index}` selects an open source document explicitly; `cloneSource.list` reports its current index and `documentId`. A closed source document or deleted sampled layer returns an error until a new source is picked. Empty slots do not reuse an earlier slot's coordinates. Cross-document mask/channel destinations return an unsupported-target error instead of sampling the wrong document.
|
||||
- For pixel-layer destinations, Clone Stamp and Healing Brush source slots remember the picked document and layer. Alt-click in one open document, switch tabs, and paint in another; Current Layer reads the picked layer, Current & Below reads its source stack, and All Layers reads its source document composite. Clone Stamp requires matching document color modes; Healing Brush additionally allows Grayscale on either side. Compatible cross-document colors use the document ICC profiles through the CMS. `cloneSource.set {"source":[x,y],"document":index}` selects an open source document explicitly; `cloneSource.list` reports its current index and `documentId`. A closed source document or deleted sampled layer returns an error until a new source is picked. Empty slots do not reuse an earlier slot's coordinates. Source canvas coverage is retained independently of stored alpha: no-alpha pixels inside the canvas are opaque, including black; pixels outside it do not paint. Wrapped sampling repeats the source canvas. Opaque destination surfaces retain their original native format after blending. Cross-document mask/channel destinations return an unsupported-target error instead of sampling the wrong document.
|
||||
- Clone Source X/Y are signed document-pixel offsets, using the existing `source - destination` convention. The panel derives the current preview/stroke pairing without anchoring it on hover. `cloneSource.list` exposes `anchor` (persistent Aligned pairing), `lastAnchor` (most recently used successful pairing), and `offset` (source minus that last reference). Unaligned strokes update the readout while restarting at the sample point each time; failed or canceled strokes do not commit a pairing. To edit the offset shown for a preview, use `cloneSource.set {"offset":[dx,dy],"anchor":[destinationX,destinationY]}`; without an explicit anchor an edit uses the last reported reference, then the existing aligned reference or sample point. Source picking clears both anchors; resetTransform retains them. Null optional coordinates are omitted consistently in mapping and source-document selection. Invalid coordinates, slot indexes, and oversized transformed sampling windows return errors without painting.
|
||||
- Brush Pose's `pose.overrideTiltX` and `pose.overrideTiltY` are independent booleans. For example, `engine.execute {"command":"tools.setBrush","params":{"pose":{"enabled":true,"tiltX":45,"overrideTiltX":true,"overrideTiltY":false}}}` fixes X at 45° while Y follows the stylus. Pose tilts are degrees (±90); the Brush Settings panel displays percentages (±100). Old stored `overrideTilt` values migrate to both axes. In command patches, `overrideTilt` sets both axes unless an explicit axis field in the same patch overrides it. `brush.get` includes both axis flags and the legacy combined readback (`overrideTilt` is true only when both flags are true). Axis-only journals omit that derived combined key so replay retains the other axis. Present flag values must be booleans; null and other types return an error.
|
||||
- `ui.set` also accepts the Eyedropper options bar (#1649): `eyedropperSampleSize` (`"point"` or 1, 3, 5, 11, 31, 51, 101: the side of the averaged square, shared by the Eyedropper, a painting tool's Alt-click eyedropper, the Curves/Color Picker eyedroppers and the Info panel), `eyedropperSample` (`current`, `currentAndBelow`, `all`, `allNoAdjustments`, `currentAndBelowNoAdjustments`) and `eyedropperRing` (boolean, Show Sampling Ring). `ui.inspect` reports them under `toolOptions` (`eyedropper_size`, `eyedropper_sample`, `eyedropper_ring`). The engine command `document.sampleColor {x, y, size, sampleLayer}` returns the colour such a sample picks, as four floats 0..1 (not 0..255).
|
||||
|
||||
@@ -40,3 +40,5 @@ Stamp; Healing Brush additionally permits Grayscale on either side. The sampler
|
||||
previews enforce those rules while converting compatible source/destination ICC profiles.
|
||||
The current 2026 help omits that compatibility detail; this follows the explicit reference
|
||||
rather than claiming a measurement of current Photoshop.
|
||||
|
||||
Source-edge regressions also cover sources and destinations without stored alpha, including opaque black. Canvas coverage survives native-channel conversion, affine filtering and wrapping; the destination storage format is retained.
|
||||
Reference in new issue
Block a user