mirror of
https://github.com/storytold/lightcraft.git
synced 2026-12-02 02:46:10 -06:00
LR-EDIT-LENSBLUR: camera-like Lens Blur with AI subject focus and per-mask bokeh
Part of the Lens Blur row (`LR-EDIT-LENSBLUR`, ⬜ → 🟡: no depth map yet). Related: #377 (SAM 3 subject selection, used here for the Lens Blur focus).
## Problem
Lens Blur settings existed but nothing rendered them: there was no way to add a shallow depth of field, keep the subject sharp while the rest falls out of focus, or blur only part of a photo through a mask.
## Change
**Edit → Lens Blur** (`section.lensBlur`, ⌘6)
- **Apply**, **Amount**, **Boost** (brighter bokeh highlights) and **Transition** (how gradually the blur grows away from what is in focus, so the subject doesn't look cut out).
- **In Focus**: *Subject* (a mask) or a fixed shape: **Auto / Round / Horizontal / Vertical**, buttons drawn in code that work on the light themes.
- **Move & Resize** (tool `lensBlurShape`) drags the ellipse on the photo and stretches it by its handles. Each drag is one undo step; a shape button puts the ellipse back in the middle.
- **Find Subject** (`lensBlur.findSubject`) runs only when clicked, never automatically on Apply.
- It starts from the focus point the camera recorded, when the file has one (Sony ILCE-1 and ILCE-7SM3, the models `lightcraft_meta` reads today). Otherwise it starts from the subject estimate.
- SAM 3 keeps the prominent people and animals: those at the focus point and those of a similar size. When the focus point falls on neither, it falls back to an object click at that point.
- The result is a normal Object mask ("Lens Blur Subject") that can be refined in Masking.
- It runs on the background segment worker, and on remote SAM 3 too (`Operation::Subject`). While the mask is pending, the UI shows a spinner and the render keeps the subject estimate in focus, so the photo is never blurred whole.
- Without the model, it returns the model-missing error, changes nothing, and the UI offers the SAM 3 download.
- **Brush Refinement**: Focus and Blur brushes painted on the photo (`lensBlur.brushStroke`, `lensBlur.brushReset`), with Size, Feather, Flow, Amount and Auto Mask.
- While Apply is off, In Focus, the shapes, Move & Resize and Find Subject are disabled.
**Masking: a Lens Blur block in every mask** (`section:maskLensBlur`, under Refine Edges)
- **Blur: Selection / Outside**. Outside blurs what the mask leaves out, without inverting the mask's other adjustments.
- **Amount**, **Boost** and **Transition**, per mask. The header's eye switches the block off and keeps its values; the header folds the block.
- Stored as `lens_blur`, `lens_blur_outside`, `lens_blur_boost`, `lens_blur_transition` and `lens_blur_off` on `LocalAdjustments`, set through `mask.adjust`.
**Rendering** (`crates/pipeline/src/lens_blur.rs`)
- Runs in the scene-linear stage after denoise; its settings are part of `pre_nr_key`.
- Disc (bokeh) kernel at four levels on coarse grids, with a normalized convolution weighted by the circle of confusion, so sharp areas don't bleed halos into the blur. Transition uses a chamfer distance to the in-focus area.
- The radius is relative to the long edge, so the blur doesn't depend on resolution. The work stays bounded on large exports: the disc kernel has a fixed size, and each level's coarse grid stays within a cell budget.
- Zoomed windows, both 8-bit and deep (16-bit/float), read around them and are cut back to the request. The grids follow the whole output's origin, and the automatic subject estimate is made once from the whole photo. A window therefore matches the whole render.
- GPU path: read back, apply on the CPU, upload (`crates/gpu/src/render.rs`).
- Hostile values (NaN or infinite sizes, out-of-range areas and focus points, oversized stroke lists) are sanitized or rejected, never a panic.
All new strings are in the 17 locales.
**Not in this PR:**
- Real depth. The falloff is the image distance from the focus, not scene depth; a depth model (e.g. Depth Anything V2 Small on candle) would be a separate PR.
- Rotating the ellipse.
- Aperture shapes.
- Focus points for more camera makes and models.
- Find Subject doesn't resume by itself after the SAM 3 download (the Masking tools do). Like the existing Object / Describe jobs, it shows no row in the activity stack.
## How it was checked
- [x] Full `cargo xtask ci` on Windows 11 x86_64 after the latest merge of `main` (465c8722):
- fmt, clippy, heif, parity, layers, assets and wasm pass;
- every Lens Blur test passes;
- the only failures are five tests outside this change that fail on Windows on `main` too: `export::tests::sixteen_bit_zip_tiff_is_never_larger_than_uncompressed`, the two GPU out-of-memory tests in `gpu::ctx`, `dialog_role::settings_is_a_dialog_too` (needs craft-fonts) and `folder_drop::dont_ask_again_moves_the_next_drop_at_once`.
- [x] Tests that fail without the change:
- **pipeline**:
- the `lens_blur` tests: shapes and moved or hostile areas, blur growth away from the focus, the fallback while an AI mask is pending, brushes, masks blurring their selection or outside with Transition, hostile input;
- `large_image_blur_work_is_bounded`: on a 60 MP export with the strongest global and per-mask settings, the disc kernel stays a fixed size and every level's coarse grid stays within its cell budget, including an offset render window;
- window/full-render parity at U8 and U16, including the automatic subject.
- **engine**: brushes with undo; Find Subject without the model changes nothing; deleting the focus mask clears the focus; a partial effect preset sets `lens_blur`; with the `sam` feature, Find Subject fills the waiting mask.
- **segment**: `prominent_subjects`, and remote `Subject` validation.
- **catalog**: `op_variants_are_versioned` with the new format version.
- **ui-egui**: the brushes painting on the photo, the shape buttons, the controls disabled while Apply is off, Move & Resize with undo and redo, the mask block (side, sliders, eye, folding).
- [x] User-visible change: ran the app and looked at the result (dark and light themes).
## Screenshots
**Before / after**
<img width="1402" height="952" alt="before" src="https://github.com/user-attachments/assets/8baceb99-7708-4c25-990c-8da29b6bc1b4" />
<img width="1320" height="937" alt="after" src="https://github.com/user-attachments/assets/a1476510-558a-4460-8766-b25bda0dfd3d" />
**Edit → Lens Blur** and **the mask's Lens Blur block**
<img width="457" height="626" alt="main painel" src="https://github.com/user-attachments/assets/47a19637-29a8-4446-a003-2eef416975b7" />
<img width="463" height="333" alt="mask painel" src="https://github.com/user-attachments/assets/345ffc14-66d2-4adc-af3c-b756727201de" />
## Merging
- **Overlap:** #1713 (Clearfall; a draft since 2026-10-14 that conflicts with main) implements the same row on the CPU. It has aperture shapes and XMP roundtrip, which this PR lacks. This PR adds the per-mask block, SAM 3 Find Subject from the camera's focus point, the GPU path and window parity. Only one should land; happy to port what #1713 has that this lacks.
- **Existing edits and libraries:** unchanged. Lens Blur is off by default and every new field is omitted from the JSON at its default, so existing settings keep their JSON and hashes.
- **Shared numbers taken:** catalog format `VERSION` 12 (`crates/catalog/src/journal.rs`). main already uses 10 (`Mask.on_photo`) and 11 (`EmbeddedLens.source`), so Lens Blur takes one past them. If another pull request lands with 12 first, I'll take the next one when I merge main. No render-cache, look or process version change.
- **Where it came from:** own implementation; nothing derived from GPL code or Adobe data. The camera focus point comes from the existing `lightcraft_meta` reader; subject selection uses SAM 3 through the existing segment crate.
- **New dependencies, `unsafe`, build scripts, network access, spawned processes, deleted files, CI or `xtask` gate changes:** none. The remote SAM 3 protocol gains one request (`Operation::Subject`). An older worker rejects it with an error, as `docs/ai-masks.md` notes.
## Checklist
- [x] No new panic path in non-test code
- [x] New text on screen goes through `tr()` with keys in all `locales/*.json`; ⌘6 opens the new section (KEY-SECTIONS)
- [x] `docs/parity-checklist.md` rows updated (LR-EDIT-LENSBLUR 🟡, LR-MASK-SLIDERS, KEY-SECTIONS); `docs/gaps.md` has no Lens Blur entry
- [x] New code has a caller
- [x] No new assets (the shape icons are drawn in code)
- [x] Ready to merge
<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
<!-- coderabbit-ai-generated:v1 -->
## Summary by CodeRabbit
* **New Features**
* Added Lens Blur with adjustable strength, highlight boost, and transition controls, plus Round, Wide, and Tall focus shapes.
* Keep a subject or selected mask in focus, find people or animals automatically, and refine focus or blur with brushes. Move and resize the focus area directly on the photo.
* Apply Lens Blur to individual masks, including selections or areas outside them.
* **Bug Fixes**
* Improved Lens Blur rendering for cropped views and preserved focus-mask assignments correctly when masks are edited.
* **Documentation**
* Updated feature and control guides, with Lens Blur interface translations added across multiple languages.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
This commit is contained in:
@@ -28,6 +28,7 @@ pub enum Section {
|
||||
Calibration,
|
||||
PointColor,
|
||||
RedEye,
|
||||
LensBlur,
|
||||
}
|
||||
|
||||
impl Section {
|
||||
@@ -49,6 +50,7 @@ impl Section {
|
||||
Section::Calibration => "Calibration",
|
||||
Section::PointColor => "Point Color",
|
||||
Section::RedEye => "Red Eye",
|
||||
Section::LensBlur => "Lens Blur",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -286,6 +288,9 @@ controls! {
|
||||
"geometry.scale" => geometry.scale, "Scale", Geometry, 50, 150, 100, 1, 0, Plain;
|
||||
"geometry.offsetX" => geometry.offset_x, "Offset X", Geometry, -100, 100, 0, 0.1, 1, Centered;
|
||||
"geometry.offsetY" => geometry.offset_y, "Offset Y", Geometry, -100, 100, 0, 0.1, 1, Centered;
|
||||
"lensBlur.amount" => lens_blur.amount, "Blur Amount", LensBlur, 0, 100, 0, 1, 0, Plain;
|
||||
"lensBlur.boost" => lens_blur.boost, "Boost", LensBlur, 0, 100, 0, 1, 0, Plain;
|
||||
"lensBlur.transition" => lens_blur.transition, "Transition", LensBlur, 0, 100, 50, 1, 0, Plain;
|
||||
"calibration.shadowsTint" => calibration.shadows_tint, "Shadows Tint", Calibration, -100, 100, 0, 1, 0, Tint;
|
||||
"calibration.redHue" => calibration.red_hue, "Red Hue", Calibration, -100, 100, 0, 1, 0, Gradient { from: "#e0306a", to: "#e08a30" };
|
||||
"calibration.redSat" => calibration.red_sat, "Red Saturation", Calibration, -100, 100, 0, 1, 0, Gradient { from: "#7a7a7a", to: "#e03a3a" };
|
||||
|
||||
@@ -200,6 +200,14 @@ impl DevelopSettings {
|
||||
}
|
||||
}
|
||||
|
||||
/// The middle of the crop, in normalized photo coordinates (the photo's middle when the crop
|
||||
/// isn't a usable rectangle).
|
||||
pub fn crop_center(&self) -> lightcraft_geom::Point {
|
||||
let r = self.crop.geometry.rect;
|
||||
let (x, y) = ((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0);
|
||||
if x.is_finite() && y.is_finite() { lightcraft_geom::Point::new(x, y) } else { lightcraft_geom::Point::new(0.5, 0.5) }
|
||||
}
|
||||
|
||||
/// Next free mask id: one past the highest, or, when that is `u32::MAX` (ids come from files,
|
||||
/// pastes and agents), the lowest one no mask uses.
|
||||
pub fn next_mask_id(&self) -> u32 {
|
||||
|
||||
@@ -898,6 +898,25 @@ pub struct LocalAdjustments {
|
||||
pub noise: f64,
|
||||
pub moire: f64,
|
||||
pub defringe: f64,
|
||||
/// Lens Blur inside the mask, 0..100 (`lightcraft_pipeline::lens_blur`): disc (bokeh) blur
|
||||
/// whose radius follows the mask's strength. Omitted while 0, so masks without it keep their
|
||||
/// JSON (and hash).
|
||||
#[serde(skip_serializing_if = "is_zero")]
|
||||
pub lens_blur: f64,
|
||||
/// The mask's Lens Blur block switched off (its values kept).
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub lens_blur_off: bool,
|
||||
/// Blur what the mask leaves out instead of what it selects (the mask's other adjustments
|
||||
/// still go where it selects).
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub lens_blur_outside: bool,
|
||||
/// Brighter bokeh highlights in the mask's blur, 0..100.
|
||||
#[serde(skip_serializing_if = "is_zero")]
|
||||
pub lens_blur_boost: f64,
|
||||
/// How gradually the mask's blur grows away from what stays sharp, 0..100 (0: it follows the
|
||||
/// mask's own edge).
|
||||
#[serde(skip_serializing_if = "is_zero")]
|
||||
pub lens_blur_transition: f64,
|
||||
/// Colour overlay (hue degrees, saturation 0..100); sat 0 = none.
|
||||
pub color_hue: f64,
|
||||
pub color_sat: f64,
|
||||
@@ -925,6 +944,11 @@ impl Default for LocalAdjustments {
|
||||
noise: 0.0,
|
||||
moire: 0.0,
|
||||
defringe: 0.0,
|
||||
lens_blur: 0.0,
|
||||
lens_blur_off: false,
|
||||
lens_blur_outside: false,
|
||||
lens_blur_boost: 0.0,
|
||||
lens_blur_transition: 0.0,
|
||||
color_hue: 0.0,
|
||||
color_sat: 0.0,
|
||||
amount: 100.0,
|
||||
@@ -1266,13 +1290,157 @@ impl Default for RedEye {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
/// Lens Blur: a shallow depth of field added after the fact (`lightcraft_pipeline::lens_blur`).
|
||||
/// What stays sharp is the photo's subject, or the selection of the mask [`LensBlur::focus_mask`]
|
||||
/// names; everything else gets disc-shaped (bokeh) blur up to [`LensBlur::amount`].
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct LensBlur {
|
||||
pub enabled: bool,
|
||||
/// Blur of what is out of focus, 0..100 (100: a disc of 3.5 % of the long edge).
|
||||
pub amount: f64,
|
||||
/// Reserved for a depth map (not rendered yet).
|
||||
pub focal_distance: f64,
|
||||
/// Reserved for a depth map (not rendered yet).
|
||||
pub focal_range: f64,
|
||||
/// How much brighter the out-of-focus highlights turn into bokeh discs, 0..100. Omitted while
|
||||
/// 0, so settings without it keep their JSON (and hash).
|
||||
#[serde(skip_serializing_if = "is_zero")]
|
||||
pub boost: f64,
|
||||
/// The id of the mask whose selection stays in focus (any mask, shown or hidden); `None`, or a
|
||||
/// mask that no longer exists: the photo's subject.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub focus_mask: Option<u32>,
|
||||
/// Brush Refinement, Focus brush: strokes painted in focus (their strength: how far; erase
|
||||
/// strokes take it back). Omitted while empty.
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub focus_strokes: Vec<BrushStroke>,
|
||||
/// Brush Refinement, Blur brush: strokes painted out of focus, over the focus and the Focus
|
||||
/// brush. Omitted while empty.
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub blur_strokes: Vec<BrushStroke>,
|
||||
/// How gradually the blur grows away from what is in focus, 0..100: 0 a sharp cut at the
|
||||
/// focus's edge, higher a longer ramp (a stand-in for depth until there is a depth map).
|
||||
/// Omitted at its default, so settings without it keep their JSON (and hash).
|
||||
#[serde(skip_serializing_if = "LensBlur::is_default_transition")]
|
||||
pub transition: f64,
|
||||
/// What stays in focus without a focus mask: the subject estimate, or a fixed shape in the
|
||||
/// middle of the framing. Omitted while automatic.
|
||||
#[serde(skip_serializing_if = "FocusShape::is_auto")]
|
||||
pub shape: FocusShape,
|
||||
/// Where a fixed shape sits and how large it is, once moved or resized on the photo; `None`:
|
||||
/// the shape's preset, in the middle of the crop.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub area: Option<FocusArea>,
|
||||
}
|
||||
|
||||
/// A fixed focus shape on the photo: an upright ellipse.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct FocusArea {
|
||||
/// Normalized (uncropped, oriented) photo coordinates, as mask shapes.
|
||||
pub center: Point,
|
||||
/// Half-width and half-height, in units of the photo's long edge.
|
||||
pub rx: f64,
|
||||
pub ry: f64,
|
||||
}
|
||||
|
||||
impl FocusArea {
|
||||
/// Smallest and largest radius (long-edge units).
|
||||
pub const MIN_RADIUS: f64 = 0.02;
|
||||
pub const MAX_RADIUS: f64 = 1.0;
|
||||
|
||||
/// Usable values: finite, the radii within range, the centre no farther than a photo's width
|
||||
/// outside it. A hostile value falls back to the middle and the default size.
|
||||
pub fn sanitized(self) -> FocusArea {
|
||||
let r = |v: f64, d: f64| if v.is_finite() { v.clamp(Self::MIN_RADIUS, Self::MAX_RADIUS) } else { d };
|
||||
let c = |v: f64| if v.is_finite() { v.clamp(-1.0, 2.0) } else { 0.5 };
|
||||
FocusArea { center: Point::new(c(self.center.x), c(self.center.y)), rx: r(self.rx, 0.22), ry: r(self.ry, 0.22) }
|
||||
}
|
||||
}
|
||||
|
||||
impl LensBlur {
|
||||
/// The fixed focus shape in effect, if any: the moved / resized [`LensBlur::area`], else the
|
||||
/// shape's preset centred on `crop_center`. `None` for [`FocusShape::Auto`].
|
||||
pub fn focus_area(&self, crop_center: Point) -> Option<FocusArea> {
|
||||
let (rx, ry) = self.shape.radii()?;
|
||||
Some(self.area.unwrap_or(FocusArea { center: crop_center, rx, ry }).sanitized())
|
||||
}
|
||||
}
|
||||
|
||||
/// The focus area [`LensBlur`] uses when no mask says what is in focus.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum FocusShape {
|
||||
/// A circle.
|
||||
Round,
|
||||
/// An oval lying down (landscape).
|
||||
Wide,
|
||||
/// An oval standing up (portrait).
|
||||
Tall,
|
||||
/// The photo's subject, estimated (person mattes, else a saliency heuristic). Also what a
|
||||
/// shape this build doesn't know reads as (so it is last: serde's `other`).
|
||||
#[default]
|
||||
#[serde(other)]
|
||||
Auto,
|
||||
}
|
||||
|
||||
impl FocusShape {
|
||||
pub const ALL: [FocusShape; 4] = [FocusShape::Auto, FocusShape::Round, FocusShape::Wide, FocusShape::Tall];
|
||||
|
||||
/// Whether this is the default (Auto: no fixed shape), for skipping it in the JSON.
|
||||
fn is_auto(&self) -> bool {
|
||||
*self == FocusShape::Auto
|
||||
}
|
||||
|
||||
/// The fixed shape's half-width and half-height, in units of the photo's long edge; `None`
|
||||
/// for [`FocusShape::Auto`].
|
||||
pub fn radii(self) -> Option<(f64, f64)> {
|
||||
match self {
|
||||
FocusShape::Auto => None,
|
||||
FocusShape::Round => Some((0.22, 0.22)),
|
||||
FocusShape::Wide => Some((0.32, 0.17)),
|
||||
FocusShape::Tall => Some((0.17, 0.32)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The name shown on the shape's button (translated by the UI).
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
FocusShape::Auto => "Auto",
|
||||
FocusShape::Round => "Round",
|
||||
FocusShape::Wide => "Horizontal",
|
||||
FocusShape::Tall => "Vertical",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl LensBlur {
|
||||
/// [`LensBlur::transition`]'s default.
|
||||
pub const DEFAULT_TRANSITION: f64 = 50.0;
|
||||
|
||||
/// Whether `v` is [`Self::DEFAULT_TRANSITION`], for skipping it in the JSON.
|
||||
fn is_default_transition(v: &f64) -> bool {
|
||||
*v == Self::DEFAULT_TRANSITION
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for LensBlur {
|
||||
/// Off, with the default Transition and everything else empty.
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: false,
|
||||
amount: 0.0,
|
||||
focal_distance: 0.0,
|
||||
focal_range: 0.0,
|
||||
boost: 0.0,
|
||||
focus_mask: None,
|
||||
focus_strokes: Vec::new(),
|
||||
blur_strokes: Vec::new(),
|
||||
transition: Self::DEFAULT_TRANSITION,
|
||||
shape: FocusShape::Auto,
|
||||
area: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
|
||||
Reference in New Issue
Block a user