Skip to content

Commit b28661a

Browse files
authored
Merge pull request storytold#3550 from OneSlips/pr/mask-on-photo
LR-MASK-GEOMETRY: masks stay on the photo under lens corrections, Upright, Transform and Rotate
2 parents fd8b0b2 + 61a8560 commit b28661a

22 files changed

Lines changed: 1735 additions & 41 deletions

File tree

‎crates/catalog/src/journal.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@
5252
//! | 7 | Kelvin white balance for raws whose camera has matrices (#730) | `Op::SetAsShotWb`, `WhiteBalance.scale` |
5353
//! | 8 | History cursor: Go to History Step adds no step | `Op::SetHistoryCursor`, `Photo.history_cursor` |
5454
//! | 9 | preview-only recheck | `Photo.preview_checked`, `Op::SetContent.preview_checked` |
55+
//! | 10 | masks stay on the photo under lens corrections, Upright and Transform | `Mask.on_photo` (develop settings) |
5556
//!
5657
//! Rules:
5758
//! - **Bump [`VERSION`]** (and add a row above) in the change that adds an [`Op`] variant or a
@@ -76,7 +77,7 @@ pub const LOG: &str = "catalog.log";
7677
const FORMAT: &str = "lightcraft-catalog";
7778
/// The catalog format this build writes (and the newest it reads). See the module docs →
7879
/// *Format versions*; bump it whenever an [`Op`] variant or a serialized field is added.
79-
pub const VERSION: u32 = 9;
80+
pub const VERSION: u32 = 10;
8081

8182
/// When [`Journal::wants_snapshot`] says it's time to compact the log.
8283
#[derive(Clone, Copy, Debug)]

‎crates/catalog/src/tests_format_version.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -238,8 +238,8 @@ fn op_variants_are_versioned() {
238238
Op::SetHistoryCursor { .. } => 8,
239239
}
240240
}
241-
/// v9: `Photo.preview_checked` and `Op::SetContent.preview_checked`.
242-
const NEWEST_FIELDS: u32 = 9;
241+
/// v10: `Mask.on_photo` (v9: `Photo.preview_checked` and `Op::SetContent.preview_checked`).
242+
const NEWEST_FIELDS: u32 = 10;
243243
let newest = since(&Op::SetHistoryCursor { id: PhotoId(1), cursor: None });
244244
assert_eq!(newest.max(NEWEST_FIELDS), VERSION, "the newest op's or fields' version must be the current format version");
245245
}

‎crates/develop/src/settings.rs‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1054,15 +1054,35 @@ pub struct Mask {
10541054
/// Refine Edges 0..100: the mask's edges snap to the photo's (guided filter).
10551055
#[serde(skip_serializing_if = "is_zero")]
10561056
pub refine: f64,
1057+
/// Where its coordinates (gradients, brush strokes, AI selections) live: `true`, on the photo as
1058+
/// shot (user orientation, before lens corrections, Upright and Transform), so the mask stays
1059+
/// on the same content whatever those do; `false`, a mask from before that, on the corrected
1060+
/// frame. Read as `false` when absent; [`Mask::default`] (every new mask) is `true`, and an
1061+
/// edit converts an old one (`lightcraft_pipeline::mask_space::attach`).
1062+
#[serde(default, skip_serializing_if = "is_false")]
1063+
pub on_photo: bool,
10571064
}
10581065

10591066
fn is_zero(v: &f64) -> bool {
10601067
*v == 0.0
10611068
}
10621069

1070+
fn is_false(v: &bool) -> bool {
1071+
!*v
1072+
}
1073+
10631074
impl Default for Mask {
10641075
fn default() -> Self {
1065-
Self { id: 0, name: "Mask 1".into(), visible: true, invert: false, components: Vec::new(), adjust: LocalAdjustments::default(), refine: 0.0 }
1076+
Self {
1077+
id: 0,
1078+
name: "Mask 1".into(),
1079+
visible: true,
1080+
invert: false,
1081+
components: Vec::new(),
1082+
adjust: LocalAdjustments::default(),
1083+
refine: 0.0,
1084+
on_photo: true,
1085+
}
10661086
}
10671087
}
10681088

