Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion crates/catalog/src/journal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
//! | 7 | Kelvin white balance for raws whose camera has matrices (#730) | `Op::SetAsShotWb`, `WhiteBalance.scale` |
//! | 8 | History cursor: Go to History Step adds no step | `Op::SetHistoryCursor`, `Photo.history_cursor` |
//! | 9 | preview-only recheck | `Photo.preview_checked`, `Op::SetContent.preview_checked` |
//! | 10 | masks stay on the photo under lens corrections, Upright and Transform | `Mask.on_photo` (develop settings) |
//!
//! Rules:
//! - **Bump [`VERSION`]** (and add a row above) in the change that adds an [`Op`] variant or a
Expand All @@ -76,7 +77,7 @@ pub const LOG: &str = "catalog.log";
const FORMAT: &str = "lightcraft-catalog";
/// The catalog format this build writes (and the newest it reads). See the module docs →
/// *Format versions*; bump it whenever an [`Op`] variant or a serialized field is added.
pub const VERSION: u32 = 9;
pub const VERSION: u32 = 10;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

/// When [`Journal::wants_snapshot`] says it's time to compact the log.
#[derive(Clone, Copy, Debug)]
Expand Down
4 changes: 2 additions & 2 deletions crates/catalog/src/tests_format_version.rs
Original file line number Diff line number Diff line change
Expand Up @@ -238,8 +238,8 @@ fn op_variants_are_versioned() {
Op::SetHistoryCursor { .. } => 8,
}
}
/// v9: `Photo.preview_checked` and `Op::SetContent.preview_checked`.
const NEWEST_FIELDS: u32 = 9;
/// v10: `Mask.on_photo` (v9: `Photo.preview_checked` and `Op::SetContent.preview_checked`).
const NEWEST_FIELDS: u32 = 10;
let newest = since(&Op::SetHistoryCursor { id: PhotoId(1), cursor: None });
assert_eq!(newest.max(NEWEST_FIELDS), VERSION, "the newest op's or fields' version must be the current format version");
}
22 changes: 21 additions & 1 deletion crates/develop/src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1054,15 +1054,35 @@ pub struct Mask {
/// Refine Edges 0..100: the mask's edges snap to the photo's (guided filter).
#[serde(skip_serializing_if = "is_zero")]
pub refine: f64,
/// Where its coordinates (gradients, brush strokes, AI selections) live: `true`, on the photo as
/// shot (user orientation, before lens corrections, Upright and Transform), so the mask stays
/// on the same content whatever those do; `false`, a mask from before that, on the corrected
/// frame. Read as `false` when absent; [`Mask::default`] (every new mask) is `true`, and an
/// edit converts an old one (`lightcraft_pipeline::mask_space::attach`).
#[serde(default, skip_serializing_if = "is_false")]
pub on_photo: bool,
}

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

fn is_false(v: &bool) -> bool {
!*v
}

impl Default for Mask {
fn default() -> Self {
Self { id: 0, name: "Mask 1".into(), visible: true, invert: false, components: Vec::new(), adjust: LocalAdjustments::default(), refine: 0.0 }
Self {
id: 0,
name: "Mask 1".into(),
visible: true,
invert: false,
components: Vec::new(),
adjust: LocalAdjustments::default(),
refine: 0.0,
on_photo: true,
}
}
}

