Let one mask be built from more than one selection, and paint into it

A mask the model draws arrives approximately right — stopping inside a
shoulder, leaking into the hair — and FR-DEV-3's edge controls move the
*whole* boundary, so no value of feather or dilation fixes two errors that
go opposite ways. What fixes them is a second selection joined to the first,
and a layer that held exactly one source had nowhere to put one. The brush
the core has had all along was reachable from no control in the application.

A layer is now an ordered list of parts. Each names a source and how it
joins the mask before it — added to it, or taken out of it — and carries its
own edge treatment, because a model's soft coverage and a stroke painted
where it stopped short do not want the same feather. Invert and opacity stay
on the layer, where the composed shader already reads them.

The sidecar grows `[part]` blocks and nothing else. A layer of one part
writes exactly the bytes it always did; a mask block with no part blocks
after it reads back as one part; and a stroke, a join or a source this build
cannot read costs that part rather than the layer. So every sidecar in every
library still parses to the edit it always was.

On the device the parts fold into the layer's one slice, so eight layers
still cost eight channels: union is a `max` blend and subtraction is the
erase blend the brush already used. A part is drawn into a scratch texture
before it is joined, and that is not incidental — an erase stroke means a
hole in *that part*, not a hole in the mask, and drawn straight onto the
accumulator it would punch through the subject underneath. A layer of one
part skips all of it and takes the path it always took.

In the interface: a part list under the selected layer with a chip saying
which way each joins, Add and Subtract beside it, a Select/Paint/Erase strip
with the brush's size, hardness and flow, and a drag on the photograph that
paints. Pressing Paint on a mask that cannot hold a stroke joins a part that
can, rather than explaining that a subject is not a brush. A whole stroke is
one step in the history.