‎crates/engine/src/cmd/library/selection.rs‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -182,12 +182,17 @@ pub(super) fn rotate(s: &mut Session, p: &Value, cw: bool) -> Result<Value> {
182182
let targets = s.targets(p)?;
183183
let mut ops = Vec::new();
184184
for id in targets {
185-
if let Some(d) = s.develop_of(id) {
186-
let mut d = (*d).clone();
185+
if let Some(before) = s.develop_of(id) {
186+
let mut d = (*before).clone();
187187
d.orientation = d.orientation.rotated(cw);
188188
// the crop lives in the oriented frame, so it turns with the image (else it keeps the old width and height and cuts the photo)
189189
let turn = lightcraft_geom::Orientation::Normal.rotated(cw);
190190
d.crop.geometry.rect = turn.map_norm_rect(d.crop.geometry.rect);
191+
// and so do the masks: on the photo first (an old one), then turned with it
192+
s.attach_masks(id, &before, &mut d);
193+
for m in &mut d.masks {
194+
lightcraft_pipeline::mask_space::turn(m, turn);
195+
}
191196
d.crop.aspect = d.crop.aspect.map(|(w, h)| (h, w));
192197
ops.extend(s.develop_op(id, d, "Rotate"));
193198
}

‎crates/engine/src/cmd/masks.rs‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -464,6 +464,31 @@ pub fn specs() -> Vec<CommandSpec> {
464464
let exclude = bool_or(p, "exclude", false);
465465
let id = s.active().ok_or_else(|| bad(c, "no active photo"))?;
466466
let mid = mask_id(p, s.active_mask, c)?;
467+
// an old mask (on the corrected frame, as the click then is) goes onto the photo
468+
// first, and the click with it: the model works on the photo before lens
469+
// corrections, Upright and Transform, and reads every click there
470+
let mut at = at;
471+
if let Some(cur) = s.develop_of(id).filter(|d| d.masks.iter().any(|m| m.id == mid && !m.on_photo)) {
472+
if let Some(f) = s.mask_frame(id, &cur) {
473+
// a click on the corrected frame's blank space is off the photo, not on
474+
// its edge (a hair past it, from rounding, is on the edge)
475+
const EDGE: f64 = 1e-6;
476+
let n = f.for_mask(true).norm_to_mask(at);
477+
let on = |v: f64| v.is_finite() && (-EDGE..=1.0 + EDGE).contains(&v);
478+
if !(on(n.x) && on(n.y)) {
479+
return Err(bad(c, "the point is outside the photo"));
480+
}
481+
at = Point::new(n.x.clamp(0.0, 1.0), n.y.clamp(0.0, 1.0));
482+
}
483+
let mut on = (*cur).clone();
484+
s.attach_masks(id, &cur, &mut on);
485+
s.apply_silent(lightcraft_catalog::Op::SetDevelop {
486+
id,
487+
settings: std::sync::Arc::new(on),
488+
label: "Masks".into(),
489+
edited: None,
490+
})?;
491+
}
467492
let d = s.develop_of(id).unwrap_or_default();
468493
let m = d.masks.iter().find(|m| m.id == mid).ok_or_else(|| bad(c, format!("no mask {mid}")))?;
469494
let k = m

‎crates/engine/src/lib.rs‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1023,18 +1023,76 @@ impl Session {
10231023
/// The op that sets a photo's develop settings and appends a History entry (for batches).
10241024
pub fn develop_op(&self, id: PhotoId, settings: DevelopSettings, label: &str) -> Option<Op> {
10251025
self.catalog.photo(id)?;
1026+
let mut settings = settings;
1027+
// old masks (on the corrected frame) go onto the photo, from the frame they were drawn on:
1028+
// masks this edit kept, under the photo's settings before it (a geometry edit then moves
1029+
// the photo, not them); masks it brought in (paste, sync, a preset, a history step, a
1030+
// sidecar), under the settings they came with, where they render now. Kept masks also
1031+
// turn with an orientation change the edit makes (a sync or paste of the Crop group).
1032+
let before = match &self.interaction {
1033+
Some(i) if i.photo == id => Some(i.original.clone()),
1034+
_ => self.develop_of(id),
1035+
};
1036+
let turn = before.as_ref().and_then(|b| orientation_change(b.orientation, settings.orientation));
1037+
if settings.masks.iter().any(|m| !m.on_photo) || turn.is_some() {
1038+
let kept_frame = before.as_ref().and_then(|b| self.mask_frame(id, b));
1039+
let new_frame = self.mask_frame(id, &settings);
1040+
for m in &mut settings.masks {
1041+
let kept = before.as_ref().is_some_and(|b| b.masks.contains(m));
1042+
if let Some(f) = if kept { kept_frame.as_ref() } else { new_frame.as_ref() } {
1043+
lightcraft_pipeline::mask_space::attach(m, f);
1044+
}
1045+
if let (true, Some(t)) = (kept, turn) {
1046+
lightcraft_pipeline::mask_space::turn(m, t);
1047+
}
1048+
}
1049+
}
10261050
let settings = Arc::new(settings);
10271051
let step = lightcraft_catalog::HistoryStep { label: label.into(), settings: settings.clone() };
10281052
Some(Op::Batch {
10291053
ops: vec![Op::SetDevelop { id, settings, label: label.into(), edited: Some((self.clock)()) }, Op::PushHistory { id, step }],
10301054
})
10311055
}
10321056

1057+
/// Put the old masks of `d` (on the corrected frame, `Mask::on_photo` false) on photo `id`
1058+
/// before the warp, from the frame of `drawn` (the settings they were drawn under): they
1059+
/// render where they did and from then on stay on their content when lens corrections,
1060+
/// Upright or Transform change.
1061+
pub fn attach_masks(&self, id: PhotoId, drawn: &DevelopSettings, d: &mut DevelopSettings) {
1062+
if d.masks.iter().all(|m| m.on_photo) {
1063+
return;
1064+
}
1065+
let Some(frame) = self.mask_frame(id, drawn) else { return };
1066+
for m in &mut d.masks {
1067+
lightcraft_pipeline::mask_space::attach(m, &frame);
1068+
}
1069+
}
1070+
1071+
/// The uncropped frame of photo `id` under settings `d`, with its lens: where mask
1072+
/// coordinates go through its warp ([`lightcraft_pipeline::geometry::Frame::for_mask`]).
1073+
pub(crate) fn mask_frame(&self, id: PhotoId, d: &DevelopSettings) -> Option<lightcraft_pipeline::geometry::Frame> {
1074+
let p = self.catalog.photo(id)?;
1075+
Some(lightcraft_pipeline::geometry::Frame::with_lens(
1076+
p.width.max(1) as usize,
1077+
p.height.max(1) as usize,
1078+
&d.effective(),
1079+
false,
1080+
p.embedded_lens.as_ref(),
1081+
))
1082+
}
1083+
10331084
pub fn begin_interaction(&mut self, label: &str) -> Result<()> {
10341085
if self.interaction.is_some() {
10351086
self.end_interaction()?;
10361087
}
10371088
let id = self.active().ok_or_else(|| EngineError::Other("no active photo".into()))?;
1089+
// old masks go onto the photo before a drag moves the frame under them (they then stay on
1090+
// their content while it does, not only once it ends)
1091+
if let Some(d) = self.develop_of(id).filter(|d| d.masks.iter().any(|m| !m.on_photo)) {
1092+
let mut on = (*d).clone();
1093+
self.attach_masks(id, &d, &mut on);
1094+
self.apply_silent(Op::SetDevelop { id, settings: Arc::new(on), label: label.into(), edited: None })?;
1095+
}
10381096
let original = self.develop_of(id).unwrap_or_default();
10391097
self.interaction = Some(Interaction { label: label.into(), photo: id, original, crop_edited: false });
10401098
Ok(())
@@ -1373,3 +1431,22 @@ mod tests;
13731431
use tests::face_recognize as tests_face_recognize;
13741432
#[cfg(test)]
13751433
use tests::xmp as tests_xmp;
1434+
1435+
/// The turn or flip that takes orientation `from` to `to` (`None` when they are the same): what the
1436+
/// masks, on the oriented photo, must follow ([`lightcraft_pipeline::mask_space::turn`]).
1437+
pub(crate) fn orientation_change(from: lightcraft_geom::Orientation, to: lightcraft_geom::Orientation) -> Option<lightcraft_geom::Orientation> {
1438+
use lightcraft_geom::Orientation;
1439+
if from == to {
1440+
return None;
1441+
}
1442+
let inv = from.inverse();
1443+
let probes = [(0.2, 0.3), (0.7, 0.1), (0.4, 0.9)];
1444+
let close = |a: (f64, f64), b: (f64, f64)| (a.0 - b.0).abs() < 1e-9 && (a.1 - b.1).abs() < 1e-9;
1445+
(0..8u8).map(|k| Orientation::from_parts(k >= 4, k % 4)).find(|t| {
1446+
probes.iter().all(|&(x, y)| {
1447+
let (rx, ry) = inv.map(x, y, 1.0, 1.0);
1448+
let (tx, ty) = from.map(rx, ry, 1.0, 1.0);
1449+
close(t.map(tx, ty, 1.0, 1.0), to.map(rx, ry, 1.0, 1.0))
1450+
})
1451+
})
1452+
}

‎crates/engine/src/segment.rs‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -376,12 +376,23 @@ fn clicks_of(include: &[Point], exclude: &[Point]) -> Vec<Click> {
376376
}
377377

378378
impl Session {
379-
/// The key and settings of photo `id` as the model sees it: its look without masks, uncropped.
379+
/// The key and settings of photo `id` as the model sees it: its look without masks, uncropped
380+
/// and unflipped, and without lens corrections, Upright and Transform. Mask coordinates
381+
/// (clicks, stored selections) live on the photo before those (`Mask::on_photo`), so a
382+
/// selection stays on its content when they change, and changing them doesn't ask again.
380383
#[cfg_attr(not(feature = "sam"), allow(dead_code))]
381-
fn segment_key(&self, id: PhotoId) -> Option<(u64, lightcraft_develop::DevelopSettings)> {
384+
pub(crate) fn segment_key(&self, id: PhotoId) -> Option<(u64, lightcraft_develop::DevelopSettings)> {
382385
let p = self.catalog.photo(id)?;
383386
let mut d = (*p.develop).clone();
384387
d.masks.clear();
388+
// (the crop doesn't show in the uncropped input: it doesn't ask again either)
389+
d.crop = Default::default();
390+
d.geometry = Default::default();
391+
d.optics.lens_profile = false;
392+
d.optics.distortion = 0.0;
393+
d.optics.remove_ca = false;
394+
d.optics.ca_red = 0.0;
395+
d.optics.ca_blue = 0.0;
385396
let content = crate::media::content_key(p);
386397
let mut h = mix(0xcbf2_9ce4_8422_2325, d.hash64());
387398
h = mix(h, id.0);
@@ -410,6 +421,13 @@ impl Session {
410421
region: Option<[f64; 4]>,
411422
) -> Result<worker::Job, String> {
412423
let dir = self.segmenter.model_dir()?;
424+
// old masks go onto the photo first: the selection that comes back is in its coordinates
425+
if let Some(cur) = self.develop_of(id).filter(|d| d.masks.iter().any(|m| !m.on_photo)) {
426+
let mut on = (*cur).clone();
427+
self.attach_masks(id, &cur, &mut on);
428+
self.apply_silent(lightcraft_catalog::Op::SetDevelop { id, settings: std::sync::Arc::new(on), label: "Masks".into(), edited: None })
429+
.map_err(|e| e.to_string())?;
430+
}
413431
let (key, mut d) = self.segment_key(id).ok_or("no such photo")?;
414432
let p = self.catalog.photo(id).ok_or("no such photo")?.clone();
415433
let missing = match &p.source {

‎crates/engine/src/tests.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ mod libops;
3333
mod library;
3434
mod lightroom_folder;
3535
mod mask_effects;
36+
mod mask_geometry;
3637
mod merge;
3738
mod move_to_share;
3839
mod organize;

0 commit comments

Comments
 (0)