Commit Graph
191 Commits
Author SHA1 Message Date
cezar 1a301fc2d8 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 -->
2026-11-11 08:02:05 +01:00
Jeremy Hooke bb414d220a LR-EDIT-LIGHT-SHADOWS: fix Highlights/Shadows block artefacts in fine detail; 4× faster GPU median
Fixes #3460
Related: #2936 (slow GPU kernel compiles on Windows/DX12). This PR builds the GPU kernels without wgpu's workgroup-memory zeroing, which took a DX12 release start from ~87 s to 1.4 s on a GTX 1070 with the new median kernels; it may shorten the compiles there too, but does not close it.

## Problem

Raising Shadows on a photo with dark lettering on a bright panel makes bright blocks grow beside the
letters. On a Canon CR3 of a bus (6960×4640) with a black fleet number on a yellow panel, Shadows +75
puts bright yellow rectangles in the gaps where the digits pinch together and inside the 4's counter.
At Shadows +5 there is none of this; at +75 it shows at any zoom. Narrow gaps between dark objects
generally can do it: the pinned corpus has the same thing in the gap between two posts under a machine
(Hasselblad, `coverage-6568.fff`).

## Cause

From process V2 the Highlights/Shadows base (`local::tone_base`) is the edge-aware filter of a
separable median of log luminance, at a radius of 0.15 % of the long edge (10 px here), so that thin
detail (twigs, lines, #632) takes its surroundings' shift. Text strokes and gaps are about that wide,
so each row and column window is close to half letter and half panel, and the median picks one tone
or the other in rectangles: it fills the gaps between the digits and the 4's counter with the letters'
tone. The guided filter keeps those blocks, so panel pixels whose base reads as deep shadow get
Shadows' full lift (`2^(1.7·s·w^1.5)`, up to ~1.3 EV at +75).

## Examples

Top: before, bottom: after.

The fleet number on the bus photo, Whites +54, Blacks +31, Shadows +75, at 300 %:

<img width="1020" height="976" alt="example_photo_pair" src="https://github.com/user-attachments/assets/cc5b164f-612d-4d7d-bda3-db6afd8b177f" />


The gap between two posts in the corpus' Hasselblad `coverage-6568.fff` (CC0, raw.pixls.us),
Shadows +100, at 300 %:

<!-- image: example_corpus_pair.png -->
<img width="900" height="1216" alt="example_corpus_pair" src="https://github.com/user-attachments/assets/feb4b240-194e-40b1-b5b9-c4419f840df6" />

Synthetic lettering at the scale of a bus number in a 7000 px photo, Shadows +75, at 200 %:

<!-- image: example_pair.png -->
<img width="880" height="820" alt="example_pair" src="https://github.com/user-attachments/assets/bd02e600-dda0-4648-85e9-f89ce046eb08" />

## Change

`local::detail_free` (CPU) and its GPU twin: each value of log luminance is clamped between its
separable median at r (as before) and the median of a 3× wider neighbourhood (the median at r of a
box-downscaled copy, enlarged bilinearly, like `guided_fast`'s coefficients). The base is the guided
filter of that plane.

- A twig or speck in an even surround has both medians on the surround's side and takes the nearer,
  as under the median alone (#632 unchanged).
- The gap between two strokes sits in a wider neighbourhood that is mostly panel: the medians
  disagree and the gap keeps its own tone. The strokes themselves count as fine dark detail on the
  panel (both medians agree) and keep their contrast, as twigs do.
- Steps between regions stay exact (the fine median keeps them).
- GPU: the coarse median reuses the box/bilinear resize, plus one `clamp_between_k` map kernel.
  CPU and GPU match (max 1 level).
- GPU median kernels rewritten (`median_h` / `median_v`): each workgroup loads its taps into
  workgroup memory and selects by rank, 4 neighbouring outputs per thread. The old partial selection
  sort over a private 49-tap array sat in scratch memory. Same selection, so bit for bit the CPU's
  (`median_matches_cpu_bit_for_bit`, every r 1–24); renders are byte-identical to the old kernels.
  On 6960×4640 at r = 10 (M2 Max) the median takes 191 → 47 ms.
- GPU kernels are built without wgpu's zeroing of workgroup memory (as `nn.rs` and `faces.rs` already
  are): on DX12 it made FXC take ~87 s over the new median kernels at every start of a release build
  (GTX 1070, 1.4 s without it). Every element of `med_tile` the kernels read is loaded before the barrier;
  renders are byte-identical.
- Cost on the 6960×4640 bus CR3 with Whites +54, Blacks +31, Shadows +75 (M2 Max): GPU planes
  231 ms on `main` → 113 ms here (257 ms with this PR's first kernels); CPU base ~388 → ~453 ms.
  The CPU path enlarges the coarse median while it clamps, into the fine median in place
  (`detail_free_matches_its_reference`, bit for bit).
- New process V8 (`Process::LATEST`). Existing edits keep their process and render as before, so `RENDER_CACHE_VERSION` is unchanged (it is 76 on `main`).
- Docs: `process-versions.md` (V8 row, a paragraph on the lettering fix, revision history), `parity-checklist.md`
  (LR-EDIT-LIGHT-HIGHLIGHTS / -SHADOWS notes).

An earlier revision of this PR clamped each value to the quartiles of its window instead. It fixed
the lettering but stopped treating isolated lines between r/2 and r wide as detail (twigs of 3–6 px
against a dark wall were lifted less than the wall, as under V1), which the corpus run below caught.
A fixed window can't tell an isolated line from a gap between strokes; a wider neighbourhood can.

## Process version

The new base applies from a new process, **V8** (V7 plus `local::detail_free`; `local::base_keeps_gaps` is true from V8, CPU and GPU). v0.19.0 shipped V3 to V6, and crystal grain (#3630) took V7 on `main`, so V1 to V7 render exactly as before: `tests_legacy` still locks V1 and V2, and `only_process_v8_on_takes_the_detail_free_base` checks that every earlier process keeps the plain median. New photos get V8; photos already edited keep the blocks until Update to Current Process.

The faster median kernels and the workgroup-memory change don't change pixels, so they apply to every process. They stay in this PR: the zeroing only costs time on the new median kernels (on `main` the kernels compile in 0.8 s on the GTX 1070), so on its own it would speed up nothing.

## How it was checked

- [x] New test `gaps_between_letters_keep_their_own_tone_in_the_base`: a row of synthetic "8"s
  sized like the bus number. With the median, 360 panel pixels sit more than 1 EV above their base
  (worst 2.25 EV); now none do (worst 0.8 EV). It fails with the median alone.
- [x] New test `isolated_lines_up_to_the_detail_radius_stay_out_of_the_base`: light lines 1–9 px wide
  on a dark ground (r = 10) stay out of the base, as under the median. It fails with the quartile
  clamp (a 6 px line 0.31 of the way into the base).
- [x] New test `detail_free_keeps_steps_and_regions`: steps and flat fields pass through unchanged;
  tiny, empty and NaN planes don't panic.
- [x] The #632 tests (twig/stalk contrast, local contrast, no halo at a strong edge, V1 unchanged)
  and the median reference tests pass unchanged.
- [x] `lightcraft-gpu` integration tests on a real adapter, including
  `highlights_shadows_base_matches_on_every_process` (max difference 1 level).
- [x] Corpus A/B: all 451 pinned raws (`cargo xtask corpus --download`) rendered at full size before
  and after, with Shadows +100 and with Highlights −100 (902 pairs, GPU). No failures. RMSE median
  0.18 % (Shadows) / 0.10 % (Highlights), max 0.86 %; pixels changed by more than 3 % at most 0.07 %
  of a photo; worst 8×8-block change median 10 / 7 levels, 99th percentile 44 / 41, max 61. I looked
  at the 22 largest local changes (old over new, at the worst block): no new artefacts. Most are a
  slightly different tone in small gaps among foliage or branches; one is the Hasselblad gap above.
- [x] User-visible change: rendered the bus photo at full size and at 2400 px with Whites +54,
  Blacks +31 and Shadows +5 / +75, and looked at the number, the plate, foliage against the sky and a
  brick lattice fence.
- [x] New tests `median_matches_cpu_bit_for_bit` (GPU, M2 Max) and `detail_free_matches_its_reference` (CPU).
- [x] After merging `main` and moving the base to V7 (Linux, Ryzen 5 7545U, RADV): `cargo test --release` of `lightcraft-develop`, `-pipeline` (including `tests_legacy`), `-catalog`, `-engine`, and `-gpu` on the real adapter (skipping `running_out_of_device_memory_falls_back_without_stopping_the_gpu`, which fills RAM on an APU; see above); `cargo fmt`, `cargo clippy --workspace --all-targets -D warnings`, `cargo xtask layers`, `roots`, `assets`, `parity` and `wasm`. Not run: the full `cargo xtask ci`, and the macOS-only `tests_light::v1_and_v2_render_as_before_v3` (V1 and V2 don't change, so it shouldn't need re-capturing).
- [x] After merging `main` again (with crystal grain as V7) and moving the base to V8 (Linux, Ryzen 5 7545U, RADV): `cargo test --release` of `lightcraft-develop`, `-pipeline` (including `tests_legacy` and the grain tests), `-catalog`, `-engine`, and `-gpu` on the real adapter (skipping `running_out_of_device_memory_falls_back_without_stopping_the_gpu`); `cargo fmt`, `cargo clippy --workspace --all-targets -D warnings`, `cargo xtask layers`, `roots`, `assets` and `parity`. Not run: `wasm` and the full `cargo xtask ci`.
- [x] `cargo xtask ci --quick` (with `CRAFT_FONTS_DIR`): all steps pass. After the median change: all steps pass again (without `CRAFT_FONTS_DIR`), and the CR3 renders
  byte-identical to the first kernels on GPU and CPU.


<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Bug Fixes**
  * Highlights and Shadows adjustments better preserve clean gaps in fine details such as lettering while maintaining the existing treatment of broader image features.
  * Tone adjustments are less likely to include isolated, narrow lines in the base used for processing.
  * The updated detail handling helps retain fine structure while reducing unwanted influence from closely packed details.
* **Documentation**
  * Updated process notes to explain how fine-detail handling affects Highlights and Shadows adjustments.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-11 07:31:45 +01:00
Jeremy HookeandClaude Opus 5.5 ed10d4486c Merge main into crystal-grain; the crystal grain moves to process V7
v0.19.0 shipped V4 to V6 with value-noise grain, so those stay frozen and
the crystal grain becomes a process of its own. V7 is V6 plus the grain:
without grain it renders as V6 (`without_grain_v7_renders_as_v6`), and the
GPU equivalence cases now cover V6's value noise.

Merged with main's float output (`deep`, `hdr`): the value noise keeps its
clamped luminance; the crystal grain already clamps, and fades out at and
above SDR white. The finish kernel's failed-render check stays ahead of
the aux upload.

The test of unknown process numbers now takes one past the latest: 7 was
hard-coded, and is a known process now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 10:53:18 +11:00
8a0b91a95c GPU float output for the HDR render (F32Hdr) (#3856)
* Render HDR rendition on GPU for HDR display drafts

HDR edits on HDR displays currently pay for a second CPU float render on every full render and show only SDR during drags, making slider drags several times slower.

Allow F32Hdr requests through the GPU path with a float output target matching the CPU HDR rendition, and let draft renders carry HDR again instead of being excluded.

Test: gpu_handles_f32hdr_renders_for_hdr_display failed before the change and passes after.

* Issue #2297: float output from the GPU's finish kernel for the HDR render

The kernel wrote 8 bits only, so `handles` taking F32Hdr left no float samples.
It now keeps values up to the edit's peak (highlight desaturation, vignette,
gamut map, curves above SDR white, grain, LUT profiles, as finish_with does),
encodes with the exact sRGB curve as a float render does on the CPU, and writes
three linear floats per pixel into `out`. Written words carry the sign bit, so
work that never ran still fails the render instead of reading as black.

hdr_histogram keeps its Quality::Draft exclusion: it renders on the CPU, and the
UI already runs a small render beside the drafts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 17:59:03 +01:00
8f638b33bd Treat a first intersect mask component as its base selection (#3854)
* Treat a first intersect mask component as its base selection

A mask created with Intersect as its first component currently renders as empty, so the overlay and local adjustments never appear. Using that component as the base matches how Add and Subtract first components already behave.

Change evaluate_one so the first component always sets the base alpha regardless of its combine op. Add a regression test with a single Intersect linear-gradient component asserting the start side is selected.

Test: intersect_first_component_selects_its_shape failed before the change and passes after.

* Masks: the GPU treats a first Intersect as the base too, and the process doc says so

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Docs: what changes for masks that start with Intersect

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 14:46:11 +01:00
3943279105 Colour noise reduction: joint linear chroma filter with speck brake, CPU and GPU (#815) (#1348)
* WIP: colour NR v2 prototype (env LIGHTCRAFT_NR_V2, CPU only)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: colour NR v2 on by default (LIGHTCRAFT_NR_V2=0 turns it off), GPU renders read back for it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: cache renders with the new colour NR apart from older ones

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: colour NR v2 on the GPU (fused down / apply kernels), coefficient grid sigma / 2

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: colour NR v2 on the CPU without full-size intermediates (row-streamed passes)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: report peak device-buffer use per GPU stage with LIGHTCRAFT_PROFILE

* WIP: colour NR v2 linear mode (NRV2_LINEAR=1: c - Y, additive, noise model), Jensen term, mean-drift probe

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: colour NR v2 noise model with equal-count luminance bands and a non-negative fit; probe asserts the mean over 3 noise realisations

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: colour NR v2 linear mode by default (per channel, K 64, coarse pass smooths only the coarse part); CPU on GPU renders; real-colour probe

Known: tests_window::noise_reduction_does_not_depend_on_the_window fails (the noise is measured in the
rendered window; the square-root mode failed it too).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: colour NR v2 joint guide (NRV2_JOINT=1, opt-in), luminance guide knobs, leaf-next-to-black probe, camera-look guard from 858

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: colour NR v2 reads its env knobs once (per-pixel env reads made the linear mode 11x slower); joint stage timings with LIGHTCRAFT_PROFILE

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: joint colour NR without redundant passes (fused paths + next weights, none after the last scale, delta-1 weights from the path), two-component buffers, parallel reconstruction

Bit-identical to 8b89526d (test joint_matches_the_reference_bit_for_bit against a test-only copy).
Cat 32.7 MP, CPU: 6.2 -> 5.0 s at Color 25, 7.0 -> 5.6 s at 100; working buffers 2.36 -> 1.44 GB.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: joint colour NR with separate H/V slice loops and zero-difference shortcuts (no division, weight 1 without exp)

Still bit-identical to 8b89526d. Interleaved 24 MP bench: 2.72 s vs 4.52 s for the reference.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: joint colour NR on the GPU (nrcj.wgsl), default on; whole-image noise model from samples, halo bands above 2 GB

Kernels mirror nrc_joint step for step (same scale plan, noise model fitted on the CPU from GPU samples).
Cat 32.7 MP on a Quadro M2200: wb/nr 1.2-1.3 s vs 4-5 s CPU; against the CPU max 1 LSB; bands = single.
Waits after dropping large buffers (freed memory otherwise piled up to the whole 4 GB). Cache key includes joint.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: GPU joint NR plans its bands from a budget that includes the output buffer and the device buffer limit; halo 2*sum(delta) + max delta + 8; a band that cannot fit runs only this stage on the CPU

Bands vs one piece: at most 1 LSB in a few dozen pixels (running-sum boxes round differently per band start).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: GPU joint NR budgets its bands from the free device memory where it can be asked without unsafe (nvidia-smi, amdgpu sysfs), cached 3 s; fixed 2 GB otherwise

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: docs/nr-color-v2-history.md: every approach tried, measured and dropped, speed numbers, known limits (no outlier brake yet)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: history doc: speck behaviour stated qualitatively until measured on full-size renders

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: joint colour NR speck brake: compact colour specks (chroma far past the noise, small luminance step, shift not reaching the 5x5 border) lose their colour before the guide is built; weak at Color 25, full at 100; CPU and GPU

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: joint NR CPU 5.2 -> 3.5 s (33 MP), bit for bit: guide as planes with branch-free distance rows, exponentiated paths, pilot straight into planes, speck brake in place with a min/max pre-test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: joint NR GPU: path and weight pairs instead of quads (48 instead of 60 bytes per pixel, 33 MP in one piece), speck and pilot kernels without loop-indexed private arrays, noise fit cached for identical samples; Quadro M2200 2.15 -> 1.47 s, HD 630 5.66 -> 4.26 s

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: speck brake: compactness from the second largest border share (a line or edge crosses the 5x5 border twice; one noisy border pixel no longer protects a speck)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* #815: colour noise reduction as process V3

The joint method (linear R−Y / B−Y, edge-aware guide, speck brake) is process V3 and the latest; edits on V1 and V2 keep main's blurred chromaticity. The prototype switches (LIGHTCRAFT_NR_V2, NRV2_*) and the square-root and per-channel variants they selected are gone, with their GPU kernels; nrc_params uses the former defaults as constants, so V3 renders as the prototype did. The GPU falls back to the CPU joint filter when no band fits. vram is native only (wasm build). Docs: process-versions, nr-color-joint, parity checklist, what's new.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* #815: process routing test initialises its settings in place (clippy field_reassign_with_default)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* #815: one GPU band plan at a time, with a reserve for every render on the device

An export batch renders two photos side by side (`export_parallelism`). Each joint colour NR planned
its bands from the device memory free at that moment and counted the shared buffer pool as its own,
so two plans made at once could together ask for more than there is. Measured on a Quadro M2200
(4 GB): two 33 MP exports side by side peaked at 3761 of 4096 MiB.

The plan and its bands now run under one lock (`BANDS`), and the budget leaves `VRAM_RESERVE` for
each render on the device (`RENDERS`), not just for this one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* #815: the joint colour NR's noise fit and pilot no longer switch at a hard bound

With main's preview-scaled luminance NR (#960) the CPU and GPU renders of a 640-px preview differed
by up to 10 levels (gpu equivalence `output_spaces_match`). Their images after luminance NR differ by
9e-7 rms, but one luminance band of the noise fit sat at exactly 4 times the first fit: the CPU's
samples dropped it, the GPU's kept it, and the fitted noise came out 2.6 % apart. The pilot's axis
choice then switched at a few pixels, and the edge-aware weights carried that on.

- robust_line: a band's weight fades to 0 between 4 and 5 times the fit instead of dropping at 4
  (identical below 4).
- pilot_pick: the smoother-axis mean fades in between 0.8 and 1.25 times its bound instead of
  switching at it (identical outside), on the CPU, in nrcj.wgsl and in the test reference.

All 19 CPU/GPU comparisons of the equivalence suite are within 1 level again. The new test
noise_line_does_not_jump_when_a_band_crosses_the_outlier_bound uses the bands of that preview and
fails on the old fit (5.6 % jump).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* #815: the joint colour NR measures the whole frame's noise and is keyed by process

A window measured the noise model on the pixels it held, so a loupe window
could smooth differently from the same pixels of the full render or the
export. The model now comes from fixed tiles of the whole frame
(`lightcraft_pipeline::colour_noise`, `nrc_joint::tiles`), the same for every
window, for the CPU and the GPU, and is kept in the stage cache.

The linear stage's cache key now includes the colour filter in use, so a
process change (Update to Current Process, undo) no longer reuses the other
filter's denoised image.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* M-NR: deep windows match the whole render; the VRAM query no longer stalls renders

- A U16 / F32 window with the joint colour NR is grown by the filter's reach and
  cut back, like an 8-bit one (DeepImage::crop).
- The free device memory is refreshed in the background once the cached answer is
  stale; only the first question for an adapter waits. The joint NR asks before it
  takes the BANDS lock.
- nvidia-smi starts without a console window on Windows (CREATE_NO_WINDOW).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* M-NR: the VRAM query finds the right card and keeps one answer per adapter

- A card is found by its PCI address (wgpu device_pci_bus_id, nvidia-smi pci.bus_id,
  the amdgpu sysfs directory) where both sides report one; else by a device id that
  only one card has. Two cards of one model without an address give no answer, and
  the fixed band budget applies.
- Each adapter keeps its own cached answer, so a late background refresh cannot
  replace another adapter's answer. A refresh not done after 10 s is retried.
- The cache tests wait on signals instead of fixed sleeps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* M-NR: the VRAM cache tests no longer depend on timing

The two cache tests used a 20 ms TTL: on a slow machine a refreshed answer could go
stale again between assertions and start an extra query. They now use a 30 s TTL and
age an answer explicitly (Cache::expire, test only).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* GPU: allow joint_band's eight arguments, as color_nr_joint does

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-06 09:44:58 +01:00
0429844cd9 never-crash: deny the panic lints in every crate root; GPU asserts become fail paths (#2137) (#2170)
* never-crash: deny the panic lints in every crate root; GPU asserts become fail paths (#2137)

The never-crash policy was documented but not machine-checked for the two largest crates:
engine and meta carried only #![forbid(unsafe_code)], so a future unwrap/expect/panic would
pass cargo xtask ci. Both crate roots now also carry
as does xtask (previously un-annotated); the guarded expects in meta/src/xmp.rs and xtask's
parity.rs / root() now use the documented #[allow(clippy::expect_used)] + invariant form.

crates/gpu: the three production asserts become fail(FailKind::Fatal, ..) + return, so a
binding-count mismatch, an over-long readback, or a wrong-length curve fails the render over
to the CPU instead of crashing (finish_and_read also early-returns on len == 0, which would
have issued a zero-size copy_buffer_to_buffer that wgpu rejects).

xtask: new roots check (in ci) verifies every workspace lib root and every binary main.rs
carries both attributes; crates/sysmem is the documented exception for forbid(unsafe_code)
only. A panic in placement or readback is a fail, not a crash.

* audit fixes: roots covers binary and cdylib/rlib roots; render gates on failed() after finish_block (#2137)

Two reviewers audited the first commit; both highs it found are fixed here:

- roots scanner: the by_ref().any()/any() pair consumed the kind iterator hunting for
  "lib", so every bin-only root (both app mains, the sam3-worker bin, xtask itself) and the
  cdylib/rlib web root was silently unchecked — the check covered 29 of the 33 real roots.
  Kind detection now collects the kinds once and matches lib/rlib/dylib/cdylib/staticlib,
  with a root_paths regression test over bin, lib and cdylib/rlib targets; unreadable root
  files now fail with the I/O error instead of a fake policy violation.
- render.rs: the caller gates on failed() right after finish_block, so the malformed-curve
  fail path can no longer reach the band loop's p[y0_at] index on the empty block.
- finish_and_read: the len == 0 path now submits the encoder before returning zeros, so a
  failure staged in the same render stays detectable (the old zero-size copy failed loudly
  via the error scopes; a bare return would have hidden it).
- docs: finish_block and finish_and_read state their failure contracts; USAGE and AGENTS.md
  name the new roots step in the ci enumeration.

* xtask: check a library root at the source path that cargo metadata reports

The roots check read src/lib.rs for every library target, so a package that sets its library path was checked on the wrong file. Libraries now use the reported source path, with the same default as binaries when none is given.

* xtask: match the crate-root deny lints by whole name, ignoring a trailing comment

A lint named only in a trailing comment, or a lint whose name contains another (clippy::panic inside clippy::panic_in_result_fn), satisfied the deny check. Lint names are now compared whole and a trailing comment is ignored.

* xtask: read the crate-root attributes from the header, not a fixed 30 lines

The roots check read only the first 30 lines of each crate root, so a root whose attributes came after a longer doc header was reported as missing them. The check now reads the inner attributes at the top of the file: it skips blank lines and comments, reads each attribute whole, and stops at the first item. A multi-line list is read in full and a commented-out attribute does not count.

* xtask: reword two comments in the roots check

Comments only: the lint-name match and the source-path default are described without naming a lint or a build tool. No code changes.

* xtask: report a root attribute that overrides the required denies

* xtask: accept a runtime manifest dir only when it has a parent

* xtask: render the overridden deny attribute without literal braces

The write! escaped the braces around the substituted attribute and lint,
so the violation printed `#![{allow}({clippy::panic})]`; assert the
rendered message in the allow-override test.

* Tests: new test helpers meet the crate-root panic lints

Main added test helpers after this branch; the deny at the crate root now
applies to them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* roots: crates/wincolor is the second crate allowed unsafe

Main added it for the Windows colour APIs after this branch; its module docs
already say so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 00:29:41 +01:00
Alex ChambersandClaude Opus 5.5 baf079f659 LR-BEHAV-RENDER-FIDELITY: process V5 rolls raw tone curves off into white in stops, so raising Exposure keeps highlights (#1632) (#3783)
* LR-BEHAV-RENDER-FIDELITY: V3 camera tone curve rolls off in stops past its last knot (#1632)

A raw's camera tone curve is fitted only to camera JPEG tones below 0.85, so its last knot sits
1 to 3 stops below the sensor's white. Past it, CameraTone::apply closes on white exponentially in
linear light: the sensor's white renders at 8-bit 246-254 at Exposure 0 and 254-255 from +1, and
raising Exposure turns the top stop the sensor recorded white.

Process V3 extends the curve with CameraTone::apply_rolloff: same value and slope at the knot,
then gap / (1 + c (2^t - 1)) at t stops past it, the gap halving every stop in the end. On 11 CC0
corpus files with a fitted look, unclipped pixels rendering white drop from up to 22.5% to 0 at
+1 EV and from up to 35% to 0 at +2 EV; Exposure 0 renders change by at most 1 code on average.
V1 and V2, the fit itself, JPEGs and raws without a fitted look are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* LR-BEHAV-RENDER-FIDELITY: V3 generic raw curve rolls off in stops too; DRO-off, DNG and GPU checks (#1632)

Raws without a camera curve take ToneMap::hdr, which reached white about 1/4 stop past the
sensor's white and clipped there (o.min(1.0)). Process V3 now uses ToneMap::rolloff_hdr: from half
a stop below the white point (tone::GENERIC_KNEE_STOPS) the extended Reinhard curve hands over to
the same stop-based shoulder as the camera curve (tone::rolloff_past, shared with
CameraTone::apply_rolloff), with the same value and slope at the join. The sensor's white renders
at about 235 / 248 / 252 at Exposure 0 / +1 / +2 where V1 and V2 render 239 / 255 / 255. On 6 CC0
DNGs on the generic curve, unclipped pixels rendering white drop from up to 8.4% to 0 at +1 EV and
from up to 17.2% to 0 at +2 EV.

The DRO-off gate (look_fit::at_most) also checks the V3 shoulder; the rate bound already implies it,
so no fit changes and LOOK_VERSION stays. Tests: the generic shoulder (join, slope, monotone, below
white, no kink), a regression test that fails with the clipping curve, a DNG ProfileToneCurve under
V3, the DRO-off property tests on the V3 shoulder, and a per-process camera-curve GPU check.
Docs: process-versions, parity checklist (LR-BEHAV-RENDER-FIDELITY, LRC-DEV-PROCESS), gap 3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* LR-BEHAV-RENDER-FIDELITY: what's new: process 3 keeps raw highlights when Exposure is raised (#1632)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* LR-BEHAV-RENDER-FIDELITY: a flat last camera-curve segment joins the V3 shoulder with its own slope (#1632)

The V3 camera shoulder took the last segment's slope with a floor of 0.1, so a flat or shallow
segment (valid for a fitted, DNG or saved curve) joined with a kink: slope 0 on the curve, about
0.1 just past it. The shoulder now keeps the segment's own slope at the knot. Below 0.1 a quadratic
term in 2^t - 1 joins the denominator: it adds no slope at the knot and makes up the 0.1 pace
further up, so a flat curve still closes on white. Segments at 0.1 or steeper are byte-identical,
and the generic curve passes no floor. Comments now say the shoulder approaches white in real
numbers and can round to it in f32. Found in an independent review of the branch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* LR-BEHAV-RENDER-FIDELITY: V4's GPU test pins V4; the corpus DRO photos keep their knots under the V5 bound (#1632)

The GPU light-operator test assumed the default process is V4; it now sets V4, since V5 is the
default. The corpus DRO test checks that dro_off's V5 bound leaves the second-last knot where
the rate bound puts it on the Sony DRO samples, so their V1 to V4 renders don't change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* LR-BEHAV-RENDER-FIDELITY: the DRO-off curve is main's again, so V1 to V4 keep it (#1632)

CodeRabbit found that the V5 bound in `dro_off` could move the second-last knot of a DRO
photo whose fitted last segment is flat, and V1 to V4 read that curve too. `dro_off` and
`at_most` are back to main's, so the camera-look fit is unchanged and LOOK_VERSION stays.
The DRO tests check the V5 shoulder where the lowered segment's slope over its squared gap
is at most the fitted one's (then it stays below), and on the Sony DRO corpus samples.
Also: `rolloff_hdr`'s doc names the HDR lift, and the release note names DNGs whose curve
already reaches white.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 20:50:13 +01:00
eliets2andeliets2 dc0dc59a90 Keep the Vulkan driver unloaded on Windows unless it is asked for (#3667)
Windows already defaults to DX12 alone everywhere else (default_compute_backends, default_window_backends), but the window's fallback chain still probes Vulkan, and a persisted renderer name can promote it ahead of DX12. That is exactly the first-launch/second-launch asymmetry reported: the Vulkan driver is only touched on the later start, where it crashes the process before any window appears.

Treat Vulkan as opt-in on Windows in `window_renderer_order`: drop it from the platform chain and ignore a remembered or failed Vulkan renderer unless the environment explicitly forces it (`LIGHTCRAFT_GPU_BACKEND=vulkan` / `WGPU_BACKEND=vulkan`). The existing `window_renderer_fallback_order` expectations for Windows have to be updated with it.

Test: windows_never_uses_vulkan_unless_it_is_asked_for failed before the change and passes after.

Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com>
2026-11-05 20:31:20 +01:00
FredAppsandClaude Opus 5.5 b79f9971a3 GPU tests allow a level of 8-bit dither (#3789)
The CPU tests got this in #3779. These only run with a real GPU, so
hosted CI never showed them failing.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 11:30:38 +01:00
Jeremy HookeandClaude Opus 5.5 3b23f25c1c Merge main into crystal-grain; the crystal grain moves to process V4
Main took V3 (sharpening) and V4 (calibrated Contrast and Blacks) while this was
open. Neither is in a release yet (v0.18.1's latest is V2), so the grain joins V4
rather than adding a process: V1 to V3 keep the value noise, V4 draws crystals.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 21:16:35 +11:00
a220d3eb68 LR-EDIT-DETAIL-DENOISE: built-in BM3D denoising with GPU acceleration (#2982)
* LR-EDIT-DETAIL-DENOISE: AI Denoise works out of the box with a built-in denoiser

Turning AI Denoise on no longer needs an ONNX model and a denoise-model.json. Without a model of the user's own, the engine runs a built-in pure-Rust denoiser (noise measured per tile, non-local means on the Bayer planes, edge-directed demosaic) through the same tiling, cache, queue, preview and export path as a model. Installing a model stays optional; Stop using returns to the built-in one, and the id `builtin` is reserved.

The set-up prompt and its resume-after-install flow (model_setup.rs, PhotoState::NoModel) are removed. Tests updated for the new behaviour, with new tests for the built-in path; docs, trackers and locale catalogs updated.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* LR-EDIT-DETAIL-DENOISE: built-in denoiser cleans the colour planes together and adapts to the noise

The built-in denoiser now measures the photo's noise once from the whole mosaic (the model prepares the photo before its tiles run) instead of per tile, stabilises the variance (generalised Anscombe), rotates the four Bayer planes with a Hadamard transform and runs a non-local-means filter whose patch distance spans all planes, so colour blotches are cleaned with the brightness. It cleans gently at low noise to keep fine detail, and harder, with a second pass that matches on the first pass's cleaner picture, as the noise grows. Cached pictures made by the first version are made again (builtin version 2).

Adds an opt-in benchmark (tests/denoise_builtin_quality.rs, public CC0 raw plus noise of known level, scored against the original) and tests for the whole-photo noise estimate, strong noise, bad noise values and the strength ramp. On the Sony A7 III sample the result is 3.6, 7.0, 9.1 and 9.7 dB above the noisy picture at light, medium, heavy and extreme noise, against 2.9, 6.0, 6.5 and 5.8 dB for the first version.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* contributors: add esli1283

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* LR-EDIT-DETAIL-DENOISE: docs say how to run the built-in denoiser's quality benchmark

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* LR-EDIT-DETAIL-DENOISE: built-in denoiser cleans colour further, keeps more texture and leaves no isolated specks

Colour-difference planes get a wider pass guided by the cleaned brightness plane, the first-pass threshold is lower (more texture kept), and cells with no matching patch lean on a looser average in heavy noise. Skips negligible weights for speed; bumps builtin::VERSION to 3. Benchmark adds a texture figure; on the public A7 III raw the gain over the noisy picture is +3.7 / +7.2 / +9.7 / +10.4 dB (was +3.6 / +7.0 / +9.1 / +9.7).

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Windows: tests build paths one component at a time and doc_path has no unused variable

On Windows `cargo xtask ci` failed before it reached any of the work under test:
- doc_path.rs bound the gvfs path outside the cfg(not(windows)) block that
  uses it, an unused variable under -D warnings.
- tests_import and the MCP headless discovery test joined "trip/day2" onto a
  temp folder, giving mixed separators, and compared them with the normalised
  paths the folder walk returns. They now join each component.

Test and lint changes only.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* LR-EDIT-DETAIL-DENOISE: built-in denoiser filters with block-matching collaborative filtering, on the GPU

The built-in denoiser's filter is now block matching with collaborative
filtering (BM3D / CBM3D, written from the paper) instead of non-local means.
On the public Sony A7 III benchmark with added noise it scores 0.25 to 0.6 dB
higher at every noise level and keeps more texture at medium to extreme noise
(light noise keeps slightly less: 0.58 against 0.62), as fast as before on the
processor. docs/denoise.md records the comparison with non-local means and
weighted nuclear norm minimisation (tried, not kept: about +0.03 texture for ten
times the time) and what the tuning showed.

- denoise-core: bm3d.rs (matching on the brightness plane, 2-D DCT plus Haar
  across the group, hard threshold then Wiener, hard threshold rising with the
  noise). Builtin::run_with takes the filter stage, so every other step is shared
  between devices. Tuning.bm3d selects it; non-local means stays as the fallback.
  builtin::VERSION is 4, so cached pictures are made again.
- gpu: bm3d.rs and wgsl/bm3d_*.wgsl run the grouping, the filtering and the
  putting back on the graphics card, in the same order as the reference (the
  results agree to rounding: at most 0.1 noise deviation at a few tie blocks,
  4e-6 on average, identical every run). Noise measurement, stabilising and the
  demosaic stay on the processor. FXC (DX12) needs the working arrays at module
  scope and no dynamically indexed vector: documented in docs/gpu-pipeline.md.
- engine: the card is set up once per process for the first photo that may use
  it, checked against the processor on a check tile (in the filter's own domain:
  the demosaic's direction choice can flip a pixel on a tiny difference), timed,
  and used where it is faster. A tile it gets wrong runs on the processor and
  three stop it. Settings' Run on choice, device line and "Try the graphics card
  again" now work for the built-in denoiser. Its set-up marker lives in the
  models folder.
- The benchmark takes LC_GPU=1, LC_NLM=1 and LC_B_* for sweeps.

On an RTX 4080 SUPER a 256-cell tile takes 22 ms on the card against 408 ms on
one processor thread, and the 1536 x 1024 benchmark crop 0.13 to 0.24 s against
1.0 to 2.1 s on four threads, with identical scores.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* LR-EDIT-DETAIL-DENOISE: the built-in denoiser measures the noise per colour plane and sets its strength from it

The first noise estimator read a picture's texture as noise: it never reported
less than about 0.003 at mid-grey whatever the real noise, so the denoiser
always believed a photo was about as noisy as ISO 12800. The threshold curve was
tuned on that over-estimate, and its levels (0.024 to 0.14) are far noisier than
real Canon bodies produce (about 0.0025 at ISO 400 up to 0.038 above ISO 25600,
measured on a private library; only aggregates are recorded in the docs).

- estimate_noise: each colour plane is read on its own (they sit at different
  levels in a raw), a second-difference operator cancels flat and sloping signal,
  12 x 12 blocks, the quietest 5 % at each brightness divided by the bias of that
  quantile of pure noise (0.67, measured), a constrained line fit. The first
  version stays as estimate_noise_v1 to compare with. On 30 public pictures with
  known added noise the 10th to 90th percentile of estimated / true deviation at
  mid-grey is 0.97 to 1.29 at the ISO 6400 level against 0.94 to 1.96.
- bm3d::Params::lambda is a curve of the noise (1.2 at 0.0028 up to 3.5 at 0.14,
  straight against its logarithm) instead of two end values and a strength, and
  plan / filter take the noise level; the GPU path shares plan, so CPU and GPU
  agree as before. Fitted on clean low-ISO photos of a Canon EOS R and R6 Mark III
  with noise of their measured levels added: the lowest threshold within about a
  quarter of a decibel of the best at each level.
- Result (PSNR, EOS R / R6 Mark III, 10 + 5 photos): ISO 25600 level 38.36 /
  38.86 from 36.18 / 36.21, ISO 51200 level 33.83 / 34.45 from 28.42 / 28.78, ISO
  6400 39.93 / 40.69 from 39.30 / 39.74, quiet photos no longer over-smoothed;
  the noise left in the result falls from 1.3 to 3.1 down to 0.73 to 0.99.
- Tests: threshold curve, flat versus textured pictures, no-flat-area pictures,
  clipped / NaN mosaics; an opt-in accuracy harness on the public corpus
  (denoise_noise_estimate) with a calibration of the quantile bias; the benchmark
  takes LC_REAL, LC_BIN, LC_FULL, LC_EST and LC_B_LOFF.
- builtin::VERSION is 5, so cached pictures are made again. docs/denoise.md has
  "How the noise is measured" and "Fitted on real cameras".

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* LR-EDIT-DETAIL-DENOISE: GPU workspace pool cannot miss a wake-up; benchmark path and parity date fixed

Review findings (CodeRabbit) on the built-in denoiser pull request:

- bm3d::Bm3dGpu::forget and nn::NetRunner::forget changed the workspace count
  without the free-list lock. A take() that had found no free workspace and read
  made == WORKSPACES, but had not gone to sleep yet, could miss the wake-up and wait
  for good on a slot that was already free. forget now changes the count under the
  free lock, in the same order as take(), then notifies.
- A test for each runner holds the free lock and checks that forget waits for it;
  both fail on the old code and pass now.
- docs/denoise.md: the benchmark command resolves the raw file from the repository
  root, since the test runs from the crate's folder.
- docs/target-app-parity.md: Last updated matches its newest revision-history entry.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* LR-EDIT-DETAIL-DENOISE: doc comments for the functions this branch adds

CodeRabbit's pre-merge docstring check counted 49.72 % of the functions this pull request touches as documented (threshold 80 %). Every function the branch adds, the built-in denoiser's block-matching and non-local-means filters, its noise estimator, the GPU runner and their tests, now says what it does or what the test proves. Older functions the branch only touched are left as they were. Comments only: no code line changes.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* LR-EDIT-DETAIL-DENOISE: make the GPU set-up marker's folder; fix the benchmark's default path

The crash guard was lost when the models folder did not exist yet. The opt-in
quality benchmark resolved its default raw file against crates/engine.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* LR-EDIT-DETAIL-DENOISE: enforce the cache limit without a models folder

The built-in denoiser makes products when there is no models folder, but
eviction returned early in that case, so the cache could outgrow its limit.
It now applies the default limit.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* LR-EDIT-DETAIL-DENOISE: the cache-limit test needs no 20 GiB file off Unix

The no-models-folder test now checks the limit itself on every platform and
keeps the oversized sparse file for Unix only.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* S0002: review fixes for the built-in denoiser

Tell the runner a photo's noise only when it could be measured, run prepare()
after the work gate with a cancel check, reword the Settings hint for builds
without a models folder, drop untranslated placeholder locale entries (they
fall back to English) and restore the cs.json spacing; rustfmt.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* S0002: fix review findings: command descriptions, stale gpu test, self-test noise

The denoise.models.select and denoise.toggle descriptions now describe the
built-in fallback. Drop our workspace-forget test, which read fields that
upstream's Workspaces pool (#2631, same fix) replaced and so did not compile;
upstream's own tests cover it. The built-in self-test is told a noise instead
of measuring a 16-cell tile too small to measure.

Co-Authored-By: Claude Code <noreply@anthropic.com>

---------

Co-authored-by: esli1283 <esli.aaron@outlook.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
Co-authored-by: FredApps <FredApps@users.noreply.github.com>
2026-11-05 09:36:22 +01:00
stephen schureskoandFredApps 56d1cc2865 pipeline: apply 8x8 ordered Bayer dithering to prevent display banding (#3509)
* pipeline: apply 8x8 ordered Bayer dithering to prevent display banding

Quantizing float linear/display pixel values to 8-bit integers using
round-to-nearest produces noticeable Mach bands and contour stepping on
smooth gradients (skies, shallow depth-of-field backgrounds, skin tones).

This applies an 8x8 ordered Bayer dithering pattern centered around round-to-nearest
with sub-LSB amplitude in both CPU finish (crates/pipeline) and GPU compute
shader (crates/gpu/src/wgsl/finish.wgsl). Exact integer levels, pure black,
and white remain noise-free, while fractional gradients smoothly dissolve into
continuous gradations. Dithering coordinates account for window/tile view offsets
to maintain phase alignment across zoom tiles.

* pipeline, gpu: address review feedback on Bayer dithering

- Always pack VIG_VIEW in GPU params so windowed renders without a vignette
  maintain the correct absolute view origin for Bayer dithering coordinates.
- Restore the full Bayer threshold range (0..1) without deadzones, preserving
  float white via direct half-LSB rounding to prevent edge quantization drop.
- Return the true sampled bounds midpoint in geometry sub-pixel edge detector
  fallbacks.
- Add docstrings to satisfy coverage checks.

* pipeline, gpu: narrow highlight white guard to allow dithering on 254.5

* tests(pipeline): assert edge contrast in manual keystone tracking windows

* docs(pipeline): add docstrings to touched test functions

* Export tests: count distinct levels however the dither orders them

* Mask geometry tests ignore a level of 8-bit dither

---------

Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-05 06:47:45 +01:00
FredAppsandClaude Opus 5.5 2e66a00d55 Tests: two catalog flakes; a readback waits as long as a render (#3777)
a_failed_write_is_held_reported_and_retried raced the log thread: it
could fail the first append before the second arrived, which is then
refused by design. The test now hands both over in one append.

a_file_path_rule_allocates_nothing_per_photo counted heap blocks on every
thread, so the test harness's own thread could fail it (four blocks, on
PRs that don't touch this code). An allocation per photo is thousands, so
the bound stays far below that.

read_texture waited 10 s where the render path waits 60 s, so a view
could be dropped from a headless screenshot while earlier work ran.

The GPU guide now says what the code does about the window's card.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 06:39:08 +01:00
fc97c72864 LR-BEHAV-RENDER-FIDELITY: calibrated Contrast and Blacks in process V3 (#523) (#1383)
* LR-BEHAV-RENDER-FIDELITY: split V3 Contrast and Blacks

Port calibrated global Contrast and Blacks with shared CPU and GPU tables.
Preserve V2 Whites, local adjustments, other source paths, and all V1 and V2
renders and persistent cache keys.

Generate the constants from public Contrast and Blacks fits. Cover numeric
references, legacy renders, keys that include the resolved process, windows
and GPU parity. Document the measurements, limits and provisional number.

Co-Authored-By: Codex <noreply@openai.com>

* LR-BEHAV-RENDER-FIDELITY: reduce V3 preview cost and sanitize fits

Compose calibrated CPU preview operators over linear input and skip unused
mix endpoints. Keep high-bit-depth exports on the original operator path.

Require three distinct photos per published error group and band, regenerate
the fit hashes, and cover the sanitizer with synthetic tests. Document release
measurements and identify the separate measurement tool proposed in #1181.

Co-Authored-By: Codex <noreply@openai.com>

* LR-BEHAV-RENDER-FIDELITY: preserve V3 luminance evaluation

Retain the original operator evaluation for luminance mixes, including
preceding Contrast, so preview interpolation cannot change the cutoff.
Keep the fused per-channel path and exact deep exports.

Add CPU and GPU regressions for both uniform cutoff fixtures. Document
the measured CPU cost of positive Blacks and the retained fused path.

Co-Authored-By: Codex <noreply@openai.com>

* LR-BEHAV-RENDER-FIDELITY: finish split-module integration

Import the persistent process-key helper directly in the session module. Keep the existing V3 operator selection and evaluation order in an inline helper so the combined finish-stage closure stays within the complexity limit.

Refresh the V1/V2 golden hashes only after the exact fixture produces identical hashes on plain current main. Keep the cross-platform legacy samples unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* LR-BEHAV-RENDER-FIDELITY: date the calibrated Light gap summary

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Codex <noreply@openai.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-05 06:15:05 +01:00
d977d3e1a4 LR-EDIT-DETAIL-SHARPEN: Radius and Detail work, and sharpening acts at pixel scale (#757) (#762)
* LR-EDIT-DETAIL-SHARPEN: Radius and Detail work, and sharpening acts at pixel scale (#757)

* LR-EDIT-DETAIL-SHARPEN: an enlarging export keeps every Radius step (#757)

The sharpening blur's sigma was capped at 4 px, so a 2x export rendered
Radius 2 and 3 alike (both scaled past 4 px). The cap is now the largest
sigma the Gaussian taps support, GAUSS_SIGMA_MAX (64), which the CPU and
GPU blurs share. Test: enlarged_export_keeps_radius_steps_apart.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014ti8KemZbjE2ZgHgV1q1BM

* LR-EDIT-DETAIL-SHARPEN: preserve process-aware previews after rebase (#757)

Use the V3 pixel-scale blur and Masking weight for the Radius, Detail and
Masking previews on both renderers. Preserve the legacy texture-band previews
for V1/V2 and compute the same Gaussian when sharpening is disabled.

Cover process selection, radius changes, and prepared/fresh plane equivalence.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014ti8KemZbjE2ZgHgV1q1BM

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-05 05:21:13 +01:00
OneSlipandClaude Opus 5.5 077f4a507f GPU-FULL: more of the render on the GPU, loupe drafts from GPU textures (#1065)
* GPU-FULL-1: LUT profiles, Refine Edges and soft proofs render on the GPU

These three sent the whole loupe / compare / export render back to the CPU
pipeline (media::develop and lightcraft_gpu::render declined them).

- LUT profiles: the .cube table rides in the finish kernel's aux buffer
  (LUT_* parameters); lut_apply mirrors Lut3d::apply (trilinear, domain),
  applied after grain and blended by the profile amount, as on the CPU.
- Refine Edges: the cross guided filter Auto Mask already ran on the device,
  now with a combine mode (max for strokes, mix by sqrt(refine) for Refine),
  applied to the combined alpha before the mask's invert and amount.
- Soft proofing: proof-space gamut mapping and the destination / display
  gamut warnings in the kernel (PROOF_* parameters, GAMUT_WARN and warning
  colours generated from the CPU constants), for output spaces and displays.

Equivalence tests (RTX 5070, DX12): LUT profiles at three amounts and a
non-default domain, Refine 15/60/100 on two masks, proofs in 16 combinations
of space, output, display and warnings - all max 1 LSB, mean <= 0.0005 LSB.
The tests also check that strong refine and the destination warning change
the image (so they aren't comparing two unchanged renders).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* GPU-FULL-2: spot removal, defringe and the histogram on the GPU

Spots and defringe made every render that had them (and every white
balance or spot edit) read the resampled image back, run the scene-linear
stage on the CPU and upload it again. Now only the ProRAW local tone map
(off by default) does.

- Defringe: OkLab pass, separable lightness min/max filter, per-pixel
  apply. Parameters come from the new optics::defringe_params, which the
  CPU stage now uses too.
- Spots: new spot module (spot_prep / spot_apply over each spot's box, the
  Heal tone correction as device Gaussians), spot by spot in place so each
  reads what the earlier ones left, as on the CPU. Remove's automatic
  source: spot_score rates the 48 candidates on the device and only the
  scores come back. Layout, candidates, spoke directions, radii and ranking
  are shared helpers in pipeline::spots (spots::apply uses them; behaviour
  unchanged, pipeline tests green).
- Histogram: counted with atomics on the device on Histogram::of_srgb8's
  sampling grid (exact), instead of a CPU pass over the readback.

Tests: spots (clone, heal, auto remove incl. near the edge where no
candidate fits, brushed strokes, feather 0, cut by the edge, overlapping)
and defringe (purple/green, hue ranges, preview and full size) max 1 LSB;
the device histogram equals the CPU count of the returned image for small,
sampled (>1 MP) and windowed renders; the scoring kernel picks the CPU's
candidate. (The edge case caught a real bug: "doesn't fit" was written as a
decimal literal that rounds below f32::MAX.) Unit tests that create the
device now take turns with the crash-sentinel test, which swaps a global.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* GPU-FULL-2: fix the spot kernels' build; GPU tests fail when kernels don't build

07d4680b's spot module declared `const F32_MAX = bitcast<f32>(...)`, which
naga can't evaluate as a constant: the kernels failed to build, the device
was unavailable, and the equivalence tests skipped as if there were no
adapter - so that commit's GPU tests didn't actually run. f32::MAX is now a
function, and the equivalence suite (and the device unit test) fail instead
of skipping when an adapter exists but the kernels don't build.

Re-verified on the RTX 5070 (DX12), all on the device: 21 equivalence tests
incl. the 8 spot cases (max 1 LSB), defringe, the exact device histogram,
and the auto-source unit test.

Adds an ignored thumbnail throughput bench (tests/thumbs_bench.rs).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* GPU-FULL-3: thumbnails render on the GPU once the device is ready

Every cached job (grid and filmstrip thumbnails, preset and profile
previews, faces, quick stand-ins) was forced onto the CPU. They now use the
GPU when lightcraft_gpu::ready() - so they never block on device creation
at startup (1.8 s incl. kernels here) and render on the CPU until then.
Views and exports keep waiting for the device as before.

tests/thumbs_bench.rs (ignored): six workers rendering 256 px thumbnails of
512 px sources with preset-like settings (NR, sharpening, clarity, grading,
a gradient mask): RTX 5070 3.6 ms each vs 4.3-5.2 ms on 32 CPU threads,
with the cores left free for raw decoding.

Engine and UI suites: unchanged (only the 12 failures that predate this
branch on Windows: tests_sync paths, tests_model_setup).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* GPU-FULL-4: the loupe's drafts are drawn straight from the GPU

Rendering and drawing now share one device: the desktop app creates the
window's wgpu device with the adapter's limits and hands it to the GPU
renderer (lightcraft_gpu::adopt_window_device, on a background thread at
startup, under the crash sentinel; a device that doesn't suit falls back to
one of the renderer's own, as before).

A drag's drafts of the views are RenderJob::on_screen: the render ends in an
Rgba8Unorm texture (lightcraft_gpu::render_display -> Output::Display, new
`present` kernels: unwritten-pixel count, row padding for the copy) and
egui-wgpu draws it as a native texture (ui-egui ScreenTextures, implemented
by the app) - no readback, no conversion to egui pixels, no re-upload. The
readback's checks run on the device (atomic unwritten count, device
histogram). Renders that need pixels keep the readback: the settled full
render (view cache, overlays, screenshots), thumbnails, exports, overlays,
windows that spots grew, a monitor profile.

- engine: RenderJob::on_screen, RenderResult::frame (ScreenFrame).
- ui-egui: Tex::native / Tex::id() (21 draw sites), Renderer
  set_screen_textures, natives per slot (freed when pixels return),
  ui.inspect perf.gpuWindowDevice / screenTextures / mainOnGpu.
- app: WindowTextures, window device limits, LIGHTCRAFT_GPU_WINDOW=0 to opt
  out.

Tests: crates/gpu/tests/display.rs adopts a device in its own process and
checks the texture holds exactly the readback's pixels (padded and
unpadded widths, draft and full), the histogram matches, and overlays /
grown windows come back as pixels. In the app (RTX 5070, a 45 MP CR3 from
the user's library copy): all 90 drafts of a drag drawn from GPU textures,
1.69 ms vs 2.05 ms median per draft render with the readback; the frame
screenshot shows the image correctly; pixels return after the drag.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* GPU-FULL-2: the denoise runner tests take turns with the crash-sentinel tests

Building a denoise runner creates a device and compiles kernels under the
init marker. Running in parallel with backend::tests, it could arm the marker
the test had just set, so "is removed afterwards" failed now and then. The
runner tests now hold DEVICE_TEST_LOCK while they build, like the render tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* GPU-FULL-4: fix the build after merging upstream main

Upstream's QuickJob panic guard builds a RenderResult (add `frame: None`),
its idle-trim test builds a Tex (add `native: None`), and its on_exit test
builds App (add the WindowTextures slot).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* GPU-FULL-2: upstream's blur tests take turns with the crash-sentinel tests

gaussian_matches_cpu and bench_kernels create the device, so they hold
DEVICE_TEST_LOCK like every other device test in lightcraft-gpu.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tests: the same-folder export test compares paths separator-blind (Windows)

The written path is the original's folder (`\` on Windows) joined with `Exports/IMG_1.jpg`;
the expected one had `\Exports`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tests: the folder-drop tests find folder widgets separator-blind (Windows)

The folder tree spells its paths with `/`; the tests built widget ids from Windows paths with
`\`, so none was found and every test failed on Windows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tests: the Windows path fixes take the same form as in the other PR branches

So the branches merge into main without conflicts between their copies of the fix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* GPU-FULL: headless screenshots read back GPU-drawn views; LIGHTCRAFT_GPU_LIMITS caps the adopted device

Review of PR #1065:
- A headless `ui.screenshot` taken mid-drag showed the photo as a white
  rectangle: the GPU-resident draft left no CPU copy. With keep_pixels
  (control channel) the renderer now keeps each view's frame, and
  `cpu_textures` reads it back through `ScreenTextures::read`
  (`lightcraft_gpu::read_texture`). Drawing still never reads back, so
  drags keep the speed-up.
- Adopting the window's device skipped LIGHTCRAFT_GPU_LIMITS; `Gpu::adopt`
  now caps its limits the same way `Gpu::new` does.

Tests: a_headless_screenshot_reads_back_a_view_drawn_from_the_gpu (ui-egui),
the_limits_override_caps_an_adopted_device (gpu); the display test uses
read_texture and skips through lightcraft_testkit::skip!.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* GPU-FULL: review fixes (CodeRabbit 2026-10-21) and slideshow/print draw GPU-drawn views

- the window-device adoption is announced before its thread starts: until it finishes, the
  settings' warm-up and renders don't create a device of their own (they raced it)
- the device error / device-lost handlers go on only after the kernels build, so a declined
  window device keeps the window's own handler
- releasing a slot frees its GPU-resident texture and kept frame
- a soft proof into a colour space drafts full size on the GPU; only one to a device profile
  counts as proofed for `handles`
- docs: Fill spots and device-profile soft proofs render on the CPU
- slideshow, slide layout and print draw `Tex::id()` (the GPU texture when there is one)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* GPU-FULL: the display test skips when LIGHTCRAFT_GPU=0 switches the GPU off

It panicked ("GPU rendering is off") instead of skipping like the other GPU tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* GPU-FULL: a view readback never panics on a lost device

read_texture (headless screenshots of GPU-drawn views) polled the device
directly. On a lost device wgpu 30 panics in Device::poll; it now goes
through the same guard as the renderer's own polls (poll_device): a lost
device returns an error, stops the GPU and is not polled again. Review of
PR #1065. Also quiets a browser-build dead-code warning on OnScreen::Frame.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* GPU-FULL: an HDR edit's histogram shows the HDR range on the on-screen GPU path too

develop_on_screen returned the GPU's SDR histogram for both its Display and Image arms; it now
applies lightcraft_pipeline::hdr_histogram as develop_reporting does (None for drafts, windows,
proofs and non-HDR edits, which keep the GPU's histogram).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* GPU-FULL: the Navigator draws the photo's texture as it is drawn in the loupe

The Navigator falls back to the main view's texture before the photo has a thumbnail. It drew
`t.tex`, which is stale (or the 1x1 placeholder) when the main view holds a GPU-resident draft;
it now draws `Tex::id()`, like every other draw site.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* GPU-FULL: the egui 0.37 lifecycle test's texture names no native id

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* GPU-FULL: rustfmt the lifecycle test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* GPU-FULL: the second window fits the frame's size; freed GPU frames drop their views

The second window sized its image from the texture handle, which is only a
1x1 placeholder for a GPU-resident render; it now uses the frame's size.
When a GPU-resident render can't be shown and every native texture is
freed, the views pointing at them (Before, Region, Compare tiles) are
dropped too, so they render again as pixels instead of drawing a freed id.
Test: freeing_gpu_frames_drops_the_views_drawn_from_them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(gpu): LIGHTCRAFT_GPU_ADAPTER picks the card for rendering too

The variable chose the card only for AI Denoise and the face detector
(two copies of the same enumerate-and-match code); photo rendering
always took the first high-performance adapter, on a two-card machine
the one driving the screens.

One helper, backend::pick_adapter, now serves the render device
(Gpu::new), the denoise network and the face detector: the first
hardware card whose name contains the value (any case), else the
high-performance one. A name that matches no card is logged and falls
back instead of failing. backend::may_adopt_window_device says whether
rendering may share the window's device (only for the window's card).
Name matching is unit-tested without a GPU; the equivalence tests print
the card they ran on. Documented in docs/gpu-pipeline.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* GPU-FULL: a view switching to a GPU texture releases its pixel image

Review of #1065 (CodeRabbit nitpick): when a slot that had pixels switched to
a GPU-resident texture, its egui texture kept the full-size image, never drawn
while the native texture is set. Tex::show_native now swaps it for a 1x1
placeholder on the switch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(gpu): LIGHTCRAFT_GPU_ADAPTER picks among several matches in a defined order and logs once

Review of #3428:
- several cards match: the one whose whole name it is, then dedicated before built-in before
  virtual cards, then wgpu's order (backend::choose_named_adapter); the log names every match
  and the one used;
- no match: the default choice, with a warning that lists the cards;
- a name matching only a software renderer: never used, and the warning says so;
- each line is logged once (backend::log_once), though the render device, AI Denoise and the
  face models each ask;
- tests on fake adapter lists: a_fake_adapter_list_picks_in_a_defined_order,
  a_choice_is_logged_once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* GPU-FULL: the release note gives the GPU's documented bound against the CPU (3 levels, mean under half a level)

Review of PR #3544.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* GPU-FULL: the window's device isn't adopted when LIGHTCRAFT_GPU_ADAPTER names another card

With #3428 merged, Gpu::new already makes the render device on the named card; the window's
device was still adopted first, so the app rendered on the screen's card whatever the variable
said. backend::may_adopt_window_device (tested on names in backend.rs) now decides: another
card named renders on a device of its own, and the window stays on the screen's card.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 05:10:32 +01:00
FredApps 9423635e8c LR-EDIT-OPTICS-PROFILE: merge main (#3550 took catalog format 10; EmbeddedLens.source moves to format 11) 2026-11-04 13:21:54 +01:00
FredApps ca557c7d4e Merge remote-tracking branch 'origin/main' into pr-3550
# Conflicts:
#	docs/parity-checklist.md
2026-11-04 12:19:58 +01:00
FredApps 36b244286a Merge remote-tracking branch 'origin/main' into pr-3073
# Conflicts:
#	docs/gaps.md
2026-11-04 12:11:30 +01:00
Dylan M. Taylor 03e03f382e security(tests): test fixture directories are created exclusively, never reused from a predictable name (#3721) 2026-11-03 17:49:04 -05:00
Jeremy HookeandClaude Opus 5.5 2038ebc760 LR-EDIT-EFFECTS-GRAIN: review fixes (one draw per missed tile, table copies read back)
- A render that misses a crystal tile another thread is drawing (another render, or the
  background draw of a drag) waits for it instead of drawing it again; the marker is cleared and
  waiters woken on success and failure. Pool workers still draw for themselves: blocked, one
  could hold up part of the very drawing it waits for. Regression test.
- The grain-table replacement test copies into a destination per render and reads both back
  against their tile's tables.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 13:37:43 +11:00
Jeremy HookeandClaude Opus 5.5 b908538a16 LR-EDIT-EFFECTS-GRAIN: review fixes (shared grain tables, own test cache, per-pixel preview check)
- Gpu::grain_tables returns the resident buffer it copied from as an Arc that the render keeps
  until it submits: replacing the tables on another thread no longer hands the buffer back to
  the pool while a recorded copy from it is unsubmitted (regression test).
- The drag test uses a tile cache of its own, so other V3 tests can't evict its stand-in.
- small_render_matches_the_downscaled_large_render compares the grain pixel by pixel (measured
  0.003 of 255 levels apart), not only its strength.
- GPU equivalence covers V1 and V2 grain again.
- docs/grain.md: the drag benchmark command sets FRAMES=100; the rotated-frame footprint is an
  axis-aligned square (documented, also in crystal.rs).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 12:08:45 +11:00
Jeremy HookeandClaude Opus 5.5 50e6422a72 LR-EDIT-EFFECTS-GRAIN: grain drag benchmark; Ryzen numbers for main and #1060
`grain_drag_bench` (lightcraft-gpu example): GPU draft renders of a 2.5 MP
preview while Amount or Size is dragged, ms per frame. It doesn't depend on
the grain model, so it runs unchanged on other branches. docs/grain.md gets
its results on the Ryzen 5 7545U / Radeon 740M for main, #1060 and this
model, and the whole-render grain cost of main and #1060 there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 11:11:55 +11:00
Jeremy HookeandClaude Opus 5.5 fe6e064975 LR-EDIT-EFFECTS-GRAIN: crystal grain keeps slider drags in budget on slower machines
Measured on a Ryzen 5 7545U with a Radeon 740M (RADV), where grain cost what
the M2 Max hid:

- The tables stay on the GPU between renders (Gpu::grain_tables) and are
  copied into the finish kernel's aux buffer on the device, instead of being
  appended to aux and uploaded (12 MB) on every render. Amount drag, 2.5 MP
  preview: 16.9 -> 11-15 ms a frame (no grain: 8 ms).
- A draft render (a drag) doesn't wait for a tile it hasn't got: the last tile
  of the seed stands in while the new one is drawn in the background, on a
  pool of half the cores; the full render when the drag ends waits for the
  exact tile. Size drag: 62-66 -> 13-14 ms a frame. wasm drafts still wait.
- Stamps draw each row as a 64-bit mask, a fixed number of rows per layer,
  rows outside the band landing in scratch rows around it: no branch per row.
  Tiles 10-20 % faster at every setting, bit-identical.

Tests: GPU grain patterns in turn (same, new size, new roughness, new seed,
back) match the CPU; a drag takes the last tile while the next is drawn, then
the exact one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 08:59:46 +11:00
Jeremy HookeandClaude Opus 5.5 c81368470b LR-EDIT-EFFECTS-GRAIN: film grain from crystal layers (process V3)
Grain under the new process V3 is drawn from a simulated emulsion of crystal
layers, after Aurélien Pierre's crystallographic grain model (implemented from
the article's description). It fades out towards black and white as on a print,
is applied symmetrically in the display-encoded domain (no shadow darkening, no
grey specks in blown highlights), and matches Lightroom Classic's strength and
grain width at mid grey.

The emulsion is drawn once per Size / Roughness / seed on two periodic tiles in
frame coordinates and kept as summed-area tables, so each output pixel takes
the exact mean of the emulsion under its footprint: a preview is the export's
grain box-downscaled. CPU and GPU read the same tables (the GPU from the finish
kernel's aux buffer). V1 and V2 keep their value-noise grain exactly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 23:30:16 +11:00
Brandon Thomas d6a947bea0 Merge PR #3370 2026-11-01 22:06:44 -05:00
OneSlipsandClaude Opus 5.5 432fbed3d5 LR-MASK-GEOMETRY: review fixes: old masks keep their region and frame, clicks and handles in mask coordinates
CodeRabbit's review of #3550:
- An old gradient goes onto the photo through the warp's local linear part: a radial's radii and
  angle, a linear's direction and width (the mean alpha error halves; the largest drops 3x).
- Old masks an edit brings in (paste, sync, preset, history step, sidecar) go onto the photo from
  the settings they came with; masks an edit keeps, from the settings before it.
- A click on an old Object mask attaches the mask and the click before the model reads them.
- The handles and arrow keys read a mask after Begin Interaction attached it, so a drag never mixes
  frames; a linear gradient's guides are drawn through the warp.
- A brush point the warp can't place lays no dab; a resampled zoomed-in pass takes the whole-photo
  selection past its own area; mapped boxes sample 16 points per edge.
- The CPU and GPU geometry tests also cover a quarter turn.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 04:34:36 +10:00
OneSlipsandClaude Opus 5.5 2ad7207127 LR-MASK-GEOMETRY: masks stay on the photo under lens corrections, Upright, Transform and Rotate
Mask coordinates lived on the corrected frame, so a Transform, Upright or lens-correction change
moved the photo under them and the masked look stayed behind, offset from the person it was drawn
on (4.3 px on a 240 px render under Vertical 25 + Rotate 4: about 100 px at 6000 px). Rotate Left /
Right turned the crop but not the masks.

A mask's coordinates are now on the photo before the warp (Mask::on_photo, catalog format 10):
the CPU render, the GPU render, Auto Mask brush windows and the on-photo tools map them through
the warp (Frame::for_mask, Warp::from_source). Rotate Left / Right turns masks with the photo
(mask_space::turn). The AI models see the photo without lens corrections, Upright, Transform,
crop or flips, so stored Object / Prompt selections stay on their content and changing those
doesn't ask the model again. Older masks (no on_photo) render where they were and move onto the
photo, without moving, at their next edit (mask_space::attach).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 03:14:38 +10:00
Chad ElliottandClaude Opus 5.5 21a7d64d46 docs(gpu): #1050 run the GPU tests locally on a software adapter
docs/gpu-pipeline.md says how to run lightcraft-gpu's tests on a machine
without a GPU: LIGHTCRAFT_GPU_ALLOW_SOFTWARE=1 admits Mesa's lavapipe on
Linux and WARP on Windows (Metal on macOS needs nothing), and
LIGHTCRAFT_SKIP_LOG shows whether anything still skipped for want of an
adapter. The comments on the variable and in equivalence.rs no longer
say CI runs them: the platform CI legs of #1148 are not landing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 22:26:51 -05:00
Chad ElliottandClaude Opus 5.5 fc99d212f6 test(gpu): #1050 opt-in software adapter for the equivalence tests
`Gpu::new` refuses software adapters (llvmpipe / lavapipe, WARP): the CPU
pipeline is faster. CI runners have nothing else, so the CPU <-> GPU
equivalence tests have always skipped there.

`LIGHTCRAFT_GPU_ALLOW_SOFTWARE=1` admits them. The app never sets it and
the default is unchanged. On lavapipe all 134 compared renders stay within
max 1 LSB, mean <= 0.0003 LSB, the same as Metal on an M4 Pro.

The two big-source window tests used a 24 MP (288 MB) source. That is over
lavapipe's 128 MiB storage binding (the WebGPU default), so geometry ran on
the CPU and nothing was uploaded: one test failed and the other passed
without checking anything. They now use 3200 x 3200 (117 MiB): above
RETAIN_SOURCE_BYTES, so the source is still shared, and uploaded on every
adapter.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 22:26:43 -05:00
OneSlipsandClaude Opus 5.5 29443e117c LR-EDIT-OPTICS-PROFILE: merge main (#3430 integration round 3, #3390)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 03:45:27 +10:00
NetterSilverandClaude Haiku 5.5 4cb62dcfaa Reject overflowing LIGHTCRAFT_GPU_LIMITS values instead of panicking
Found while testing crates/gpu/src/ctx.rs:768 (parse_limits)

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-31 13:00:19 +00:00
aiongg ee0a627536 Merge track r3-t10
# Conflicts:
#	crates/engine/src/cmd/masks.rs
#	crates/ui-egui/locales/de.json
#	crates/ui-egui/locales/es.json
#	crates/ui-egui/locales/fr.json
#	crates/ui-egui/locales/ja.json
#	crates/ui-egui/locales/ka.json
#	crates/ui-egui/locales/pt-br.json
#	crates/ui-egui/locales/ru.json
#	crates/ui-egui/locales/uk.json
#	crates/ui-egui/locales/zh-hant.json
#	docs/gaps.md
#	docs/parity-checklist.md
#	docs/whats-new.md
2026-10-31 02:31:38 +00:00
aiongg 56c842d8fe Merge track r3-t09
# Conflicts:
#	docs/parity-checklist.md
#	docs/raw-parity.md
#	docs/ui-parity.md
#	docs/whats-new.md
2026-10-31 02:31:25 +00:00
aiongg c524a2d12c Merge PR #3419: Issue #1764: running out of device memory falls back without stopping the GPU 2026-10-31 02:11:06 +00:00
aiongg 799beaf5e4 Merge PR #2989: GPU-TESTS: every WGSL kernel parses and validates in the test run, without a GPU 2026-10-31 02:11:06 +00:00
aiongg c2155326d6 Merge PR #2942: Issue #2936: build the GPU kernels on parallel threads 2026-10-31 02:11:04 +00:00
aiongg f12012bc9f Merge PR #2844: GPU: black pixels take the colour tools and a light vignette as on the CPU 2026-10-31 02:10:48 +00:00
aiongg 4a50aacb8a Merge PR #2731: Brush dabs: build only as far as the caller will look (#1520)
crates/pipeline/src/masks.rs: main moved the tests to masks/tests.rs; the PR's test ported there
2026-10-31 02:10:46 +00:00
aiongg 5d08f8632f Merge PR #2631: LR-EDIT-DETAIL-DENOISE: GPU denoise doesn't hang when its tiles in flight fail (#2577) 2026-10-31 02:10:23 +00:00
aiongg 78e70ab8f8 Merge PR #2545: Issue #136: applying the GPU setting never waits for the device on the UI thread 2026-10-31 02:10:21 +00:00
aiongg 06a94d2d7f Merge PR #3015: Never crash: an oversize export size is an error, not a multiply overflow
crates/engine/src/media.rs: main moved render_now and export_job to media/session.rs; the two size checks ported there
crates/engine/src/tests_export.rs: the test is appended to tests/export.rs
2026-10-31 02:08:30 +00:00
aiongg 1b32dab094 Merge PR #999: Alt/Option-drag previews for clipping and sharpening (#937)
Conflicts resolved:
- crates/engine/src/media.rs: main split it; the render and display-profile hunks are ported into media/render.rs
- crates/ui-egui/src/lib.rs, panels/detail.rs: main split them; alt_held is set in app/frame.rs, view_overlay and overlay_supports_window ported (panels/detail/window.rs)
- crates/ui-egui/src/tests_alt_preview.rs moved to tests/alt_preview.rs
- crates/pipeline/src/finish.rs, local.rs: main's code kept, sharpen_mask_weight and texture_sigma applied to it
- docs: both sides kept; summary counts from main (regenerated later)
2026-10-31 02:08:19 +00:00
Antonio Sokic 35c7abb7cc Issue #1764: keep a failed upload out of the shared source
Record the out-of-memory failure when the staging buffer can't be allocated, and don't publish the zeroed buffer to SHARED_SOURCE when the render has failed, so a concurrent render can't reuse it.
2026-10-31 02:01:05 +01:00
Antonio Sokic 003ab49b5c Release shared source after out-of-memory fallback
Clear SHARED_SOURCE in the OutOfMemory branch so the next render does not reuse a zeroed buffer, and keep the OOM test's allocations within the device's max_buffer_size, failing on unexpected validation errors.
2026-10-31 01:31:12 +01:00
Antonio Sokic 99d4de32c7 Issue #1764: running out of device memory falls back without stopping the GPU
An upload whose buffer couldn't be allocated tried again through create_buffer_init, which maps the new buffer and panics inside wgpu when that allocation fails too ("Failed to get mapped range for buffer created with mapped_at_creation"). The panic stopped GPU use for the session. Uploads and kernel parameters now go through the queue into an unmapped buffer, and a failed upload is not retried, so out of memory stays an out-of-memory fallback to the CPU for that render.

Claude-Session: https://claude.ai/code/session_01SF8KiKFYZpuGzdTuzsm3cr
2026-10-30 21:43:50 +01:00
Bruno-Alumn 06e2ec43ba LR-MASK-COLORRANGE: a colour-range mask keeps at most 64 samples however it is loaded (#2556)
Render cost is pixels x samples (CPU and GPU), and only mask.add / mask.update capped the list, so a
sidecar's lc:settings, a preset, develop.merge, render --settings or a catalog / history load could
carry thousands and stall a render or lose the GPU device. MAX_COLOR_RANGE_SAMPLES moves to
lightcraft-develop and ColorRange::samples deserializes through a capped visitor (the first 64 in
order, the rest skipped as IgnoredAny); the CPU and GPU renders also take at most 64 for settings
built in code.
2026-10-30 12:03:03 +01:00
radialmonsterandClaude Opus 5.5 1bfa617a5a GPU: black pixels take the colour tools and a light vignette as on the CPU
The GPU colour tools took the hue of every pixel with atan2(a, b). For a black pixel both are
0, and WGSL leaves atan2(0, 0) undefined: on an RTX 3090 (Vulkan) it is NaN, so with any
colour tool on (saturation, vibrance, the mixer) every exactly black pixel became NaN. NaN is
written as 0, so it stayed black and nothing showed, until a later step lightened it: with a
positive vignette the CPU lifts the black corners and the GPU left them black (up to 127
levels apart in 8-bit). A neutral pixel now gets hue 0, as Rust's atan2 gives on the CPU.

Regression test: black bars under a light vignette with saturation, vibrance or the mixer
(fails on main: mean 12.8, max 127 levels).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014ti8KemZbjE2ZgHgV1q1BM
2026-10-28 13:58:46 -04:00
OneSlipsandClaude Opus 5.5 698352009d LR-EDIT-OPTICS-PROFILE: merge main (59a5d00c6, the ui-egui split of #3111)
The lens-database dialog arms go into main's split dialogs module; quick.rs
and frame.rs take main's explicit imports plus what this PR uses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 18:57:22 +10:00