The edge controls now shape the part that is selected rather than the layer,
which is the one behaviour change to an existing control: with a correction
selected, the feather slider softens the correction and leaves the model's
mask alone.
This commit is contained in:
2026-09-07 20:00:40 +02:00
parent 9ede23073d
commit df741a8a49
20 changed files with 2998 additions and 654 deletions
+8 -8
View File
@@ -161,7 +161,7 @@ fn main() {
drain.set_param("saturation", ParamId("saturation"), -100.0); drain.set_param("saturation", ParamId("saturation"), -100.0);
// A touch of feather, or the colour stops dead on the model's outline and // A touch of feather, or the colour stops dead on the model's outline and
// the eye goes straight to the edge instead of to the subject. // the eye goes straight to the edge instead of to the subject.
drain.feather = 0.02; drain.base_mut().feather = 0.02;
pop.push(drain); pop.push(drain);
render_stack( render_stack(
@@ -183,14 +183,14 @@ fn main() {
let mut brighter = subject_layer("m1", index, subject); let mut brighter = subject_layer("m1", index, subject);
brighter.set_param("exposure", ParamId("exposure"), 0.45); brighter.set_param("exposure", ParamId("exposure"), 0.45);
brighter.feather = 0.015; brighter.base_mut().feather = 0.015;
lift.push(brighter); lift.push(brighter);
let mut darker = subject_layer("m2", index, subject); let mut darker = subject_layer("m2", index, subject);
darker.invert = true; darker.invert = true;
darker.set_param("exposure", ParamId("exposure"), -0.55); darker.set_param("exposure", ParamId("exposure"), -0.55);
darker.set_param("saturation", ParamId("saturation"), -25.0); darker.set_param("saturation", ParamId("saturation"), -25.0);
darker.feather = 0.03; darker.base_mut().feather = 0.03;
lift.push(darker); lift.push(darker);
render_stack( render_stack(
@@ -221,9 +221,9 @@ fn main() {
let mut layer = subject_layer("m1", index, subject); let mut layer = subject_layer("m1", index, subject);
layer.invert = true; layer.invert = true;
layer.set_param("saturation", ParamId("saturation"), -100.0); layer.set_param("saturation", ParamId("saturation"), -100.0);
layer.feather = 0.004; layer.base_mut().feather = 0.004;
layer.morphology = morphology; layer.base_mut().morphology = morphology;
layer.morph_radius = radius; layer.base_mut().morph_radius = radius;
stack.push(layer); stack.push(layer);
render_stack( render_stack(
@@ -307,14 +307,14 @@ fn render_stack(
pw as usize, pw as usize,
ph as usize, ph as usize,
128, 128,
match layer.morphology { match layer.base().morphology {
Morphology::None => dr_segment::Morphology::None, Morphology::None => dr_segment::Morphology::None,
Morphology::Dilate => dr_segment::Morphology::Dilate, Morphology::Dilate => dr_segment::Morphology::Dilate,
Morphology::Erode => dr_segment::Morphology::Erode, Morphology::Erode => dr_segment::Morphology::Erode,
Morphology::Close => dr_segment::Morphology::Close, Morphology::Close => dr_segment::Morphology::Close,
Morphology::Open => dr_segment::Morphology::Open, Morphology::Open => dr_segment::Morphology::Open,
}, },
layer.morph_radius * pw.min(ph) as f32, layer.base().morph_radius * pw.min(ph) as f32,
) )
.distance .distance
}) })
+397 -102
View File
@@ -41,7 +41,7 @@
//! `region_count`. The compaction is CPU-side and once per image, which is the //! `region_count`. The compaction is CPU-side and once per image, which is the
//! same place and cadence the region adjacency graph is already built at. //! same place and cadence the region adjacency graph is already built at.
use dr_pipeline::mask::{MaskSource, MaskStack, Stroke, MAX_LAYERS}; use dr_pipeline::mask::{Join, MaskSource, MaskStack, Stroke, MAX_LAYERS};
use wgpu::util::DeviceExt; use wgpu::util::DeviceExt;
@@ -95,6 +95,12 @@ struct MaskParams {
/// The same packing the generated adjust shader uses, so the two agree by /// The same packing the generated adjust shader uses, so the two agree by
/// construction rather than by inspection. /// construction rather than by inspection.
as_shot_wb: [f32; 4], as_shot_wb: [f32; 4],
/// Whether this part is turned over before it joins the mask. Read by the
/// combine pass and by nothing else — see `fs_combine`.
invert: u32,
/// A uniform buffer is a multiple of sixteen bytes, and the flag above
/// takes four of them.
_pad: [u32; 3],
} }
/// One stroke, as `mask.wgsl`'s `StrokeHeader` expects it. /// One stroke, as `mask.wgsl`'s `StrokeHeader` expects it.
@@ -383,6 +389,19 @@ pub struct MaskPass {
/// `dst(1 - a)` to erase. /// `dst(1 - a)` to erase.
brush_add: wgpu::RenderPipeline, brush_add: wgpu::RenderPipeline,
brush_erase: wgpu::RenderPipeline, brush_erase: wgpu::RenderPipeline,
/// Reads a part back out of [`Self::scratch`] and blends it into the
/// layer's slice. The set operation is the blend state, so these two are
/// one shader as well.
combine_layout: wgpu::BindGroupLayout,
combine_union: wgpu::RenderPipeline,
combine_subtract: wgpu::RenderPipeline,
/// Where a part is drawn before it is joined.
///
/// One texture for the whole stack rather than one per layer, because
/// layers rasterise in sequence and a part is read back immediately after
/// it is drawn. Allocated the first time a layer has more than one part,
/// so a library of unedited masks never pays for it.
scratch: Option<Scratch>,
array: Option<MaskArray>, array: Option<MaskArray>,
/// How many times the array texture has been (re)allocated. /// How many times the array texture has been (re)allocated.
/// ///
@@ -551,6 +570,88 @@ impl MaskPass {
"mask-brush-add", "mask-brush-add",
blend_state(wgpu::BlendFactor::One, wgpu::BlendFactor::OneMinusSrc), blend_state(wgpu::BlendFactor::One, wgpu::BlendFactor::OneMinusSrc),
); );
// The pipelines that join one part to the mask so far. The blend
// state is the set operation and the shader is the same three
// vertices either way — which is why adding a way to combine masks
// cost no shader arithmetic at all.
let combine_layout =
ctx.device
.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("mask-combine-bgl"),
entries: &[
uniform_entry(0),
wgpu::BindGroupLayoutEntry {
binding: 7,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
// Loaded texel by texel at matching size, so
// there is nothing to filter and no sampler.
sample_type: wgpu::TextureSampleType::Float { filterable: false },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
],
});
let combine_pipeline_layout =
ctx.device
.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("mask-combine-layout"),
bind_group_layouts: &[Some(&combine_layout)],
immediate_size: 0,
});
let combine = |label, blend| {
ctx.device
.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&combine_pipeline_layout),
vertex: wgpu::VertexState {
module: &module,
entry_point: Some("vs"),
compilation_options: Default::default(),
buffers: &[],
},
fragment: Some(wgpu::FragmentState {
module: &module,
entry_point: Some("fs_combine"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format: MaskArray::FORMAT,
blend: Some(blend),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
primitive: wgpu::PrimitiveState::default(),
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
})
};
// `max`, not source-over: a union must not build up where two parts
// overlap. Two selections that both half-cover a pixel select it half
// — adding them would make the overlap of two soft edges harder than
// either, which is a seam exactly where a photographer joined two
// things to avoid one.
let combine_union = combine(
"mask-combine-union",
wgpu::BlendState {
color: MAX_BLEND,
alpha: MAX_BLEND,
},
);
// `dst * (1 - src)`, which is the erase blend one level up: what the
// mask had, minus what this part covers, in proportion to how much of
// it the part covers.
let combine_subtract = combine(
"mask-combine-subtract",
blend_state(wgpu::BlendFactor::Zero, wgpu::BlendFactor::OneMinusSrc),
);
// The same, with the deposit thrown away: coverage is only ever taken // The same, with the deposit thrown away: coverage is only ever taken
// off what earlier strokes on this layer put down. There is no negative // off what earlier strokes on this layer put down. There is no negative
// coverage to accumulate, so erasing an unpainted layer is a no-op // coverage to accumulate, so erasing an unpainted layer is a no-op
@@ -577,6 +678,10 @@ impl MaskPass {
brush_layout, brush_layout,
brush_add, brush_add,
brush_erase, brush_erase,
combine_layout,
combine_union,
combine_subtract,
scratch: None,
array: None, array: None,
allocations: 0, allocations: 0,
placeholder, placeholder,
@@ -617,77 +722,130 @@ impl MaskPass {
}); });
for (slot, layer) in stack.active().enumerate().take(MAX_LAYERS) { for (slot, layer) in stack.active().enumerate().take(MAX_LAYERS) {
let field = match (&layer.source, labels) { // **The path a mask with one part takes is the path every mask
(MaskSource::Regions { .. }, None) => { // took before parts existed**: drawn straight into the layer's
log::warn!( // slice, cleared by the draw itself. Nothing about an unedited
"mask layer {} is a region mask with no segmentation loaded; skipping", // library's rendering changes, and the scratch texture is never
layer.id // allocated for it.
); //
continue; // An inverted base is the exception, because turning a part over
} // is done where it is read back rather than where it is drawn —
(MaskSource::Regions { .. }, Some(f)) => f, // a brush deposits dabs and cannot know what the rest of the
(_, _) => &self.placeholder, // frame is. See `fs_combine`.
}; let direct = layer.parts().len() == 1 && !layer.base().invert;
if !direct {
self.ensure_scratch(width, height)?;
}
// A subject layer whose instance is missing is skipped for the for (index, part) in layer.parts().iter().enumerate() {
// same reason a region layer without a segmentation is: an absent let base = index == 0;
// mask that defaults to "everything" would apply the adjustment to let field = match (&part.source, labels) {
// the whole photograph, which is a much louder failure than none. (MaskSource::Regions { .. }, None) => {
// Indexed by *slot*, not by the instance the layer names: the log::warn!(
// fields are built per layer, in this same order, because two "mask layer {} is a region mask with no segmentation loaded; skipping",
// layers over one subject can carry different morphology. layer.id
let subject = match &layer.source { );
// Category alongside Subject: both are model coverage turned if base {
// into a distance field, both are built per layer in this same break;
// order, and leaving a category out of here is precisely the }
// failure the comment above warns about — it binds the 1x1 continue;
// placeholder, so the mask covers everything and the }
// adjustment silently goes global. (MaskSource::Regions { .. }, Some(f)) => f,
MaskSource::Subject { .. } | MaskSource::Category { .. } => { (_, _) => &self.placeholder,
match subjects.filter(|s| slot < s.len()) { };
Some(s) => (s, slot),
None => { // A subject part whose instance is missing is skipped for the
log::warn!("mask layer {} has no distance field; skipping", layer.id); // same reason a region part without a segmentation is: an
continue; // absent mask that defaults to "everything" would apply the
// adjustment to the whole photograph, which is a much louder
// failure than none.
//
// Indexed by *slot*, not by the instance the part names: the
// fields are built per layer, in this same order, because two
// layers over one subject can carry different morphology.
// Which is also why only a base part can have one — a model
// part joined to a mask has no field built for it yet, and it
// is skipped rather than drawn against a placeholder that
// would cover the frame.
let subject = match &part.source {
// Category alongside Subject: both are model coverage
// turned into a distance field, both are built per layer
// in this same order, and leaving a category out of here
// is precisely the failure the comment above warns about —
// it binds the 1x1 placeholder, so the mask covers
// everything and the adjustment silently goes global.
MaskSource::Subject { .. } | MaskSource::Category { .. } => {
match subjects.filter(|s| base && slot < s.len()) {
Some(s) => (s, slot),
None => {
log::warn!(
"part {} of mask layer {} has no distance field; skipping",
part.id,
layer.id
);
if base {
break;
}
continue;
}
} }
} }
} _ => (&self.empty_subject, 0),
_ => (&self.empty_subject, 0), };
};
// TRACES: FR-DEV-10 // TRACES: FR-DEV-10
// A range layer with no photograph bound is skipped rather than // A range part with no photograph bound is skipped rather than
// drawn against the placeholder, on exactly the rule the two // drawn against the placeholder, on exactly the rule the two
// cases above follow: an absent mask that defaults to "everything" // cases above follow: an absent mask that defaults to
// takes a local adjustment global, which is a far quieter failure // "everything" takes a local adjustment global, which is a far
// than a layer that visibly did not render. // quieter failure than a part that visibly did not render.
let image = match (&layer.source, source) { let image = match (&part.source, source) {
(s, None) if s.is_range() => { (s, None) if s.is_range() => {
log::warn!( log::warn!(
"mask layer {} selects a range with no image loaded; skipping", "mask layer {} selects a range with no image loaded; skipping",
layer.id layer.id
); );
continue; if base {
} break;
(_, image) => image, }
}; continue;
}
(_, image) => image,
};
let params = self.params(layer, field, image, width, height); let params = self.params(part, field, image, width, height);
match &layer.source { let target = if direct {
MaskSource::Brush { strokes } => { self.slice_view(slot as u32)
self.draw_brush(&mut encoder, slot as u32, &params, strokes, width, height) } else {
self.scratch_view()
};
match &part.source {
MaskSource::Brush { strokes } => {
self.draw_brush(&mut encoder, &target, &params, strokes, width, height)
}
_ => {
let selected = self.selection_buffer(part, field);
self.draw(
&mut encoder,
&target,
&params,
field,
&selected,
subject,
image,
);
}
} }
_ => {
let selected = self.selection_buffer(layer, field); if !direct {
self.draw( // The first part joins a cleared slice, so it lands
&mut encoder, // exactly as it was drawn whichever way it says it joins —
slot as u32, // there is nothing yet for a subtraction to take away
&params, // from, and a mask that began by subtracting from nothing
field, // would render as empty however it was painted afterwards.
&selected, let join = if base { Join::Union } else { part.join };
subject, self.combine(&mut encoder, slot as u32, join, base, &params);
image,
);
} }
} }
} }
@@ -708,7 +866,7 @@ impl MaskPass {
fn params( fn params(
&self, &self,
layer: &dr_pipeline::mask::MaskLayer, part: &dr_pipeline::mask::MaskPart,
field: &LabelField, field: &LabelField,
source: Option<&DemosaicedImage>, source: Option<&DemosaicedImage>,
width: u32, width: u32,
@@ -758,9 +916,11 @@ impl MaskPass {
[m[6], m[7], m[8], 0.0], [m[6], m[7], m[8], 0.0],
], ],
as_shot_wb: [wb[0], wb[1], wb[2], if non_linear { 1.0 } else { 0.0 }], as_shot_wb: [wb[0], wb[1], wb[2], if non_linear { 1.0 } else { 0.0 }],
invert: u32::from(part.invert),
_pad: [0; 3],
}; };
match &layer.source { match &part.source {
// `softness` carries the layer's feather. The model's coverage is // `softness` carries the layer's feather. The model's coverage is
// already a soft sigmoid, so zero means "use the edge the model // already a soft sigmoid, so zero means "use the edge the model
// drew" rather than "hard edge" — the one place in this shader // drew" rather than "hard edge" — the one place in this shader
@@ -780,12 +940,12 @@ impl MaskPass {
MaskParams { MaskParams {
mode: MODE_SUBJECT, mode: MODE_SUBJECT,
// `softness` is the feather half-width in pixels. // `softness` is the feather half-width in pixels.
softness: (layer.feather * short).max(0.0), softness: (part.feather * short).max(0.0),
// `angle` carries the morphology offset — reused rather // `angle` carries the morphology offset — reused rather
// than padded, since a subject layer has no ellipse to // than padded, since a subject layer has no ellipse to
// rotate. // rotate.
angle: morph_offset(layer) * short, angle: morph_offset(part) * short,
falloff: falloff_code(layer.falloff), falloff: falloff_code(part.falloff),
..base ..base
} }
} }
@@ -871,7 +1031,7 @@ impl MaskPass {
fn draw_brush( fn draw_brush(
&self, &self,
encoder: &mut wgpu::CommandEncoder, encoder: &mut wgpu::CommandEncoder,
slot: u32, target: &wgpu::TextureView,
params: &MaskParams, params: &MaskParams,
strokes: &[Stroke], strokes: &[Stroke],
width: u32, width: u32,
@@ -933,19 +1093,10 @@ impl MaskPass {
}) })
}); });
let array = self.array.as_ref().expect("array ensured by caller");
let view = array.texture.create_view(&wgpu::TextureViewDescriptor {
label: Some("mask-slice"),
dimension: Some(wgpu::TextureViewDimension::D2),
base_array_layer: slot,
array_layer_count: Some(1),
..Default::default()
});
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("mask-brush-pass"), label: Some("mask-brush-pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment { color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view, view: target,
depth_slice: None, depth_slice: None,
resolve_target: None, resolve_target: None,
ops: wgpu::Operations { ops: wgpu::Operations {
@@ -991,11 +1142,11 @@ impl MaskPass {
/// One byte-flag per region, or a single zero for a non-region layer. /// One byte-flag per region, or a single zero for a non-region layer.
fn selection_buffer( fn selection_buffer(
&self, &self,
layer: &dr_pipeline::mask::MaskLayer, part: &dr_pipeline::mask::MaskPart,
field: &LabelField, field: &LabelField,
) -> wgpu::Buffer { ) -> wgpu::Buffer {
let mut flags = vec![0u32; field.region_count.max(1) as usize]; let mut flags = vec![0u32; field.region_count.max(1) as usize];
if let MaskSource::Regions { ids, .. } = &layer.source { if let MaskSource::Regions { ids, .. } = &part.source {
for &id in ids { for &id in ids {
if let Some(slot) = flags.get_mut(id as usize) { if let Some(slot) = flags.get_mut(id as usize) {
*slot = 1; *slot = 1;
@@ -1016,7 +1167,7 @@ impl MaskPass {
fn draw( fn draw(
&self, &self,
encoder: &mut wgpu::CommandEncoder, encoder: &mut wgpu::CommandEncoder,
slot: u32, target: &wgpu::TextureView,
params: &MaskParams, params: &MaskParams,
field: &LabelField, field: &LabelField,
selected: &wgpu::Buffer, selected: &wgpu::Buffer,
@@ -1072,19 +1223,10 @@ impl MaskPass {
// The array slice is selected by the attachment rather than by a // The array slice is selected by the attachment rather than by a
// uniform the shader reads — one fewer value that can disagree with // uniform the shader reads — one fewer value that can disagree with
// where the pass actually writes. // where the pass actually writes.
let array = self.array.as_ref().expect("array ensured by caller");
let view = array.texture.create_view(&wgpu::TextureViewDescriptor {
label: Some("mask-slice"),
dimension: Some(wgpu::TextureViewDimension::D2),
base_array_layer: slot,
array_layer_count: Some(1),
..Default::default()
});
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("mask-pass"), label: Some("mask-pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment { color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view, view: target,
depth_slice: None, depth_slice: None,
resolve_target: None, resolve_target: None,
ops: wgpu::Operations { ops: wgpu::Operations {
@@ -1105,6 +1247,140 @@ impl MaskPass {
pass.draw(0..3, 0..1); pass.draw(0..3, 0..1);
} }
/// A view of one layer's slice of the array.
fn slice_view(&self, slot: u32) -> wgpu::TextureView {
// The array slice is selected by the attachment rather than by a
// uniform the shader reads — one fewer value that can disagree with
// where the pass actually writes.
let array = self.array.as_ref().expect("array ensured by caller");
array.texture.create_view(&wgpu::TextureViewDescriptor {
label: Some("mask-slice"),
dimension: Some(wgpu::TextureViewDimension::D2),
base_array_layer: slot,
array_layer_count: Some(1),
..Default::default()
})
}
fn scratch_view(&self) -> wgpu::TextureView {
self.scratch
.as_ref()
.expect("scratch ensured by caller")
.texture
.create_view(&wgpu::TextureViewDescriptor {
label: Some("mask-part"),
..Default::default()
})
}
/// Blend the part sitting in [`Self::scratch`] into a layer's slice.
///
/// `first` clears the slice instead of loading it, which is both cheaper
/// on a tiler and the only thing that makes the fold start from nothing
/// covered rather than from whatever the last rasterisation left.
fn combine(
&self,
encoder: &mut wgpu::CommandEncoder,
slot: u32,
join: Join,
first: bool,
params: &MaskParams,
) {
let params_buf = self
.ctx
.device
.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("mask-combine-params"),
contents: bytemuck::bytes_of(params),
usage: wgpu::BufferUsages::UNIFORM,
});
let bind_group = self
.ctx
.device
.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("mask-combine-bind"),
layout: &self.combine_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: params_buf.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 7,
resource: wgpu::BindingResource::TextureView(&self.scratch_view()),
},
],
});
let target = self.slice_view(slot);
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("mask-combine-pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &target,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: if first {
wgpu::LoadOp::Clear(wgpu::Color::BLACK)
} else {
wgpu::LoadOp::Load
},
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
pass.set_pipeline(match join {
Join::Union => &self.combine_union,
Join::Subtract => &self.combine_subtract,
});
pass.set_bind_group(0, &bind_group, &[]);
pass.draw(0..3, 0..1);
}
/// The texture a part is drawn in before it is joined.
///
/// Allocated on the first mask that has more than one part and kept at the
/// rasterisation size, which is the same size the array is: a part and the
/// slice it joins are compared texel for texel, so there is nothing to
/// scale and nothing to sample between.
fn ensure_scratch(&mut self, width: u32, height: u32) -> Result<(), GpuError> {
if self
.scratch
.as_ref()
.is_some_and(|s| s.width == width && s.height == height)
{
return Ok(());
}
let texture = self.ctx.device.create_texture(&wgpu::TextureDescriptor {
label: Some("mask-scratch"),
size: wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: MaskArray::FORMAT,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
});
self.scratch = Some(Scratch {
texture,
width,
height,
});
Ok(())
}
fn ensure_array(&mut self, width: u32, height: u32, layers: u32) -> Result<(), GpuError> { fn ensure_array(&mut self, width: u32, height: u32, layers: u32) -> Result<(), GpuError> {
if self if self
.array .array
@@ -1147,6 +1423,25 @@ impl MaskPass {
} }
} }
/// The texture one part is drawn into on its way into a layer's slice.
struct Scratch {
texture: wgpu::Texture,
width: u32,
height: u32,
}
/// `max(dst, src)` — the union of two parts.
///
/// Not source-over, which would build up: two parts that each half-cover a
/// pixel select it half, and adding them would make the overlap of two soft
/// edges harder than either of them, drawing a seam exactly where a
/// photographer joined two selections to avoid one.
const MAX_BLEND: wgpu::BlendComponent = wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::One,
dst_factor: wgpu::BlendFactor::One,
operation: wgpu::BlendOperation::Max,
};
/// TRACES: FR-DEV-10 /// TRACES: FR-DEV-10
/// A single black texel, bound at the image slot for a mask that is not a /// A single black texel, bound at the image slot for a mask that is not a
/// range. /// range.
@@ -1192,11 +1487,11 @@ fn field_short_edge(width: u32, height: u32) -> f32 {
/// Zero for closing and opening: those are folded into the field itself when /// Zero for closing and opening: those are folded into the field itself when
/// it is built, because their second half acts on a shape the original field /// it is built, because their second half acts on a shape the original field
/// does not describe. /// does not describe.
fn morph_offset(layer: &dr_pipeline::mask::MaskLayer) -> f32 { fn morph_offset(part: &dr_pipeline::mask::MaskPart) -> f32 {
use dr_pipeline::mask::Morphology; use dr_pipeline::mask::Morphology;
match layer.morphology { match part.morphology {
Morphology::Dilate => layer.morph_radius, Morphology::Dilate => part.morph_radius,
Morphology::Erode => -layer.morph_radius, Morphology::Erode => -part.morph_radius,
Morphology::None | Morphology::Close | Morphology::Open => 0.0, Morphology::None | Morphology::Close | Morphology::Open => 0.0,
} }
} }
@@ -1362,11 +1657,11 @@ mod tests {
fn painted(gestures: &[Gesture]) -> MaskLayer { fn painted(gestures: &[Gesture]) -> MaskLayer {
let mut layer = lit(MaskSource::brush()); let mut layer = lit(MaskSource::brush());
for (erase, radius, path) in gestures { for (erase, radius, path) in gestures {
layer.begin_stroke(*erase, *radius, 0.5, 1.0); layer.begin_stroke(0, *erase, *radius, 0.5, 1.0);
for &(x, y) in path { for &(x, y) in path {
layer.extend_stroke(x, y); layer.extend_stroke(0, x, y);
} }
layer.end_stroke(); layer.end_stroke(0);
} }
layer layer
} }
+42
View File
@@ -78,6 +78,22 @@ struct MaskParams {
// rgb: as-shot white balance. w: non-zero when the source arrived // rgb: as-shot white balance. w: non-zero when the source arrived
// gamma-encoded rather than linear. // gamma-encoded rather than linear.
as_shot_wb: vec4<f32>, as_shot_wb: vec4<f32>,
// Whether this part is turned over before it joins the mask.
//
// Read by `fs_combine` and by nothing else, deliberately. A brush deposits
// dabs onto an empty field and has no idea what the rest of the frame is,
// so a stroke shader cannot invert anything; doing it where the finished
// part is read back is the one place that works for every kind of source.
invert: u32,
// Three scalars rather than a `vec3<u32>`: a three-component vector is
// aligned to sixteen bytes in the uniform address space, so it would sit
// at offset 144 and make this struct 160 bytes against the Rust side's
// 144 — a mismatch wgpu reports as a binding too small for the shader,
// several layers away from the padding that caused it.
_pad0: u32,
_pad1: u32,
_pad2: u32,
} }
@group(0) @binding(0) var<uniform> p: MaskParams; @group(0) @binding(0) var<uniform> p: MaskParams;
@@ -597,3 +613,29 @@ fn fs_brush(in: BrushVertex) -> @location(0) vec4<f32> {
return vec4<f32>(clamp(coverage * s.flow, 0.0, 1.0), 0.0, 0.0, 1.0); return vec4<f32>(clamp(coverage * s.flow, 0.0, 1.0), 0.0, 0.0, 1.0);
} }
// ---------------------------------------------------------------------------
// Joining one part to the mask so far
// ---------------------------------------------------------------------------
//
// A layer's mask is a fold over its parts, and the set operation is the *blend
// state* rather than arithmetic here: union is `max(dst, src)`, subtraction is
// `dst * (1 - src)`. Both are fixed-function, so joining a part costs one
// full-screen draw and no second texture beyond the one being read.
//
// # Why a part is drawn aside first, rather than straight onto the mask
//
// Because an erase stroke inside a part means "a hole in *this* part", not "a
// hole in the mask". Painted straight onto the accumulator it would take away
// whatever the parts before it had put there — so a correction that tidied its
// own edge would punch through the subject underneath, and the failure would
// look like the model's mask had holes in it.
@group(0) @binding(7) var part_mask: texture_2d<f32>;
@fragment
fn fs_combine(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
let v = textureLoad(part_mask, vec2<i32>(i32(pos.x), i32(pos.y)), 0).r;
let m = select(v, 1.0 - v, p.invert != 0u);
return vec4<f32>(clamp(m, 0.0, 1.0), 0.0, 0.0, 1.0);
}
+188 -7
View File
@@ -12,7 +12,7 @@
use dr_gpu::{AdjustPass, DemosaicedImage, GpuContext, LabelField, MaskPass}; use dr_gpu::{AdjustPass, DemosaicedImage, GpuContext, LabelField, MaskPass};
use dr_pipeline::descriptor::ParamId; use dr_pipeline::descriptor::ParamId;
use dr_pipeline::mask::{MaskLayer, MaskSource, MaskStack}; use dr_pipeline::mask::{Join, MaskLayer, MaskPart, MaskSource, MaskStack};
use dr_pipeline::operation::compose_full; use dr_pipeline::operation::compose_full;
use dr_pipeline::spot::SpotSet; use dr_pipeline::spot::SpotSet;
use dr_pipeline::{ops, EditGraph, Framing}; use dr_pipeline::{ops, EditGraph, Framing};
@@ -286,11 +286,11 @@ type Gesture = (bool, f32, f32, Vec<(f32, f32)>);
fn painted(gestures: &[Gesture]) -> MaskLayer { fn painted(gestures: &[Gesture]) -> MaskLayer {
let mut layer = brighten(MaskSource::brush()); let mut layer = brighten(MaskSource::brush());
for (erase, radius, flow, path) in gestures { for (erase, radius, flow, path) in gestures {
layer.begin_stroke(*erase, *radius, 0.9, *flow); layer.begin_stroke(0, *erase, *radius, 0.9, *flow);
for &(x, y) in path { for &(x, y) in path {
layer.extend_stroke(x, y); layer.extend_stroke(0, x, y);
} }
layer.end_stroke(); layer.end_stroke(0);
} }
layer layer
} }
@@ -505,9 +505,9 @@ fn hardness_decides_how_quickly_the_edge_falls_away() {
let edge = |hardness: f32| { let edge = |hardness: f32| {
let mut layer = brighten(MaskSource::brush()); let mut layer = brighten(MaskSource::brush());
layer.begin_stroke(false, 0.4, hardness, 1.0); layer.begin_stroke(0, false, 0.4, hardness, 1.0);
layer.extend_stroke(0.5, 0.5); layer.extend_stroke(0, 0.5, 0.5);
layer.end_stroke(); layer.end_stroke(0);
let pixels = render(&ctx, &stack_of(layer), None); let pixels = render(&ctx, &stack_of(layer), None);
// How many pixels along the centre row are neither fully painted nor // How many pixels along the centre row are neither fully painted nor
@@ -608,3 +608,184 @@ fn an_empty_stack_renders_exactly_as_the_unmasked_path() {
let masked = render(&ctx, &MaskStack::new(), None); let masked = render(&ctx, &MaskStack::new(), None);
assert_eq!(plain, masked, "an empty mask stack must be a no-op"); assert_eq!(plain, masked, "an empty mask stack must be a no-op");
} }
// ---------------------------------------------------------------------------
// Parts — a mask built from more than one selection
// ---------------------------------------------------------------------------
/// Everything, so a part joined to it has something to change.
fn whole_frame() -> MaskSource {
MaskSource::Regions {
signature: 1,
level: 2,
ids: vec![0, 1],
}
}
/// Paint one gesture into a part of a layer, at a radius large enough that a
/// 32-pixel frame can tell where it landed.
fn paint(layer: &mut MaskLayer, part: usize, erase: bool, path: &[(f32, f32)]) {
assert!(
layer.begin_stroke(part, erase, 0.2, 1.0, 1.0),
"the layer had no room for a stroke"
);
for &(x, y) in path {
layer.extend_stroke(part, x, y);
}
layer.end_stroke(part);
}
#[test]
fn a_union_part_adds_what_the_base_did_not_cover() {
let Some(ctx) = ctx() else {
eprintln!("no adapter; skipping");
return;
};
let mut layer = brighten(MaskSource::Regions {
signature: 1,
level: 2,
ids: vec![0],
});
assert!(layer.push_part(MaskPart::painted("p2", Join::Union)));
paint(&mut layer, 1, false, &[(0.85, 0.5)]);
let mut stack = MaskStack::new();
stack.push(layer);
let pixels = render(&ctx, &stack, Some(&split_field(&ctx)));
assert!(
luma_at(&pixels, 4, 16) > 200,
"the base region is still masked"
);
assert!(
luma_at(&pixels, 27, 16) > 200,
"and the painted part joined the other half in"
);
assert_eq!(
luma_at(&pixels, 20, 2),
128,
"while what neither covers is untouched"
);
}
#[test]
fn a_subtract_part_takes_a_bite_out_of_the_mask() {
let Some(ctx) = ctx() else {
eprintln!("no adapter; skipping");
return;
};
let mut layer = brighten(whole_frame());
assert!(layer.push_part(MaskPart::painted("p2", Join::Subtract)));
paint(&mut layer, 1, false, &[(0.5, 0.5)]);
let mut stack = MaskStack::new();
stack.push(layer);
let pixels = render(&ctx, &stack, Some(&split_field(&ctx)));
assert_eq!(
luma_at(&pixels, 16, 16),
128,
"the middle was taken back out of the mask"
);
assert!(
luma_at(&pixels, 1, 1) > 200,
"and the corner the stroke never reached is still in it"
);
}
/// **The test the scratch texture exists for.** An erase stroke means a hole in
/// the part it was painted into, not a hole in the mask: drawn straight onto
/// the accumulator it would take away whatever the parts before it had put
/// there, so tidying the edge of a correction would punch through the subject
/// underneath — and the failure would read as the model's mask having holes.
#[test]
fn an_erase_stroke_holes_its_own_part_and_not_the_mask() {
let Some(ctx) = ctx() else {
eprintln!("no adapter; skipping");
return;
};
let mut layer = brighten(whole_frame());
assert!(layer.push_part(MaskPart::painted("p2", Join::Union)));
paint(&mut layer, 1, false, &[(0.5, 0.5)]);
paint(&mut layer, 1, true, &[(0.5, 0.5)]);
let mut stack = MaskStack::new();
stack.push(layer);
let pixels = render(&ctx, &stack, Some(&split_field(&ctx)));
assert!(
luma_at(&pixels, 16, 16) > 200,
"the base still covers where the correction erased itself"
);
}
#[test]
fn an_inverted_part_joins_everything_it_did_not_paint() {
let Some(ctx) = ctx() else {
eprintln!("no adapter; skipping");
return;
};
// A base that covers nothing, so what shows is the part alone.
let mut layer = brighten(MaskSource::brush());
paint(&mut layer, 0, false, &[(0.1, 0.1)]);
assert!(layer.push_part(MaskPart::painted("p2", Join::Union)));
layer.parts_mut()[1].invert = true;
paint(&mut layer, 1, false, &[(0.5, 0.5)]);
let mut stack = MaskStack::new();
stack.push(layer);
let pixels = render(&ctx, &stack, Some(&split_field(&ctx)));
assert_eq!(
luma_at(&pixels, 16, 16),
128,
"where the inverted part was painted is outside the mask"
);
assert!(
luma_at(&pixels, 30, 30) > 200,
"and everywhere it was not is inside it"
);
}
/// Parts fold in order, so the same two selections joined the other way round
/// are a different mask. A subtraction that lands before the part it was meant
/// to cut into would take away nothing at all.
#[test]
fn the_order_parts_are_joined_in_is_the_mask() {
let Some(ctx) = ctx() else {
eprintln!("no adapter; skipping");
return;
};
let render_pair = |cut_first: bool| {
let mut layer = brighten(MaskSource::brush());
if cut_first {
layer.push_part(MaskPart::painted("p2", Join::Subtract));
layer.push_part(MaskPart::painted("p3", Join::Union));
paint(&mut layer, 1, false, &[(0.5, 0.5)]);
paint(&mut layer, 2, false, &[(0.5, 0.5)]);
} else {
layer.push_part(MaskPart::painted("p2", Join::Union));
layer.push_part(MaskPart::painted("p3", Join::Subtract));
paint(&mut layer, 1, false, &[(0.5, 0.5)]);
paint(&mut layer, 2, false, &[(0.5, 0.5)]);
}
let mut stack = MaskStack::new();
stack.push(layer);
render(&ctx, &stack, Some(&split_field(&ctx)))
};
assert!(
luma_at(&render_pair(true), 16, 16) > 200,
"adding after a subtraction leaves the addition standing"
);
assert_eq!(
luma_at(&render_pair(false), 16, 16),
128,
"and subtracting after an addition takes it away again"
);
}
+1 -1
View File
@@ -51,7 +51,7 @@ fn brightening_stack() -> MaskStack {
}, },
); );
layer.set_param("exposure", ParamId("exposure"), 2.0); layer.set_param("exposure", ParamId("exposure"), 2.0);
layer.feather = 0.0; layer.base_mut().feather = 0.0;
stack.push(layer); stack.push(layer);
stack stack
} }
+19 -5
View File
@@ -989,12 +989,26 @@ impl EditGraph {
// out of step the first time a variant gains a field — silently, // out of step the first time a variant gains a field — silently,
// and showing as a mask that stops updating. `Debug` cannot fall // and showing as a mask that stops updating. `Debug` cannot fall
// out of step, because it is derived from the definition itself. // out of step, because it is derived from the definition itself.
colour = hash_bytes(colour, format!("{:?}", layer.source).as_bytes());
colour = mix(colour, u64::from(layer.enabled)); colour = mix(colour, u64::from(layer.enabled));
colour = mix(colour, u64::from(layer.invert)); colour = mix(colour, u64::from(layer.invert));
colour = hash_bytes(colour, layer.falloff.name().as_bytes()); colour = mix(
for v in [layer.opacity, layer.feather, layer.morph_radius] { colour,
colour = mix(colour, u64::from(crate::operation::canonical_bits(v))); u64::from(crate::operation::canonical_bits(layer.opacity)),
);
// Every part, in order, because the mask is the fold over them: a
// part added, removed, reshaped or joined the other way round is a
// different shape even when nothing else moved. The order is
// folded in by construction — the same parts joined the other way
// round hash differently because they arrive in the other order.
for part in layer.parts() {
colour = hash_bytes(colour, part.id.as_bytes());
colour = hash_bytes(colour, part.join.name().as_bytes());
colour = hash_bytes(colour, format!("{:?}", part.source).as_bytes());
colour = mix(colour, u64::from(part.invert));
colour = hash_bytes(colour, part.falloff.name().as_bytes());
for v in [part.feather, part.morph_radius] {
colour = mix(colour, u64::from(crate::operation::canonical_bits(v)));
}
} }
for (op_id, param_id, value) in layer.params() { for (op_id, param_id, value) in layer.params() {
colour = hash_bytes(colour, op_id.as_bytes()); colour = hash_bytes(colour, op_id.as_bytes());
@@ -1795,7 +1809,7 @@ mod tests {
// Moving the gradient is a different mask, so a different result. // Moving the gradient is a different mask, so a different result.
if let Some(layer) = g.masks_mut().get_mut("l1") { if let Some(layer) = g.masks_mut().get_mut("l1") {
layer.source = MaskSource::Linear { layer.base_mut().source = MaskSource::Linear {
centre: (0.2, 0.7), centre: (0.2, 0.7),
angle: 0.4, angle: 0.4,
width: 0.2, width: 0.2,
File diff suppressed because it is too large Load Diff
+281 -85
View File
@@ -69,7 +69,9 @@ use std::fmt::Write as _;
use crate::coverage::Coverage; use crate::coverage::Coverage;
use crate::graph::EditGraph; use crate::graph::EditGraph;
use crate::mask::{Falloff, MaskLayer, MaskSource, MaskStack, Morphology, Stroke, DEFAULT_FEATHER}; use crate::mask::{
Falloff, Join, MaskLayer, MaskPart, MaskSource, MaskStack, Morphology, Stroke, DEFAULT_FEATHER,
};
use crate::preset::Preset; use crate::preset::Preset;
use crate::spot::{Spot, SpotMode, SpotSet}; use crate::spot::{Spot, SpotMode, SpotSet};
use crate::state::{EditState, FilmRebake}; use crate::state::{EditState, FilmRebake};
@@ -833,6 +835,10 @@ impl Sidecar {
// then simply dropped instead of corrupting whichever version // then simply dropped instead of corrupting whichever version
// happened to be open. // happened to be open.
let mut mask: Option<PartialMask> = None; let mut mask: Option<PartialMask> = None;
// Whether the `[part]` block being read names a mask that is not the
// one above it. Its keys are dropped rather than falling through to
// the version, where they would be read as somebody's global edit.
let mut orphan_part = false;
let mut masks: Vec<(String, MaskLayer)> = Vec::new(); let mut masks: Vec<(String, MaskLayer)> = Vec::new();
for raw in lines { for raw in lines {
@@ -846,6 +852,7 @@ impl Sidecar {
.and_then(|s| s.strip_suffix(']')) .and_then(|s| s.strip_suffix(']'))
{ {
masks.extend(mask.take().and_then(PartialMask::finish)); masks.extend(mask.take().and_then(PartialMask::finish));
orphan_part = false;
if let Some(v) = current.take() { if let Some(v) = current.take() {
sidecar.put(v); sidecar.put(v);
} }
@@ -861,6 +868,7 @@ impl Sidecar {
.and_then(|s| s.strip_suffix(']')) .and_then(|s| s.strip_suffix(']'))
{ {
masks.extend(mask.take().and_then(PartialMask::finish)); masks.extend(mask.take().and_then(PartialMask::finish));
orphan_part = false;
match head.split_once(char::is_whitespace) { match head.split_once(char::is_whitespace) {
Some((version, id)) => { Some((version, id)) => {
mask = Some(PartialMask::new(version.trim(), id.trim())); mask = Some(PartialMask::new(version.trim(), id.trim()));
@@ -874,6 +882,36 @@ impl Sidecar {
continue; continue;
} }
// A part of the mask block above this one. **Three names**, and
// the two it repeats are checked rather than assumed: a block
// reordered by a hand edit or by a merge would otherwise attach
// somebody's correction to whichever mask happened to precede it,
// which is a wrong mask rather than a missing one.
if let Some(head) = line
.strip_prefix("[part ")
.and_then(|s| s.strip_suffix(']'))
{
let mut names = head.split_whitespace();
orphan_part = true;
if let (Some(version), Some(layer), Some(part)) =
(names.next(), names.next(), names.next())
{
match mask.as_mut() {
Some(m) if m.version == version && m.id == layer => {
m.begin_part(part);
orphan_part = false;
}
_ => log::warn!(
"sidecar: part '{part}' names mask {layer} of version {version}, \
which is not the block it follows; ignoring it"
),
}
} else {
log::warn!("sidecar: malformed part header '{line}'; ignoring");
}
continue;
}
let Some((key, value)) = line.split_once('=') else { let Some((key, value)) = line.split_once('=') else {
// Not a key-value line and not a block header. Keep it so a // Not a key-value line and not a block header. Keep it so a
// newer format's construct survives a round trip here. // newer format's construct survives a round trip here.
@@ -887,6 +925,10 @@ impl Sidecar {
}; };
let (key, value) = (key.trim(), value.trim()); let (key, value) = (key.trim(), value.trim());
if orphan_part {
continue;
}
if let Some(m) = mask.as_mut() { if let Some(m) = mask.as_mut() {
m.set(key, value); m.set(key, value);
continue; continue;
@@ -1062,9 +1104,59 @@ fn write_mask(out: &mut String, version: &str, layer: &MaskLayer) {
if !layer.name.is_empty() { if !layer.name.is_empty() {
let _ = writeln!(out, "name = {}", layer.name); let _ = writeln!(out, "name = {}", layer.name);
} }
let _ = writeln!(out, "source = {}", layer.source.kind());
match &layer.source { // **The base part is written into the layer's own block**, without a name
// and without a join, and that is what makes this format change no file
// that does not use it: a layer of one part is the same bytes it always
// was, and a block with no `[part]` after it reads back as one part
// (see [`PartialMask::finish`]).
write_source(out, layer.base());
if layer.invert {
let _ = writeln!(out, "invert = 1");
}
if layer.opacity != 1.0 {
let _ = writeln!(out, "opacity = {}", format_value(layer.opacity));
}
if !layer.enabled {
let _ = writeln!(out, "enabled = 0");
}
write_shaping(out, layer.base());
for (op, param, value) in layer.params() {
let _ = writeln!(out, "{op}.{param} = {}", format_value(value));
}
write_coverage(out, layer.base());
for part in &layer.parts()[1..] {
write_part(out, version, &layer.id, part);
}
}
/// Write one part of a layer's mask as its own block.
///
/// Its own block rather than a nested key, because a merge compares lines and
/// a part is the granularity a photographer edits: adding a correction to a
/// mask should read, in a diff, as a correction added — not as the whole mask
/// having been rewritten. The version and the layer are both named in the
/// header for the reason [`write_mask`] names the version: "belongs to
/// whatever appeared above me" is a relationship that does not survive a hand
/// edit or a merge.
fn write_part(out: &mut String, version: &str, layer: &str, part: &MaskPart) {
let _ = write!(out, "\n[part {version} {layer} {}]\n", part.id);
let _ = writeln!(out, "join = {}", part.join.name());
write_source(out, part);
if part.invert {
let _ = writeln!(out, "invert = 1");
}
write_shaping(out, part);
write_coverage(out, part);
}
/// The `source = …` line and whatever else that kind of source needs.
fn write_source(out: &mut String, part: &MaskPart) {
let _ = writeln!(out, "source = {}", part.source.kind());
match &part.source {
MaskSource::Regions { MaskSource::Regions {
signature, signature,
level, level,
@@ -1170,54 +1262,46 @@ fn write_mask(out: &mut String, version: &str, layer: &MaskLayer) {
); );
} }
} }
}
if layer.invert { /// The edge treatment, written only where it is not the default — the same
let _ = writeln!(out, "invert = 1"); /// rule the parameters follow, so a file stays readable and a mask nobody has
/// fiddled with contributes four fewer lines.
fn write_shaping(out: &mut String, part: &MaskPart) {
if part.feather != DEFAULT_FEATHER {
let _ = writeln!(out, "edge-feather = {}", format_value(part.feather));
} }
if layer.opacity != 1.0 { if part.falloff != Falloff::default() {
let _ = writeln!(out, "opacity = {}", format_value(layer.opacity)); let _ = writeln!(out, "edge-falloff = {}", part.falloff.name());
} }
if !layer.enabled { if part.morphology != Morphology::default() {
let _ = writeln!(out, "enabled = 0"); let _ = writeln!(out, "morphology = {}", part.morphology.name());
} let _ = writeln!(out, "morph-radius = {}", format_value(part.morph_radius));
// The edge treatment, written only when it is not the default — the same
// rule the parameters follow, so a file stays readable and a mask nobody
// has fiddled with contributes four fewer lines.
if layer.feather != DEFAULT_FEATHER {
let _ = writeln!(out, "edge-feather = {}", format_value(layer.feather));
}
if layer.falloff != Falloff::default() {
let _ = writeln!(out, "edge-falloff = {}", layer.falloff.name());
}
if layer.morphology != Morphology::default() {
let _ = writeln!(out, "morphology = {}", layer.morphology.name());
let _ = writeln!(out, "morph-radius = {}", format_value(layer.morph_radius));
} }
// Absent means zero, which is the model's own weighting — so a file // Absent means zero, which is the model's own weighting — so a file
// written before this control existed reads back looking exactly as it did. // written before this control existed reads back looking exactly as it did.
if layer.refine != 0.0 { if part.refine != 0.0 {
let _ = writeln!(out, "refine = {}", format_value(layer.refine)); let _ = writeln!(out, "refine = {}", format_value(part.refine));
}
for (op, param, value) in layer.params() {
let _ = writeln!(out, "{op}.{param} = {}", format_value(value));
} }
}
// TRACES: FR-DEV-3 | FR-CAT-8 /// TRACES: FR-DEV-3 | FR-CAT-8
// The pixels a model found, so that opening the photograph again — or /// The pixels a model found, so that opening the photograph again — or
// exporting it from the grid, where no model is ever run — renders the /// exporting it from the grid, where no model is ever run — renders the part
// layer instead of silently dropping it. See [`crate::coverage`] for the /// instead of silently dropping it. See [`crate::coverage`] for the encoding
// encoding and for why it is one line. /// and for why it is one line.
// ///
// **Last in the block, and that is on purpose.** It is thousands of /// **Last in the block, and that is on purpose.** It is thousands of
// characters against a dozen elsewhere, and a sidecar is read by hand when /// characters against a dozen elsewhere, and a sidecar is read by hand when an
// an edit has gone wrong (ARCH §6.12); everything a human is looking for /// edit has gone wrong (ARCH §6.12); everything a human is looking for should
// should be above it rather than after it. /// be above it rather than after it.
// ///
// Omitted, not truncated, when it will not encode: a layer with no stored /// Omitted, not truncated, when it will not encode: a part with no stored
// coverage behaves exactly as every layer did before this existed, which /// coverage behaves exactly as every layer did before this existed, which is a
// is a mask that needs the model run — where a *partial* one would be a /// mask that needs the model run — where a *partial* one would be a mask that
// mask that is confidently wrong. /// is confidently wrong.
if let Some(coverage) = layer.coverage.as_ref() { fn write_coverage(out: &mut String, part: &MaskPart) {
if let Some(coverage) = part.coverage.as_ref() {
let _ = writeln!(out, "coverage = {}", coverage.to_text()); let _ = writeln!(out, "coverage = {}", coverage.to_text());
} }
} }
@@ -1295,15 +1379,14 @@ fn parse_stroke(value: &str) -> Option<Stroke> {
(!stroke.is_empty()).then_some(stroke) (!stroke.is_empty()).then_some(stroke)
} }
/// A mask block being read, before it is complete enough to be a layer. /// One part of a mask being read, before it is complete enough to be a part.
/// ///
/// Separate from [`MaskLayer`] because the source cannot be built until every /// Separate from [`MaskPart`] because the source cannot be built until every
/// one of its fields has been seen, and the fields arrive one line at a time /// one of its fields has been seen, and the fields arrive one line at a time
/// in whatever order the writer chose. /// in whatever order the writer chose.
struct PartialMask { struct PartialPart {
version: String,
id: String, id: String,
name: String, join: Join,
kind: String, kind: String,
signature: u64, signature: u64,
level: u32, level: u32,
@@ -1321,16 +1404,14 @@ struct PartialMask {
/// A range source's band: its two bounds and the fade at each edge. /// A range source's band: its two bounds and the fade at each edge.
/// ///
/// One triple for both range kinds — tone positions for a luminance /// One triple for both range kinds — tone positions for a luminance
/// layer, chroma for a colour one — because they are the same line in the /// part, chroma for a colour one — because they are the same line in the
/// file and reading them into two sets of fields would be two ways to /// file and reading them into two sets of fields would be two ways to
/// spell one thing. /// spell one thing.
band: (f32, f32, f32), band: (f32, f32, f32),
/// A colour range's arc: centre and half-width, in turns. /// A colour range's arc: centre and half-width, in turns.
hue: (f32, f32), hue: (f32, f32),
invert: bool, invert: bool,
opacity: f32, /// The *part's* edge transition, distinct from the radial source's own
enabled: bool,
/// The *layer's* edge transition, distinct from the radial source's own
/// `feather` above — different quantity, different units, different key. /// `feather` above — different quantity, different units, different key.
edge_feather: f32, edge_feather: f32,
falloff: Falloff, falloff: Falloff,
@@ -1339,15 +1420,13 @@ struct PartialMask {
refine: f32, refine: f32,
coverage: Option<Coverage>, coverage: Option<Coverage>,
strokes: Vec<Stroke>, strokes: Vec<Stroke>,
params: Vec<(String, String, f32)>,
} }
impl PartialMask { impl PartialPart {
fn new(version: &str, id: &str) -> Self { fn new(id: &str) -> Self {
Self { Self {
version: version.to_string(),
id: id.to_string(), id: id.to_string(),
name: String::new(), join: Join::default(),
kind: String::new(), kind: String::new(),
signature: 0, signature: 0,
level: 0, level: 0,
@@ -1367,8 +1446,6 @@ impl PartialMask {
band: (0.5, 1.0, crate::mask::DEFAULT_RANGE_SOFTNESS), band: (0.5, 1.0, crate::mask::DEFAULT_RANGE_SOFTNESS),
hue: (0.06, 0.05), hue: (0.06, 0.05),
invert: false, invert: false,
opacity: 1.0,
enabled: true,
edge_feather: DEFAULT_FEATHER, edge_feather: DEFAULT_FEATHER,
falloff: Falloff::default(), falloff: Falloff::default(),
morphology: Morphology::default(), morphology: Morphology::default(),
@@ -1376,13 +1453,12 @@ impl PartialMask {
refine: 0.0, refine: 0.0,
coverage: None, coverage: None,
strokes: Vec::new(), strokes: Vec::new(),
params: Vec::new(),
} }
} }
fn set(&mut self, key: &str, value: &str) { /// Take one key, returning whether it was one of this part's.
fn set(&mut self, key: &str, value: &str) -> bool {
match key { match key {
"name" => self.name = value.to_string(),
"source" => self.kind = value.to_string(), "source" => self.kind = value.to_string(),
"signature" => self.signature = value.parse().unwrap_or(0), "signature" => self.signature = value.parse().unwrap_or(0),
"level" => self.level = value.parse().unwrap_or(0), "level" => self.level = value.parse().unwrap_or(0),
@@ -1434,8 +1510,6 @@ impl PartialMask {
// and the file's line order is the order they were painted in. // and the file's line order is the order they were painted in.
"stroke" => self.strokes.extend(parse_stroke(value)), "stroke" => self.strokes.extend(parse_stroke(value)),
"invert" => self.invert = value != "0", "invert" => self.invert = value != "0",
"opacity" => self.opacity = value.parse::<f32>().unwrap_or(1.0).clamp(0.0, 1.0),
"enabled" => self.enabled = value != "0",
// Clamped, not trusted: a feather wider than the frame is not a // Clamped, not trusted: a feather wider than the frame is not a
// mask, and a negative one is a distance field read backwards. // mask, and a negative one is a distance field read backwards.
"edge-feather" => { "edge-feather" => {
@@ -1472,19 +1546,18 @@ impl PartialMask {
Morphology::default() Morphology::default()
}) })
} }
_ => match (key.split_once('.'), value.parse::<f32>()) { // Not one of ours. The caller decides what that means: an
(Some((op, param)), Ok(v)) if v.is_finite() => { // adjustment's parameter inside the mask block, or a key nothing
self.params.push((op.to_string(), param.to_string(), v)); // in this build understands.
} _ => return false,
_ => log::warn!("sidecar: unreadable mask key {key}; ignoring"),
},
} }
true
} }
/// Build the layer, or `None` if the source kind is one this build has /// Build the part, or `None` if the source kind is one this build has
/// never heard of — a newer format's mask type, which is skipped rather /// never heard of — a newer format's mask type, which is skipped rather
/// than guessed at. /// than guessed at.
fn finish(self) -> Option<(String, MaskLayer)> { fn finish(self) -> Option<MaskPart> {
let source = match self.kind.as_str() { let source = match self.kind.as_str() {
"regions" => MaskSource::Regions { "regions" => MaskSource::Regions {
signature: self.signature, signature: self.signature,
@@ -1529,33 +1602,156 @@ impl PartialMask {
), ),
other => { other => {
log::warn!( log::warn!(
"sidecar: unknown mask source '{other}'; skipping layer {}", "sidecar: unknown mask source '{other}'; skipping part {}",
self.id self.id
); );
return None; return None;
} }
}; };
let mut layer = MaskLayer::new(self.id, source); let mut part = MaskPart::new(self.id, self.join, source);
layer.name = self.name; part.invert = self.invert;
layer.invert = self.invert; part.feather = self.edge_feather;
layer.opacity = self.opacity; part.falloff = self.falloff;
layer.enabled = self.enabled; part.morphology = self.morphology;
layer.feather = self.edge_feather; part.morph_radius = self.morph_radius;
layer.falloff = self.falloff; part.refine = self.refine;
layer.morphology = self.morphology; // Only where there is a model behind the part to have produced it. A
layer.morph_radius = self.morph_radius;
layer.refine = self.refine;
// Only where there is a model behind the layer to have produced it. A
// gradient or a brush that arrived carrying one is a file that has // gradient or a brush that arrived carrying one is a file that has
// been hand-edited or written by a build that means something else by // been hand-edited or written by a build that means something else by
// the key, and honouring it would upload a raster nothing samples. // the key, and honouring it would upload a raster nothing samples.
layer.coverage = match layer.source { part.coverage = match part.source {
MaskSource::Subject { .. } | MaskSource::Category { .. } => { MaskSource::Subject { .. } | MaskSource::Category { .. } => {
self.coverage.map(std::sync::Arc::new) self.coverage.map(std::sync::Arc::new)
} }
_ => None, _ => None,
}; };
Some(part)
}
}
/// A mask block being read, before it is complete enough to be a layer.
///
/// Holds what belongs to the *layer* — its name, its inversion, its opacity,
/// its adjustments — and one [`PartialPart`] per selection the mask is built
/// from. `parts[0]` is filled by the mask block's own keys, which is what
/// makes a file written before parts existed read back as a layer of one.
struct PartialMask {
version: String,
id: String,
name: String,
invert: bool,
opacity: f32,
enabled: bool,
params: Vec<(String, String, f32)>,
parts: Vec<PartialPart>,
/// Whether a `[part]` block is open, so `invert` can be told apart: in the
/// mask block it flips the finished mask, and in a part block it flips
/// that part before it is joined. Same word, two controls, and the block
/// is the only thing that distinguishes them.
in_part: bool,
}
impl PartialMask {
fn new(version: &str, id: &str) -> Self {
Self {
version: version.to_string(),
id: id.to_string(),
name: String::new(),
invert: false,
opacity: 1.0,
enabled: true,
params: Vec::new(),
parts: vec![PartialPart::new(crate::mask::FIRST_PART_ID)],
in_part: false,
}
}
/// Open a `[part]` block. Every key from here to the next block header
/// belongs to it.
fn begin_part(&mut self, id: &str) {
self.parts.push(PartialPart::new(id));
self.in_part = true;
}
fn set(&mut self, key: &str, value: &str) {
// The layer's own keys, and only while no part block is open. A part
// has an `invert` of its own and no opacity at all, so which of the
// two an `invert` line means is decided by the block it is in.
if !self.in_part {
match key {
"name" => {
self.name = value.to_string();
return;
}
"invert" => {
self.invert = value != "0";
return;
}
"opacity" => {
self.opacity = value.parse::<f32>().unwrap_or(1.0).clamp(0.0, 1.0);
return;
}
"enabled" => {
self.enabled = value != "0";
return;
}
_ => {}
}
} else if key == "join" {
// Unknown falls back to a union rather than dropping the part: a
// join this build does not have is a part that joins some other
// way, and adding it is the reading that keeps the selection
// visible and therefore fixable. Silently subtracting under a name
// nobody could see would not be.
if let Some(part) = self.parts.last_mut() {
part.join = Join::from_name(value).unwrap_or_else(|| {
log::warn!("sidecar: unknown join '{value}'; adding the part instead");
Join::Union
});
}
return;
}
if let Some(part) = self.parts.last_mut() {
if part.set(key, value) {
return;
}
}
// Whatever is left is an adjustment, which belongs to the layer
// however deep in the block it was written.
match (key.split_once('.'), value.parse::<f32>()) {
(Some((op, param)), Ok(v)) if v.is_finite() => {
self.params.push((op.to_string(), param.to_string(), v));
}
_ => log::warn!("sidecar: unreadable mask key {key}; ignoring"),
}
}
/// Build the layer, or `None` when its base part cannot be built — a
/// newer format's mask type, which is skipped rather than guessed at.
///
/// A *later* part that cannot be built costs that part and not the layer,
/// on the rule [`parse_stroke`] already follows: the rest of the mask is
/// work the photographer did, and throwing it away to protect the
/// consistency of one correction loses more than it saves.
fn finish(self) -> Option<(String, MaskLayer)> {
let id = self.id;
let mut parts = Vec::new();
for (i, part) in self.parts.into_iter().enumerate() {
match (part.finish(), i) {
(Some(p), _) => parts.push(p),
(None, 0) => return None,
(None, _) => {}
}
}
let mut layer = MaskLayer::from_parts(id, parts)?;
layer.name = self.name;
layer.invert = self.invert;
layer.opacity = self.opacity;
layer.enabled = self.enabled;
for (op, param, value) in &self.params { for (op, param, value) in &self.params {
// `ParamId` holds a `&'static str` and this one came off disk, so // `ParamId` holds a `&'static str` and this one came off disk, so
// it is matched against the descriptors and the *static* id is // it is matched against the descriptors and the *static* id is
+319 -44
View File
@@ -5,8 +5,8 @@
//! round-trip is not a persistence bug, it is lost work, and the tests here //! round-trip is not a persistence bug, it is lost work, and the tests here
//! are about the ways that happens quietly rather than loudly. //! are about the ways that happens quietly rather than loudly.
use dr_pipeline::descriptor::ParamId; use dr_pipeline::descriptor::{OpId, ParamId};
use dr_pipeline::mask::{MaskLayer, MaskSource}; use dr_pipeline::mask::{Join, MaskLayer, MaskPart, MaskSource, Morphology};
use dr_pipeline::{EditGraph, Sidecar, Version}; use dr_pipeline::{EditGraph, Sidecar, Version};
fn regions(ids: &[u32]) -> MaskSource { fn regions(ids: &[u32]) -> MaskSource {
@@ -55,7 +55,7 @@ fn a_region_mask_survives_a_round_trip() {
let layer = &layers[0]; let layer = &layers[0];
assert_eq!(layer.id, "m1"); assert_eq!(layer.id, "m1");
assert_eq!(layer.name, "Subject"); assert_eq!(layer.name, "Subject");
assert_eq!(layer.source, regions(&[3, 7, 12])); assert_eq!(layer.base().source, regions(&[3, 7, 12]));
assert_eq!( assert_eq!(
layer layer
.ops .ops
@@ -110,8 +110,14 @@ fn gradients_keep_their_geometry() {
let restored = round_trip(&graph); let restored = round_trip(&graph);
let layers = restored.masks().layers(); let layers = restored.masks().layers();
assert_eq!(layers.len(), 2); assert_eq!(layers.len(), 2);
assert_eq!(layers[0].source, graph.masks().layers()[0].source); assert_eq!(
assert_eq!(layers[1].source, graph.masks().layers()[1].source); layers[0].base().source,
graph.masks().layers()[0].base().source
);
assert_eq!(
layers[1].base().source,
graph.masks().layers()[1].base().source
);
} }
#[test] #[test]
@@ -155,7 +161,7 @@ fn region_order_is_normalised_on_read() {
let parsed = Sidecar::parse(text).expect("parse"); let parsed = Sidecar::parse(text).expect("parse");
let layer = &parsed.versions["default"].masks.layers()[0]; let layer = &parsed.versions["default"].masks.layers()[0];
assert_eq!( assert_eq!(
layer.source, layer.base().source,
MaskSource::Regions { MaskSource::Regions {
signature: 5, signature: 5,
level: 10, level: 10,
@@ -302,11 +308,11 @@ fn brushed(id: &str, gestures: &[Gesture]) -> MaskLayer {
let mut layer = MaskLayer::new(id, MaskSource::brush()); let mut layer = MaskLayer::new(id, MaskSource::brush());
layer.set_param("exposure", ParamId("exposure"), 1.0); layer.set_param("exposure", ParamId("exposure"), 1.0);
for (erase, radius, path) in gestures { for (erase, radius, path) in gestures {
layer.begin_stroke(*erase, *radius, 0.5, 1.0); layer.begin_stroke(0, *erase, *radius, 0.5, 1.0);
for &(x, y) in path { for &(x, y) in path {
layer.extend_stroke(x, y); layer.extend_stroke(0, x, y);
} }
layer.end_stroke(); layer.end_stroke(0);
} }
layer layer
} }
@@ -440,7 +446,10 @@ fn an_unpainted_brush_layer_still_persists() {
let restored = round_trip(&graph); let restored = round_trip(&graph);
assert_eq!(restored.masks().len(), 1); assert_eq!(restored.masks().len(), 1);
assert_eq!(restored.masks().layers()[0].source, MaskSource::brush()); assert_eq!(
restored.masks().layers()[0].base().source,
MaskSource::brush()
);
} }
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -576,10 +585,10 @@ fn show_a_sidecar() {
); );
subject.name = "person".into(); subject.name = "person".into();
subject.invert = true; subject.invert = true;
subject.feather = 0.02; subject.base_mut().feather = 0.02;
subject.falloff = dr_pipeline::mask::Falloff::Gaussian; subject.base_mut().falloff = dr_pipeline::mask::Falloff::Gaussian;
subject.morphology = dr_pipeline::mask::Morphology::Dilate; subject.base_mut().morphology = dr_pipeline::mask::Morphology::Dilate;
subject.morph_radius = 0.012; subject.base_mut().morph_radius = 0.012;
subject.set_param("saturation", ParamId("saturation"), -100.0); subject.set_param("saturation", ParamId("saturation"), -100.0);
subject.set_param("exposure", ParamId("exposure"), -0.4); subject.set_param("exposure", ParamId("exposure"), -0.4);
graph.masks_mut().push(subject); graph.masks_mut().push(subject);
@@ -635,7 +644,7 @@ fn category_masks_keep_their_name() {
}, },
); );
sky.name = "sky".into(); sky.name = "sky".into();
sky.feather = 0.03; sky.base_mut().feather = 0.03;
sky.set_param("exposure", ParamId("exposure"), 0.5); sky.set_param("exposure", ParamId("exposure"), 0.5);
graph.masks_mut().push(sky); graph.masks_mut().push(sky);
@@ -655,9 +664,15 @@ fn category_masks_keep_their_name() {
let restored = round_trip(&graph); let restored = round_trip(&graph);
let layers = restored.masks().layers(); let layers = restored.masks().layers();
assert_eq!(layers.len(), 2); assert_eq!(layers.len(), 2);
assert_eq!(layers[0].source, graph.masks().layers()[0].source); assert_eq!(
assert_eq!(layers[1].source, graph.masks().layers()[1].source); layers[0].base().source,
assert!((layers[0].feather - 0.03).abs() < 1e-6); graph.masks().layers()[0].base().source
);
assert_eq!(
layers[1].base().source,
graph.masks().layers()[1].base().source
);
assert!((layers[0].base().feather - 0.03).abs() < 1e-6);
} }
/// The refine strictness survives, and its absence means zero. /// The refine strictness survives, and its absence means zero.
@@ -683,7 +698,7 @@ fn a_categorys_refine_strictness_survives_and_defaults_off() {
name: "sky".into(), name: "sky".into(),
}, },
); );
sky.refine = 3.7; sky.base_mut().refine = 3.7;
graph.masks_mut().push(sky); graph.masks_mut().push(sky);
// Left at zero, so the writer omits the key entirely — which is the case // Left at zero, so the writer omits the key entirely — which is the case
@@ -711,12 +726,13 @@ fn a_categorys_refine_strictness_survives_and_defaults_off() {
let layers = round_trip(&graph); let layers = round_trip(&graph);
let layers = layers.masks().layers(); let layers = layers.masks().layers();
assert!( assert!(
(layers[0].refine - 3.7).abs() < 1e-6, (layers[0].base().refine - 3.7).abs() < 1e-6,
"got {}", "got {}",
layers[0].refine layers[0].base().refine
); );
assert_eq!( assert_eq!(
layers[1].refine, 0.0, layers[1].base().refine,
0.0,
"an absent key is the model's own mask" "an absent key is the model's own mask"
); );
} }
@@ -735,7 +751,7 @@ fn an_out_of_range_refine_is_clamped() {
name: "sky".into(), name: "sky".into(),
}, },
); );
sky.refine = 3.0; sky.base_mut().refine = 3.0;
graph.masks_mut().push(sky); graph.masks_mut().push(sky);
// Edited in the written text rather than assembled by hand, so this test // Edited in the written text rather than assembled by hand, so this test
@@ -754,7 +770,7 @@ fn an_out_of_range_refine_is_clamped() {
.apply(&mut restored) .apply(&mut restored)
.expect_no_film(); .expect_no_film();
let refine = restored.masks().layers()[0].refine; let refine = restored.masks().layers()[0].base().refine;
assert!( assert!(
refine <= dr_pipeline::mask::MAX_REFINE, refine <= dr_pipeline::mask::MAX_REFINE,
"a file asked for 900 and got {refine}" "a file asked for 900 and got {refine}"
@@ -828,7 +844,7 @@ fn inside(values: &[u8]) -> Vec<bool> {
fn with_coverage(id: &str, source: MaskSource, values: &[u8]) -> MaskLayer { fn with_coverage(id: &str, source: MaskSource, values: &[u8]) -> MaskLayer {
let mut layer = MaskLayer::new(id, source); let mut layer = MaskLayer::new(id, source);
layer.set_param("exposure", ParamId("exposure"), 0.75); layer.set_param("exposure", ParamId("exposure"), 0.75);
layer.coverage = Some(Arc::new( layer.base_mut().coverage = Some(Arc::new(
Coverage::encode(values, PROXY.0, PROXY.1, RENDERED_LEVELS).expect("a disc should encode"), Coverage::encode(values, PROXY.0, PROXY.1, RENDERED_LEVELS).expect("a disc should encode"),
)); ));
layer layer
@@ -849,11 +865,15 @@ fn a_subjects_coverage_survives_a_round_trip() {
let layer = &restored.masks().layers()[0]; let layer = &restored.masks().layers()[0];
assert_eq!( assert_eq!(
layer.source, layer.base().source,
subject(0x1234, 2), subject(0x1234, 2),
"the identity is still there" "the identity is still there"
); );
let coverage = layer.coverage.as_ref().expect("the pixels came back too"); let coverage = layer
.base()
.coverage
.as_ref()
.expect("the pixels came back too");
assert_eq!((coverage.width(), coverage.height()), PROXY); assert_eq!((coverage.width(), coverage.height()), PROXY);
assert_eq!( assert_eq!(
inside(&coverage.decode()), inside(&coverage.decode()),
@@ -876,9 +896,9 @@ fn a_categorys_coverage_survives_a_round_trip() {
let restored = round_trip(&graph); let restored = round_trip(&graph);
let layer = &restored.masks().layers()[0]; let layer = &restored.masks().layers()[0];
assert_eq!(layer.source, source); assert_eq!(layer.base().source, source);
assert_eq!( assert_eq!(
inside(&layer.coverage.as_ref().expect("coverage").decode()), inside(&layer.base().coverage.as_ref().expect("coverage").decode()),
inside(&values) inside(&values)
); );
} }
@@ -969,10 +989,10 @@ exposure.exposure = 0.75
.expect_no_film(); .expect_no_film();
let layer = &graph.masks().layers()[0]; let layer = &graph.masks().layers()[0];
assert_eq!(layer.source, subject(4660, 2)); assert_eq!(layer.base().source, subject(4660, 2));
assert_eq!(layer.name, "Dog"); assert_eq!(layer.name, "Dog");
assert!( assert!(
layer.coverage.is_none(), layer.base().coverage.is_none(),
"absent means absent, not an empty mask" "absent means absent, not an empty mask"
); );
} }
@@ -1011,9 +1031,9 @@ coverage = 96 64 999 not-a-payload
.expect_no_film(); .expect_no_film();
let layer = &graph.masks().layers()[0]; let layer = &graph.masks().layers()[0];
assert_eq!(layer.source, subject(4660, 2)); assert_eq!(layer.base().source, subject(4660, 2));
assert_eq!(layer.name, "Dog"); assert_eq!(layer.name, "Dog");
assert!(layer.coverage.is_none()); assert!(layer.base().coverage.is_none());
assert_eq!( assert_eq!(
layer layer
.ops .ops
@@ -1048,8 +1068,8 @@ fn coverage_is_not_loaded_onto_a_source_with_no_model_behind_it() {
.expect_no_film(); .expect_no_film();
let layer = &graph.masks().layers()[0]; let layer = &graph.masks().layers()[0];
assert!(matches!(layer.source, MaskSource::Radial { .. })); assert!(matches!(layer.base().source, MaskSource::Radial { .. }));
assert!(layer.coverage.is_none()); assert!(layer.base().coverage.is_none());
} }
/// TRACES: FR-NC-9 /// TRACES: FR-NC-9
@@ -1063,9 +1083,9 @@ fn coverage_is_not_loaded_onto_a_source_with_no_model_behind_it() {
fn a_coverage_one_device_has_and_the_other_lacks_is_not_a_conflict() { fn a_coverage_one_device_has_and_the_other_lacks_is_not_a_conflict() {
let layer = |with: bool| { let layer = |with: bool| {
let mut l = lit("m1", &[1], 1.0); let mut l = lit("m1", &[1], 1.0);
l.source = subject(7, 0); l.base_mut().source = subject(7, 0);
if with { if with {
l.coverage = Some(Arc::new( l.base_mut().coverage = Some(Arc::new(
Coverage::encode(&a_disc(), PROXY.0, PROXY.1, RENDERED_LEVELS).expect("encode"), Coverage::encode(&a_disc(), PROXY.0, PROXY.1, RENDERED_LEVELS).expect("encode"),
)); ));
} }
@@ -1088,7 +1108,12 @@ fn a_coverage_one_device_has_and_the_other_lacks_is_not_a_conflict() {
"running the model is not an edit: {conflicts:?}" "running the model is not an edit: {conflicts:?}"
); );
assert!( assert!(
ours.masks.get("m1").expect("layer").coverage.is_some(), ours.masks
.get("m1")
.expect("layer")
.base()
.coverage
.is_some(),
"and the side that has the pixels keeps them" "and the side that has the pixels keeps them"
); );
} }
@@ -1104,8 +1129,8 @@ fn a_real_edit_is_still_a_conflict_with_coverage_present() {
}; };
let layer = |ev: f32| { let layer = |ev: f32| {
let mut l = lit("m1", &[1], ev); let mut l = lit("m1", &[1], ev);
l.source = subject(7, 0); l.base_mut().source = subject(7, 0);
l.coverage = stored(); l.base_mut().coverage = stored();
l l
}; };
@@ -1149,11 +1174,11 @@ fn range_masks_keep_their_bands() {
let layers = restored.masks().layers(); let layers = restored.masks().layers();
assert_eq!(layers.len(), 2); assert_eq!(layers.len(), 2);
assert_eq!( assert_eq!(
layers[0].source, layers[0].base().source,
MaskSource::luminance_range(0.62, 0.91, 0.2) MaskSource::luminance_range(0.62, 0.91, 0.2)
); );
assert_eq!( assert_eq!(
layers[1].source, layers[1].base().source,
MaskSource::colour_range(0.07, 0.04, 0.2, 0.85, 0.11) MaskSource::colour_range(0.07, 0.04, 0.2, 0.85, 0.11)
); );
} }
@@ -1200,7 +1225,7 @@ fn a_crossed_band_is_ordered_on_read() {
.expect_no_film(); .expect_no_film();
assert_eq!( assert_eq!(
graph.masks().layers()[0].source, graph.masks().layers()[0].base().source,
MaskSource::luminance_range(0.2, 0.9, 0.1), MaskSource::luminance_range(0.2, 0.9, 0.1),
"the band came back as the one the numbers describe" "the band came back as the one the numbers describe"
); );
@@ -1229,5 +1254,255 @@ fn a_range_mask_with_no_band_falls_back_to_the_default_one() {
.apply(&mut graph) .apply(&mut graph)
.expect_no_film(); .expect_no_film();
assert_eq!(graph.masks().layers()[0].source, MaskSource::highlights()); assert_eq!(
graph.masks().layers()[0].base().source,
MaskSource::highlights()
);
}
// ---------------------------------------------------------------------------
// Parts
// ---------------------------------------------------------------------------
/// A subject with a correction painted on top of it — the ordinary shape of a
/// mask that has been edited by hand.
fn corrected(id: &str, join: Join) -> MaskLayer {
let mut layer = MaskLayer::new(
id,
MaskSource::Subject {
signature: 0xdead_beef,
index: 0,
class: "dog".into(),
score: 0.9,
},
);
layer.set_param("exposure", ParamId("exposure"), 0.5);
layer.push_part(MaskPart::painted(layer.next_part_id(), join));
layer.begin_stroke(1, false, 0.05, 0.5, 1.0);
for &(x, y) in &[(0.2, 0.2), (0.3, 0.25), (0.4, 0.3)] {
layer.extend_stroke(1, x, y);
}
layer.end_stroke(1);
layer
}
/// The property that makes this format change safe: a mask nobody has
/// corrected writes what it has always written, so every sidecar in every
/// library keeps parsing to the same edit and no file grows a block it does
/// not need.
#[test]
fn a_mask_of_one_part_writes_no_part_block() {
let mut sidecar = Sidecar::new();
sidecar.put(Version::from_graph(
"default",
"Default",
&graph_with_mask(),
));
let text = sidecar.to_text();
assert!(text.contains("[mask default m1]"), "{text}");
assert!(
!text.contains("[part "),
"a layer of one part invented a block for it:\n{text}"
);
assert!(
!text.contains("join ="),
"a layer of one part wrote a join nothing joins to:\n{text}"
);
}
/// And the other half of it: a file written before parts existed reads back as
/// a layer of exactly one, rather than as one with an empty correction on it.
#[test]
fn a_mask_block_with_no_part_blocks_is_one_part() {
let layers = round_trip(&graph_with_mask());
let layers = layers.masks().layers();
assert_eq!(layers[0].parts().len(), 1);
assert_eq!(layers[0].parts()[0].id, "p1", "the implied part is named");
assert_eq!(layers[0].parts()[0].join, Join::Union);
}
#[test]
fn a_correction_painted_onto_a_subject_survives_a_round_trip() {
let mut graph = EditGraph::default_chain();
let layer = corrected("m1", Join::Subtract);
let expected = layer.parts()[1].strokes().to_vec();
graph.masks_mut().push(layer);
let restored = round_trip(&graph);
let layer = &restored.masks().layers()[0];
assert_eq!(layer.parts().len(), 2, "both parts came back");
assert_eq!(layer.parts()[1].id, "p2");
assert_eq!(layer.parts()[1].join, Join::Subtract);
assert_eq!(layer.parts()[1].strokes(), expected.as_slice());
assert_eq!(
layer.parts()[0].source.kind(),
"subject",
"and the base is still what it was"
);
}
/// A part carries its own edge, which is the whole reason it is a part rather
/// than a second source on the layer: a model's soft coverage and a stroke
/// painted where it stopped short want different boundaries.
#[test]
fn each_part_keeps_its_own_shaping() {
let mut graph = EditGraph::default_chain();
let mut layer = corrected("m1", Join::Union);
layer.base_mut().feather = 0.02;
layer.base_mut().morphology = Morphology::Dilate;
layer.base_mut().morph_radius = 0.01;
layer.parts_mut()[1].feather = 0.0;
layer.parts_mut()[1].invert = true;
graph.masks_mut().push(layer);
let restored = round_trip(&graph);
let layer = &restored.masks().layers()[0];
assert_eq!(layer.parts()[0].feather, 0.02);
assert_eq!(layer.parts()[0].morphology, Morphology::Dilate);
assert_eq!(layer.parts()[1].feather, 0.0);
assert!(layer.parts()[1].invert);
assert!(
!layer.invert,
"the layer's own inversion is a different one"
);
}
#[test]
fn writing_a_corrected_mask_twice_is_byte_identical() {
let mut graph = EditGraph::default_chain();
graph.masks_mut().push(corrected("m1", Join::Subtract));
let mut sidecar = Sidecar::new();
sidecar.put(Version::from_graph("default", "Default", &graph));
let first = sidecar.to_text();
let second = Sidecar::parse(&first).expect("reparse").to_text();
assert_eq!(first, second);
}
/// A part block that names another mask is somebody's correction attached to
/// the wrong photograph if it is honoured. Dropped — and, more importantly,
/// its keys must not fall through to the version, where a `stroke` line would
/// be a global edit nobody made.
#[test]
fn a_part_naming_a_different_mask_is_dropped() {
let text = "drsc 1\n\
\n[version default]\n\
name = Default\n\
exposure.exposure = 0.25\n\
\n[mask default m1]\n\
source = brush\n\
exposure.exposure = 1\n\
\n[part default m9 p2]\n\
join = subtract\n\
source = brush\n\
stroke = add 0.05 0.5 1 0.2,0.2 0.3,0.3\n";
let parsed = Sidecar::parse(text).expect("parse");
let mut graph = EditGraph::default_chain();
parsed
.versions
.get("default")
.expect("version")
.apply(&mut graph)
.expect_no_film();
let layer = &graph.masks().layers()[0];
assert_eq!(layer.parts().len(), 1, "the orphan part was not attached");
assert_eq!(
graph.param(OpId("exposure"), ParamId("exposure")),
Some(0.25),
"and its keys did not land on the version"
);
}
/// The rule a malformed stroke already follows, one level up: a part this
/// build cannot read costs that part, and the rest of the mask — which is work
/// somebody did — survives.
#[test]
fn a_part_with_an_unknown_source_costs_only_that_part() {
let text = "drsc 1\n\
\n[version default]\n\
name = Default\n\
\n[mask default m1]\n\
source = brush\n\
stroke = add 0.05 0.5 1 0.1,0.1 0.2,0.2\n\
exposure.exposure = 1\n\
\n[part default m1 p2]\n\
join = union\n\
source = hologram\n";
let parsed = Sidecar::parse(text).expect("parse");
let mut graph = EditGraph::default_chain();
parsed
.versions
.get("default")
.expect("version")
.apply(&mut graph)
.expect_no_film();
let layer = &graph.masks().layers()[0];
assert_eq!(layer.parts().len(), 1);
assert_eq!(layer.strokes().len(), 1, "the base kept its stroke");
}
/// An unknown join adds, rather than dropping the part. A selection that is
/// visible can be fixed by the photographer; one that quietly took pixels away
/// under a name this build could not read cannot be.
#[test]
fn an_unknown_join_adds_the_part() {
let text = "drsc 1\n\
\n[version default]\n\
name = Default\n\
\n[mask default m1]\n\
source = brush\n\
exposure.exposure = 1\n\
\n[part default m1 p2]\n\
join = xor\n\
source = brush\n\
stroke = add 0.05 0.5 1 0.2,0.2 0.3,0.3\n";
let parsed = Sidecar::parse(text).expect("parse");
let mut graph = EditGraph::default_chain();
parsed
.versions
.get("default")
.expect("version")
.apply(&mut graph)
.expect_no_film();
let layer = &graph.masks().layers()[0];
assert_eq!(layer.parts().len(), 2);
assert_eq!(layer.parts()[1].join, Join::Union);
}
/// Two devices, one correcting a mask and one leaving it alone: the correction
/// arrives, because a layer merges as a whole and the part travelled with it.
#[test]
fn a_correction_made_on_one_device_reaches_the_other() {
let base = version_with("default", 1, |g| {
g.masks_mut().push(lit("m1", &[1, 2], 0.5));
});
let mut ours = base.clone();
ours.revision = 2;
let mut theirs = base.clone();
theirs.revision = 3;
if let Some(layer) = theirs.masks.get_mut("m1") {
layer.push_part(MaskPart::painted("p2", Join::Subtract));
layer.begin_stroke(1, false, 0.05, 0.5, 1.0);
layer.extend_stroke(1, 0.2, 0.2);
layer.extend_stroke(1, 0.4, 0.4);
layer.end_stroke(1);
}
let conflicts = ours.merge(&theirs, Some(&base));
assert!(conflicts.is_empty(), "only one side changed the layer");
let layer = ours.masks.get("m1").expect("layer");
assert_eq!(layer.parts().len(), 2);
assert_eq!(layer.parts()[1].join, Join::Subtract);
} }
+29 -67
View File
@@ -5,7 +5,7 @@
Every entry here is extracted from the comment beside the code that implements it, so this file cannot describe a gesture the application does not have. Add one by writing a `GESTURE:` block next to the implementation; there is nowhere else to write it. Every entry here is extracted from the comment beside the code that implements it, so this file cannot describe a gesture the application does not have. Add one by writing a `GESTURE:` block next to the implementation; there is nowhere else to write it.
35 gestures, in 4 places. 31 gestures, in 3 places.
## Develop ## Develop
@@ -25,7 +25,16 @@ Sampling a neutral is the first move of the tonal pass — every colour judgemen
Anchored on the fingers' midpoint, and on the pointer, so the gesture reads as magnifying the picture rather than sliding it about. Double-tap is the way to an exact 1:1; this is the way to everything in between. Anchored on the fingers' midpoint, and on the pointer, so the gesture reads as magnifying the picture rather than sliding it about. Double-tap is the way to an exact 1:1; this is the way to everything in between.
<sub>`ui/dr-ui/ui/app.slint:2064`</sub> <sub>`ui/dr-ui/ui/app.slint:2018`</sub>
### Paint a mask by hand
- **Touch** — Choose Paint or Erase, then drag on the photograph
- **Pointer** — Choose Paint or Erase, then drag
A model's mask stops inside a shoulder and leaks into the hair, and no single edge control fixes two errors that go opposite ways. The whole stroke is one step in the history, so taking a mark back costs one press however long it took to make.
<sub>`ui/dr-ui/ui/app.slint:2091`</sub>
### Move a magnified photograph about ### Move a magnified photograph about
@@ -34,7 +43,7 @@ Anchored on the fingers' midpoint, and on the pointer, so the gesture reads as m
Only once there is something outside the viewport to reach, which is why the cursor becomes a hand exactly then. The view is clamped to the frame: panning past the edge would show undefined area beside the photograph, and that reads as a rendering fault rather than as the end of the picture. Only once there is something outside the viewport to reach, which is why the cursor becomes a hand exactly then. The view is clamped to the frame: panning past the edge would show undefined area beside the photograph, and that reads as a rendering fault rather than as the end of the picture.
<sub>`ui/dr-ui/ui/app.slint:2217`</sub> <sub>`ui/dr-ui/ui/app.slint:2224`</sub>
### Take back the last change ### Take back the last change
@@ -44,7 +53,7 @@ Only once there is something outside the viewport to reach, which is why the cur
A whole drag is one step, so undo takes back a decision rather than a frame of a gesture. The list is there because arriving six steps back costs what arriving from one does. A whole drag is one step, so undo takes back a decision rather than a frame of a gesture. The list is there because arriving six steps back costs what arriving from one does.
<sub>`ui/dr-ui/ui/app.slint:2384`</sub> <sub>`ui/dr-ui/ui/app.slint:2391`</sub>
### Do it again after taking it back ### Do it again after taking it back
@@ -52,7 +61,7 @@ A whole drag is one step, so undo takes back a decision rather than a frame of a
- **Pointer** — Click it, or press Redo in the History header - **Pointer** — Click it, or press Redo in the History header
- **Keyboard** — Ctrl+Shift+Z - **Keyboard** — Ctrl+Shift+Z
<sub>`ui/dr-ui/ui/app.slint:2397`</sub> <sub>`ui/dr-ui/ui/app.slint:2404`</sub>
### Copy the settings from this photograph ### Copy the settings from this photograph
@@ -62,7 +71,7 @@ A whole drag is one step, so undo takes back a decision rather than a frame of a
The panel is the copy that has to work: a tablet has no modifier key to hold and no menu bar to hang the action from. The shortcut is an accelerator for a control that is on screen either way. The panel is the copy that has to work: a tablet has no modifier key to hold and no menu bar to hang the action from. The shortcut is an accelerator for a control that is on screen either way.
<sub>`ui/dr-ui/ui/app.slint:2430`</sub> <sub>`ui/dr-ui/ui/app.slint:2437`</sub>
### Paste the settings onto this photograph ### Paste the settings onto this photograph
@@ -72,7 +81,7 @@ The panel is the copy that has to work: a tablet has no modifier key to hold and
The button names what would be pasted — "3 adjustments", and whether the crop is coming with it — which the shortcut cannot say. Both paste the same scope. The button names what would be pasted — "3 adjustments", and whether the crop is coming with it — which the shortcut cannot say. Both paste the same scope.
<sub>`ui/dr-ui/ui/app.slint:2442`</sub> <sub>`ui/dr-ui/ui/app.slint:2449`</sub>
### Change which group of adjustments is on screen ### Change which group of adjustments is on screen
@@ -82,7 +91,7 @@ The button names what would be pasted — "3 adjustments", and whether the crop
The groups are whatever the operation set declares itself to be about, so there are as many as the pipeline has and no key can be assigned to one of them by name. Stepping is the binding that survives a node being added. The groups are whatever the operation set declares itself to be about, so there are as many as the pipeline has and no key can be assigned to one of them by name. Stepping is the binding that survives a node being added.
<sub>`ui/dr-ui/ui/app.slint:2470`</sub> <sub>`ui/dr-ui/ui/app.slint:2477`</sub>
### Look at the photograph at 1:1 ### Look at the photograph at 1:1
@@ -92,7 +101,7 @@ The groups are whatever the operation set declares itself to be about, so there
Noise reduction and capture sharpening are judgements about single pixels, and a fitted view averages several of the file's into each one on screen — so the frame looks softer than it is and the correction goes too far. The point and the magnification survive opening the next photograph, which is what makes checking the same eye across forty portraits forty keystrokes rather than forty pans. Noise reduction and capture sharpening are judgements about single pixels, and a fitted view averages several of the file's into each one on screen — so the frame looks softer than it is and the correction goes too far. The point and the magnification survive opening the next photograph, which is what makes checking the same eye across forty portraits forty keystrokes rather than forty pans.
<sub>`ui/dr-ui/ui/app.slint:2505`</sub> <sub>`ui/dr-ui/ui/app.slint:2512`</sub>
### Move to the next or previous photograph ### Move to the next or previous photograph
@@ -102,7 +111,7 @@ Noise reduction and capture sharpening are judgements about single pixels, and a
The edit on screen is saved on the way out, so stepping through a folder is as much a departure as going back to the grid and loses nothing. The edit on screen is saved on the way out, so stepping through a folder is as much a departure as going back to the grid and loses nothing.
<sub>`ui/dr-ui/ui/app.slint:2535`</sub> <sub>`ui/dr-ui/ui/app.slint:2542`</sub>
### See the photograph before you edited it ### See the photograph before you edited it
@@ -112,7 +121,7 @@ The edit on screen is saved on the way out, so stepping through a folder is as m
Held rather than toggled, and no split screen: a split halves the working image on the tablet the column was sized for, and the comparison photographers describe making is a flick back and forth. It takes no history step, so checking whether a frame is overcooked costs nothing to undo afterwards. Held rather than toggled, and no split screen: a split halves the working image on the tablet the column was sized for, and the comparison photographers describe making is a flick back and forth. It takes no history step, so checking whether a frame is overcooked costs nothing to undo afterwards.
<sub>`ui/dr-ui/ui/app.slint:2659`</sub> <sub>`ui/dr-ui/ui/app.slint:2666`</sub>
### Put one control back to its default ### Put one control back to its default
@@ -130,45 +139,7 @@ The column is 280px wide and the colour mixer alone puts thirty-six of these in
Disabling a layer is the before-and-after a local edit constantly wants, so it is one press away rather than inside the row. It is an edit and does take a history step, unlike holding "Before" — the layer really is off until it is switched back on. Disabling a layer is the before-and-after a local edit constantly wants, so it is one press away rather than inside the row. It is an edit and does take a history step, unlike holding "Before" — the layer really is off until it is switched back on.
<sub>`ui/dr-ui/ui/masks.slint:163`</sub> <sub>`ui/dr-ui/ui/masks.slint:195`</sub>
## Collections sidebar
### Pick a collection up to rearrange the tree
- **Touch** — Press and hold it until it lifts, then drag it
- **Pointer** — Drag it, or hold it until it lifts and then drag
The tree is inside a Flickable, which claims any drag beginning inside it — so with a finger a drag on a row is a scroll until something says otherwise. The hold is that something, and it is what every mobile list already uses to pick a row up. The row lifts the moment it fires, so the gesture says it has been understood before anything moves.
<sub>`ui/dr-ui/ui/collections.slint:335`</sub>
### Act on a collection — rename, nest, un-nest, delete
- **Touch** — Press and hold the collection, then let go without moving
- **Pointer** — Right-click it
The hold arms a drag and opens this menu, and which one you get is decided by whether you moved — the same fork the grid uses. One menu for everything done to a row, because there is one hold per row: while the hold opened the offline question by itself, nothing else the tree can do had a touch route.
<sub>`ui/dr-ui/ui/collections.slint:346`</sub>
### Take a collection back out of the one it is nested in
- **Touch** — Hold it, then drag it onto "All photographs" — or let go and choose "Move to top level"
- **Pointer** — Drag it onto "All photographs", or right-click it and choose "Move to top level"
Nesting is a drag of one row onto another, and its inverse had no gesture at all: "All photographs" refused every drop, which is right for a photograph — it is already in the library — and wrong for a collection, which has a top level to be returned to. Without it a collection dragged into another was in there permanently.
<sub>`ui/dr-ui/ui/collections.slint:356`</sub>
### Rename a collection
- **Touch** — Hold the collection, then "Rename"
- **Pointer** — Double-click its name, or right-click it and choose "Rename"
Double-click is what a file manager and a Lightroom panel use for the same thing, so it needs no discovering — but nothing on screen says so, which is what the menu item is for.
<sub>`ui/dr-ui/ui/collections.slint:369`</sub>
## People ## People
@@ -261,7 +232,7 @@ This replaced a double tap, which had no visible state and could take forty phot
"Any of them" is a union and "all of them" is an intersection. The tray is where both terms and the choice between them live, because a filter belongs on the filter bar. "Any of them" is a union and "all of them" is an intersection. The tray is where both terms and the choice between them live, because a filter belongs on the filter bar.
<sub>`ui/dr-ui/ui/library.slint:2102`</sub> <sub>`ui/dr-ui/ui/library.slint:2096`</sub>
### Resize the thumbnails ### Resize the thumbnails
@@ -270,7 +241,7 @@ This replaced a double tap, which had no visible state and could take forty phot
There is no wheel on a tablet, so without the pinch the cell size could only be changed by a control a finger cannot reach. There is no wheel on a tablet, so without the pinch the cell size could only be changed by a control a finger cannot reach.
<sub>`ui/dr-ui/ui/library.slint:2755`</sub> <sub>`ui/dr-ui/ui/library.slint:2749`</sub>
### File photographs in a collection ### File photographs in a collection
@@ -279,7 +250,7 @@ There is no wheel on a tablet, so without the pinch the cell size could only be
The selection is what the drag carries, which is why selecting several is worth the mode: forty photographs file in one gesture. The selection is what the drag carries, which is why selecting several is worth the mode: forty photographs file in one gesture.
<sub>`ui/dr-ui/ui/library.slint:2952`</sub> <sub>`ui/dr-ui/ui/library.slint:2946`</sub>
### Open a photograph ### Open a photograph
@@ -288,7 +259,7 @@ The selection is what the drag carries, which is why selecting several is worth
A tap opens; a tap that *moved* does not. Travel is what separates a deliberate tap from a hand brushing past, and it is the only thing that does: the two are the same length. An earlier version required the finger to dwell 120 ms instead, and that rejected ordinary taps — a real tap is often quicker than a brush. A tap opens; a tap that *moved* does not. Travel is what separates a deliberate tap from a hand brushing past, and it is the only thing that does: the two are the same length. An earlier version required the finger to dwell 120 ms instead, and that rejected ordinary taps — a real tap is often quicker than a brush.
<sub>`ui/dr-ui/ui/library.slint:3220`</sub> <sub>`ui/dr-ui/ui/library.slint:3214`</sub>
### Rate a photograph without opening it ### Rate a photograph without opening it
@@ -298,7 +269,7 @@ A tap opens; a tap that *moved* does not. Travel is what separates a deliberate
A star has to take the press without it also reaching the cell, or every rating throws the user into develop. A star has to take the press without it also reaching the cell, or every rating throws the user into develop.
<sub>`ui/dr-ui/ui/library.slint:3340`</sub> <sub>`ui/dr-ui/ui/library.slint:3334`</sub>
### Choose the frame a folded burst shows ### Choose the frame a folded burst shows
@@ -307,7 +278,7 @@ A star has to take the press without it also reaching the cell, or every rating
A folded burst draws its earliest frame, which is a fact about the clock and not a judgement about the photograph — nothing in this application ranks a frame (FR-CULL-5). But the point of a burst is that one of the twelve is better than the other eleven, and the photographer is the only one who knows which. So the choice is offered on the frames themselves, while they are open and side by side, which is the one moment the alternatives are on screen to be compared. A folded burst draws its earliest frame, which is a fact about the clock and not a judgement about the photograph — nothing in this application ranks a frame (FR-CULL-5). But the point of a burst is that one of the twelve is better than the other eleven, and the photographer is the only one who knows which. So the choice is offered on the frames themselves, while they are open and side by side, which is the one moment the alternatives are on screen to be compared.
<sub>`ui/dr-ui/ui/library.slint:3471`</sub> <sub>`ui/dr-ui/ui/library.slint:3465`</sub>
### Drop the selection but keep selecting ### Drop the selection but keep selecting
@@ -316,7 +287,7 @@ A folded burst draws its earliest frame, which is a fact about the clock and not
Distinct from Done, which leaves the mode entirely. Clearing keeps it, so the next selection can start straight away. Distinct from Done, which leaves the mode entirely. Clearing keeps it, so the next selection can start straight away.
<sub>`ui/dr-ui/ui/library.slint:4132`</sub> <sub>`ui/dr-ui/ui/library.slint:4126`</sub>
### Select everything the grid is showing ### Select everything the grid is showing
@@ -325,13 +296,4 @@ Distinct from Done, which leaves the mode entirely. Clearing keeps it, so the ne
A scoped grid of two hundred frames is two hundred taps otherwise, and "all of them, except those three" is a far more common shape than the taps it took to say it. A scoped grid of two hundred frames is two hundred taps otherwise, and "all of them, except those three" is a far more common shape than the taps it took to say it.
<sub>`ui/dr-ui/ui/library.slint:4149`</sub> <sub>`ui/dr-ui/ui/library.slint:4143`</sub>
### Take photographs out of a collection
- **Touch** — Select them, then "Collections…" in the selection bar
- **Pointer** — Select them, then "Collections…" in the selection bar
The badge on a cell says a photograph is filed in three collections and never which. This is the sheet that names them, and the only way out of one the grid is not currently scoped to.
<sub>`ui/dr-ui/ui/library.slint:4264`</sub>
+23 -7
View File
@@ -259,16 +259,32 @@ slice, so eight layers still cost eight channels.
The set operations are already expressible in fixed-function blending over The set operations are already expressible in fixed-function blending over
`r8unorm`, which is why this is the cheap half of the feature: `r8unorm`, which is why this is the cheap half of the feature:
| Join | `src_factor`, `dst_factor`, op | Result | | Join | `src_factor`, `dst_factor`, op | Result | Built |
|------|-------------------------------|--------| |------|-------------------------------|--------|-------|
| Union | `One`, `One`, `Max` | `max(dst, src)` | | Union | `One`, `One`, `Max` | `max(dst, src)` | M1 |
| Subtract | `Zero`, `OneMinusSrc`, `Add` | `dst · (1 − src)` | | Subtract | `Zero`, `OneMinusSrc`, `Add` | `dst · (1 − src)` | M1 |
| Intersect | `Zero`, `Src`, `Add` | `dst · src` | | Intersect | `Zero`, `Src`, `Add` | `dst · src` | M2 |
The middle row is `brush_erase`, already constructed in The middle row is `brush_erase`, already constructed in
[`MaskPass::new`](../core/dr-gpu/src/mask.rs). The other two are the same [`MaskPass::new`](../core/dr-gpu/src/mask.rs). The other two are the same
pipeline with a different `BlendState` — three pipeline variants over one three vertices with a different `BlendState`, and nothing is read back.
shader, no new bind group layout, no new shader code, and nothing read back.
**One correction to the first draft of this section, found in the building.**
It claimed no second texture was needed, because a part could be blended
straight onto the layer's slice. That is wrong, and the reason is the erase
stroke: an erase inside a part means *a hole in that part*, not a hole in the
mask. Drawn straight onto the accumulator it takes away whatever the parts
before it had put there — so tidying the edge of a correction punches through
the subject underneath, and the failure reads as the model's mask having holes
in it.
So a part is drawn into one scratch texture (proxy-sized, `r8unorm`, allocated
the first time any layer has more than one part) and blended from there. A
layer of one part still takes the old path exactly — straight into its slice,
no scratch, no combine pass — which is what keeps every existing mask
rendering as it did. `an_erase_stroke_holes_its_own_part_and_not_the_mask` in
[`local_adjustments.rs`](../core/dr-gpu/tests/local_adjustments.rs) is the test
that holds this in place.
`Max` blending on `r8unorm` is core WGPU and universally supported on the `Max` blending on `r8unorm` is core WGPU and universally supported on the
desktop backends; **verify it on the Android adapter before M2 lands**, since desktop backends; **verify it on the Android adapter before M2 lands**, since
+22
View File
@@ -495,6 +495,28 @@ blend without a halo — the boundary is the picture's own, at whatever detail t
also the only route to selecting by skin tone, and the prerequisite for composing a selection from also the only route to selecting by skin tone, and the prerequisite for composing a selection from
several criteria at once. several criteria at once.
**FR-DEV-19 — Mask editing.** A mask layer's coverage shall be editable by hand after it is
created: painted into, erased from, and built from more than one selection. Every edit is stored as
geometry and parameters in the edit graph; no rasterised mask is written to a file and none exists
in CPU memory (ARCH §5.4).
A model finds a subject in a second and, before this, the photographer could not then change it by a
single pixel. The coverage arrives approximately right — stopping inside a shoulder, leaking into
the hair — and FR-DEV-3's edge controls move the *whole* boundary, so no value of either fixes two
errors that go opposite ways. Every competing developer has had a brush over its selections for a
decade; a mask that cannot be corrected is the reason an edit leaves this application for a pixel
editor.
**FR-DEV-19a — Mask composition.** A layer's mask is an ordered list of parts, each naming a source
and how it joins the mask before it — added to it, or taken out of it. A layer of one part is
exactly the layer that existed before this, and reads and writes the same sidecar. The parts of a
layer merge under FR-NC-9 as the layer does, and each carries its own edge treatment.
**FR-DEV-19b — Hand correction.** A part may be painted, with add and erase strokes, at a radius,
hardness and flow the photographer sets. Strokes are stored as normalised source coordinates and
rasterised on the device, so a correction stays on what it was painted on through a crop, a zoom and
an export at any size. A whole stroke is one step in the history.
### 3.4 Display and interaction ### 3.4 Display and interaction
**FR-DSP-1 — Proxy-resolution rendering.** The develop view renders at the resolution actually **FR-DSP-1 — Proxy-resolution rendering.** The develop view renders at the resolution actually
+62 -59
View File
File diff suppressed because one or more lines are too long
+363 -60
View File
@@ -830,6 +830,30 @@ pub struct DevelopSession {
/// "make these three subjects a stop darker" is one gesture rather than /// "make these three subjects a stop darker" is one gesture rather than
/// three. Order is insertion order and nothing reads it, only membership. /// three. Order is insertion order and nothing reads it, only membership.
active_masks: Vec<String>, active_masks: Vec<String>,
/// TRACES: FR-DEV-19a
/// Which part of the selected layer the tools and the edge controls point
/// at. Zero — the base — whenever a layer is selected afresh.
///
/// An index rather than an id, because it addresses a row the panel is
/// already showing by position, and because a gesture that outlived the
/// part it was aimed at would be a stroke landing somewhere nobody asked
/// for. Clamped on the way in and re-checked on the way out.
active_part: usize,
/// TRACES: FR-DEV-19b
/// The layer and part a stroke in progress is going into.
///
/// Captured on press and held for the gesture: the panel's selection can
/// change under a finger — a stray tap, a sync arriving — and a stroke
/// that changed target half way through would leave half a mark in each.
painting: Option<(String, usize)>,
/// TRACES: FR-DEV-19b
/// The brush: radius as a fraction of the frame's shorter edge, hardness,
/// and flow.
///
/// On the session rather than on a layer, because it belongs to the
/// *tool*: somebody who sets a small eraser expects it to still be small
/// the next time they erase, whichever mask they are working on.
brush: (f32, f32, f32),
/// TRACES: FR-DEV-8 /// TRACES: FR-DEV-8
/// Which repair the panel is describing, if any. /// Which repair the panel is describing, if any.
/// ///
@@ -987,6 +1011,13 @@ impl DevelopSession {
subjects: None, subjects: None,
subject_key: 0, subject_key: 0,
active_masks: Vec::new(), active_masks: Vec::new(),
active_part: 0,
painting: None,
brush: (
dr_pipeline::mask::DEFAULT_BRUSH_RADIUS,
dr_pipeline::mask::DEFAULT_BRUSH_HARDNESS,
dr_pipeline::mask::DEFAULT_BRUSH_FLOW,
),
selected_spot: None, selected_spot: None,
show_overlay: false, show_overlay: false,
active_tab: None, active_tab: None,
@@ -1903,17 +1934,17 @@ impl DevelopSession {
}; };
for layer in self.graph.masks().active() { for layer in self.graph.masks().active() {
match &layer.source { match &layer.base().source {
MaskSource::Subject { index, .. } => { MaskSource::Subject { index, .. } => {
mix(1); mix(1);
mix(*index as u64); mix(*index as u64);
if layer.morphology.is_compound() { if layer.base().morphology.is_compound() {
mix(match layer.morphology { mix(match layer.base().morphology {
Morphology::Close => 2, Morphology::Close => 2,
Morphology::Open => 3, Morphology::Open => 3,
_ => 0, _ => 0,
}); });
mix(layer.morph_radius.to_bits() as u64); mix(layer.base().morph_radius.to_bits() as u64);
} }
} }
// Hashed by *name*, and `4` rather than `1` so a category // Hashed by *name*, and `4` rather than `1` so a category
@@ -1925,13 +1956,13 @@ impl DevelopSession {
mix(*b as u64); mix(*b as u64);
} }
// Only the compound operations change the field itself. // Only the compound operations change the field itself.
if layer.morphology.is_compound() { if layer.base().morphology.is_compound() {
mix(match layer.morphology { mix(match layer.base().morphology {
Morphology::Close => 2, Morphology::Close => 2,
Morphology::Open => 3, Morphology::Open => 3,
_ => 0, _ => 0,
}); });
mix(layer.morph_radius.to_bits() as u64); mix(layer.base().morph_radius.to_bits() as u64);
} }
// The refine control changes which pixels are in the mask // The refine control changes which pixels are in the mask
// at all, so it changes the coverage the field is measured // at all, so it changes the coverage the field is measured
@@ -1939,7 +1970,7 @@ impl DevelopSession {
// is already correct. Omitting it here is the bug where // is already correct. Omitting it here is the bug where
// the slider moves and nothing happens until some other // the slider moves and nothing happens until some other
// control happens to invalidate the cache. // control happens to invalidate the cache.
mix(layer.refine.to_bits() as u64); mix(layer.base().refine.to_bits() as u64);
} }
_ => mix(0), _ => mix(0),
} }
@@ -1975,8 +2006,10 @@ impl DevelopSession {
let live = self let live = self
.segmentation .segmentation
.as_ref() .as_ref()
.and_then(|seg| match &layer.source { .and_then(|seg| match &layer.base().source {
MaskSource::Category { name, .. } => seg.category_mask_at(name, layer.refine), MaskSource::Category { name, .. } => {
seg.category_mask_at(name, layer.base().refine)
}
MaskSource::Subject { index, .. } => { MaskSource::Subject { index, .. } => {
seg.instance_mask(*index as usize).map(Cow::Borrowed) seg.instance_mask(*index as usize).map(Cow::Borrowed)
} }
@@ -1986,10 +2019,11 @@ impl DevelopSession {
return live; return live;
} }
match layer.source { match layer.base().source {
// Resampled where it was written against a different proxy edge; // Resampled where it was written against a different proxy edge;
// in the ordinary case the sizes match and this is the decode. // in the ordinary case the sizes match and this is the decode.
MaskSource::Subject { .. } | MaskSource::Category { .. } => layer MaskSource::Subject { .. } | MaskSource::Category { .. } => layer
.base()
.coverage .coverage
.as_ref() .as_ref()
.map(|stored| Cow::Owned(stored.decode_at(width, height))), .map(|stored| Cow::Owned(stored.decode_at(width, height))),
@@ -2038,8 +2072,10 @@ impl DevelopSession {
let (pw, ph) = seg.proxy_size(); let (pw, ph) = seg.proxy_size();
for layer in stack.layers_mut() { for layer in stack.layers_mut() {
let values = match &layer.source { let values = match &layer.base().source {
MaskSource::Category { name, .. } => seg.category_mask_at(name, layer.refine), MaskSource::Category { name, .. } => {
seg.category_mask_at(name, layer.base().refine)
}
MaskSource::Subject { index, .. } => { MaskSource::Subject { index, .. } => {
seg.instance_mask(*index as usize).map(Cow::Borrowed) seg.instance_mask(*index as usize).map(Cow::Borrowed)
} }
@@ -2059,7 +2095,8 @@ impl DevelopSession {
// would describe the layer at some earlier refine, and a mask of // would describe the layer at some earlier refine, and a mask of
// the wrong shape presented as authoritative is worse than the // the wrong shape presented as authoritative is worse than the
// honest state, which is that this one needs the model run. // honest state, which is that this one needs the model run.
layer.coverage = Coverage::encode(&values, pw, ph, RENDERED_LEVELS).map(Arc::new); layer.base_mut().coverage =
Coverage::encode(&values, pw, ph, RENDERED_LEVELS).map(Arc::new);
} }
stack stack
@@ -2096,10 +2133,10 @@ impl DevelopSession {
pw, pw,
ph, ph,
128, 128,
morphology_for(layer.morphology), morphology_for(layer.base().morphology),
// Radii are fractions of the shorter edge; the field // Radii are fractions of the shorter edge; the field
// is in proxy pixels. // is in proxy pixels.
layer.morph_radius * pw.min(ph) as f32, layer.base().morph_radius * pw.min(ph) as f32,
) )
.distance .distance
} }
@@ -2322,7 +2359,7 @@ impl DevelopSession {
/// `None` for a layer that is not a subject at all (a gradient has no /// `None` for a layer that is not a subject at all (a gradient has no
/// instance to re-detect). /// instance to re-detect).
pub fn subject_instance_index(&self, id: &str) -> Option<usize> { pub fn subject_instance_index(&self, id: &str) -> Option<usize> {
match &self.graph.masks().get(id)?.source { match &self.graph.masks().get(id)?.base().source {
MaskSource::Subject { index, .. } => Some(*index as usize), MaskSource::Subject { index, .. } => Some(*index as usize),
_ => None, _ => None,
} }
@@ -2487,7 +2524,7 @@ impl DevelopSession {
/// What kind of mask a layer is — "regions", "linear", "radial". /// What kind of mask a layer is — "regions", "linear", "radial".
pub fn mask_kind(&self, id: &str) -> &'static str { pub fn mask_kind(&self, id: &str) -> &'static str {
self.graph.masks().get(id).map_or("", |l| l.source.kind()) self.part_of(id).map_or("", |p| p.source.kind())
} }
pub fn mask_inverted(&self, id: &str) -> bool { pub fn mask_inverted(&self, id: &str) -> bool {
@@ -2544,7 +2581,7 @@ impl DevelopSession {
return Vec::new(); return Vec::new();
}; };
let (sw, sh) = self.demosaiced.size(); let (sw, sh) = self.demosaiced.size();
crate::gradient::handles(&layer.source, self.graph.framing(), (sw, sh)) crate::gradient::handles(&layer.base().source, self.graph.framing(), (sw, sh))
} }
/// Drag one handle of the selected gradient, from `press` to `now`, both /// Drag one handle of the selected gradient, from `press` to `now`, both
@@ -2569,11 +2606,11 @@ impl DevelopSession {
let id = self.active_masks.first()?.clone(); let id = self.active_masks.first()?.clone();
let start = match origin { let start = match origin {
Some(s) => s.clone(), Some(s) => s.clone(),
None => self.graph.masks().get(&id)?.source.clone(), None => self.graph.masks().get(&id)?.base().source.clone(),
}; };
let moved = crate::gradient::drag(&start, role, press, now, &framing, (sw, sh)); let moved = crate::gradient::drag(&start, role, press, now, &framing, (sw, sh));
self.graph.masks_mut().get_mut(&id)?.source = moved; self.graph.masks_mut().get_mut(&id)?.base_mut().source = moved;
// **Nothing recorded here.** A drag delivers a pointer event a frame, // **Nothing recorded here.** A drag delivers a pointer event a frame,
// and a history step per frame would make undo walk a gesture back // and a history step per frame would make undo walk a gesture back
// pixel by pixel. `Edit` coalesces by operation id and a mask's shape // pixel by pixel. `Edit` coalesces by operation id and a mask's shape
@@ -2591,6 +2628,266 @@ impl DevelopSession {
.record(&self.graph, Edit::Action(labels::step::MASK_MOVED)); .record(&self.graph, Edit::Action(labels::step::MASK_MOVED));
} }
// --- editing a mask by hand (FR-DEV-19) --------------------------------
/// TRACES: FR-DEV-19a
/// Which part of `id` the edge controls act on.
///
/// The selected part when this is the layer being edited, and the base
/// otherwise — because a panel that is not showing a layer's parts has not
/// offered anybody a way to choose one, and answering with a part they
/// cannot see would make the same slider mean different things depending
/// on what was selected a moment ago.
fn shaped_part(&self, id: &str) -> usize {
match self.active_masks.as_slice() {
[only] if only == id => self.active_part,
_ => 0,
}
}
/// The part of `id` the edge controls read.
fn part_of(&self, id: &str) -> Option<&dr_pipeline::mask::MaskPart> {
let index = self.shaped_part(id);
self.graph.masks().get(id)?.part(index)
}
/// The same, to write through.
fn part_of_mut(&mut self, id: &str) -> Option<&mut dr_pipeline::mask::MaskPart> {
let index = self.shaped_part(id);
self.graph.masks_mut().get_mut(id)?.part_mut(index)
}
/// Which part of the selected layer the tools point at.
pub fn active_part(&self) -> usize {
self.active_part
}
/// Point the tools at one part, or at the base when the index is past the
/// end — which is what a part being removed under the selection leaves.
pub fn set_active_part(&mut self, index: usize) {
let parts = self.active_layer().map_or(1, |l| l.parts().len());
self.active_part = if index < parts { index } else { 0 };
}
/// The parts of a layer: id, what to call it, and how it joins.
///
/// The join of the first is meaningless — there is nothing before it to
/// join to — and the panel shows it as the selection the layer *is*
/// rather than as a row with a chip that does nothing.
pub fn mask_parts(&self, id: &str) -> Vec<(String, String, usize)> {
let Some(layer) = self.graph.masks().get(id) else {
return Vec::new();
};
layer
.parts()
.iter()
.map(|p| {
let join = dr_pipeline::mask::Join::ALL
.iter()
.position(|&j| j == p.join)
.unwrap_or(0);
(p.id.clone(), p.source.kind().to_string(), join)
})
.collect()
}
/// TRACES: FR-DEV-19a
/// Join a fresh painted part to a layer, returning its index.
///
/// Painted, because that is the correction a photographer reaches for
/// first and the only source that needs nothing found for it. The other
/// sources arrive when a part can carry its own distance field.
pub fn add_mask_part(&mut self, id: &str, join: usize) -> Option<usize> {
use dr_pipeline::mask::{Join, MaskPart};
let &join = Join::ALL.get(join)?;
let layer = self.graph.masks_mut().get_mut(id)?;
let part_id = layer.next_part_id();
if !layer.push_part(MaskPart::painted(part_id, join)) {
return None;
}
let index = layer.parts().len() - 1;
self.active_part = index;
self.history
.record(&self.graph, Edit::Action(labels::step::MASK_PART_ADDED));
Some(index)
}
/// Take a part back out of a layer. The base is not removable — removing
/// the selection a layer *is* is removing the layer.
pub fn remove_mask_part(&mut self, id: &str, index: usize) {
let Some(layer) = self.graph.masks_mut().get_mut(id) else {
return;
};
if layer.remove_part(index).is_none() {
return;
}
self.set_active_part(self.active_part.min(index.saturating_sub(1)));
self.history
.record(&self.graph, Edit::Action(labels::step::MASK_PART_REMOVED));
}
/// Change how a part joins: added to the mask, or taken out of it.
pub fn set_mask_part_join(&mut self, id: &str, index: usize, join: usize) {
use dr_pipeline::mask::Join;
let Some(&join) = Join::ALL.get(join) else {
return;
};
let Some(layer) = self.graph.masks_mut().get_mut(id) else {
return;
};
// The first part joins nothing, so saying how it joins would be a
// control that moves and changes no pixel.
if index == 0 {
return;
}
let Some(part) = layer.part_mut(index) else {
return;
};
part.join = join;
self.history
.record(&self.graph, Edit::Action(labels::step::MASK_JOINED));
}
/// The brush: radius, hardness, flow.
pub fn brush(&self) -> (f32, f32, f32) {
self.brush
}
/// Set the brush. Radius is a fraction of the frame's shorter edge, so it
/// means the same thing on the phone and on the desktop and at any zoom.
pub fn set_brush(&mut self, radius: f32, hardness: f32, flow: f32) {
self.brush = (
radius.clamp(0.002, 0.5),
hardness.clamp(0.0, 1.0),
flow.clamp(0.01, 1.0),
);
}
/// How many stroke points the selected layer may still record.
///
/// Asked by the panel so that a mask approaching its budget can say so
/// before a gesture is refused mid-stroke — which is the moment the
/// refusal is least explicable.
pub fn mask_room(&self) -> usize {
self.active_layer().map_or(0, |l| l.room())
}
/// TRACES: FR-DEV-19b
/// Begin a stroke at a point in fractions of the shown image.
///
/// **Paints into the active part, or joins one if that part cannot hold a
/// stroke.** Pressing Paint on a mask the model made is the ordinary way
/// this is reached, and it must not answer with a refusal explaining that
/// a subject is not a brush: the correction the photographer is about to
/// make *is* a new part, so it is made.
///
/// Returns whether a stroke was started. `false` means the layer is full
/// or there is nothing selected, and the caller should not send moves.
pub fn begin_mask_stroke(&mut self, x: f32, y: f32, erase: bool) -> bool {
let Some(id) = self.active_masks.first().cloned() else {
return false;
};
if self.active_masks.len() != 1 {
// Several layers share the slider drags; a stroke has one target
// and guessing which of three it is would be worse than refusing.
return false;
}
let paintable = self
.graph
.masks()
.get(&id)
.and_then(|l| l.part(self.active_part))
.is_some_and(|p| matches!(p.source, MaskSource::Brush { .. }));
if !paintable {
use dr_pipeline::mask::Join;
let join = if erase { Join::Subtract } else { Join::Union };
let position = Join::ALL.iter().position(|&j| j == join).unwrap_or(0);
if self.add_mask_part(&id, position).is_none() {
return false;
}
}
let part = self.active_part;
let (radius, hardness, flow) = self.brush;
// An erase stroke inside a part that subtracts would take away from
// what the part removes, which reads backwards. In a subtracting part
// the brush's two modes are already the right way round.
let subtracting = self
.graph
.masks()
.get(&id)
.and_then(|l| l.part(part))
.is_some_and(|p| p.join == dr_pipeline::mask::Join::Subtract);
let erase = erase && !subtracting;
let Some(layer) = self.graph.masks_mut().get_mut(&id) else {
return false;
};
if !layer.begin_stroke(part, erase, radius, hardness, flow) {
return false;
}
self.painting = Some((id, part));
self.extend_mask_stroke(x, y);
true
}
/// Carry the stroke to another point, in fractions of the shown image.
///
/// The point is mapped into normalised **source** coordinates on the way
/// in, through the same framing map the shader applies — so a stroke stays
/// on the thing it was painted on through a zoom, a pan, a crop and a
/// straighten, and lands in an export at any size where it was drawn.
pub fn extend_mask_stroke(&mut self, x: f32, y: f32) {
let Some((id, part)) = self.painting.clone() else {
return;
};
let (sw, sh) = self.demosaiced.size();
let (sx, sy) = self.graph.framing().source_at((x, y), sw, sh);
if let Some(layer) = self.graph.masks_mut().get_mut(&id) {
layer.extend_stroke(part, sx, sy);
}
}
/// Finish the stroke: one history step for the whole gesture.
///
/// One step, on release, for the reason a handle drag records once — a
/// stroke is a decision, and undo that walked it back dab by dab would
/// make taking a mark back cost as many presses as making it did.
pub fn end_mask_stroke(&mut self) {
let Some((id, part)) = self.painting.take() else {
return;
};
let erased = self
.graph
.masks()
.get(&id)
.and_then(|l| l.part(part))
.and_then(|p| p.strokes().last())
.is_some_and(|s| s.erase);
if let Some(layer) = self.graph.masks_mut().get_mut(&id) {
layer.end_stroke(part);
}
let step = if erased {
labels::step::MASK_ERASED
} else {
labels::step::MASK_PAINTED
};
self.history.record(&self.graph, Edit::Action(step));
}
/// Abandon a stroke that turned out to be something else — a pinch, or a
/// gesture the window cancelled. Nothing is recorded, because nothing
/// happened as far as the photographer is concerned.
pub fn cancel_mask_stroke(&mut self) {
let Some((id, part)) = self.painting.take() else {
return;
};
if let Some(layer) = self.graph.masks_mut().get_mut(&id) {
layer.drop_last_stroke(part);
}
}
// --- repairs (FR-DEV-8) ------------------------------------------------ // --- repairs (FR-DEV-8) ------------------------------------------------
/// TRACES: FR-DEV-8 /// TRACES: FR-DEV-8
@@ -2827,13 +3124,19 @@ impl DevelopSession {
/// The selected layer's mask rule, for a caller that has to remember what /// The selected layer's mask rule, for a caller that has to remember what
/// a gesture started from. /// a gesture started from.
pub fn active_mask_source(&self) -> Option<MaskSource> { pub fn active_mask_source(&self) -> Option<MaskSource> {
self.active_layer().map(|l| l.source.clone()) self.active_layer().map(|l| l.base().source.clone())
} }
/// Select exactly one layer for editing, or `None` to return the panel to /// Select exactly one layer for editing, or `None` to return the panel to
/// the global chain. Replaces whatever was selected before, including a /// the global chain. Replaces whatever was selected before, including a
/// multi-selection — the ordinary, unmodified click. /// multi-selection — the ordinary, unmodified click.
/// Selecting a layer points the tools at its base again.
///
/// Without this, selecting a two-part mask after a three-part one would
/// leave the brush aimed at a part that is not there — or, worse, at a
/// different part than the one highlighted in the panel.
pub fn set_active_mask(&mut self, id: Option<&str>) { pub fn set_active_mask(&mut self, id: Option<&str>) {
self.active_part = 0;
self.active_masks = id self.active_masks = id
.filter(|id| self.graph.masks().get(id).is_some()) .filter(|id| self.graph.masks().get(id).is_some())
.map(|id| vec![id.to_string()]) .map(|id| vec![id.to_string()])
@@ -2916,7 +3219,7 @@ impl DevelopSession {
.as_ref() .as_ref()
.is_some_and(|seg| seg.category_is_refinable(name)) .is_some_and(|seg| seg.category_is_refinable(name))
{ {
layer.refine = dr_segment::STRICTNESS_DEFAULT; layer.base_mut().refine = dr_segment::STRICTNESS_DEFAULT;
} }
if !self.graph.masks_mut().push(layer) { if !self.graph.masks_mut().push(layer) {
return None; return None;
@@ -3038,7 +3341,7 @@ impl DevelopSession {
/// asks first, and a callback that arrives against a layer the user has /// asks first, and a callback that arrives against a layer the user has
/// since replaced is ordinary rather than a fault. /// since replaced is ordinary rather than a fault.
pub fn set_mask_band(&mut self, id: &str, lo: f32, hi: f32, softness: f32) { pub fn set_mask_band(&mut self, id: &str, lo: f32, hi: f32, softness: f32) {
let Some(layer) = self.graph.masks_mut().get_mut(id) else { let Some(layer) = self.part_of_mut(id) else {
return; return;
}; };
// Built into a temporary first: the arc is read out of the layer and // Built into a temporary first: the arc is read out of the layer and
@@ -3061,7 +3364,7 @@ impl DevelopSession {
/// TRACES: FR-DEV-10 /// TRACES: FR-DEV-10
/// Move a colour range's arc — its centre hue and its half-width. /// Move a colour range's arc — its centre hue and its half-width.
pub fn set_mask_hue(&mut self, id: &str, hue: f32, width: f32) { pub fn set_mask_hue(&mut self, id: &str, hue: f32, width: f32) {
let Some(layer) = self.graph.masks_mut().get_mut(id) else { let Some(layer) = self.part_of_mut(id) else {
return; return;
}; };
// A temporary, for the reason `set_mask_band` gives. // A temporary, for the reason `set_mask_band` gives.
@@ -3085,19 +3388,14 @@ impl DevelopSession {
/// TRACES: FR-DEV-10 /// TRACES: FR-DEV-10
/// Whether the band controls apply to this layer. /// Whether the band controls apply to this layer.
pub fn mask_is_ranged(&self, id: &str) -> bool { pub fn mask_is_ranged(&self, id: &str) -> bool {
self.graph self.part_of(id).is_some_and(|p| p.source.is_range())
.masks()
.get(id)
.is_some_and(|l| l.source.is_range())
} }
/// TRACES: FR-DEV-10 /// TRACES: FR-DEV-10
/// Whether this layer's band is over colour rather than over brightness. /// Whether this layer's band is over colour rather than over brightness.
pub fn mask_is_chromatic(&self, id: &str) -> bool { pub fn mask_is_chromatic(&self, id: &str) -> bool {
self.graph self.part_of(id)
.masks() .is_some_and(|p| matches!(p.source, MaskSource::Colour { .. }))
.get(id)
.is_some_and(|l| matches!(l.source, MaskSource::Colour { .. }))
} }
/// TRACES: FR-DEV-10 /// TRACES: FR-DEV-10
@@ -3108,7 +3406,7 @@ impl DevelopSession {
/// one panel control drives both. Zeroes for a layer that has no band, /// one panel control drives both. Zeroes for a layer that has no band,
/// which the panel never draws. /// which the panel never draws.
pub fn mask_band(&self, id: &str) -> (f32, f32, f32) { pub fn mask_band(&self, id: &str) -> (f32, f32, f32) {
match self.graph.masks().get(id).map(|l| &l.source) { match self.part_of(id).map(|p| &p.source) {
Some(MaskSource::Luminance { lo, hi, softness }) => (*lo, *hi, *softness), Some(MaskSource::Luminance { lo, hi, softness }) => (*lo, *hi, *softness),
Some(MaskSource::Colour { Some(MaskSource::Colour {
chroma_lo, chroma_lo,
@@ -3123,7 +3421,7 @@ impl DevelopSession {
/// TRACES: FR-DEV-10 /// TRACES: FR-DEV-10
/// A colour range's arc: centre hue and half-width, both in turns. /// A colour range's arc: centre hue and half-width, both in turns.
pub fn mask_hue(&self, id: &str) -> (f32, f32) { pub fn mask_hue(&self, id: &str) -> (f32, f32) {
match self.graph.masks().get(id).map(|l| &l.source) { match self.part_of(id).map(|p| &p.source) {
Some(MaskSource::Colour { hue, hue_width, .. }) => (*hue, *hue_width), Some(MaskSource::Colour { hue, hue_width, .. }) => (*hue, *hue_width),
_ => (0.0, 0.0), _ => (0.0, 0.0),
} }
@@ -3155,8 +3453,8 @@ impl DevelopSession {
/// Edge transition half-width, in fractions of the shorter edge. /// Edge transition half-width, in fractions of the shorter edge.
pub fn set_mask_feather(&mut self, id: &str, feather: f32) { pub fn set_mask_feather(&mut self, id: &str, feather: f32) {
if let Some(layer) = self.graph.masks_mut().get_mut(id) { if let Some(part) = self.part_of_mut(id) {
layer.feather = feather.clamp(0.0, 1.0); part.feather = feather.clamp(0.0, 1.0);
self.history self.history
.record(&self.graph, Edit::Control(labels::step::MASK_FEATHER)); .record(&self.graph, Edit::Control(labels::step::MASK_FEATHER));
} }
@@ -3171,8 +3469,8 @@ impl DevelopSession {
/// `subject_signature`. It still runs no model: the evidence was fitted /// `subject_signature`. It still runs no model: the evidence was fitted
/// during segmentation and this is a smoothstep over it. /// during segmentation and this is a smoothstep over it.
pub fn set_mask_refine(&mut self, id: &str, refine: f32) { pub fn set_mask_refine(&mut self, id: &str, refine: f32) {
if let Some(layer) = self.graph.masks_mut().get_mut(id) { if let Some(part) = self.part_of_mut(id) {
layer.refine = refine.clamp(0.0, dr_pipeline::mask::MAX_REFINE); part.refine = refine.clamp(0.0, dr_pipeline::mask::MAX_REFINE);
self.history self.history
.record(&self.graph, Edit::Control(labels::step::MASK_REFINE)); .record(&self.graph, Edit::Control(labels::step::MASK_REFINE));
} }
@@ -3183,8 +3481,8 @@ impl DevelopSession {
let Some(&falloff) = Falloff::ALL.get(index) else { let Some(&falloff) = Falloff::ALL.get(index) else {
return; return;
}; };
if let Some(layer) = self.graph.masks_mut().get_mut(id) { if let Some(part) = self.part_of_mut(id) {
layer.falloff = falloff; part.falloff = falloff;
self.history self.history
.record(&self.graph, Edit::Action(labels::step::MASK_FALLOFF)); .record(&self.graph, Edit::Action(labels::step::MASK_FALLOFF));
} }
@@ -3195,12 +3493,12 @@ impl DevelopSession {
let Some(&morphology) = Morphology::ALL.get(index) else { let Some(&morphology) = Morphology::ALL.get(index) else {
return; return;
}; };
if let Some(layer) = self.graph.masks_mut().get_mut(id) { if let Some(part) = self.part_of_mut(id) {
layer.morphology = morphology; part.morphology = morphology;
// Picking an operation with no amount set would appear to do // Picking an operation with no amount set would appear to do
// nothing, and the user would reasonably conclude it is broken. // nothing, and the user would reasonably conclude it is broken.
if morphology != Morphology::None && layer.morph_radius <= 0.0 { if morphology != Morphology::None && part.morph_radius <= 0.0 {
layer.morph_radius = 0.006; part.morph_radius = 0.006;
} }
self.history self.history
.record(&self.graph, Edit::Action(labels::step::MASK_MORPHOLOGY)); .record(&self.graph, Edit::Action(labels::step::MASK_MORPHOLOGY));
@@ -3208,8 +3506,8 @@ impl DevelopSession {
} }
pub fn set_mask_morph_radius(&mut self, id: &str, radius: f32) { pub fn set_mask_morph_radius(&mut self, id: &str, radius: f32) {
if let Some(layer) = self.graph.masks_mut().get_mut(id) { if let Some(part) = self.part_of_mut(id) {
layer.morph_radius = radius.clamp(0.0, 1.0); part.morph_radius = radius.clamp(0.0, 1.0);
self.history self.history
.record(&self.graph, Edit::Control(labels::step::MASK_MORPH)); .record(&self.graph, Edit::Control(labels::step::MASK_MORPH));
} }
@@ -3218,34 +3516,34 @@ impl DevelopSession {
/// Which falloff a layer uses, as an index into `Falloff::ALL`. /// Which falloff a layer uses, as an index into `Falloff::ALL`.
pub fn mask_falloff(&self, id: &str) -> usize { pub fn mask_falloff(&self, id: &str) -> usize {
use dr_pipeline::mask::Falloff; use dr_pipeline::mask::Falloff;
self.graph.masks().get(id).map_or(0, |l| { self.part_of(id).map_or(0, |p| {
Falloff::ALL Falloff::ALL
.iter() .iter()
.position(|&f| f == l.falloff) .position(|&f| f == p.falloff)
.unwrap_or(0) .unwrap_or(0)
}) })
} }
pub fn mask_morphology(&self, id: &str) -> usize { pub fn mask_morphology(&self, id: &str) -> usize {
use dr_pipeline::mask::Morphology; use dr_pipeline::mask::Morphology;
self.graph.masks().get(id).map_or(0, |l| { self.part_of(id).map_or(0, |p| {
Morphology::ALL Morphology::ALL
.iter() .iter()
.position(|&m| m == l.morphology) .position(|&m| m == p.morphology)
.unwrap_or(0) .unwrap_or(0)
}) })
} }
pub fn mask_feather(&self, id: &str) -> f32 { pub fn mask_feather(&self, id: &str) -> f32 {
self.graph.masks().get(id).map_or(0.0, |l| l.feather) self.part_of(id).map_or(0.0, |p| p.feather)
} }
pub fn mask_morph_radius(&self, id: &str) -> f32 { pub fn mask_morph_radius(&self, id: &str) -> f32 {
self.graph.masks().get(id).map_or(0.0, |l| l.morph_radius) self.part_of(id).map_or(0.0, |p| p.morph_radius)
} }
pub fn mask_refine(&self, id: &str) -> f32 { pub fn mask_refine(&self, id: &str) -> f32 {
self.graph.masks().get(id).map_or(0.0, |l| l.refine) self.part_of(id).map_or(0.0, |p| p.refine)
} }
/// Whether this layer has a refinement to act on. /// Whether this layer has a refinement to act on.
@@ -3263,7 +3561,11 @@ impl DevelopSession {
let Some(layer) = self.graph.masks().get(id) else { let Some(layer) = self.graph.masks().get(id) else {
return false; return false;
}; };
let MaskSource::Category { name, .. } = &layer.source else { let index = self.shaped_part(id);
let Some(part) = layer.part(index) else {
return false;
};
let MaskSource::Category { name, .. } = &part.source else {
return false; return false;
}; };
self.segmentation self.segmentation
@@ -3286,9 +3588,9 @@ impl DevelopSession {
/// units rather than in pixels — see `MaskSource::Luminance`. /// units rather than in pixels — see `MaskSource::Luminance`.
pub fn mask_is_shapeable(&self, id: &str) -> bool { pub fn mask_is_shapeable(&self, id: &str) -> bool {
use dr_pipeline::mask::MaskSource; use dr_pipeline::mask::MaskSource;
self.graph.masks().get(id).is_some_and(|l| { self.part_of(id).is_some_and(|p| {
matches!( matches!(
l.source, p.source,
MaskSource::Subject { .. } MaskSource::Subject { .. }
| MaskSource::Category { .. } | MaskSource::Category { .. }
| MaskSource::Regions { .. } | MaskSource::Regions { .. }
@@ -5719,7 +6021,7 @@ mod tests {
); );
layer.set_param("exposure", ParamId("exposure"), 2.0); layer.set_param("exposure", ParamId("exposure"), 2.0);
if stored { if stored {
layer.coverage = Some(Arc::new( layer.base_mut().coverage = Some(Arc::new(
Coverage::encode(&values, pw, ph, RENDERED_LEVELS).expect("a half frame encodes"), Coverage::encode(&values, pw, ph, RENDERED_LEVELS).expect("a half frame encodes"),
)); ));
} }
@@ -6015,7 +6317,7 @@ mod tests {
assert_eq!(stored.len(), 1); assert_eq!(stored.len(), 1);
assert!( assert!(
stored.layers()[0].coverage.is_some(), stored.layers()[0].base().coverage.is_some(),
"the raster the sidecar gave us must go back to the sidecar" "the raster the sidecar gave us must go back to the sidecar"
); );
} }
@@ -6131,6 +6433,7 @@ mod tests {
let coverage = stored let coverage = stored
.get(&id) .get(&id)
.expect("the layer is in the stack") .expect("the layer is in the stack")
.base()
.coverage .coverage
.as_ref() .as_ref()
.expect("a subject the model found has coverage to store"); .expect("a subject the model found has coverage to store");
@@ -6173,7 +6476,7 @@ mod tests {
{ {
let layer = session.graph.masks_mut().get_mut(&id).expect("the layer"); let layer = session.graph.masks_mut().get_mut(&id).expect("the layer");
layer.set_param("exposure", ParamId("exposure"), 2.0); layer.set_param("exposure", ParamId("exposure"), 2.0);
layer.coverage = Some(Arc::new( layer.base_mut().coverage = Some(Arc::new(
dr_pipeline::Coverage::encode( dr_pipeline::Coverage::encode(
&mirrored, &mirrored,
pw, pw,
+7
View File
@@ -36,6 +36,13 @@ pub const GESTURES: &[Gesture] = &[
pointer: "The scroll wheel over it", pointer: "The scroll wheel over it",
keys: "", keys: "",
}, },
Gesture {
title: "Paint a mask by hand",
section: "Develop",
touch: "Choose Paint or Erase, then drag on the photograph",
pointer: "Choose Paint or Erase, then drag",
keys: "",
},
Gesture { Gesture {
title: "Move a magnified photograph about", title: "Move a magnified photograph about",
section: "Develop", section: "Develop",
+22
View File
@@ -61,6 +61,18 @@ pub mod step {
/// A range mask's band moved — its bounds, its softness, or its hue arc. /// A range mask's band moved — its bounds, its softness, or its hue arc.
pub const MASK_RANGE: LocalizedKey = LocalizedKey("history.mask_range"); pub const MASK_RANGE: LocalizedKey = LocalizedKey("history.mask_range");
/// TRACES: FR-DEV-19b
/// A stroke, named for what the hand did rather than for the part it
/// landed in: a photographer takes back the mark they made, and which
/// selection was holding it is not what they were thinking about.
pub const MASK_PAINTED: LocalizedKey = LocalizedKey("history.mask_painted");
pub const MASK_ERASED: LocalizedKey = LocalizedKey("history.mask_erased");
/// TRACES: FR-DEV-19a
/// A selection joined to a mask, taken out of it, or joined the other way.
pub const MASK_PART_ADDED: LocalizedKey = LocalizedKey("history.mask_part_added");
pub const MASK_PART_REMOVED: LocalizedKey = LocalizedKey("history.mask_part_removed");
pub const MASK_JOINED: LocalizedKey = LocalizedKey("history.mask_joined");
/// TRACES: FR-DEV-8 /// TRACES: FR-DEV-8
/// A repair's own settings changed — its radius, its source, its opacity. /// A repair's own settings changed — its radius, its source, its opacity.
pub const SPOT: LocalizedKey = LocalizedKey("history.spot"); pub const SPOT: LocalizedKey = LocalizedKey("history.spot");
@@ -105,6 +117,11 @@ pub mod step {
MASK_MORPHOLOGY, MASK_MORPHOLOGY,
MASK_REFINE, MASK_REFINE,
MASK_RANGE, MASK_RANGE,
MASK_PAINTED,
MASK_ERASED,
MASK_PART_ADDED,
MASK_PART_REMOVED,
MASK_JOINED,
SPOT, SPOT,
SPOT_PLACED, SPOT_PLACED,
SPOT_MOVED, SPOT_MOVED,
@@ -294,6 +311,11 @@ fn catalogued(key: &str) -> Option<&'static str> {
"history.mask_morphology" => "Mask Grow/Shrink", "history.mask_morphology" => "Mask Grow/Shrink",
"history.mask_refine" => "Mask Refine", "history.mask_refine" => "Mask Refine",
"history.mask_range" => "Mask Range", "history.mask_range" => "Mask Range",
"history.mask_painted" => "Paint Mask",
"history.mask_erased" => "Erase Mask",
"history.mask_part_added" => "Add To Mask",
"history.mask_part_removed" => "Remove From Mask",
"history.mask_joined" => "Change How A Mask Joins",
"history.spot" => "Adjust Repair", "history.spot" => "Adjust Repair",
"history.spot_placed" => "Add Repair", "history.spot_placed" => "Add Repair",
"history.spot_moved" => "Move Repair", "history.spot_moved" => "Move Repair",
+265 -1
View File
@@ -30,7 +30,9 @@ use slint::{ComponentHandle as _, Model as _, ModelRc, VecModel};
use crate::develop::{Abandon, DevelopSession, RefinedInstance, Segmented, SessionId}; use crate::develop::{Abandon, DevelopSession, RefinedInstance, Segmented, SessionId};
use crate::segmentation; use crate::segmentation;
use crate::{sync_rows, AppWindow, CategoryRow, GradientHandle, MaskRow, ParamRow, SubjectRow}; use crate::{
sync_rows, AppWindow, CategoryRow, GradientHandle, MaskRow, ParamRow, PartRow, SubjectRow,
};
/// What the adjust panel's heading says when the controls are global. /// What the adjust panel's heading says when the controls are global.
/// ///
@@ -238,6 +240,31 @@ pub(crate) fn sync(window: &AppWindow, session: &Rc<RefCell<Option<DevelopSessio
.collect(); .collect();
window.set_category_rows(ModelRc::new(VecModel::from(categories))); window.set_category_rows(ModelRc::new(VecModel::from(categories)));
// TRACES: FR-DEV-19a
// Only the selected layer's parts, and only when exactly one is selected:
// a stroke has one target, and so does the edge the sliders shape.
let parts: Vec<PartRow> = match s.active_masks() {
[id] => s
.mask_parts(id)
.into_iter()
.enumerate()
.map(|(i, (part_id, label, join))| PartRow {
id: part_id.into(),
label: label.into(),
join: join as i32,
selected: i == s.active_part(),
base: i == 0,
})
.collect(),
_ => Vec::new(),
};
window.set_mask_parts(ModelRc::new(VecModel::from(parts)));
let (radius, hardness, flow) = s.brush();
window.set_brush_radius(radius);
window.set_brush_hardness(hardness);
window.set_brush_flow(flow);
window.set_segmented(s.has_segmentation()); window.set_segmented(s.has_segmentation());
window.set_adjust_scope(scope_label(s).into()); window.set_adjust_scope(scope_label(s).into());
sync_handles(window, s); sync_handles(window, s);
@@ -723,6 +750,141 @@ pub(crate) fn wire(
} }
// --- adding layers ------------------------------------------------------ // --- adding layers ------------------------------------------------------
// TRACES: FR-DEV-19b
// Painting. Three handlers for one gesture, and the middle one runs per
// pointer report — so it does the least it can: map the point, record it,
// redraw. No sync, because nothing the panel shows changes while a finger
// is down, and rebuilding eight rows a frame is how a brush starts to lag.
{
let weak = window.as_weak();
let session = session.clone();
let redraw = redraw.clone();
window.on_paint_began(move |x, y| {
let Some(w) = weak.upgrade() else { return };
let erase = w.get_mask_tool() == 2;
if let Some(s) = session.borrow_mut().as_mut() {
s.begin_mask_stroke(x, y, erase);
}
redraw(&w);
});
}
{
let weak = window.as_weak();
let session = session.clone();
let redraw = redraw.clone();
window.on_paint_moved(move |x, y| {
let Some(w) = weak.upgrade() else { return };
if let Some(s) = session.borrow_mut().as_mut() {
s.extend_mask_stroke(x, y);
}
redraw(&w);
});
}
{
let weak = window.as_weak();
let session = session.clone();
let redraw = redraw.clone();
let rows = rows.clone();
window.on_paint_ended(move || {
let Some(w) = weak.upgrade() else { return };
if let Some(s) = session.borrow_mut().as_mut() {
s.end_mask_stroke();
}
// Now the panel is worth rebuilding: the gesture may have joined a
// part to the mask, and the history has a step in it.
sync(&w, &session);
sync_rows(&w, &rows, &session);
redraw(&w);
});
}
{
let weak = window.as_weak();
let session = session.clone();
window.on_brush_changed(move |radius, hardness, flow| {
let Some(w) = weak.upgrade() else { return };
if let Some(s) = session.borrow_mut().as_mut() {
s.set_brush(radius, hardness, flow);
}
sync(&w, &session);
});
}
{
let weak = window.as_weak();
let session = session.clone();
window.on_mask_tool_picked(move |_tool| {
// The tool itself lives in the interface — it arms a gesture and
// changes no pixel — so nothing is set here. What this does is
// re-sync, because arming the brush is what makes the parts of a
// mask worth showing.
let Some(w) = weak.upgrade() else { return };
sync(&w, &session);
});
}
// TRACES: FR-DEV-19a
{
let weak = window.as_weak();
let session = session.clone();
let redraw = redraw.clone();
let rows = rows.clone();
window.on_mask_part_selected(move |_id, index| {
let Some(w) = weak.upgrade() else { return };
if let Some(s) = session.borrow_mut().as_mut() {
s.set_active_part(index.max(0) as usize);
}
sync(&w, &session);
sync_rows(&w, &rows, &session);
redraw(&w);
});
}
{
let weak = window.as_weak();
let session = session.clone();
let redraw = redraw.clone();
let rows = rows.clone();
window.on_mask_part_added(move |id, join| {
let Some(w) = weak.upgrade() else { return };
if let Some(s) = session.borrow_mut().as_mut() {
s.add_mask_part(&id, join.max(0) as usize);
}
// Armed, because adding an empty painted part and leaving the
// pointer in "select" would look like the button did nothing —
// the part covers no pixels until something is painted into it.
if w.get_mask_tool() == 0 {
w.set_mask_tool(1);
}
sync(&w, &session);
sync_rows(&w, &rows, &session);
redraw(&w);
});
}
{
let weak = window.as_weak();
let session = session.clone();
let redraw = redraw.clone();
let rows = rows.clone();
window.on_mask_part_removed(move |id, index| {
let Some(w) = weak.upgrade() else { return };
if let Some(s) = session.borrow_mut().as_mut() {
s.remove_mask_part(&id, index.max(0) as usize);
}
sync(&w, &session);
sync_rows(&w, &rows, &session);
redraw(&w);
});
}
{
let weak = window.as_weak();
let session = session.clone();
let redraw = redraw.clone();
window.on_mask_part_join_picked(move |id, index, join| {
let Some(w) = weak.upgrade() else { return };
if let Some(s) = session.borrow_mut().as_mut() {
s.set_mask_part_join(&id, index.max(0) as usize, join.max(0) as usize);
}
sync(&w, &session);
redraw(&w);
});
}
{ {
let weak = window.as_weak(); let weak = window.as_weak();
let session = session.clone(); let session = session.clone();
@@ -948,6 +1110,108 @@ mod tests {
DevelopSession::open_rgb(&ctx, &rgba, 32, 32, dr_types::Orientation::NORMAL).ok() DevelopSession::open_rgb(&ctx, &rgba, 32, 32, dr_types::Orientation::NORMAL).ok()
} }
/// TRACES: FR-DEV-19b
/// Pressing Paint on a mask the model made must not answer with a
/// refusal about a subject not being a brush. The correction the
/// photographer is about to make *is* a new part, so it is made.
#[test]
fn painting_on_a_mask_that_cannot_hold_a_stroke_joins_a_part_that_can() {
let Some(mut s) = session() else {
eprintln!("no adapter; skipping");
return;
};
let id = s.add_gradient_mask(true).expect("radial");
s.set_active_mask(Some(&id));
assert_eq!(s.mask_parts(&id).len(), 1, "one selection to begin with");
assert!(s.begin_mask_stroke(0.5, 0.5, false), "the stroke started");
s.extend_mask_stroke(0.55, 0.5);
s.end_mask_stroke();
let parts = s.mask_parts(&id);
assert_eq!(parts.len(), 2, "a painted part was joined");
assert_eq!(parts[1].1, "brush");
assert_eq!(s.active_part(), 1, "and the tools point at it");
}
/// A stroke is one decision. Recording per pointer report would make
/// taking a mark back cost as many presses as making it did.
#[test]
fn a_whole_stroke_is_one_step_in_the_history() {
let Some(mut s) = session() else {
eprintln!("no adapter; skipping");
return;
};
let id = s.add_gradient_mask(true).expect("radial");
s.set_active_mask(Some(&id));
let before = s.history_rows().len();
assert!(s.begin_mask_stroke(0.4, 0.4, false));
for i in 0..12 {
s.extend_mask_stroke(0.4 + i as f32 * 0.02, 0.5);
}
s.end_mask_stroke();
// Two: joining the part is its own step, and the stroke is the other.
assert_eq!(
s.history_rows().len(),
before + 2,
"a stroke recorded more than one step"
);
}
/// A gesture the window cancels leaves nothing behind — including in the
/// history, because as far as the photographer is concerned nothing
/// happened.
#[test]
fn a_cancelled_stroke_leaves_no_mark() {
let Some(mut s) = session() else {
eprintln!("no adapter; skipping");
return;
};
let id = s.add_gradient_mask(true).expect("radial");
s.set_active_mask(Some(&id));
assert!(s.begin_mask_stroke(0.4, 0.4, false));
s.extend_mask_stroke(0.5, 0.5);
let steps = s.history_rows().len();
s.cancel_mask_stroke();
assert_eq!(s.history_rows().len(), steps, "nothing was recorded");
assert!(
s.masks()
.get(&id)
.expect("layer")
.part(1)
.expect("part")
.strokes()
.is_empty(),
"and the abandoned stroke is not in the mask"
);
}
/// TRACES: FR-DEV-19a
/// The edge controls point at the part that is selected, so that dragging
/// the feather while a correction is selected does not silently soften the
/// model's mask underneath it.
#[test]
fn the_edge_controls_shape_the_selected_part() {
let Some(mut s) = session() else {
eprintln!("no adapter; skipping");
return;
};
let id = s.add_gradient_mask(true).expect("radial");
s.set_active_mask(Some(&id));
s.set_mask_feather(&id, 0.03);
let index = s.add_mask_part(&id, 0).expect("a part was joined");
assert_eq!(s.active_part(), index);
s.set_mask_feather(&id, 0.0);
assert_eq!(s.mask_feather(&id), 0.0, "the selected part was shaped");
s.set_active_part(0);
assert_eq!(s.mask_feather(&id), 0.03, "and the base was left alone");
}
/// TRACES: FR-DEV-3 | FR-UI-1 /// TRACES: FR-DEV-3 | FR-UI-1
/// The fault this pass exists for, stated as a test. /// The fault this pass exists for, stated as a test.
/// ///
+2 -2
View File
@@ -1162,9 +1162,9 @@ mod tests {
assert_eq!(back.id, "m1"); assert_eq!(back.id, "m1");
assert!((back.opacity - 0.75).abs() < 1e-6, "and with its settings"); assert!((back.opacity - 0.75).abs() < 1e-6, "and with its settings");
assert!( assert!(
matches!(back.source, MaskSource::Radial { .. }), matches!(back.base().source, MaskSource::Radial { .. }),
"and its kind: {:?}", "and its kind: {:?}",
back.source.kind() back.base().source.kind()
); );
} }
+100 -2
View File
@@ -1,6 +1,6 @@
import { Theme } from "theme.slint"; import { Theme } from "theme.slint";
import { AdjustPanel, ComposePanel, GroupStrip, ParamRow, TransferPanel, ViewMode } from "adjust.slint"; import { AdjustPanel, ComposePanel, GroupStrip, ParamRow, TransferPanel, ViewMode } from "adjust.slint";
import { CategoryRow, GradientHandle, GradientHandles, HandleRole, MaskPanel, MaskRow, SubjectRow } from "masks.slint"; import { CategoryRow, GradientHandle, GradientHandles, HandleRole, MaskPanel, MaskRow, PartRow, SubjectRow } from "masks.slint";
import { SpotHandle, SpotHandles, SpotPanel, SpotRole } from "spots.slint"; import { SpotHandle, SpotHandles, SpotPanel, SpotRole } from "spots.slint";
import { CropOverlay } from "crop.slint"; import { CropOverlay } from "crop.slint";
import { HistoryPanel, HistoryRow } from "history.slint"; import { HistoryPanel, HistoryRow } from "history.slint";
@@ -1146,7 +1146,35 @@ export component AppWindow inherits Window {
/// which meant local masking could be open with picking off — a mode /// which meant local masking could be open with picking off — a mode
/// entered and doing nothing. Arming a click is part of what local mode /// entered and doing nothing. Arming a click is part of what local mode
/// *is*, so it follows the mode and the existence of something to pick. /// *is*, so it follows the mode and the existence of something to pick.
property <bool> region-picking: root.local-mode && root.segmented; /// TRACES: FR-DEV-19b
/// What a drag on the photograph does while a mask is selected: 0 selects
/// a subject, 1 paints into the mask, 2 erases from it.
in-out property <int> mask-tool: 0;
/// TRACES: FR-DEV-19a
/// The parts of the selected mask, for the panel.
in property <[PartRow]> mask-parts;
in property <float> brush-radius: 0.05;
in property <float> brush-hardness: 0.5;
in property <float> brush-flow: 1.0;
callback mask-tool-picked(int);
callback brush-changed(float, float, float);
callback mask-part-selected(string, int);
callback mask-part-join-picked(string, int, int);
callback mask-part-removed(string, int);
callback mask-part-added(string, int);
/// TRACES: FR-DEV-19b
/// A stroke, in fractions of the photograph as it is currently shown.
callback paint-began(float, float);
callback paint-moved(float, float);
callback paint-ended();
// Clicking to select a subject and dragging to paint are the same press,
// so exactly one of them is armed at a time. Without this the first dab of
// every stroke would also re-select whatever was under it, and the mask
// being painted would be replaced by the one the click made.
property <bool> region-picking: root.local-mode && root.segmented && root.mask-tool == 0;
property <bool> painting: root.local-mode && root.mask-tool > 0;
/// Whether shift is down, tracked by the develop key scope below. /// Whether shift is down, tracked by the develop key scope below.
/// ///
@@ -2134,6 +2162,59 @@ in property <bool> panel-visible: true;
} }
} }
// GESTURE: Paint a mask by hand
// where: Develop
// touch: Choose Paint or Erase, then drag on the
// photograph
// pointer: Choose Paint or Erase, then drag
// why: A model's mask stops inside a shoulder and
// leaks into the hair, and no single edge
// control fixes two errors that go opposite
// ways. The whole stroke is one step in the
// history, so taking a mark back costs one
// press however long it took to make.
//
// TRACES: FR-DEV-19b
//
// In front of the region picker rather than beside it: the
// two want the same press, and `region-picking` is false
// whenever this is armed so only one of them exists at a
// time.
if root.painting && root.total > 0 && root.load-error == "": paint := TouchArea {
x: parent.shown-x;
y: parent.shown-y;
width: parent.shown-w;
height: parent.shown-h;
mouse-cursor: crosshair;
enabled: !root.cropping;
pointer-event(ev) => {
if ev.kind == PointerEventKind.down {
root.paint-began(
self.mouse-x / max(self.width, 1px),
self.mouse-y / max(self.height, 1px),
);
}
// A cancelled gesture ends the stroke like a
// release does. The alternative is a stroke left
// open across the next press, which paints a line
// between two places the finger never travelled.
if ev.kind == PointerEventKind.up
|| ev.kind == PointerEventKind.cancel {
root.paint-ended();
}
}
moved => {
if self.pressed {
root.paint-moved(
self.mouse-x / max(self.width, 1px),
self.mouse-y / max(self.height, 1px),
);
}
}
}
// TRACES: FR-DEV-8 // TRACES: FR-DEV-8
// Placing a repair, beside the region picker and for the // Placing a repair, beside the region picker and for the
// same reasons: a click and a pan want different handlers, // same reasons: a click and a pan want different handlers,
@@ -3061,7 +3142,24 @@ in property <bool> panel-visible: true;
// the value alone. // the value alone.
overlay-hidden <=> root.overlay-hidden; overlay-hidden <=> root.overlay-hidden;
parts: root.mask-parts;
tool: root.mask-tool;
brush-radius: root.brush-radius;
brush-hardness: root.brush-hardness;
brush-flow: root.brush-flow;
segment(fine) => { root.segment-image(fine); } segment(fine) => { root.segment-image(fine); }
tool-picked(i) => {
root.mask-tool = i;
root.mask-tool-picked(i);
}
brush-changed(r, h, f) => { root.brush-changed(r, h, f); }
part-selected(id, i) => { root.mask-part-selected(id, i); }
part-join-picked(id, i, j) => {
root.mask-part-join-picked(id, i, j);
}
part-removed(id, i) => { root.mask-part-removed(id, i); }
part-added(id, j) => { root.mask-part-added(id, j); }
mask-selected(id, extend) => { root.mask-selected(id, extend); } mask-selected(id, extend) => { root.mask-selected(id, extend); }
mask-removed(id) => { root.mask-removed(id); } mask-removed(id) => { root.mask-removed(id); }
mask-refined(id) => { root.mask-refined(id); } mask-refined(id) => { root.mask-refined(id); }
+194
View File
@@ -67,6 +67,26 @@ export struct MaskRow {
adjusted: bool, adjusted: bool,
} }
/// One selection inside a layer's mask (FR-DEV-19a).
///
/// A mask is a fold over these, so the list is ordered and the order is what
/// it means: a subtraction placed before the part it was meant to cut into
/// takes nothing away.
export struct PartRow {
/// Identity, opaque to this file — the callbacks carry the index instead,
/// because that is what a row is addressed by on screen.
id: string,
/// What this part selects — "brush", "subject", "radial".
label: string,
/// 0 adds to the mask, 1 takes away from it. Meaningless on the first.
join: int,
/// Whether the brush and the edge controls point at this part.
selected: bool,
/// The selection the layer began as. It joins nothing and cannot be
/// removed — removing it is removing the layer.
base: bool,
}
/// Which part of a gradient a canvas handle drags. /// Which part of a gradient a canvas handle drags.
/// ///
/// Named by the job rather than by the field, because the two gradients keep /// Named by the job rather than by the field, because the two gradients keep
@@ -114,6 +134,10 @@ component MaskEntry inherits Rectangle {
/// Whether a refine pass is running (for any row — only one runs at a /// Whether a refine pass is running (for any row — only one runs at a
/// time), so this row's button can say so and refuse a second press. /// time), so this row's button can say so and refuse a second press.
in property <bool> refining: false; in property <bool> refining: false;
/// TRACES: FR-DEV-19a
/// What this layer's mask is built from. Empty unless the row is the one
/// selected, since the parts of a mask nobody is editing are noise.
in property <[PartRow]> parts;
/// `true` when the click should add this row to the selection rather /// `true` when the click should add this row to the selection rather
/// than replace it with just this row. /// than replace it with just this row.
@@ -135,6 +159,14 @@ component MaskEntry inherits Rectangle {
callback hue-changed(float, float); callback hue-changed(float, float);
callback refined(); callback refined();
/// TRACES: FR-DEV-19a
/// Point the tools at one part, change how it joins, or take it out.
callback part-selected(int);
callback part-join-picked(int, int);
callback part-removed(int);
/// Join a fresh painted correction: 0 adds, 1 subtracts.
callback part-added(int);
height: layout.preferred-height; height: layout.preferred-height;
background: root.data.selected ? Theme.surface-raised : transparent; background: root.data.selected ? Theme.surface-raised : transparent;
border-radius: Theme.radius; border-radius: Theme.radius;
@@ -248,6 +280,95 @@ component MaskEntry inherits Rectangle {
spacing: Theme.gap-sm; spacing: Theme.gap-sm;
padding-top: Theme.gap-sm; padding-top: Theme.gap-sm;
// TRACES: FR-DEV-19a
// What this mask is built from, in the order it is built.
//
// Shown even when there is only one part, because the row is what
// says the edge controls below belong to a *selection* rather than
// to the whole layer — and because it is where the next one is
// added. A photographer who cannot see that a mask has parts has
// no way to guess that the feather they are dragging moves one of
// them.
for part[i] in root.parts: Rectangle {
height: Theme.touch-target;
background: part.selected ? Theme.surface : transparent;
border-radius: Theme.radius;
// Declared before the two buttons, so it sits *behind* them: a
// press on the join chip or the cross does its own job, and a
// press anywhere else on the row points the tools at the part.
pick := TouchArea {
mouse-cursor: pointer;
enabled: root.enabled;
clicked => { root.part-selected(i); }
}
HorizontalLayout {
padding-left: Theme.gap-sm;
padding-right: Theme.gap-sm;
spacing: Theme.gap-sm;
// One chip, two states, because there are two ways to
// join and a photographer flips between them while
// looking at the picture rather than at a menu.
join := TouchArea {
width: Theme.touch-target;
mouse-cursor: part.base ? MouseCursor.default : MouseCursor.pointer;
enabled: root.enabled && !part.base;
clicked => { root.part-join-picked(i, part.join == 0 ? 1 : 0); }
Label {
// The first part joins nothing — a chip saying
// "adds" on it would be a control that moves and
// changes no pixel.
text: part.base ? "◆" : (part.join == 0 ? "+" : "−");
emphasised: join.has-hover || part.selected;
horizontal-alignment: center;
vertical-alignment: center;
}
}
Caption {
text: part.label;
overflow: elide;
min-width: 0px;
max-width: 140px;
vertical-alignment: center;
horizontal-stretch: 1;
}
if !part.base: cut := TouchArea {
width: Theme.touch-target;
mouse-cursor: pointer;
enabled: root.enabled;
clicked => { root.part-removed(i); }
Label {
text: "×";
emphasised: cut.has-hover;
horizontal-alignment: center;
vertical-alignment: center;
}
}
}
}
HorizontalLayout {
spacing: Theme.gap-sm;
Button {
text: "+ Add";
enabled: root.enabled;
clicked => { root.part-added(0); }
}
Button {
text: "− Subtract";
enabled: root.enabled;
clicked => { root.part-added(1); }
}
}
SliderRow { SliderRow {
label: "Opacity"; label: "Opacity";
value: root.data.opacity; value: root.data.opacity;
@@ -432,6 +553,18 @@ component MaskEntry inherits Rectangle {
export component MaskPanel inherits Rectangle { export component MaskPanel inherits Rectangle {
in property <bool> enabled: true; in property <bool> enabled: true;
in property <[MaskRow]> masks; in property <[MaskRow]> masks;
/// TRACES: FR-DEV-19a
/// The parts of the selected layer. Empty when none is selected, or when
/// more than one is — a stroke has one target, and so does an edge.
in property <[PartRow]> parts;
/// TRACES: FR-DEV-19b
/// What a drag on the photograph does: 0 selects, 1 paints, 2 erases.
in property <int> tool: 0;
/// The brush: radius as a fraction of the frame's shorter edge, hardness,
/// and flow.
in property <float> brush-radius: 0.05;
in property <float> brush-hardness: 0.5;
in property <float> brush-flow: 1.0;
in property <[SubjectRow]> subjects; in property <[SubjectRow]> subjects;
in property <[CategoryRow]> categories; in property <[CategoryRow]> categories;
@@ -467,6 +600,15 @@ export component MaskPanel inherits Rectangle {
callback mask-band-changed(string, float, float, float); callback mask-band-changed(string, float, float, float);
callback mask-hue-changed(string, float, float); callback mask-hue-changed(string, float, float);
/// TRACES: FR-DEV-19b
callback tool-picked(int);
callback brush-changed(float, float, float);
/// TRACES: FR-DEV-19a
callback part-selected(string, int);
callback part-join-picked(string, int, int);
callback part-removed(string, int);
callback part-added(string, int);
callback add-gradient(bool); callback add-gradient(bool);
/// `true` asks for the colour range rather than the brightness one. /// `true` asks for the colour range rather than the brightness one.
callback add-range(bool); callback add-range(bool);
@@ -496,6 +638,51 @@ export component MaskPanel inherits Rectangle {
if !root.enabled: Caption { text: "No image"; } if !root.enabled: Caption { text: "No image"; }
// TRACES: FR-DEV-19b
// **In the panel and not in the tool rail.** The rail's entries arm a
// gesture for the whole photograph; a brush has no meaning without a
// mask to paint into, and a rail entry that lit up with nothing
// selected would either do nothing or silently make a layer. Here the
// strip can simply be absent until there is something to paint on.
if root.enabled && root.parts.length > 0: Segmented {
options: ["Select", "Paint", "Erase"];
selected: root.tool;
picked(i) => { root.tool-picked(i); }
}
if root.enabled && root.tool > 0: SliderRow {
label: "Size";
value: root.brush-radius;
default-value: 0.05;
minimum: 0.005;
maximum: 0.4;
precision: 3;
changed(v) => { root.brush-changed(v, root.brush-hardness, root.brush-flow); }
reset => { root.brush-changed(0.05, root.brush-hardness, root.brush-flow); }
}
if root.enabled && root.tool > 0: SliderRow {
label: "Hardness";
value: root.brush-hardness;
default-value: 0.5;
minimum: 0.0;
maximum: 1.0;
precision: 2;
changed(v) => { root.brush-changed(root.brush-radius, v, root.brush-flow); }
reset => { root.brush-changed(root.brush-radius, 0.5, root.brush-flow); }
}
if root.enabled && root.tool > 0: SliderRow {
label: "Flow";
value: root.brush-flow;
default-value: 1.0;
minimum: 0.05;
maximum: 1.0;
precision: 2;
changed(v) => { root.brush-changed(root.brush-radius, root.brush-hardness, v); }
reset => { root.brush-changed(root.brush-radius, root.brush-hardness, 1.0); }
}
// --- the region map --------------------------------------------- // --- the region map ---------------------------------------------
// //
// Segmentation is a thing the user starts. Half a second of watershed // Segmentation is a thing the user starts. Half a second of watershed
@@ -752,6 +939,13 @@ export component MaskPanel inherits Rectangle {
morph-radius-changed(v) => { root.mask-morph-radius-changed(mask.id, v); } morph-radius-changed(v) => { root.mask-morph-radius-changed(mask.id, v); }
band-changed(lo, hi, soft) => { root.mask-band-changed(mask.id, lo, hi, soft); } band-changed(lo, hi, soft) => { root.mask-band-changed(mask.id, lo, hi, soft); }
hue-changed(h, w) => { root.mask-hue-changed(mask.id, h, w); } hue-changed(h, w) => { root.mask-hue-changed(mask.id, h, w); }
// Only the selected row is given any, so seven unselected stacks
// of parts are not built and drawn behind the one being worked on.
parts: mask.selected ? root.parts : [];
part-selected(i) => { root.part-selected(mask.id, i); }
part-join-picked(i, j) => { root.part-join-picked(mask.id, i, j); }
part-removed(i) => { root.part-removed(mask.id, i); }
part-added(j) => { root.part-added(mask.id, j); }
} }
// No caption saying which chain the sliders below are pointed at. // No caption saying which chain the sliders below are pointed at.