Expand Down
9 changes: 7 additions & 2 deletions crates/engine/src/cmd/library/selection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,12 +182,17 @@ pub(super) fn rotate(s: &mut Session, p: &Value, cw: bool) -> Result<Value> {
let targets = s.targets(p)?;
let mut ops = Vec::new();
for id in targets {
if let Some(d) = s.develop_of(id) {
let mut d = (*d).clone();
if let Some(before) = s.develop_of(id) {
let mut d = (*before).clone();
d.orientation = d.orientation.rotated(cw);
// 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)
let turn = lightcraft_geom::Orientation::Normal.rotated(cw);
d.crop.geometry.rect = turn.map_norm_rect(d.crop.geometry.rect);
// and so do the masks: on the photo first (an old one), then turned with it
s.attach_masks(id, &before, &mut d);
for m in &mut d.masks {
lightcraft_pipeline::mask_space::turn(m, turn);
}
d.crop.aspect = d.crop.aspect.map(|(w, h)| (h, w));
ops.extend(s.develop_op(id, d, "Rotate"));
}
Expand Down
25 changes: 25 additions & 0 deletions crates/engine/src/cmd/masks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -464,6 +464,31 @@ pub fn specs() -> Vec<CommandSpec> {
let exclude = bool_or(p, "exclude", false);
let id = s.active().ok_or_else(|| bad(c, "no active photo"))?;
let mid = mask_id(p, s.active_mask, c)?;
// an old mask (on the corrected frame, as the click then is) goes onto the photo
// first, and the click with it: the model works on the photo before lens
// corrections, Upright and Transform, and reads every click there
let mut at = at;
if let Some(cur) = s.develop_of(id).filter(|d| d.masks.iter().any(|m| m.id == mid && !m.on_photo)) {
if let Some(f) = s.mask_frame(id, &cur) {
// a click on the corrected frame's blank space is off the photo, not on
// its edge (a hair past it, from rounding, is on the edge)
const EDGE: f64 = 1e-6;
let n = f.for_mask(true).norm_to_mask(at);
let on = |v: f64| v.is_finite() && (-EDGE..=1.0 + EDGE).contains(&v);
if !(on(n.x) && on(n.y)) {
return Err(bad(c, "the point is outside the photo"));
}
at = Point::new(n.x.clamp(0.0, 1.0), n.y.clamp(0.0, 1.0));
}
let mut on = (*cur).clone();
s.attach_masks(id, &cur, &mut on);
s.apply_silent(lightcraft_catalog::Op::SetDevelop {
id,
settings: std::sync::Arc::new(on),
label: "Masks".into(),
edited: None,
})?;
}
let d = s.develop_of(id).unwrap_or_default();
let m = d.masks.iter().find(|m| m.id == mid).ok_or_else(|| bad(c, format!("no mask {mid}")))?;
let k = m
Expand Down
77 changes: 77 additions & 0 deletions crates/engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1023,18 +1023,76 @@ impl Session {
/// The op that sets a photo's develop settings and appends a History entry (for batches).
pub fn develop_op(&self, id: PhotoId, settings: DevelopSettings, label: &str) -> Option<Op> {
self.catalog.photo(id)?;
let mut settings = settings;
// old masks (on the corrected frame) go onto the photo, from the frame they were drawn on:
// masks this edit kept, under the photo's settings before it (a geometry edit then moves
// the photo, not them); masks it brought in (paste, sync, a preset, a history step, a
// sidecar), under the settings they came with, where they render now. Kept masks also
// turn with an orientation change the edit makes (a sync or paste of the Crop group).
let before = match &self.interaction {
Some(i) if i.photo == id => Some(i.original.clone()),
_ => self.develop_of(id),
};
let turn = before.as_ref().and_then(|b| orientation_change(b.orientation, settings.orientation));
if settings.masks.iter().any(|m| !m.on_photo) || turn.is_some() {
let kept_frame = before.as_ref().and_then(|b| self.mask_frame(id, b));
let new_frame = self.mask_frame(id, &settings);
for m in &mut settings.masks {
let kept = before.as_ref().is_some_and(|b| b.masks.contains(m));
if let Some(f) = if kept { kept_frame.as_ref() } else { new_frame.as_ref() } {
lightcraft_pipeline::mask_space::attach(m, f);
}
if let (true, Some(t)) = (kept, turn) {
lightcraft_pipeline::mask_space::turn(m, t);
}
}
}
let settings = Arc::new(settings);
let step = lightcraft_catalog::HistoryStep { label: label.into(), settings: settings.clone() };
Some(Op::Batch {
ops: vec![Op::SetDevelop { id, settings, label: label.into(), edited: Some((self.clock)()) }, Op::PushHistory { id, step }],
})
}

/// Put the old masks of `d` (on the corrected frame, `Mask::on_photo` false) on photo `id`
/// before the warp, from the frame of `drawn` (the settings they were drawn under): they
/// render where they did and from then on stay on their content when lens corrections,
/// Upright or Transform change.
pub fn attach_masks(&self, id: PhotoId, drawn: &DevelopSettings, d: &mut DevelopSettings) {
if d.masks.iter().all(|m| m.on_photo) {
return;
}
let Some(frame) = self.mask_frame(id, drawn) else { return };
for m in &mut d.masks {
lightcraft_pipeline::mask_space::attach(m, &frame);
}
}

/// The uncropped frame of photo `id` under settings `d`, with its lens: where mask
/// coordinates go through its warp ([`lightcraft_pipeline::geometry::Frame::for_mask`]).
pub(crate) fn mask_frame(&self, id: PhotoId, d: &DevelopSettings) -> Option<lightcraft_pipeline::geometry::Frame> {
let p = self.catalog.photo(id)?;
Some(lightcraft_pipeline::geometry::Frame::with_lens(
p.width.max(1) as usize,
p.height.max(1) as usize,
&d.effective(),
false,
p.embedded_lens.as_ref(),
))
}

pub fn begin_interaction(&mut self, label: &str) -> Result<()> {
if self.interaction.is_some() {
self.end_interaction()?;
}
let id = self.active().ok_or_else(|| EngineError::Other("no active photo".into()))?;
// old masks go onto the photo before a drag moves the frame under them (they then stay on
// their content while it does, not only once it ends)
if let Some(d) = self.develop_of(id).filter(|d| d.masks.iter().any(|m| !m.on_photo)) {
let mut on = (*d).clone();
self.attach_masks(id, &d, &mut on);
self.apply_silent(Op::SetDevelop { id, settings: Arc::new(on), label: label.into(), edited: None })?;
}
let original = self.develop_of(id).unwrap_or_default();
self.interaction = Some(Interaction { label: label.into(), photo: id, original, crop_edited: false });
Ok(())
Expand Down Expand Up @@ -1373,3 +1431,22 @@ mod tests;
use tests::face_recognize as tests_face_recognize;
#[cfg(test)]
use tests::xmp as tests_xmp;

/// The turn or flip that takes orientation `from` to `to` (`None` when they are the same): what the
/// masks, on the oriented photo, must follow ([`lightcraft_pipeline::mask_space::turn`]).
pub(crate) fn orientation_change(from: lightcraft_geom::Orientation, to: lightcraft_geom::Orientation) -> Option<lightcraft_geom::Orientation> {
use lightcraft_geom::Orientation;
if from == to {
return None;
}
let inv = from.inverse();
let probes = [(0.2, 0.3), (0.7, 0.1), (0.4, 0.9)];
let close = |a: (f64, f64), b: (f64, f64)| (a.0 - b.0).abs() < 1e-9 && (a.1 - b.1).abs() < 1e-9;
(0..8u8).map(|k| Orientation::from_parts(k >= 4, k % 4)).find(|t| {
probes.iter().all(|&(x, y)| {
let (rx, ry) = inv.map(x, y, 1.0, 1.0);
let (tx, ty) = from.map(rx, ry, 1.0, 1.0);
close(t.map(tx, ty, 1.0, 1.0), to.map(rx, ry, 1.0, 1.0))
})
})
}
22 changes: 20 additions & 2 deletions crates/engine/src/segment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -376,12 +376,23 @@ fn clicks_of(include: &[Point], exclude: &[Point]) -> Vec<Click> {
}

impl Session {
/// The key and settings of photo `id` as the model sees it: its look without masks, uncropped.
/// The key and settings of photo `id` as the model sees it: its look without masks, uncropped
/// and unflipped, and without lens corrections, Upright and Transform. Mask coordinates
/// (clicks, stored selections) live on the photo before those (`Mask::on_photo`), so a
/// selection stays on its content when they change, and changing them doesn't ask again.
#[cfg_attr(not(feature = "sam"), allow(dead_code))]
fn segment_key(&self, id: PhotoId) -> Option<(u64, lightcraft_develop::DevelopSettings)> {
pub(crate) fn segment_key(&self, id: PhotoId) -> Option<(u64, lightcraft_develop::DevelopSettings)> {
let p = self.catalog.photo(id)?;
let mut d = (*p.develop).clone();
d.masks.clear();
// (the crop doesn't show in the uncropped input: it doesn't ask again either)
d.crop = Default::default();
d.geometry = Default::default();
d.optics.lens_profile = false;
d.optics.distortion = 0.0;
d.optics.remove_ca = false;
d.optics.ca_red = 0.0;
d.optics.ca_blue = 0.0;
let content = crate::media::content_key(p);
let mut h = mix(0xcbf2_9ce4_8422_2325, d.hash64());
h = mix(h, id.0);
Expand Down Expand Up @@ -410,6 +421,13 @@ impl Session {
region: Option<[f64; 4]>,
) -> Result<worker::Job, String> {
let dir = self.segmenter.model_dir()?;
// old masks go onto the photo first: the selection that comes back is in its coordinates
if let Some(cur) = self.develop_of(id).filter(|d| d.masks.iter().any(|m| !m.on_photo)) {
let mut on = (*cur).clone();
self.attach_masks(id, &cur, &mut on);
self.apply_silent(lightcraft_catalog::Op::SetDevelop { id, settings: std::sync::Arc::new(on), label: "Masks".into(), edited: None })
.map_err(|e| e.to_string())?;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
let (key, mut d) = self.segment_key(id).ok_or("no such photo")?;
let p = self.catalog.photo(id).ok_or("no such photo")?.clone();
let missing = match &p.source {
Expand Down
1 change: 1 addition & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ mod libops;
mod library;
mod lightroom_folder;
mod mask_effects;
mod mask_geometry;
mod merge;
mod move_to_share;
mod organize;
Expand Down
Loading
Loading