Replace the Lensfun WebAssembly runtime with our own lens engine.
The wrapper's wasm, its 5 MB data blob and the runtime chunk were fragile to serve (CSP, MIME, cache) and pulled an LGPL runtime into the bundle just for calibration data. The Lensfun XML is now converted at build time into public/lens-db/profiles.json, and search, matching and the correction maths live in src/lib/lensDb.ts and src/lib/lensEngine.ts. Maps are pinned against output captured from the previous implementation, so results are unchanged. 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com>
This commit is contained in:
@@ -456,7 +456,7 @@ Data directory
|
|||||||
| `src/lib/preview16.ts` | 16-bit raw-proxy PNG parser, camera matrix and half-float conversion for the RGBA16F source texture |
|
| `src/lib/preview16.ts` | 16-bit raw-proxy PNG parser, camera matrix and half-float conversion for the RGBA16F source texture |
|
||||||
| `src/lib/softProof.ts` | ICC parsing (lut8/lut16/mAB), printer A2B/B2A round trip and the 3D proof cube |
|
| `src/lib/softProof.ts` | ICC parsing (lut8/lut16/mAB), printer A2B/B2A round trip and the 3D proof cube |
|
||||||
| `src/lib/dcp.ts` | DCP tag reader and the camera-to-sRGB matrix recipe |
|
| `src/lib/dcp.ts` | DCP tag reader and the camera-to-sRGB matrix recipe |
|
||||||
| `src/lib/lensfun.ts`, `lensNames.ts`, `lensDefaults.ts` | Lensfun client, EXIF matching, saved defaults |
|
| `src/lib/lensDb.ts`, `lensEngine.ts`, `lensNames.ts`, `lensDefaults.ts` | Lens database, correction maps, EXIF matching, saved defaults |
|
||||||
| `src/lib/merge.ts` | HDR / panorama / focus-stack composition |
|
| `src/lib/merge.ts` | HDR / panorama / focus-stack composition |
|
||||||
| `src/lib/autoMask.ts`, `noiseProfile.ts` | On-device masks and ISO-aware noise starting points |
|
| `src/lib/autoMask.ts`, `noiseProfile.ts` | On-device masks and ISO-aware noise starting points |
|
||||||
| `src/lib/xmp.ts` | Lightroom-compatible XMP sidecar reader/writer |
|
| `src/lib/xmp.ts` | Lightroom-compatible XMP sidecar reader/writer |
|
||||||
@@ -907,22 +907,24 @@ licensed implementation.
|
|||||||
|
|
||||||
## Lens profiles
|
## Lens profiles
|
||||||
|
|
||||||
Lens correction uses the [Lensfun](https://lensfun.github.io/) camera and lens database
|
Lens correction uses the calibration data of the
|
||||||
through the [`@neoanaloglabkk/lensfun-wasm`](https://github.com/lexluthor0304/LensfunWasm)
|
[Lensfun](https://lensfun.github.io/) camera and lens database, converted at build time
|
||||||
build. Runtime assets are served from `public/lensfun/`.
|
into the compact profile file the editor ships. The correction maths is Luminary's own
|
||||||
|
(`src/lib/lensEngine.ts`): PanoTools, poly3 and poly5 distortion, poly3 TCA and `pa`
|
||||||
|
vignetting, evaluated in the same normalised coordinates Lensfun used. No WebAssembly
|
||||||
|
runtime, no XML parser and no `blob:` or eval allowance is involved, and a unit test
|
||||||
|
pins the output against maps captured from the previous implementation.
|
||||||
|
|
||||||
- **Database** — © Lensfun contributors, licensed
|
- **Database** — © Lensfun contributors, licensed
|
||||||
[CC BY-SA 3.0 Unported](https://creativecommons.org/licenses/by-sa/3.0/), taken from
|
[CC BY-SA 3.0 Unported](https://creativecommons.org/licenses/by-sa/3.0/), taken from
|
||||||
Lensfun `data/db` at commit
|
Lensfun `data/db` at commit
|
||||||
[`655a9c4`](https://github.com/lensfun/lensfun/tree/655a9c4e3e53c25bc04843c853e7e7a0121359e7/data).
|
[`655a9c4`](https://github.com/lensfun/lensfun/tree/655a9c4e3e53c25bc04843c853e7e7a0121359e7/data)
|
||||||
It is redistributed as bundled by the wrapper build; Luminary adds no profiles of its
|
and converted by `scripts/build-lens-db.mjs` into `public/lens-db/profiles.json`.
|
||||||
own.
|
Luminary adds no profiles of its own.
|
||||||
- **Library** — Lensfun is LGPL-3.0 (the bundled notice states "or later"), compiled to
|
- **Engine** — `src/lib/lensDb.ts` (loading, matching, camera lookup) and
|
||||||
WebAssembly. Corresponding source is the upstream repository at the pinned commit plus
|
`src/lib/lensEngine.ts` (maps, auto-scale), both MIT like the rest of the app code.
|
||||||
the wrapper's build scripts.
|
- **Bundled files** — `public/lens-db/NOTICE.md` records the attribution and the pin;
|
||||||
- **Bundled files** — `public/lensfun/LICENSE` is the **MIT licence of the WASM
|
`public/lens-db/profiles.json` carries the same provenance in its `source` field.
|
||||||
wrapper**, not of the database or the library. `NOTICE.md`,
|
|
||||||
`THIRD_PARTY_LICENSES.md` and `UPSTREAM.md` record the other components and the pin.
|
|
||||||
|
|
||||||
See [Third-party attribution and licences](#third-party-attribution-and-licences) before
|
See [Third-party attribution and licences](#third-party-attribution-and-licences) before
|
||||||
redistributing the app or its container image.
|
redistributing the app or its container image.
|
||||||
@@ -1090,15 +1092,11 @@ including Lensfun's CC BY-SA 3.0 database, which the MIT licence does not relice
|
|||||||
|
|
||||||
| Component | Version / pin | Upstream | Licence | Notes |
|
| Component | Version / pin | Upstream | Licence | Notes |
|
||||||
| --- | --- | --- | --- | --- |
|
| --- | --- | --- | --- | --- |
|
||||||
| Lensfun library | `655a9c4` | [lensfun/lensfun](https://github.com/lensfun/lensfun) | LGPL-3.0; bundled notices say "or later" | Compiled to WebAssembly; distribution needs the licence text and corresponding source |
|
| Lensfun database | `655a9c4` | [lensfun `data/db`](https://github.com/lensfun/lensfun/tree/655a9c4e3e53c25bc04843c853e7e7a0121359e7/data) | CC BY-SA 3.0 Unported | © Lensfun contributors; shipped as `public/lens-db/profiles.json`; attribution and share-alike apply to the data only |
|
||||||
| Lensfun database | `655a9c4` | [lensfun `data/db`](https://github.com/lensfun/lensfun/tree/655a9c4e3e53c25bc04843c853e7e7a0121359e7/data) | CC BY-SA 3.0 Unported | © Lensfun contributors; shipped as `public/lensfun/lensfun-core.data`; attribution and share-alike apply |
|
|
||||||
| Lensfun WASM wrapper | 0.1.3 | [lexluthor0304/LensfunWasm](https://github.com/lexluthor0304/LensfunWasm) | MIT | `public/lensfun/LICENSE` is this licence and covers neither the database nor the library |
|
|
||||||
| LibRaw | via `libraw-wasm` 1.6.0 | [LibRaw/LibRaw](https://github.com/LibRaw/LibRaw) | LGPL-2.1 **or** CDDL-1.0 (dual) | The decoder compiled into the WASM |
|
| LibRaw | via `libraw-wasm` 1.6.0 | [LibRaw/LibRaw](https://github.com/LibRaw/LibRaw) | LGPL-2.1 **or** CDDL-1.0 (dual) | The decoder compiled into the WASM |
|
||||||
| `libraw-wasm` | 1.6.0 | [ybouane/LibRaw-Wasm](https://github.com/ybouane/LibRaw-Wasm) | ISC | Binding layer only; its metadata does not replace LibRaw's terms for the compiled library |
|
| `libraw-wasm` | 1.6.0 | [ybouane/LibRaw-Wasm](https://github.com/ybouane/LibRaw-Wasm) | ISC | Binding layer only; its metadata does not replace LibRaw's terms for the compiled library |
|
||||||
| `sharp` | 0.35.5 | [lovell/sharp](https://github.com/lovell/sharp) | Apache-2.0 | Prebuilt binaries bundle libvips |
|
| `sharp` | 0.35.5 | [lovell/sharp](https://github.com/lovell/sharp) | Apache-2.0 | Prebuilt binaries bundle libvips |
|
||||||
| libvips | bundled by `sharp` | [libvips/libvips](https://github.com/libvips/libvips) | LGPL-2.1-or-later | Applies when distributing binaries or container images |
|
| libvips | bundled by `sharp` | [libvips/libvips](https://github.com/libvips/libvips) | LGPL-2.1-or-later | Applies when distributing binaries or container images |
|
||||||
| tinyxml2 | bundled in Lensfun WASM | [leethomason/tinyxml2](https://github.com/leethomason/tinyxml2) | zlib | |
|
|
||||||
| utf8proc | bundled in Lensfun WASM | [JuliaStrings/utf8proc](https://github.com/JuliaStrings/utf8proc) | MIT | |
|
|
||||||
| `exifr` | 7.1.3 | [MikeKovarik/exifr](https://github.com/MikeKovarik/exifr) | MIT | Browser EXIF parsing |
|
| `exifr` | 7.1.3 | [MikeKovarik/exifr](https://github.com/MikeKovarik/exifr) | MIT | Browser EXIF parsing |
|
||||||
| `nodemailer` | 10.6.1 | [nodemailer](https://github.com/nodemailer/nodemailer) | MIT-0 | SMTP notifications |
|
| `nodemailer` | 10.6.1 | [nodemailer](https://github.com/nodemailer/nodemailer) | MIT-0 | SMTP notifications |
|
||||||
| React / React DOM | 18.3.1 | [facebook/react](https://github.com/facebook/react) | MIT | |
|
| React / React DOM | 18.3.1 | [facebook/react](https://github.com/facebook/react) | MIT | |
|
||||||
@@ -1122,18 +1120,15 @@ Creative Commons content licence, and it grants neither patent nor trademark rig
|
|||||||
|
|
||||||
### Redistribution checklist
|
### Redistribution checklist
|
||||||
|
|
||||||
`public/lensfun/` currently ships the notices (`NOTICE.md`, `THIRD_PARTY_LICENSES.md`,
|
`public/lens-db/` currently ships the converted data and `NOTICE.md`, but **not** the
|
||||||
`UPSTREAM.md`) and the wrapper's MIT `LICENSE`, but **not** the full LGPL-3.0 or
|
full CC BY-SA 3.0 text. Before distributing Luminary or its container image:
|
||||||
CC BY-SA 3.0 texts. Before distributing Luminary or its container image:
|
|
||||||
|
|
||||||
1. Add the upstream licence texts beside the assets: Lensfun `COPYING` and
|
1. Add the upstream licence text beside the data: Lensfun
|
||||||
`COPYING.LESSER` (the LGPL incorporates GPL-3.0 by reference), and
|
`data/COPYING.CC_BY-SA_3.0`.
|
||||||
`data/COPYING.CC_BY-SA_3.0` for the database.
|
2. Keep the notice, the pinned commit and the attribution block above in the distributed
|
||||||
2. Keep the notices, the pinned commit and the attribution block above in the distributed
|
copy, served from `public/lens-db/` as it is today.
|
||||||
copy, served from `public/lensfun/` as they are today.
|
3. Provide corresponding source for the LGPL components still shipped: LibRaw at the
|
||||||
3. Provide corresponding source for the LGPL components: Lensfun and LibRaw at the
|
version actually built.
|
||||||
versions actually built, plus tinyxml2 and utf8proc. Leave
|
|
||||||
`dist/lensfun/lensfun-core.wasm` and its JS loader replaceable.
|
|
||||||
4. When publishing a container image, include the same files and the libvips, Node.js and
|
4. When publishing a container image, include the same files and the libvips, Node.js and
|
||||||
Debian notices.
|
Debian notices.
|
||||||
5. Do not relicense third-party assets under Luminary's own terms, and do not add
|
5. Do not relicense third-party assets under Luminary's own terms, and do not add
|
||||||
|
|||||||
+8
-12
@@ -3,35 +3,31 @@
|
|||||||
**Luminary** — notices resolved 23 November 2026.
|
**Luminary** — notices resolved 23 November 2026.
|
||||||
|
|
||||||
This file consolidates the notices for third-party software that Luminary bundles,
|
This file consolidates the notices for third-party software that Luminary bundles,
|
||||||
links, or ships in its build output and container image. `public/lensfun/NOTICE.md`
|
links, or ships in its build output and container image. `public/lens-db/NOTICE.md`
|
||||||
and `public/lensfun/THIRD_PARTY_LICENSES.md` remain the notices served with the
|
remains the notice served with the Lensfun-derived calibration data; this file does not
|
||||||
Lensfun assets; this file does not replace them.
|
replace it.
|
||||||
|
|
||||||
The Luminary application code is licensed under the [MIT licence](LICENSE). That licence
|
The Luminary application code is licensed under the [MIT licence](LICENSE). That licence
|
||||||
covers only Luminary's original code: it grants no rights in the components below and
|
covers only Luminary's original code: it grants no rights in the components below and
|
||||||
does not replace their terms.
|
does not replace their terms.
|
||||||
Versions are those resolved in `package-lock.json`; the Lensfun pin is
|
Versions are those resolved in `package-lock.json`; the lens database pin is
|
||||||
`655a9c4e3e53c25bc04843c853e7e7a0121359e7` (see `public/lensfun/UPSTREAM.md`).
|
`655a9c4e3e53c25bc04843c853e7e7a0121359e7` (see `public/lens-db/NOTICE.md`).
|
||||||
|
|
||||||
## Runtime components
|
## Runtime components
|
||||||
|
|
||||||
| Component | Version / pin | Licence | Notice |
|
| Component | Version / pin | Licence | Notice |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| Lensfun library | `655a9c4` | LGPL-3.0-or-later | © Lensfun contributors — https://github.com/lensfun/lensfun |
|
| Lensfun camera/lens database (data only) | `655a9c4` | CC BY-SA 3.0 Unported | © Lensfun contributors — https://creativecommons.org/licenses/by-sa/3.0/ |
|
||||||
| Lensfun camera/lens database | `655a9c4` | CC BY-SA 3.0 Unported | © Lensfun contributors — https://creativecommons.org/licenses/by-sa/3.0/ |
|
|
||||||
| Lensfun WebAssembly wrapper | 0.1.3 | MIT | © 2026 lex — https://github.com/lexluthor0304/LensfunWasm |
|
|
||||||
| LibRaw (compiled into `libraw-wasm`) | via `libraw-wasm` 1.6.0 | LGPL-2.1 **or** CDDL-1.0 | © LibRaw LLC — https://github.com/LibRaw/LibRaw |
|
| LibRaw (compiled into `libraw-wasm`) | via `libraw-wasm` 1.6.0 | LGPL-2.1 **or** CDDL-1.0 | © LibRaw LLC — https://github.com/LibRaw/LibRaw |
|
||||||
| `libraw-wasm` | 1.6.0 | ISC | Copyright holder not stated by the package — https://github.com/ybouane/LibRaw-Wasm |
|
| `libraw-wasm` | 1.6.0 | ISC | Copyright holder not stated by the package — https://github.com/ybouane/LibRaw-Wasm |
|
||||||
| `sharp` | 0.35.5 | Apache-2.0 | https://github.com/lovell/sharp |
|
| `sharp` | 0.35.5 | Apache-2.0 | https://github.com/lovell/sharp |
|
||||||
| libvips (bundled in `sharp` binaries) | shipped by `sharp` 0.35.5 | LGPL-2.1-or-later | © libvips contributors — https://github.com/libvips/libvips |
|
| libvips (bundled in `sharp` binaries) | shipped by `sharp` 0.35.5 | LGPL-2.1-or-later | © libvips contributors — https://github.com/libvips/libvips |
|
||||||
| tinyxml2 (in the Lensfun WASM) | — | zlib | © Lee Thomason — https://github.com/leethomason/tinyxml2 |
|
|
||||||
| utf8proc (in the Lensfun WASM) | — | MIT | © utf8proc contributors — https://github.com/JuliaStrings/utf8proc |
|
|
||||||
| `exifr` | 7.1.3 | MIT | © 2020 Mike Kovařík, Mutiny.cz — https://github.com/MikeKovarik/exifr |
|
| `exifr` | 7.1.3 | MIT | © 2020 Mike Kovařík, Mutiny.cz — https://github.com/MikeKovarik/exifr |
|
||||||
| `nodemailer` | 7.0.13 | MIT-0 | © 2011-2023 Andris Reinman — https://github.com/nodemailer/nodemailer |
|
| `nodemailer` | 7.0.13 | MIT-0 | © 2011-2023 Andris Reinman — https://github.com/nodemailer/nodemailer |
|
||||||
| React / React DOM | 18.3.1 | MIT | © Facebook, Inc. and its affiliates — https://github.com/facebook/react |
|
| React / React DOM | 18.3.1 | MIT | © Facebook, Inc. and its affiliates — https://github.com/facebook/react |
|
||||||
|
|
||||||
The Lensfun database is a separate asset from the Lensfun library: CC BY-SA 3.0
|
The lens database is a separate asset from Luminary's code: CC BY-SA 3.0 applies to
|
||||||
applies to the profile data, not to Luminary's application code. Attribution and
|
Lensfun's calibration data, not to the correction engine that reads it. Attribution and
|
||||||
share-alike requirements are summarised in the README under
|
share-alike requirements are summarised in the README under
|
||||||
[Third-party attribution and licences](README.md#third-party-attribution-and-licences).
|
[Third-party attribution and licences](README.md#third-party-attribution-and-licences).
|
||||||
|
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ This matters because an earlier design assumed an Electron desktop app. It is no
|
|||||||
- **Raw path:** `libraw-wasm` in a `worker_threads` pool (`server/libraw-pool.mjs`),
|
- **Raw path:** `libraw-wasm` in a `worker_threads` pool (`server/libraw-pool.mjs`),
|
||||||
`open()` + `imageData()` → 8-bit sRGB JPEG proxy at `RAW_PREVIEW_EDGE = 6000`
|
`open()` + `imageData()` → 8-bit sRGB JPEG proxy at `RAW_PREVIEW_EDGE = 6000`
|
||||||
long edge (`server/config.mjs:14`, `RAW_PREVIEW_EDGE`). `sharp` for JPEG ingest,
|
long edge (`server/config.mjs:14`, `RAW_PREVIEW_EDGE`). `sharp` for JPEG ingest,
|
||||||
`lensfun-wasm` for lens correction.
|
Lensfun's calibration data with Luminary's own correction engine (`src/lib/lensEngine.ts`).
|
||||||
- **Renderer:** `src/gl/renderer.ts`. `setImage()` uploads one `u_src` texture
|
- **Renderer:** `src/gl/renderer.ts`. `setImage()` uploads one `u_src` texture
|
||||||
(`:1144`), grade pass samples it at `:1296`, finish pass at `:1553`.
|
(`:1144`), grade pass samples it at `:1296`, finish pass at `:1553`.
|
||||||
- **Export:** `src/lib/export.ts` builds a fresh `Renderer` from `getBitmap()` — a
|
- **Export:** `src/lib/export.ts` builds a fresh `Renderer` from `getBitmap()` — a
|
||||||
|
|||||||
Generated
-7
@@ -9,7 +9,6 @@
|
|||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@neoanaloglabkk/lensfun-wasm": "^0.1.3",
|
|
||||||
"exifr": "^7.1.3",
|
"exifr": "^7.1.3",
|
||||||
"libraw-wasm": "^1.6.0",
|
"libraw-wasm": "^1.6.0",
|
||||||
"nodemailer": "^10.6.1",
|
"nodemailer": "^10.6.1",
|
||||||
@@ -1307,12 +1306,6 @@
|
|||||||
"@jridgewell/sourcemap-codec": "^1.4.14"
|
"@jridgewell/sourcemap-codec": "^1.4.14"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@neoanaloglabkk/lensfun-wasm": {
|
|
||||||
"version": "0.1.3",
|
|
||||||
"resolved": "https://registry.npmjs.org/@neoanaloglabkk/lensfun-wasm/-/lensfun-wasm-0.1.3.tgz",
|
|
||||||
"integrity": "sha512-+Me+P4kqr2CgJ7Tg+VatLSTfWxJkBt/xE9kG0qxD3KCcVY4MVgm/kkMwiVWTJt4EgzdIi3mFwUGO7HEuyziBpw==",
|
|
||||||
"license": "LGPL-3.0-or-later"
|
|
||||||
},
|
|
||||||
"node_modules/@rolldown/pluginutils": {
|
"node_modules/@rolldown/pluginutils": {
|
||||||
"version": "1.0.0-beta.27",
|
"version": "1.0.0-beta.27",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz",
|
||||||
|
|||||||
+2
-2
@@ -12,10 +12,10 @@
|
|||||||
"start": "node server/index.mjs",
|
"start": "node server/index.mjs",
|
||||||
"preview": "vite preview",
|
"preview": "vite preview",
|
||||||
"typecheck": "tsc --noEmit",
|
"typecheck": "tsc --noEmit",
|
||||||
"test": "vitest run"
|
"test": "vitest run",
|
||||||
|
"build:lens-db": "node scripts/build-lens-db.mjs"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@neoanaloglabkk/lensfun-wasm": "^0.1.3",
|
|
||||||
"exifr": "^7.1.3",
|
"exifr": "^7.1.3",
|
||||||
"libraw-wasm": "^1.6.0",
|
"libraw-wasm": "^1.6.0",
|
||||||
"nodemailer": "^10.6.1",
|
"nodemailer": "^10.6.1",
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
# Lens database notice
|
||||||
|
|
||||||
|
`profiles.json` in this directory is a converted copy of the Lensfun camera and lens
|
||||||
|
database, produced by `scripts/build-lens-db.mjs`.
|
||||||
|
|
||||||
|
```text
|
||||||
|
Lens database: © Lensfun contributors, CC BY-SA 3.0 Unported
|
||||||
|
https://lensfun.github.io/ · https://creativecommons.org/licenses/by-sa/3.0/
|
||||||
|
Pinned source: https://github.com/lensfun/lensfun/tree/655a9c4e3e53c25bc04843c853e7e7a0121359e7/data
|
||||||
|
```
|
||||||
|
|
||||||
|
- Only the calibration measurements come from Lensfun. The correction maths, the
|
||||||
|
search/matching code and the file format are Luminary's own (MIT).
|
||||||
|
- The data remains under CC BY-SA 3.0. Keep this attribution with it, and if you edit
|
||||||
|
`profiles.json` or regenerate it with different calibration data, distribute the
|
||||||
|
result under CC BY-SA 3.0 or a compatible licence and indicate the changes.
|
||||||
|
- Do not describe the database as MIT, public domain or OSI-approved open source: it is
|
||||||
|
a Creative Commons content licence and grants neither patent nor trademark rights.
|
||||||
|
- The full licence text is not bundled here; add Lensfun's
|
||||||
|
`data/COPYING.CC_BY-SA_3.0` beside this file before redistributing the app or its
|
||||||
|
container image.
|
||||||
File diff suppressed because one or more lines are too long
@@ -1,21 +0,0 @@
|
|||||||
MIT License
|
|
||||||
|
|
||||||
Copyright (c) 2026 lex
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
|
||||||
in the Software without restriction, including without limitation the rights
|
|
||||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
||||||
copies of the Software, and to permit persons to whom the Software is
|
|
||||||
furnished to do so, subject to the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all
|
|
||||||
copies or substantial portions of the Software.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
||||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
||||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
||||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
||||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
||||||
SOFTWARE.
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
# Notices
|
|
||||||
|
|
||||||
This project bundles and/or links the following third-party components:
|
|
||||||
|
|
||||||
1. Lensfun library source code (`third_party/lensfun/libs`) under LGPL-3.0-or-later.
|
|
||||||
2. Lensfun camera/lens database (`third_party/lensfun/data/db`) under CC BY-SA 3.0.
|
|
||||||
3. tinyxml2 (`third_party/tinyxml2`) under zlib license.
|
|
||||||
4. utf8proc (`third_party/utf8proc`) under MIT license.
|
|
||||||
|
|
||||||
Refer to `THIRD_PARTY_LICENSES.md` for license texts and links.
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
# Third-Party Licenses
|
|
||||||
|
|
||||||
## Lensfun
|
|
||||||
|
|
||||||
- Repository: https://github.com/lensfun/lensfun
|
|
||||||
- Library license: GNU LGPL v3.0 or later
|
|
||||||
- Database license: Creative Commons Attribution-ShareAlike 3.0
|
|
||||||
- Copyright: Lensfun contributors
|
|
||||||
|
|
||||||
## tinyxml2
|
|
||||||
|
|
||||||
- Repository: https://github.com/leethomason/tinyxml2
|
|
||||||
- License: zlib
|
|
||||||
- Copyright: Lee Thomason
|
|
||||||
|
|
||||||
## utf8proc
|
|
||||||
|
|
||||||
- Repository: https://github.com/JuliaStrings/utf8proc
|
|
||||||
- License: MIT
|
|
||||||
- Copyright: utf8proc contributors
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
# Upstream Tracking
|
|
||||||
|
|
||||||
## Source of truth
|
|
||||||
|
|
||||||
- Upstream repo: https://github.com/lensfun/lensfun.git
|
|
||||||
- Integration mode: git submodule (`third_party/lensfun`)
|
|
||||||
- Current pinned commit: `655a9c4e3e53c25bc04843c853e7e7a0121359e7`
|
|
||||||
- Commit date: `2026-02-28`
|
|
||||||
- Commit subject: `Add tca data for Meike SL 35mm F1.8 STM PRO`
|
|
||||||
|
|
||||||
## Update policy
|
|
||||||
|
|
||||||
- Pin exact commits.
|
|
||||||
- Upgrade manually via PR.
|
|
||||||
- Run full build/test after each bump.
|
|
||||||
|
|
||||||
## Update steps
|
|
||||||
|
|
||||||
1. `scripts/sync-upstream.sh origin/master`
|
|
||||||
2. Review upstream diff impact (API, DB changes, compile behavior)
|
|
||||||
3. Rebuild wasm assets
|
|
||||||
4. Run tests
|
|
||||||
5. Update this file with new commit metadata
|
|
||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
Binary file not shown.
@@ -0,0 +1,308 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
/**
|
||||||
|
* Builds the lens profile database the editor ships.
|
||||||
|
*
|
||||||
|
* The calibration measurements come from the Lensfun project's database
|
||||||
|
* (CC BY-SA 3.0, © Lensfun contributors); this script only converts the XML
|
||||||
|
* into the compact form `src/lib/lensDb.ts` reads, so the app no longer needs
|
||||||
|
* the Lensfun WebAssembly runtime. Data, not code: the maths lives in
|
||||||
|
* `src/lib/lensEngine.ts`.
|
||||||
|
*
|
||||||
|
* Usage:
|
||||||
|
* node scripts/build-lens-db.mjs --db <lensfun/data/db> [--out <file>]
|
||||||
|
*
|
||||||
|
* `--db` is a checkout of https://github.com/lensfun/lensfun at the pinned commit
|
||||||
|
* recorded in `public/lens-db/NOTICE.md`; only its `data/db/*.xml` files are read.
|
||||||
|
* The generated file is committed, so a normal build does not need the checkout.
|
||||||
|
*/
|
||||||
|
import { readFileSync, writeFileSync, readdirSync, mkdirSync, existsSync } from 'node:fs';
|
||||||
|
import { dirname, join, resolve } from 'node:path';
|
||||||
|
|
||||||
|
const DIST_MODELS = ['poly3', 'poly5', 'ptlens', 'linear', 'acm'];
|
||||||
|
const TCA_MODELS = ['poly3', 'linear', 'acm'];
|
||||||
|
|
||||||
|
const args = process.argv.slice(2);
|
||||||
|
const argValue = (name, fallback) => {
|
||||||
|
const at = args.indexOf(name);
|
||||||
|
return at >= 0 && args[at + 1] ? args[at + 1] : fallback;
|
||||||
|
};
|
||||||
|
const DB_DIR = argValue('--db', '');
|
||||||
|
const OUT = resolve(argValue('--out', 'public/lens-db/profiles.json'));
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ parsing */
|
||||||
|
|
||||||
|
/** Rounds to six decimals and drops trailing zeros, to keep the file small. */
|
||||||
|
function round(n) {
|
||||||
|
return Number.isFinite(n) ? Math.round(n * 1e6) / 1e6 : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function num(value) {
|
||||||
|
if (value == null || value === '') return 0;
|
||||||
|
return round(Number(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "3:2" or "1.5" as a number, 0 when absent so the engine can use the image. */
|
||||||
|
function aspectRatio(value) {
|
||||||
|
if (!value) return 0;
|
||||||
|
const parts = value.split(':').map(Number);
|
||||||
|
if (parts.length === 2 && parts[0] > 0 && parts[1] > 0) return round(parts[0] / parts[1]);
|
||||||
|
return num(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
const TAG = /<(\/?)([a-zA-Z0-9_:.-]+)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
|
||||||
|
const ATTR = /([a-zA-Z0-9_:.-]+)\s*=\s*("([^"]*)"|'([^']*)')/g;
|
||||||
|
|
||||||
|
function attributes(source) {
|
||||||
|
const out = {};
|
||||||
|
for (const match of source.matchAll(ATTR)) {
|
||||||
|
out[match[1]] = decode(match[3] ?? match[4] ?? '');
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Minimal XML reader for the Lensfun schema: elements, attributes and text.
|
||||||
|
* Comments and the doctype are skipped; nothing here needs namespaces,
|
||||||
|
* entities beyond the five predefined ones, or CDATA.
|
||||||
|
*/
|
||||||
|
function parseXml(source) {
|
||||||
|
// Comments carry prose (and markup examples) that must not reach the tag
|
||||||
|
// scanner, or they unbalance the element stack.
|
||||||
|
const xml = source.replace(/<!--[\s\S]*?-->/g, '');
|
||||||
|
const root = { name: '#root', attrs: {}, children: [], text: '' };
|
||||||
|
const stack = [root];
|
||||||
|
let cursor = 0;
|
||||||
|
TAG.lastIndex = 0;
|
||||||
|
for (let match = TAG.exec(xml); match; match = TAG.exec(xml)) {
|
||||||
|
const [whole, closing, name, rawAttrs, selfClosing] = match;
|
||||||
|
const between = xml.slice(cursor, match.index);
|
||||||
|
cursor = match.index + whole.length;
|
||||||
|
if (between.trim()) stack[stack.length - 1].text += decode(between.trim());
|
||||||
|
if (closing) {
|
||||||
|
if (stack.length > 1) stack.pop();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const node = { name, attrs: attributes(rawAttrs), children: [], text: '' };
|
||||||
|
stack[stack.length - 1].children.push(node);
|
||||||
|
if (!selfClosing) stack.push(node);
|
||||||
|
}
|
||||||
|
return root;
|
||||||
|
}
|
||||||
|
|
||||||
|
function decode(text) {
|
||||||
|
return text
|
||||||
|
.replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>')
|
||||||
|
.replace(/"/g, '"')
|
||||||
|
.replace(/'/g, "'")
|
||||||
|
.replace(/&/g, '&');
|
||||||
|
}
|
||||||
|
|
||||||
|
const kids = (node, name) => node.children.filter((child) => child.name === name);
|
||||||
|
const kid = (node, name) => kids(node, name)[0];
|
||||||
|
const text = (node) => (node ? node.text.trim() : '');
|
||||||
|
|
||||||
|
/** Picks the untagged value, falling back to English. */
|
||||||
|
function localized(node, name) {
|
||||||
|
const all = kids(node, name);
|
||||||
|
if (!all.length) return '';
|
||||||
|
const plain = all.find((entry) => !entry.attrs.lang);
|
||||||
|
if (plain) return text(plain);
|
||||||
|
const english = all.find((entry) => entry.attrs.lang === 'en' || entry.attrs.lang === 'en_US');
|
||||||
|
return text(english ?? all[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --------------------------------------------------------------- conversion */
|
||||||
|
|
||||||
|
function convertFile(xml, db) {
|
||||||
|
const doc = parseXml(xml);
|
||||||
|
const root = kid(doc, 'lensdatabase');
|
||||||
|
if (!root) return;
|
||||||
|
|
||||||
|
for (const mount of kids(root, 'mount')) {
|
||||||
|
const name = text(kid(mount, 'name'));
|
||||||
|
if (name) db.mounts.add(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const camera of kids(root, 'camera')) {
|
||||||
|
const maker = localized(camera, 'maker');
|
||||||
|
const model = localized(camera, 'model');
|
||||||
|
if (!maker || !model) continue;
|
||||||
|
db.cameras.push({ maker, model, mount: text(kid(camera, 'mount')), crop: num(text(kid(camera, 'cropfactor'))) || 1 });
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const lens of kids(root, 'lens')) {
|
||||||
|
const maker = localized(lens, 'maker');
|
||||||
|
const model = localized(lens, 'model');
|
||||||
|
if (!maker || !model) continue;
|
||||||
|
const record = {
|
||||||
|
maker,
|
||||||
|
model,
|
||||||
|
crop: num(text(kid(lens, 'cropfactor'))) || 1,
|
||||||
|
mounts: kids(lens, 'mount').map((entry) => text(entry)).filter(Boolean),
|
||||||
|
aspect: aspectRatio(text(kid(lens, 'aspect-ratio'))),
|
||||||
|
centerX: num(text(kid(lens, 'center-x'))),
|
||||||
|
centerY: num(text(kid(lens, 'center-y'))),
|
||||||
|
d: [],
|
||||||
|
t: [],
|
||||||
|
v: [],
|
||||||
|
};
|
||||||
|
const calibration = kid(lens, 'calibration');
|
||||||
|
if (calibration) {
|
||||||
|
for (const entry of kids(calibration, 'distortion')) {
|
||||||
|
const terms = distortionTerms(entry);
|
||||||
|
if (!terms) continue;
|
||||||
|
// A few calibrations were measured at a focal length other than the
|
||||||
|
// nominal one; Lensfun scales by the ratio, so keep it (0 = same focal).
|
||||||
|
record.d.push([
|
||||||
|
num(entry.attrs.focal),
|
||||||
|
terms.model,
|
||||||
|
...terms.terms,
|
||||||
|
num(entry.attrs['real-focal']),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
for (const entry of kids(calibration, 'tca')) {
|
||||||
|
const terms = tcaTerms(entry);
|
||||||
|
if (!terms) continue;
|
||||||
|
record.t.push([num(entry.attrs.focal), terms.model, ...terms.terms]);
|
||||||
|
}
|
||||||
|
for (const entry of kids(calibration, 'vignetting')) {
|
||||||
|
const model = entry.attrs.model;
|
||||||
|
if (model !== 'pa' && model !== 'acm') continue;
|
||||||
|
record.v.push([
|
||||||
|
num(entry.attrs.focal),
|
||||||
|
num(entry.attrs.aperture),
|
||||||
|
num(entry.attrs.distance),
|
||||||
|
num(entry.attrs.k1),
|
||||||
|
num(entry.attrs.k2),
|
||||||
|
num(entry.attrs.k3),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
db.stats.lenses += 1;
|
||||||
|
if (record.d.length || record.t.length || record.v.length) db.lenses.push(record);
|
||||||
|
else db.stats.withoutCalibration += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lensfun stores poly3 as `k1`, polygon (poly5) as `k1`/`k2`, and PanoTools as
|
||||||
|
* `a`/`b`/`c`. Everything is normalised to the `a·r³ + b·r² + c·r + 1` form the
|
||||||
|
* engine evaluates, with the PanoTools `d = 1 - a - b - c` factor divided out
|
||||||
|
* the way Lensfun does so the focal length is preserved.
|
||||||
|
*/
|
||||||
|
function distortionTerms(entry) {
|
||||||
|
const attrs = entry.attrs;
|
||||||
|
switch (attrs.model) {
|
||||||
|
case 'poly3': {
|
||||||
|
const k1 = num(attrs.k1);
|
||||||
|
const d = 1 - k1;
|
||||||
|
return { model: DIST_MODELS.indexOf('poly3'), terms: [0, round(k1 / d ** 3), 0] };
|
||||||
|
}
|
||||||
|
case 'poly5':
|
||||||
|
return { model: DIST_MODELS.indexOf('poly5'), terms: [0, num(attrs.k1), num(attrs.k2)] };
|
||||||
|
case 'ptlens': {
|
||||||
|
const a = num(attrs.a);
|
||||||
|
const b = num(attrs.b);
|
||||||
|
const c = num(attrs.c);
|
||||||
|
const d = 1 - a - b - c;
|
||||||
|
return {
|
||||||
|
model: DIST_MODELS.indexOf('ptlens'),
|
||||||
|
terms: [round(a / d ** 4), round(b / d ** 3), round(c / d ** 2)],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
case 'linear':
|
||||||
|
return { model: DIST_MODELS.indexOf('linear'), terms: [0, 0, 0] };
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function tcaTerms(entry) {
|
||||||
|
const attrs = entry.attrs;
|
||||||
|
if (attrs.model === 'poly3') {
|
||||||
|
// Stored per channel as [br, cr, vr] / [bb, cb, vb], matching the term
|
||||||
|
// order the engine evaluates: r_d = r * (v + c*r + b*r^2).
|
||||||
|
return {
|
||||||
|
model: TCA_MODELS.indexOf('poly3'),
|
||||||
|
terms: [num(attrs.br), num(attrs.cr), num(attrs.vr || 1), num(attrs.bb), num(attrs.cb), num(attrs.vb || 1)],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (attrs.model === 'linear') {
|
||||||
|
return { model: TCA_MODELS.indexOf('linear'), terms: [num(attrs.kr || 1), num(attrs.kb || 1)] };
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --------------------------------------------------------------------- main */
|
||||||
|
|
||||||
|
function loadXmlFiles() {
|
||||||
|
if (!DB_DIR) {
|
||||||
|
throw new Error(
|
||||||
|
'pass --db <path to lensfun/data/db>; the profiles are committed, so this is only ' +
|
||||||
|
'needed when refreshing them',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const dir = resolve(DB_DIR);
|
||||||
|
if (!existsSync(dir)) throw new Error(`database directory not found: ${dir}`);
|
||||||
|
return readdirSync(dir)
|
||||||
|
.filter((name) => name.endsWith('.xml'))
|
||||||
|
.sort()
|
||||||
|
.map((name) => readFileSync(join(dir, name), 'utf8'));
|
||||||
|
}
|
||||||
|
|
||||||
|
const db = { mounts: new Set(), cameras: [], lenses: [], stats: { lenses: 0, withoutCalibration: 0 } };
|
||||||
|
for (const xml of loadXmlFiles()) {
|
||||||
|
try {
|
||||||
|
convertFile(xml, db);
|
||||||
|
} catch (err) {
|
||||||
|
console.warn(`skipped a database file: ${err.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const slug = (value) =>
|
||||||
|
value
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/[^a-z0-9]+/g, '-')
|
||||||
|
.replace(/^-|-$/g, '');
|
||||||
|
|
||||||
|
const seen = new Map();
|
||||||
|
const lenses = db.lenses.map((lens) => {
|
||||||
|
const base = `${slug(lens.maker)}-${slug(lens.model)}`;
|
||||||
|
const count = (seen.get(base) ?? 0) + 1;
|
||||||
|
seen.set(base, count);
|
||||||
|
return {
|
||||||
|
id: count === 1 ? base : `${base}-${count}`,
|
||||||
|
maker: lens.maker,
|
||||||
|
model: lens.model,
|
||||||
|
crop: lens.crop,
|
||||||
|
mounts: lens.mounts,
|
||||||
|
aspect: lens.aspect,
|
||||||
|
centerX: lens.centerX,
|
||||||
|
centerY: lens.centerY,
|
||||||
|
d: lens.d.sort((a, b) => a[0] - b[0]),
|
||||||
|
t: lens.t.sort((a, b) => a[0] - b[0]),
|
||||||
|
v: lens.v.sort((a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
source: {
|
||||||
|
project: 'lensfun',
|
||||||
|
commit: '655a9c4e3e53c25bc04843c853e7e7a0121359e7',
|
||||||
|
licence: 'CC BY-SA 3.0 Unported',
|
||||||
|
note: 'Calibration data only; the correction maths is Luminary\u2019s own.',
|
||||||
|
},
|
||||||
|
models: { distortion: DIST_MODELS, tca: TCA_MODELS },
|
||||||
|
mounts: [...db.mounts].sort(),
|
||||||
|
cameras: db.cameras.sort((a, b) => a.maker.localeCompare(b.maker) || a.model.localeCompare(b.model)),
|
||||||
|
lenses,
|
||||||
|
};
|
||||||
|
|
||||||
|
mkdirSync(dirname(OUT), { recursive: true });
|
||||||
|
writeFileSync(OUT, `${JSON.stringify(payload)}\n`);
|
||||||
|
console.log(
|
||||||
|
`wrote ${OUT}: ${lenses.length} lenses with calibration (${db.stats.withoutCalibration} of ` +
|
||||||
|
`${db.stats.lenses} entries have none), ${payload.cameras.length} cameras, ` +
|
||||||
|
`${lenses.reduce((n, lens) => n + lens.v.length, 0)} vignetting samples`,
|
||||||
|
);
|
||||||
@@ -2294,6 +2294,8 @@ const MIME = {
|
|||||||
'.ico': 'image/x-icon',
|
'.ico': 'image/x-icon',
|
||||||
'.woff2': 'font/woff2',
|
'.woff2': 'font/woff2',
|
||||||
'.map': 'application/json; charset=utf-8',
|
'.map': 'application/json; charset=utf-8',
|
||||||
|
// Served for any WebAssembly asset that ends up in the build output.
|
||||||
|
'.wasm': 'application/wasm',
|
||||||
};
|
};
|
||||||
|
|
||||||
async function serveStatic(req, res, url) {
|
async function serveStatic(req, res, url) {
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from 'react';
|
|||||||
import { get16BitSource, getBitmap } from '../lib/images';
|
import { get16BitSource, getBitmap } from '../lib/images';
|
||||||
import type { Preview16 } from '../lib/preview16';
|
import type { Preview16 } from '../lib/preview16';
|
||||||
import { rotatedBounds, Renderer } from '../gl/renderer';
|
import { rotatedBounds, Renderer } from '../gl/renderer';
|
||||||
import { buildLensCorrection, type LensCorrection } from '../lib/lensfun';
|
import { buildLensCorrection, type LensCorrection } from '../lib/lensEngine';
|
||||||
import type { PhotoRecord } from '../types';
|
import type { PhotoRecord } from '../types';
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ import {
|
|||||||
correctLensPoint,
|
correctLensPoint,
|
||||||
uncorrectLensPoint,
|
uncorrectLensPoint,
|
||||||
type LensCorrection,
|
type LensCorrection,
|
||||||
} from '../lib/lensfun';
|
} from '../lib/lensEngine';
|
||||||
import {
|
import {
|
||||||
frameToSource,
|
frameToSource,
|
||||||
rotatedBounds,
|
rotatedBounds,
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ import {
|
|||||||
type SavedCameraProfile,
|
type SavedCameraProfile,
|
||||||
} from '../lib/dcpLibrary';
|
} from '../lib/dcpLibrary';
|
||||||
import { usePresetThumbs } from './PresetThumbs';
|
import { usePresetThumbs } from './PresetThumbs';
|
||||||
import { availableFor, findLensForMeta, searchLens, type LensSearchResult } from '../lib/lensfun';
|
import { availableFor, findLensForMeta, searchLens, type LensSearchResult } from '../lib/lensDb';
|
||||||
import {
|
import {
|
||||||
getCameraLensDefault,
|
getCameraLensDefault,
|
||||||
removeCameraLensDefault,
|
removeCameraLensDefault,
|
||||||
@@ -1905,8 +1905,9 @@ export function OpticsPanel({
|
|||||||
};
|
};
|
||||||
}, [profile]);
|
}, [profile]);
|
||||||
|
|
||||||
const applyProfile = (result: Pick<LensSearchResult, 'maker' | 'model' | 'crop'>) => {
|
const applyProfile = (result: Pick<LensSearchResult, 'id' | 'maker' | 'model' | 'crop'>) => {
|
||||||
const next: LensProfile = {
|
const next: LensProfile = {
|
||||||
|
id: result.id,
|
||||||
maker: result.maker,
|
maker: result.maker,
|
||||||
model: result.model,
|
model: result.model,
|
||||||
crop: result.crop,
|
crop: result.crop,
|
||||||
|
|||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
import type { LensCorrection } from '../lib/lensfun';
|
import type { LensCorrection } from '../lib/lensEngine';
|
||||||
import type { Preview16 } from '../lib/preview16';
|
import type { Preview16 } from '../lib/preview16';
|
||||||
import type { Edits, GeometryEdits } from '../types';
|
import type { Edits, GeometryEdits } from '../types';
|
||||||
import { buildSampler, clamp01 } from '../lib/curves';
|
import { buildSampler, clamp01 } from '../lib/curves';
|
||||||
|
|||||||
Vendored
-83
@@ -1,83 +0,0 @@
|
|||||||
/**
|
|
||||||
* The published package's `types` entry points at a file that is not shipped in
|
|
||||||
* 0.1.3, so declare the small surface we use here.
|
|
||||||
*/
|
|
||||||
declare module '@neoanaloglabkk/lensfun-wasm' {
|
|
||||||
export interface LensfunInitOptions {
|
|
||||||
moduleFactory?: (options?: Record<string, unknown>) => Promise<unknown>;
|
|
||||||
moduleJsUrl?: string;
|
|
||||||
wasmUrl?: string;
|
|
||||||
dataUrl?: string;
|
|
||||||
dbPath?: string;
|
|
||||||
autoInitDb?: boolean;
|
|
||||||
locateFile?: (path: string, prefix: string) => string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface LensMatch {
|
|
||||||
handle: number;
|
|
||||||
maker: string;
|
|
||||||
model: string;
|
|
||||||
score: number;
|
|
||||||
minFocal: number;
|
|
||||||
maxFocal: number;
|
|
||||||
minAperture: number;
|
|
||||||
maxAperture: number;
|
|
||||||
cropFactor: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface CameraMatch {
|
|
||||||
maker: string;
|
|
||||||
model: string;
|
|
||||||
variant: string;
|
|
||||||
mount: string;
|
|
||||||
cropFactor: number;
|
|
||||||
score: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface SearchLensesInput {
|
|
||||||
lensMaker?: string;
|
|
||||||
lensModel: string;
|
|
||||||
cameraMaker?: string;
|
|
||||||
cameraModel?: string;
|
|
||||||
searchFlags?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface SearchCamerasInput {
|
|
||||||
maker?: string;
|
|
||||||
model?: string;
|
|
||||||
searchFlags?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface CorrectionInput {
|
|
||||||
lensHandle: number;
|
|
||||||
width: number;
|
|
||||||
height: number;
|
|
||||||
focal: number;
|
|
||||||
crop: number;
|
|
||||||
step?: number;
|
|
||||||
reverse?: boolean;
|
|
||||||
includeTca?: boolean;
|
|
||||||
includeVignetting?: boolean;
|
|
||||||
aperture?: number;
|
|
||||||
distance?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface CorrectionMaps {
|
|
||||||
gridWidth: number;
|
|
||||||
gridHeight: number;
|
|
||||||
step: number;
|
|
||||||
geometry: Float32Array;
|
|
||||||
tca?: Float32Array;
|
|
||||||
vignetting?: Float32Array;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface LensfunClient {
|
|
||||||
dispose(): void;
|
|
||||||
searchLenses(input: SearchLensesInput): LensMatch[];
|
|
||||||
searchCameras(input: SearchCamerasInput): CameraMatch[];
|
|
||||||
getAvailableModifications(lensHandle: number, crop: number): number;
|
|
||||||
buildCorrectionMaps(input: CorrectionInput): CorrectionMaps;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function createLensfun(options?: LensfunInitOptions): Promise<LensfunClient>;
|
|
||||||
}
|
|
||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
import type { Edits, PhotoRecord } from '../types';
|
import type { Edits, PhotoRecord } from '../types';
|
||||||
import { get16BitSource, getBitmap } from './images';
|
import { get16BitSource, getBitmap } from './images';
|
||||||
import { normalizeEdits } from './edits';
|
import { normalizeEdits } from './edits';
|
||||||
import { buildLensCorrection } from './lensfun';
|
import { buildLensCorrection } from './lensEngine';
|
||||||
import { outputSize, Renderer } from '../gl/renderer';
|
import { outputSize, Renderer } from '../gl/renderer';
|
||||||
import { getDenoisedBitmap } from './images';
|
import { getDenoisedBitmap } from './images';
|
||||||
import { createZipBlob, zipFileName } from './zip';
|
import { createZipBlob, zipFileName } from './zip';
|
||||||
|
|||||||
@@ -0,0 +1,92 @@
|
|||||||
|
import { beforeAll, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { availableFor, findCamera, findLensForMeta, searchLens, type LensDatabase } from './lensDb';
|
||||||
|
import { fixtureLenses } from './lensEngine.fixture';
|
||||||
|
import type { LensProfile } from '../types';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A miniature database: enough to exercise matching (brand, focal length, exact
|
||||||
|
* model), the mount tie-break and the availability flags without downloading
|
||||||
|
* the real 1.7 MB file.
|
||||||
|
*/
|
||||||
|
const database: LensDatabase = {
|
||||||
|
source: { project: 'lensfun', commit: 'test', licence: 'CC BY-SA 3.0', note: '' },
|
||||||
|
models: { distortion: ['poly3', 'poly5', 'ptlens', 'linear', 'acm'], tca: ['poly3', 'linear', 'acm'] },
|
||||||
|
mounts: ['Nikon F AF', 'Canon EF', 'Canon EF-M'],
|
||||||
|
cameras: [
|
||||||
|
{ maker: 'Nikon Corporation', model: 'Nikon D700', mount: 'Nikon F AF', crop: 1 },
|
||||||
|
{ maker: 'Canon', model: 'Canon EOS R5', mount: 'Canon EF', crop: 1 },
|
||||||
|
],
|
||||||
|
lenses: [
|
||||||
|
...fixtureLenses,
|
||||||
|
{
|
||||||
|
id: 'canon-ef-50mm-f1-8',
|
||||||
|
maker: 'Canon',
|
||||||
|
model: 'Canon EF 50mm f/1.8 STM',
|
||||||
|
crop: 1,
|
||||||
|
mounts: ['Canon EF'],
|
||||||
|
aspect: 0,
|
||||||
|
centerX: 0,
|
||||||
|
centerY: 0,
|
||||||
|
d: [[50, 0, 0, -0.01, 0, 0]],
|
||||||
|
t: [],
|
||||||
|
v: [],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
vi.stubGlobal('fetch', async () => new Response(JSON.stringify(database), { status: 200 }));
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('lens search', () => {
|
||||||
|
it('finds a maker the way people type it', async () => {
|
||||||
|
const results = await searchLens('tamron');
|
||||||
|
expect(results.length).toBeGreaterThan(0);
|
||||||
|
expect(results.every((result) => result.maker === 'Tamron')).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('finds a lens by focal length alone', async () => {
|
||||||
|
const results = await searchLens('28-75');
|
||||||
|
expect(results[0]?.model).toContain('28-75');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('matches an EXIF lens name to a profile', async () => {
|
||||||
|
const match = await findLensForMeta({
|
||||||
|
camera: 'NIKON CORPORATION NIKON D700',
|
||||||
|
lens: 'Tamron SP AF 28-75mm f/2.8 XR Di LD Aspherical (IF) Macro',
|
||||||
|
});
|
||||||
|
expect(match?.maker).toBe('Tamron');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns nothing for a name that is not in the database', async () => {
|
||||||
|
expect(await searchLens('zzzz nonexistent lens')).toEqual([]);
|
||||||
|
expect(await searchLens('')).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('camera lookup', () => {
|
||||||
|
it('reads the mount and crop factor from an EXIF body name', async () => {
|
||||||
|
const camera = await findCamera('NIKON CORPORATION NIKON D700');
|
||||||
|
expect(camera).toMatchObject({ mount: 'Nikon F AF', cropFactor: 1 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps lenses filed under another mount findable', async () => {
|
||||||
|
// The Canon EF 50mm is not a Nikon F lens, but a search must not hide it.
|
||||||
|
const results = await searchLens('canon ef 50mm', { camera: 'NIKON CORPORATION NIKON D700' });
|
||||||
|
expect(results.some((result) => result.model.includes('50mm'))).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('availability', () => {
|
||||||
|
it('reports which corrections a profile supports', async () => {
|
||||||
|
const [tamron] = fixtureLenses;
|
||||||
|
const profile: LensProfile = {
|
||||||
|
maker: tamron.maker,
|
||||||
|
model: tamron.model,
|
||||||
|
crop: tamron.crop,
|
||||||
|
corrections: { distortion: true, tca: true, vignetting: true },
|
||||||
|
};
|
||||||
|
// Distortion, TCA and vignetting all have calibration samples.
|
||||||
|
expect(await availableFor(profile)).toBe(11);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,251 @@
|
|||||||
|
import type { LensProfile, PhotoMeta } from '../types';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lens profiles are built from the Lensfun project's calibration database
|
||||||
|
* (CC BY-SA 3.0, © Lensfun contributors) by `scripts/build-lens-db.mjs`. Only
|
||||||
|
* the measurements come from there; searching, matching and the correction
|
||||||
|
* maths are ours, so the editor ships no WebAssembly runtime and no database
|
||||||
|
* parser.
|
||||||
|
*
|
||||||
|
* The file is fetched the first time the Optics panel, a stored profile or a
|
||||||
|
* lens-corrected export needs it, and then kept in memory.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** [focal, model, a, b, c, realFocal] — a·r³ + b·r² + c·r + 1; 0 = nominal focal */
|
||||||
|
export type DistortionSample = [number, number, number, number, number, number];
|
||||||
|
/** [focal, model, br, cr, vr, bb, cb, vb] — r·(v + c·r + b·r²) per channel */
|
||||||
|
export type TcaSample = [number, number, number, number, number, number, number, number];
|
||||||
|
/** [focal, aperture, distance, k1, k2, k3] */
|
||||||
|
export type VignettingSample = [number, number, number, number, number, number];
|
||||||
|
|
||||||
|
export const DIST_MODEL = { poly3: 0, poly5: 1, ptlens: 2, linear: 3, acm: 4 } as const;
|
||||||
|
export const TCA_MODEL = { poly3: 0, linear: 1, acm: 2 } as const;
|
||||||
|
|
||||||
|
export interface LensEntry {
|
||||||
|
id: string;
|
||||||
|
maker: string;
|
||||||
|
model: string;
|
||||||
|
/** Crop factor the calibration was measured at. */
|
||||||
|
crop: number;
|
||||||
|
mounts: string[];
|
||||||
|
/** Calibration sensor aspect ratio, 0 when the database does not say. */
|
||||||
|
aspect: number;
|
||||||
|
centerX: number;
|
||||||
|
centerY: number;
|
||||||
|
d: DistortionSample[];
|
||||||
|
t: TcaSample[];
|
||||||
|
v: VignettingSample[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CameraEntry {
|
||||||
|
maker: string;
|
||||||
|
model: string;
|
||||||
|
mount: string;
|
||||||
|
crop: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LensDatabase {
|
||||||
|
source: { project: string; commit: string; licence: string; note: string };
|
||||||
|
models: { distortion: string[]; tca: string[] };
|
||||||
|
mounts: string[];
|
||||||
|
cameras: CameraEntry[];
|
||||||
|
lenses: LensEntry[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CameraMatch {
|
||||||
|
maker: string;
|
||||||
|
model: string;
|
||||||
|
mount: string;
|
||||||
|
cropFactor: number;
|
||||||
|
score: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LensSearchResult {
|
||||||
|
id: string;
|
||||||
|
maker: string;
|
||||||
|
model: string;
|
||||||
|
crop: number;
|
||||||
|
score: number;
|
||||||
|
/** Bit mask of the corrections the calibration supports. */
|
||||||
|
available: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const FLAG_TCA = 1;
|
||||||
|
export const FLAG_VIGNETTING = 2;
|
||||||
|
export const FLAG_DISTORTION = 8;
|
||||||
|
|
||||||
|
let databasePromise: Promise<LensDatabase> | null = null;
|
||||||
|
|
||||||
|
export function loadLensDatabase(): Promise<LensDatabase> {
|
||||||
|
if (!databasePromise) {
|
||||||
|
databasePromise = fetch('/lens-db/profiles.json')
|
||||||
|
.then((response) => {
|
||||||
|
if (!response.ok) throw new Error(`The lens database could not be loaded (${response.status})`);
|
||||||
|
return response.json() as Promise<LensDatabase>;
|
||||||
|
})
|
||||||
|
.catch((err) => {
|
||||||
|
databasePromise = null;
|
||||||
|
throw err;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return databasePromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Available corrections for a profile, matching the flags the renderer uses. */
|
||||||
|
export function availableFlags(entry: LensEntry): number {
|
||||||
|
return (
|
||||||
|
(entry.d.length ? FLAG_DISTORTION : 0) |
|
||||||
|
(entry.t.length ? FLAG_TCA : 0) |
|
||||||
|
(entry.v.length ? FLAG_VIGNETTING : 0)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function toResult(entry: LensEntry, score = 0): LensSearchResult {
|
||||||
|
return {
|
||||||
|
id: entry.id,
|
||||||
|
maker: entry.maker,
|
||||||
|
model: entry.model,
|
||||||
|
crop: entry.crop,
|
||||||
|
score,
|
||||||
|
available: availableFlags(entry),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ matching */
|
||||||
|
|
||||||
|
/** Lowercase word tokens, with units folded so "28-75mm" meets "28-75". */
|
||||||
|
function tokens(value: string): string[] {
|
||||||
|
return value
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/[^a-z0-9]+/g, ' ')
|
||||||
|
.trim()
|
||||||
|
.split(' ')
|
||||||
|
.filter(Boolean)
|
||||||
|
.map((token) => token.replace(/mm$/, '').replace(/^f(?=\d)/, ''));
|
||||||
|
}
|
||||||
|
|
||||||
|
function coverage(query: string[], target: Set<string>): number {
|
||||||
|
if (!query.length) return 0;
|
||||||
|
let hit = 0;
|
||||||
|
for (const token of query) if (target.has(token)) hit += 1;
|
||||||
|
return hit / query.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 3 for an exact model, otherwise the fraction of query words the entry covers,
|
||||||
|
* with a small bonus when every word matches. Both maker and model count, so
|
||||||
|
* "tamron" finds Tamron glass without needing the focal length.
|
||||||
|
*/
|
||||||
|
function scoreEntry(entry: LensEntry, variants: string[]): number {
|
||||||
|
const target = new Set([...tokens(entry.maker), ...tokens(entry.model)]);
|
||||||
|
const maker = tokens(entry.maker);
|
||||||
|
const model = tokens(entry.model);
|
||||||
|
let best = 0;
|
||||||
|
for (const variant of variants) {
|
||||||
|
const query = tokens(variant);
|
||||||
|
if (!query.length) continue;
|
||||||
|
const name = [...maker, ...model].join(' ');
|
||||||
|
if (query.join(' ') === name || query.join(' ') === model.join(' ')) return 3;
|
||||||
|
const hit = coverage(query, target);
|
||||||
|
best = Math.max(best, hit >= 1 ? 1.25 : hit);
|
||||||
|
}
|
||||||
|
return best;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Variants of the query worth matching: as typed, plus unit-normalised forms. */
|
||||||
|
function queryVariants(query: string): string[] {
|
||||||
|
const raw = query.trim();
|
||||||
|
if (raw.length < 2) return [];
|
||||||
|
const compact = raw.replace(/(\d)\s*mm\b/gi, '$1mm').replace(/\s+/g, ' ');
|
||||||
|
return [...new Set([raw, compact, compact.replace(/\s+/g, '')])].filter((text) => text.length >= 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------- queries */
|
||||||
|
|
||||||
|
export async function searchLens(
|
||||||
|
query: string,
|
||||||
|
meta?: Pick<PhotoMeta, 'camera' | 'lens'>,
|
||||||
|
): Promise<LensSearchResult[]> {
|
||||||
|
const variants = queryVariants(query);
|
||||||
|
if (!variants.length) return [];
|
||||||
|
const db = await loadLensDatabase();
|
||||||
|
const camera = await findCamera(meta?.camera);
|
||||||
|
const mount = camera?.mount ?? '';
|
||||||
|
const scored: { entry: LensEntry; score: number }[] = [];
|
||||||
|
for (const entry of db.lenses) {
|
||||||
|
const score = scoreEntry(entry, variants);
|
||||||
|
if (score < 0.5) continue;
|
||||||
|
// A mount the camera actually uses is a tie-break, never a filter: a
|
||||||
|
// profile that is in the database but filed under another mount must still
|
||||||
|
// be findable.
|
||||||
|
const fits = mount && entry.mounts.includes(mount) ? 0.3 : 0;
|
||||||
|
scored.push({ entry, score: score + fits });
|
||||||
|
}
|
||||||
|
scored.sort((a, b) => b.score - a.score || a.entry.model.length - b.entry.model.length);
|
||||||
|
return scored.slice(0, 20).map(({ entry, score }) => toResult(entry, Math.min(3, score)));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function findLensForMeta(
|
||||||
|
meta: Pick<PhotoMeta, 'camera' | 'lens'>,
|
||||||
|
): Promise<LensSearchResult | null> {
|
||||||
|
if (!meta.lens) return null;
|
||||||
|
const results = await searchLens(meta.lens, meta);
|
||||||
|
return results.find((result) => result.score >= 0.75) ?? results[0] ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const cameraCache = new Map<string, CameraMatch | null>();
|
||||||
|
|
||||||
|
export async function findCamera(camera?: string): Promise<CameraMatch | null> {
|
||||||
|
if (!camera) return null;
|
||||||
|
const cached = cameraCache.get(camera);
|
||||||
|
if (cached !== undefined) return cached;
|
||||||
|
const db = await loadLensDatabase();
|
||||||
|
const query = tokens(camera);
|
||||||
|
let best: CameraMatch | null = null;
|
||||||
|
let bestScore = 0;
|
||||||
|
for (const entry of db.cameras) {
|
||||||
|
const target = new Set([...tokens(entry.maker), ...tokens(entry.model)]);
|
||||||
|
// Ignore the maker prefix the EXIF repeats, e.g. "NIKON CORPORATION".
|
||||||
|
const model = tokens(entry.model);
|
||||||
|
const score = Math.max(coverage(query, target), coverage(model, target) * 0.9);
|
||||||
|
if (score > bestScore) {
|
||||||
|
bestScore = score;
|
||||||
|
best = {
|
||||||
|
maker: entry.maker,
|
||||||
|
model: entry.model,
|
||||||
|
mount: entry.mount,
|
||||||
|
cropFactor: entry.crop,
|
||||||
|
score,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const match = bestScore >= 0.6 ? best : null;
|
||||||
|
cameraCache.set(camera, match);
|
||||||
|
return match;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Exact entry for a stored profile, falling back to the closest name match. */
|
||||||
|
export async function getLensEntry(profile: LensProfile): Promise<LensEntry | null> {
|
||||||
|
const db = await loadLensDatabase();
|
||||||
|
if (profile.id) {
|
||||||
|
const byId = db.lenses.find((entry) => entry.id === profile.id);
|
||||||
|
if (byId) return byId;
|
||||||
|
}
|
||||||
|
const maker = profile.maker.trim().toLowerCase();
|
||||||
|
const model = profile.model.trim().toLowerCase();
|
||||||
|
const exact = db.lenses.find(
|
||||||
|
(entry) => entry.maker.toLowerCase() === maker && entry.model.toLowerCase() === model,
|
||||||
|
);
|
||||||
|
if (exact) return exact;
|
||||||
|
const sameModel = db.lenses.filter((entry) => entry.model.toLowerCase() === model);
|
||||||
|
if (sameModel.length === 1) return sameModel[0];
|
||||||
|
const scored = db.lenses
|
||||||
|
.map((entry) => ({ entry, score: scoreEntry(entry, [profile.model, `${profile.maker} ${profile.model}`]) }))
|
||||||
|
.sort((a, b) => b.score - a.score);
|
||||||
|
return scored[0] && scored[0].score >= 0.5 ? scored[0].entry : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function availableFor(profile: LensProfile): Promise<number> {
|
||||||
|
const entry = await getLensEntry(profile);
|
||||||
|
return entry ? availableFlags(entry) : 0;
|
||||||
|
}
|
||||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,91 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { autoScaleFor, computeMaps, type LensCorrection, type LensMap } from './lensEngine';
|
||||||
|
import { fixtureLenses, referenceCases } from './lensEngine.fixture';
|
||||||
|
|
||||||
|
const GRID = { width: 64, height: 43 };
|
||||||
|
|
||||||
|
function mapsFor(model: string, focal: number, aperture: number) {
|
||||||
|
const entry = fixtureLenses.find((lens) => lens.model === model);
|
||||||
|
expect(entry, model).toBeTruthy();
|
||||||
|
return computeMaps(entry!, {
|
||||||
|
...GRID,
|
||||||
|
focal,
|
||||||
|
crop: entry!.crop,
|
||||||
|
aperture,
|
||||||
|
distance: 1000,
|
||||||
|
distortion: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The reference values were captured from the Lensfun WebAssembly build this
|
||||||
|
* engine replaced, at 25 points of a 64x43 grid. Matching them proves the ported
|
||||||
|
* models (PanoTools and poly3 distortion, poly3 TCA, pa vignetting) agree with
|
||||||
|
* what the editor used to render.
|
||||||
|
*/
|
||||||
|
describe('lens engine matches the reference implementation', () => {
|
||||||
|
for (const testCase of referenceCases) {
|
||||||
|
it(`corrects ${testCase.model} the same way`, () => {
|
||||||
|
const maps = mapsFor(testCase.model, testCase.focal, testCase.aperture);
|
||||||
|
for (const point of testCase.points) {
|
||||||
|
const index = point.y * GRID.width + point.x;
|
||||||
|
const where = `${testCase.key} at ${point.x},${point.y}`;
|
||||||
|
expect(maps.geometry[index * 2], `${where} x`).toBeCloseTo(point.g[0], 3);
|
||||||
|
expect(maps.geometry[index * 2 + 1], `${where} y`).toBeCloseTo(point.g[1], 3);
|
||||||
|
if (point.t && maps.tca) {
|
||||||
|
expect(maps.tca[index * 6], `${where} red x`).toBeCloseTo(point.t[0], 3);
|
||||||
|
expect(maps.tca[index * 6 + 1], `${where} red y`).toBeCloseTo(point.t[1], 3);
|
||||||
|
expect(maps.tca[index * 6 + 4], `${where} blue x`).toBeCloseTo(point.t[2], 3);
|
||||||
|
expect(maps.tca[index * 6 + 5], `${where} blue y`).toBeCloseTo(point.t[3], 3);
|
||||||
|
}
|
||||||
|
if (point.v != null && maps.vignetting) {
|
||||||
|
expect(maps.vignetting[index * 3], `${where} gain`).toBeCloseTo(point.v, 3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('lens engine basics', () => {
|
||||||
|
it('leaves coordinates untouched when the calibration has no distortion', () => {
|
||||||
|
const entry = { ...fixtureLenses[0], d: [] };
|
||||||
|
const maps = computeMaps(entry, { ...GRID, focal: 50, crop: entry.crop, distortion: true });
|
||||||
|
for (const [x, y] of [
|
||||||
|
[0, 0],
|
||||||
|
[31, 21],
|
||||||
|
[63, 42],
|
||||||
|
]) {
|
||||||
|
const index = y * GRID.width + x;
|
||||||
|
expect(maps.geometry[index * 2]).toBeCloseTo(x, 3);
|
||||||
|
expect(maps.geometry[index * 2 + 1]).toBeCloseTo(y, 3);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('only emits the maps the calibration and the toggles ask for', () => {
|
||||||
|
const entry = fixtureLenses[0];
|
||||||
|
const plain = computeMaps(entry, { ...GRID, focal: 50, crop: entry.crop, distortion: false });
|
||||||
|
expect(plain.tca).toBeUndefined();
|
||||||
|
|
||||||
|
const cooled = computeMaps(entry, { ...GRID, focal: 28, crop: entry.crop, aperture: 2.8, distortion: true });
|
||||||
|
expect(cooled.tca?.length).toBe(GRID.width * GRID.height * 6);
|
||||||
|
expect(cooled.vignetting?.length).toBe(GRID.width * GRID.height * 3);
|
||||||
|
// Flat-field gains brighten the corners of a vignetted lens.
|
||||||
|
expect(cooled.vignetting![0]).toBeGreaterThan(cooled.vignetting![(21 * GRID.width + 31) * 3]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('scales up when the correction samples outside the frame', () => {
|
||||||
|
const geometry: LensMap = {
|
||||||
|
width: 3,
|
||||||
|
height: 3,
|
||||||
|
// Every sample points slightly outside the image.
|
||||||
|
data: new Float32Array(3 * 3 * 4),
|
||||||
|
};
|
||||||
|
for (let i = 0; i < 3 * 3; i++) {
|
||||||
|
geometry.data[i * 4] = -0.1;
|
||||||
|
geometry.data[i * 4 + 1] = -0.1;
|
||||||
|
geometry.data[i * 4 + 3] = 1;
|
||||||
|
}
|
||||||
|
const correction: LensCorrection = { key: 'test', geometry, scale: 1 };
|
||||||
|
expect(autoScaleFor(correction.geometry)).toBeGreaterThan(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,448 @@
|
|||||||
|
import {
|
||||||
|
DIST_MODEL,
|
||||||
|
TCA_MODEL,
|
||||||
|
getLensEntry,
|
||||||
|
type DistortionSample,
|
||||||
|
type LensEntry,
|
||||||
|
type TcaSample,
|
||||||
|
type VignettingSample,
|
||||||
|
} from './lensDb';
|
||||||
|
import type { LensProfile, PhotoMeta } from '../types';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lens correction without Lensfun's runtime.
|
||||||
|
*
|
||||||
|
* The calibration data comes from the Lensfun database (see `lensDb.ts`); the
|
||||||
|
* maths below is a port of the models it describes, evaluated in the same
|
||||||
|
* normalised coordinate system so results match what the previous WebAssembly
|
||||||
|
* build produced:
|
||||||
|
*
|
||||||
|
* norm = (36, 24) diagonal / crop / hypot(width + 1, height + 1) / focal
|
||||||
|
* x = column * norm - centreX
|
||||||
|
*
|
||||||
|
* Distortion maps sample the original image for each corrected pixel, TCA maps
|
||||||
|
* carry per-channel positions, and the vignetting map is a flat-field gain.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export interface LensMap {
|
||||||
|
data: Float32Array;
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LensCorrection {
|
||||||
|
key: string;
|
||||||
|
geometry: LensMap;
|
||||||
|
/** RG offsets: red dx, red dy, blue dx, blue dy, normalized source units. */
|
||||||
|
tca?: LensMap;
|
||||||
|
/** RGB vignetting gains. */
|
||||||
|
vignette?: LensMap;
|
||||||
|
/** Centre zoom needed to hide transformed corners. */
|
||||||
|
scale: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
const SENSOR_DIAGONAL = Math.hypot(36, 24);
|
||||||
|
const DEFAULT_ASPECT = 3 / 2;
|
||||||
|
|
||||||
|
const correctionCache = new Map<string, LensCorrection>();
|
||||||
|
|
||||||
|
function clampAspect(entry: LensEntry) {
|
||||||
|
return entry.aspect > 0 ? entry.aspect : DEFAULT_ASPECT;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Lensfun rescales each coefficient by focal / half-diagonal, per model. */
|
||||||
|
function distortionScale(entry: LensEntry, realFocal: number) {
|
||||||
|
const halfDiagonalMm = SENSOR_DIAGONAL / entry.crop / Math.hypot(clampAspect(entry), 1) / 2;
|
||||||
|
return realFocal / halfDiagonalMm;
|
||||||
|
}
|
||||||
|
|
||||||
|
function vignettingScale(entry: LensEntry, focal: number) {
|
||||||
|
const halfDiagonalMm = SENSOR_DIAGONAL / entry.crop / 2;
|
||||||
|
return focal / halfDiagonalMm;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------- interpolation */
|
||||||
|
|
||||||
|
function pickDistortion(entry: LensEntry, focal: number): DistortionSample | null {
|
||||||
|
const samples = entry.d;
|
||||||
|
if (!samples.length) return null;
|
||||||
|
return nearestByFocal(samples, focal);
|
||||||
|
}
|
||||||
|
|
||||||
|
function pickTca(entry: LensEntry, focal: number): TcaSample | null {
|
||||||
|
const samples = entry.t;
|
||||||
|
if (!samples.length) return null;
|
||||||
|
return nearestByFocal(samples, focal);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Linear in focal for a pair of samples that share a model; otherwise the
|
||||||
|
* closest focal. Lensfun uses splines, but at the handful of focal lengths
|
||||||
|
* these calibrations carry the difference is far below a pixel.
|
||||||
|
*/
|
||||||
|
function nearestByFocal<T extends number[]>(samples: T[], focal: number): T {
|
||||||
|
if (samples.length === 1 || !focal) return samples[0];
|
||||||
|
if (focal <= samples[0][0]) return samples[0];
|
||||||
|
const last = samples[samples.length - 1];
|
||||||
|
if (focal >= last[0]) return last;
|
||||||
|
let index = 0;
|
||||||
|
while (index < samples.length - 1 && samples[index + 1][0] < focal) index += 1;
|
||||||
|
const a = samples[index];
|
||||||
|
const b = samples[index + 1];
|
||||||
|
const span = b[0] - a[0];
|
||||||
|
if (!span) return a;
|
||||||
|
const t = (focal - a[0]) / span;
|
||||||
|
return a.map((value, i) => value + (b[i] - value) * t) as unknown as T;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Closest focal group, then closest aperture, then closest focus distance. */
|
||||||
|
function pickVignetting(entry: LensEntry, focal: number, aperture: number, distance: number): VignettingSample | null {
|
||||||
|
const samples = entry.v;
|
||||||
|
if (!samples.length) return null;
|
||||||
|
const closest = (values: number[], target: number) =>
|
||||||
|
values.reduce((best, value) => (Math.abs(value - target) < Math.abs(best - target) ? value : best), values[0]);
|
||||||
|
|
||||||
|
const focals = [...new Set(samples.map((sample) => sample[0]))];
|
||||||
|
const focalPick = focal ? closest(focals, focal) : focals[0];
|
||||||
|
let group = samples.filter((sample) => sample[0] === focalPick);
|
||||||
|
if (!group.length) group = samples;
|
||||||
|
|
||||||
|
const apertures = [...new Set(group.map((sample) => sample[1]))];
|
||||||
|
const aperturePick = aperture ? closest(apertures, aperture) : apertures[0];
|
||||||
|
group = group.filter((sample) => sample[1] === aperturePick);
|
||||||
|
if (!group.length) group = samples;
|
||||||
|
|
||||||
|
const distances = [...new Set(group.map((sample) => sample[2]))];
|
||||||
|
const distancePick = distance ? closest(distances, distance) : distances[0];
|
||||||
|
return group.find((sample) => sample[2] === distancePick) ?? group[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ the maps */
|
||||||
|
|
||||||
|
type TcaTerms =
|
||||||
|
| { model: 1; kr: number; kb: number }
|
||||||
|
| { model: 0; r: [number, number, number]; b: [number, number, number] };
|
||||||
|
|
||||||
|
export interface MapOptions {
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
|
focal: number;
|
||||||
|
crop: number;
|
||||||
|
aperture?: number;
|
||||||
|
distance?: number;
|
||||||
|
distortion: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MapSet {
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
|
/** 2 floats per point: source x/y in map pixels. */
|
||||||
|
geometry: Float32Array;
|
||||||
|
/** 6 floats per point: red x/y, input x/y, blue x/y. */
|
||||||
|
tca?: Float32Array;
|
||||||
|
/** 3 floats per point: the same gain for R, G and B. */
|
||||||
|
vignetting?: Float32Array;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function computeMaps(entry: LensEntry, options: MapOptions): MapSet {
|
||||||
|
const { width, height } = options;
|
||||||
|
const crop = options.crop || entry.crop;
|
||||||
|
const distortion = pickDistortion(entry, options.focal);
|
||||||
|
const realFocal = (distortion && distortion[5]) || options.focal;
|
||||||
|
const normScale = SENSOR_DIAGONAL / crop / Math.hypot(width, height) / realFocal || 1;
|
||||||
|
const centreSize = Math.min(width - 1, height - 1);
|
||||||
|
const centreX = ((width - 1) / 2 + (centreSize / 2) * entry.centerX) * normScale;
|
||||||
|
const centreY = ((height - 1) / 2 + (centreSize / 2) * entry.centerY) * normScale;
|
||||||
|
|
||||||
|
const scale = distortionScale(entry, realFocal);
|
||||||
|
const dTerms =
|
||||||
|
distortion && options.distortion
|
||||||
|
? {
|
||||||
|
model: distortion[1],
|
||||||
|
a: distortion[2],
|
||||||
|
b: distortion[3],
|
||||||
|
c: distortion[4],
|
||||||
|
scaled:
|
||||||
|
distortion[1] === DIST_MODEL.ptlens
|
||||||
|
? [distortion[2] * scale ** 3, distortion[3] * scale ** 2, distortion[4] * scale]
|
||||||
|
: distortion[1] === DIST_MODEL.poly5
|
||||||
|
? [0, distortion[3] * scale ** 2, distortion[4] * scale ** 4]
|
||||||
|
: [0, distortion[3] * scale ** 2, 0],
|
||||||
|
}
|
||||||
|
: null;
|
||||||
|
|
||||||
|
const tcaSample = options.distortion ? pickTca(entry, options.focal) : null;
|
||||||
|
const tcaTerms: TcaTerms | null = tcaSample
|
||||||
|
? tcaSample[1] === TCA_MODEL.linear
|
||||||
|
? { model: 1, kr: tcaSample[2], kb: tcaSample[5] }
|
||||||
|
: {
|
||||||
|
model: 0,
|
||||||
|
// r·(v + c·r + b·r²); c is scaled by focal, b by focal squared.
|
||||||
|
r: [tcaSample[2] * scale ** 2, tcaSample[3] * scale, tcaSample[4]],
|
||||||
|
b: [tcaSample[5] * scale ** 2, tcaSample[6] * scale, tcaSample[7]],
|
||||||
|
}
|
||||||
|
: null;
|
||||||
|
|
||||||
|
const vignSample = pickVignetting(entry, options.focal, options.aperture ?? 0, options.distance ?? 1000);
|
||||||
|
const vigScale = vignettingScale(entry, options.focal);
|
||||||
|
const vigTerms = vignSample
|
||||||
|
? [
|
||||||
|
vignSample[3] * vigScale ** 2,
|
||||||
|
vignSample[4] * vigScale ** 4,
|
||||||
|
vignSample[5] * vigScale ** 6,
|
||||||
|
]
|
||||||
|
: null;
|
||||||
|
|
||||||
|
const geometry = new Float32Array(width * height * 2);
|
||||||
|
const tca = tcaTerms ? new Float32Array(width * height * 6) : undefined;
|
||||||
|
const vignetting = vigTerms ? new Float32Array(width * height * 3) : undefined;
|
||||||
|
|
||||||
|
for (let row = 0; row < height; row++) {
|
||||||
|
const v = row * normScale - centreY;
|
||||||
|
for (let col = 0; col < width; col++) {
|
||||||
|
const u = col * normScale - centreX;
|
||||||
|
const radius2 = u * u + v * v;
|
||||||
|
const at = row * width + col;
|
||||||
|
|
||||||
|
let factor = 1;
|
||||||
|
if (dTerms) {
|
||||||
|
if (dTerms.model === DIST_MODEL.ptlens) {
|
||||||
|
const r = Math.sqrt(radius2);
|
||||||
|
factor = 1 + dTerms.scaled[0] * radius2 * r + dTerms.scaled[1] * radius2 + dTerms.scaled[2] * r;
|
||||||
|
} else if (dTerms.model === DIST_MODEL.poly5) {
|
||||||
|
factor = 1 + dTerms.scaled[1] * radius2 + dTerms.scaled[2] * radius2 * radius2;
|
||||||
|
} else if (dTerms.model === DIST_MODEL.poly3) {
|
||||||
|
factor = 1 + dTerms.scaled[1] * radius2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
geometry[at * 2] = (u * factor + centreX) / normScale;
|
||||||
|
geometry[at * 2 + 1] = (v * factor + centreY) / normScale;
|
||||||
|
|
||||||
|
if (tca && tcaTerms) {
|
||||||
|
const r = Math.sqrt(radius2);
|
||||||
|
if (tcaTerms.model === 1) {
|
||||||
|
tca[at * 6] = (u * tcaTerms.kr + centreX) / normScale;
|
||||||
|
tca[at * 6 + 1] = (v * tcaTerms.kr + centreY) / normScale;
|
||||||
|
tca[at * 6 + 4] = (u * tcaTerms.kb + centreX) / normScale;
|
||||||
|
tca[at * 6 + 5] = (v * tcaTerms.kb + centreY) / normScale;
|
||||||
|
} else {
|
||||||
|
const red = tcaTerms.r[0] * radius2 + tcaTerms.r[1] * r + tcaTerms.r[2];
|
||||||
|
const blue = tcaTerms.b[0] * radius2 + tcaTerms.b[1] * r + tcaTerms.b[2];
|
||||||
|
tca[at * 6] = (u * red + centreX) / normScale;
|
||||||
|
tca[at * 6 + 1] = (v * red + centreY) / normScale;
|
||||||
|
tca[at * 6 + 4] = (u * blue + centreX) / normScale;
|
||||||
|
tca[at * 6 + 5] = (v * blue + centreY) / normScale;
|
||||||
|
}
|
||||||
|
// Green keeps the input position; the renderer only needs red and blue.
|
||||||
|
tca[at * 6 + 2] = col;
|
||||||
|
tca[at * 6 + 3] = row;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (vignetting && vigTerms) {
|
||||||
|
const gain =
|
||||||
|
1 / (1 + vigTerms[0] * radius2 + vigTerms[1] * radius2 ** 2 + vigTerms[2] * radius2 ** 3);
|
||||||
|
vignetting[at * 3] = gain;
|
||||||
|
vignetting[at * 3 + 1] = gain;
|
||||||
|
vignetting[at * 3 + 2] = gain;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { width, height, geometry, tca, vignetting };
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --------------------------------------------------------------- assembling */
|
||||||
|
|
||||||
|
function bilinear(values: Float32Array, w: number, h: number, x: number, y: number, stride: number, offset: number) {
|
||||||
|
const px = Math.max(0, Math.min(w - 1, x * (w - 1)));
|
||||||
|
const py = Math.max(0, Math.min(h - 1, y * (h - 1)));
|
||||||
|
const x0 = Math.floor(px);
|
||||||
|
const y0 = Math.floor(py);
|
||||||
|
const x1 = Math.min(w - 1, x0 + 1);
|
||||||
|
const y1 = Math.min(h - 1, y0 + 1);
|
||||||
|
const fx = px - x0;
|
||||||
|
const fy = py - y0;
|
||||||
|
const at = (xx: number, yy: number) => (yy * w + xx) * stride + offset;
|
||||||
|
const a = values[at(x0, y0)];
|
||||||
|
const b = values[at(x1, y0)];
|
||||||
|
const c = values[at(x0, y1)];
|
||||||
|
const d = values[at(x1, y1)];
|
||||||
|
return (a * (1 - fx) + b * fx) * (1 - fy) + (c * (1 - fx) + d * fx) * fy;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function autoScaleFor(geometry: LensMap): number {
|
||||||
|
const sample = (x: number, y: number) => {
|
||||||
|
const px = x * (geometry.width - 1);
|
||||||
|
const py = y * (geometry.height - 1);
|
||||||
|
const x0 = Math.max(0, Math.min(geometry.width - 1, Math.floor(px)));
|
||||||
|
const y0 = Math.max(0, Math.min(geometry.height - 1, Math.floor(py)));
|
||||||
|
const x1 = Math.min(geometry.width - 1, x0 + 1);
|
||||||
|
const y1 = Math.min(geometry.height - 1, y0 + 1);
|
||||||
|
const fx = px - x0;
|
||||||
|
const fy = py - y0;
|
||||||
|
const at = (xx: number, yy: number) => (yy * geometry.width + xx) * 4;
|
||||||
|
const a = at(x0, y0);
|
||||||
|
const b = at(x1, y0);
|
||||||
|
const c = at(x0, y1);
|
||||||
|
const d = at(x1, y1);
|
||||||
|
return {
|
||||||
|
x: (geometry.data[a] * (1 - fx) + geometry.data[b] * fx) * (1 - fy) +
|
||||||
|
(geometry.data[c] * (1 - fx) + geometry.data[d] * fx) * fy,
|
||||||
|
y: (geometry.data[a + 1] * (1 - fx) + geometry.data[b + 1] * fx) * (1 - fy) +
|
||||||
|
(geometry.data[c + 1] * (1 - fx) + geometry.data[d + 1] * fx) * fy,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
const inside = (scale: number) => {
|
||||||
|
for (let iy = 0; iy <= 24; iy++) {
|
||||||
|
for (let ix = 0; ix <= 24; ix++) {
|
||||||
|
const x = 0.5 + (ix / 24 - 0.5) / scale;
|
||||||
|
const y = 0.5 + (iy / 24 - 0.5) / scale;
|
||||||
|
const p = sample(x, y);
|
||||||
|
if (p.x < 0.001 || p.y < 0.001 || p.x > 0.999 || p.y > 0.999) return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
if (inside(1)) return 1;
|
||||||
|
let lo = 1;
|
||||||
|
let hi = 2.5;
|
||||||
|
for (let i = 0; i < 12; i++) {
|
||||||
|
const mid = (lo + hi) / 2;
|
||||||
|
if (inside(mid)) hi = mid;
|
||||||
|
else lo = mid;
|
||||||
|
}
|
||||||
|
return hi;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function buildLensCorrection(
|
||||||
|
profile: LensProfile,
|
||||||
|
photo: { width: number; height: number; meta: Pick<PhotoMeta, 'focal' | 'aperture'> },
|
||||||
|
): Promise<LensCorrection> {
|
||||||
|
const key = `${profile.maker}\u0000${profile.model}|${profile.crop}|${photo.width}x${photo.height}|${
|
||||||
|
photo.meta.focal ?? 0
|
||||||
|
}|${photo.meta.aperture ?? 0}|${profile.corrections.distortion ? 1 : 0}${
|
||||||
|
profile.corrections.tca ? 1 : 0
|
||||||
|
}${profile.corrections.vignetting ? 1 : 0}|${profile.distance ?? 1000}`;
|
||||||
|
const cached = correctionCache.get(key);
|
||||||
|
if (cached) return cached;
|
||||||
|
|
||||||
|
const entry = await getLensEntry(profile);
|
||||||
|
if (!entry) throw new Error('Lens profile not found in the database');
|
||||||
|
const focal = Number(photo.meta.focal) || 0;
|
||||||
|
if (!focal) throw new Error('This photo has no focal length in its EXIF data');
|
||||||
|
|
||||||
|
const available =
|
||||||
|
(entry.d.length ? 8 : 0) | (entry.t.length ? 1 : 0) | (entry.v.length ? 2 : 0);
|
||||||
|
const useDistortion = profile.corrections.distortion && (available & 8) !== 0;
|
||||||
|
const useTca = profile.corrections.tca && (available & 1) !== 0;
|
||||||
|
const useVignetting =
|
||||||
|
profile.corrections.vignetting && (available & 2) !== 0 && Number(photo.meta.aperture) > 0;
|
||||||
|
|
||||||
|
const long = 640;
|
||||||
|
const aspect = Math.max(0.1, photo.width / Math.max(1, photo.height));
|
||||||
|
const mapW = aspect >= 1 ? long : Math.max(8, Math.round(long * aspect));
|
||||||
|
const mapH = aspect >= 1 ? Math.max(8, Math.round(long / aspect)) : long;
|
||||||
|
|
||||||
|
const maps = computeMaps(entry, {
|
||||||
|
width: mapW,
|
||||||
|
height: mapH,
|
||||||
|
focal,
|
||||||
|
crop: profile.crop,
|
||||||
|
aperture: Number(photo.meta.aperture) || 1,
|
||||||
|
distance: profile.distance ?? 1000,
|
||||||
|
distortion: useDistortion,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Textures are RGBA32F so the renderer can use one upload path for all three
|
||||||
|
// maps. Geometry and TCA only need the first channels, but keeping four
|
||||||
|
// channels also means the texture is always fully specified.
|
||||||
|
const geometry = new Float32Array(mapW * mapH * 4);
|
||||||
|
for (let i = 0; i < mapW * mapH; i++) {
|
||||||
|
if (useDistortion) {
|
||||||
|
geometry[i * 4] = maps.geometry[i * 2] / Math.max(1, mapW - 1);
|
||||||
|
geometry[i * 4 + 1] = maps.geometry[i * 2 + 1] / Math.max(1, mapH - 1);
|
||||||
|
} else {
|
||||||
|
geometry[i * 4] = (i % mapW) / Math.max(1, mapW - 1);
|
||||||
|
geometry[i * 4 + 1] = Math.floor(i / mapW) / Math.max(1, mapH - 1);
|
||||||
|
}
|
||||||
|
geometry[i * 4 + 3] = 1;
|
||||||
|
}
|
||||||
|
const geometryMap: LensMap = { data: geometry, width: mapW, height: mapH };
|
||||||
|
|
||||||
|
let tca: LensMap | undefined;
|
||||||
|
if (useTca && maps.tca) {
|
||||||
|
tca = { data: new Float32Array(mapW * mapH * 4), width: mapW, height: mapH };
|
||||||
|
for (let i = 0; i < mapW * mapH; i++) {
|
||||||
|
const x = (i % mapW) / Math.max(1, mapW - 1);
|
||||||
|
const y = Math.floor(i / mapW) / Math.max(1, mapH - 1);
|
||||||
|
const gx = useDistortion ? geometry[i * 4] : x;
|
||||||
|
const gy = useDistortion ? geometry[i * 4 + 1] : y;
|
||||||
|
const rx = bilinear(maps.tca, mapW, mapH, gx, gy, 6, 0) / Math.max(1, mapW - 1);
|
||||||
|
const ry = bilinear(maps.tca, mapW, mapH, gx, gy, 6, 1) / Math.max(1, mapH - 1);
|
||||||
|
const bx = bilinear(maps.tca, mapW, mapH, gx, gy, 6, 4) / Math.max(1, mapW - 1);
|
||||||
|
const by = bilinear(maps.tca, mapW, mapH, gx, gy, 6, 5) / Math.max(1, mapH - 1);
|
||||||
|
tca.data[i * 4] = rx - gx;
|
||||||
|
tca.data[i * 4 + 1] = ry - gy;
|
||||||
|
tca.data[i * 4 + 2] = bx - gx;
|
||||||
|
tca.data[i * 4 + 3] = by - gy;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let vignette: LensMap | undefined;
|
||||||
|
if (useVignetting && maps.vignetting) {
|
||||||
|
vignette = { data: new Float32Array(mapW * mapH * 4), width: mapW, height: mapH };
|
||||||
|
for (let i = 0; i < mapW * mapH; i++) {
|
||||||
|
vignette.data[i * 4] = maps.vignetting[i * 3];
|
||||||
|
vignette.data[i * 4 + 1] = maps.vignetting[i * 3 + 1];
|
||||||
|
vignette.data[i * 4 + 2] = maps.vignetting[i * 3 + 2];
|
||||||
|
vignette.data[i * 4 + 3] = 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const correction: LensCorrection = {
|
||||||
|
key,
|
||||||
|
geometry: geometryMap,
|
||||||
|
tca,
|
||||||
|
vignette,
|
||||||
|
scale: useDistortion ? autoScaleFor(geometryMap) : 1,
|
||||||
|
};
|
||||||
|
correctionCache.set(key, correction);
|
||||||
|
return correction;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------- CPU map math */
|
||||||
|
|
||||||
|
export function sampleLensMap(map: LensMap, x: number, y: number): { x: number; y: number } {
|
||||||
|
return {
|
||||||
|
x: bilinear(map.data, map.width, map.height, x, y, 4, 0),
|
||||||
|
y: bilinear(map.data, map.width, map.height, x, y, 4, 1),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function correctLensPoint(
|
||||||
|
correction: LensCorrection | null,
|
||||||
|
x: number,
|
||||||
|
y: number,
|
||||||
|
): { x: number; y: number } {
|
||||||
|
if (!correction) return { x, y };
|
||||||
|
const sx = 0.5 + (x - 0.5) / Math.max(1e-5, correction.scale);
|
||||||
|
const sy = 0.5 + (y - 0.5) / Math.max(1e-5, correction.scale);
|
||||||
|
return sampleLensMap(correction.geometry, sx, sy);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function uncorrectLensPoint(
|
||||||
|
correction: LensCorrection | null,
|
||||||
|
x: number,
|
||||||
|
y: number,
|
||||||
|
): { x: number; y: number } {
|
||||||
|
if (!correction) return { x, y };
|
||||||
|
let px = x;
|
||||||
|
let py = y;
|
||||||
|
for (let i = 0; i < 10; i++) {
|
||||||
|
const mapped = correctLensPoint(correction, px, py);
|
||||||
|
px += x - mapped.x;
|
||||||
|
py += y - mapped.y;
|
||||||
|
}
|
||||||
|
return { x: px, y: py };
|
||||||
|
}
|
||||||
@@ -1,479 +0,0 @@
|
|||||||
import type {
|
|
||||||
CameraMatch,
|
|
||||||
CorrectionMaps,
|
|
||||||
LensMatch,
|
|
||||||
LensfunClient,
|
|
||||||
} from '@neoanaloglabkk/lensfun-wasm';
|
|
||||||
import { lensMatchScore, lensSearchVariants } from './lensNames';
|
|
||||||
import type { LensProfile, PhotoMeta } from '../types';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Lensfun is loaded on demand from public/lensfun. The database and the
|
|
||||||
* WebAssembly wrapper are third-party assets; see public/lensfun/NOTICE.md.
|
|
||||||
*/
|
|
||||||
export interface LensMap {
|
|
||||||
data: Float32Array;
|
|
||||||
width: number;
|
|
||||||
height: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface LensCorrection {
|
|
||||||
key: string;
|
|
||||||
geometry: LensMap;
|
|
||||||
/** RG offsets: red dx, red dy, blue dx, blue dy, normalized source units. */
|
|
||||||
tca?: LensMap;
|
|
||||||
/** RGB vignetting gains. */
|
|
||||||
vignette?: LensMap;
|
|
||||||
/** Centre zoom needed to hide transformed corners. */
|
|
||||||
scale: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
const FLAG_TCA = 1;
|
|
||||||
const FLAG_VIGNETTING = 2;
|
|
||||||
const FLAG_DISTORTION = 8;
|
|
||||||
|
|
||||||
let clientPromise: Promise<LensfunClient> | null = null;
|
|
||||||
let client: LensfunClient | null = null;
|
|
||||||
const handleCache = new Map<string, LensMatch>();
|
|
||||||
const cameraCache = new Map<string, CameraMatch | null>();
|
|
||||||
const correctionCache = new Map<string, LensCorrection>();
|
|
||||||
|
|
||||||
async function loadCoreFactory(): Promise<(options?: Record<string, unknown>) => Promise<unknown>> {
|
|
||||||
const response = await fetch('/lensfun/lensfun-core.js');
|
|
||||||
if (!response.ok) throw new Error('Could not load the Lensfun runtime');
|
|
||||||
let source = await response.text();
|
|
||||||
// The 0.1.3 Emscripten build keeps the float heap view in a closure and the
|
|
||||||
// wrapper reads it from `module.HEAPF32`, so expose it after every memory
|
|
||||||
// resize. The asset itself is untouched on disk.
|
|
||||||
if (!source.includes('Module["HEAPF32"]')) {
|
|
||||||
const marker = 'HEAPF32=new Float32Array(b)';
|
|
||||||
if (!source.includes(marker)) throw new Error('Unexpected Lensfun runtime layout');
|
|
||||||
source = source.replace(marker, `${marker};Module["HEAPF32"]=HEAPF32;`);
|
|
||||||
}
|
|
||||||
const scriptUrl = URL.createObjectURL(new Blob([source], { type: 'text/javascript' }));
|
|
||||||
try {
|
|
||||||
await new Promise<void>((resolve, reject) => {
|
|
||||||
const script = document.createElement('script');
|
|
||||||
script.src = scriptUrl;
|
|
||||||
script.onload = () => {
|
|
||||||
script.remove();
|
|
||||||
resolve();
|
|
||||||
};
|
|
||||||
script.onerror = () => {
|
|
||||||
script.remove();
|
|
||||||
reject(new Error('Could not start the Lensfun runtime'));
|
|
||||||
};
|
|
||||||
document.head.appendChild(script);
|
|
||||||
});
|
|
||||||
} finally {
|
|
||||||
URL.revokeObjectURL(scriptUrl);
|
|
||||||
}
|
|
||||||
const factory = (globalThis as Record<string, unknown>).createLensfunCoreModule;
|
|
||||||
if (typeof factory !== 'function') throw new Error('Lensfun runtime did not initialize');
|
|
||||||
return factory as (options?: Record<string, unknown>) => Promise<unknown>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getLensfun(): Promise<LensfunClient> {
|
|
||||||
if (client) return client;
|
|
||||||
if (!clientPromise) {
|
|
||||||
clientPromise = import('@neoanaloglabkk/lensfun-wasm')
|
|
||||||
.then(async ({ createLensfun }) => {
|
|
||||||
const moduleFactory = await loadCoreFactory();
|
|
||||||
return createLensfun({
|
|
||||||
moduleFactory,
|
|
||||||
wasmUrl: '/lensfun/lensfun-core.wasm',
|
|
||||||
dataUrl: '/lensfun/lensfun-core.data',
|
|
||||||
});
|
|
||||||
})
|
|
||||||
.then((instance) => {
|
|
||||||
client = instance;
|
|
||||||
return instance;
|
|
||||||
})
|
|
||||||
.catch((err) => {
|
|
||||||
clientPromise = null;
|
|
||||||
throw err;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return clientPromise;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function profileKey(profile: LensProfile) {
|
|
||||||
return `${profile.maker}\u0000${profile.model}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface LensSearchResult {
|
|
||||||
maker: string;
|
|
||||||
model: string;
|
|
||||||
crop: number;
|
|
||||||
score: number;
|
|
||||||
available: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
function toResult(match: LensMatch, available = 0): LensSearchResult {
|
|
||||||
return {
|
|
||||||
maker: match.maker,
|
|
||||||
model: match.model,
|
|
||||||
crop: match.cropFactor,
|
|
||||||
score: match.score,
|
|
||||||
available,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function searchLens(
|
|
||||||
query: string,
|
|
||||||
meta?: Pick<PhotoMeta, 'camera' | 'lens'>,
|
|
||||||
): Promise<LensSearchResult[]> {
|
|
||||||
const variants = lensSearchVariants(query);
|
|
||||||
if (!variants.length) return [];
|
|
||||||
const lf = await getLensfun();
|
|
||||||
const camera = cameraParts(meta?.camera);
|
|
||||||
const cameraFields = {
|
|
||||||
...(camera.maker ? { cameraMaker: camera.maker } : {}),
|
|
||||||
...(camera.model ? { cameraModel: camera.model } : {}),
|
|
||||||
};
|
|
||||||
const byName = new Map<string, LensMatch>();
|
|
||||||
for (const variant of variants) {
|
|
||||||
let matches: LensMatch[] = [];
|
|
||||||
try {
|
|
||||||
matches = lf.searchLenses({ lensModel: variant, ...cameraFields });
|
|
||||||
} catch {
|
|
||||||
matches = [];
|
|
||||||
}
|
|
||||||
if (!matches.length) {
|
|
||||||
try {
|
|
||||||
matches = lf.searchLenses({ lensModel: variant });
|
|
||||||
} catch {
|
|
||||||
matches = [];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (const match of matches) {
|
|
||||||
const key = `${match.maker}\u0000${match.model}`;
|
|
||||||
if (!byName.has(key)) byName.set(key, match);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const crop = (await findCamera(meta?.camera))?.cropFactor || 1;
|
|
||||||
return [...byName.values()].slice(0, 20).map((match) => {
|
|
||||||
handleCache.set(`${match.maker}\u0000${match.model}`, match);
|
|
||||||
return toResult(match, lf.getAvailableModifications(match.handle, crop));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function findLensForMeta(
|
|
||||||
meta: Pick<PhotoMeta, 'camera' | 'lens'>,
|
|
||||||
): Promise<LensSearchResult | null> {
|
|
||||||
if (!meta.lens) return null;
|
|
||||||
const results = await searchLens(meta.lens, meta);
|
|
||||||
if (!results.length) return null;
|
|
||||||
let best = results[0];
|
|
||||||
let score = lensMatchScore(meta.lens, best.model);
|
|
||||||
for (const candidate of results.slice(1)) {
|
|
||||||
const next = lensMatchScore(meta.lens, candidate.model);
|
|
||||||
if (next > score) {
|
|
||||||
best = candidate;
|
|
||||||
score = next;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return score > 0 ? best : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function resolveLens(profile: LensProfile): Promise<LensMatch | null> {
|
|
||||||
const key = profileKey(profile);
|
|
||||||
const cached = handleCache.get(key);
|
|
||||||
if (cached) return cached;
|
|
||||||
const lf = await getLensfun();
|
|
||||||
const cam = cameraParts(profile.cameraModel);
|
|
||||||
const cameraFields = {
|
|
||||||
...(profile.cameraMaker || cam.maker ? { cameraMaker: profile.cameraMaker ?? cam.maker } : {}),
|
|
||||||
...(profile.cameraModel || cam.model ? { cameraModel: cam.model ?? profile.cameraModel } : {}),
|
|
||||||
};
|
|
||||||
const tokens = profile.model.split(/\s+/).filter(Boolean);
|
|
||||||
const focal = tokens.find((token) => /^\d+(?:\.\d+)?mm$/i.test(token));
|
|
||||||
const aperture = tokens.find((token) => /^f\/\d+(?:\.\d+)?[a-z]*$/i.test(token));
|
|
||||||
const shortened = tokens
|
|
||||||
.filter((token) => !/^(af|af-s|af-i|ai|ai-s|ais|d|g|ed|vr|if|asp|ld|dx|fx)$/i.test(token))
|
|
||||||
.join(' ');
|
|
||||||
const queries: { lensMaker?: string; lensModel: string; cameraMaker?: string; cameraModel?: string }[] = [
|
|
||||||
{ ...cameraFields, lensMaker: profile.maker, lensModel: profile.model },
|
|
||||||
{ ...cameraFields, lensModel: profile.model },
|
|
||||||
{ ...cameraFields, lensModel: shortened },
|
|
||||||
...(focal
|
|
||||||
? [{ ...cameraFields, lensModel: [tokens[0], focal, aperture].filter(Boolean).join(' ') }]
|
|
||||||
: []),
|
|
||||||
];
|
|
||||||
const attempts: LensMatch[] = [];
|
|
||||||
for (const query of queries) {
|
|
||||||
try {
|
|
||||||
const found = lf.searchLenses(query);
|
|
||||||
if (found.length) {
|
|
||||||
attempts.push(...found);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
/* try the next, looser query */
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const exact =
|
|
||||||
attempts.find(
|
|
||||||
(match) =>
|
|
||||||
match.maker.toLowerCase() === profile.maker.toLowerCase() &&
|
|
||||||
match.model.toLowerCase() === profile.model.toLowerCase(),
|
|
||||||
) ?? attempts[0];
|
|
||||||
if (exact) handleCache.set(key, exact);
|
|
||||||
return exact ?? null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function availableFor(profile: LensProfile): Promise<number> {
|
|
||||||
const match = await resolveLens(profile);
|
|
||||||
if (!match) return 0;
|
|
||||||
const lf = await getLensfun();
|
|
||||||
return lf.getAvailableModifications(match.handle, profile.crop);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ------------------------------------------------------------- camera search */
|
|
||||||
|
|
||||||
function cameraParts(camera?: string): { maker?: string; model?: string } {
|
|
||||||
if (!camera) return {};
|
|
||||||
const cleaned = camera.replace(/\s+/g, ' ').trim();
|
|
||||||
const lower = cleaned.toLowerCase();
|
|
||||||
const makerNames = [
|
|
||||||
'Nikon Corporation',
|
|
||||||
'Canon',
|
|
||||||
'Sony',
|
|
||||||
'FUJIFILM',
|
|
||||||
'Olympus',
|
|
||||||
'Panasonic',
|
|
||||||
'PENTAX',
|
|
||||||
'Sigma',
|
|
||||||
'Tamron',
|
|
||||||
'Leica',
|
|
||||||
'Hasselblad',
|
|
||||||
'Samsung',
|
|
||||||
'Ricoh',
|
|
||||||
];
|
|
||||||
const maker = makerNames.find((name) => lower.startsWith(name.toLowerCase()));
|
|
||||||
if (maker) {
|
|
||||||
return { maker, model: cleaned.slice(maker.length).trim() || cleaned };
|
|
||||||
}
|
|
||||||
const [first, ...rest] = cleaned.split(' ');
|
|
||||||
return rest.length ? { maker: first, model: rest.join(' ') } : { model: cleaned };
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function findCamera(camera?: string): Promise<CameraMatch | null> {
|
|
||||||
if (!camera) return null;
|
|
||||||
const cached = cameraCache.get(camera);
|
|
||||||
if (cached !== undefined) return cached;
|
|
||||||
const lf = await getLensfun();
|
|
||||||
const parts = cameraParts(camera);
|
|
||||||
let found: CameraMatch[] = [];
|
|
||||||
try {
|
|
||||||
found = lf.searchCameras({ ...parts, searchFlags: 1 });
|
|
||||||
} catch {
|
|
||||||
found = [];
|
|
||||||
}
|
|
||||||
if (!found.length) {
|
|
||||||
try {
|
|
||||||
found = lf.searchCameras({ model: camera, searchFlags: 1 });
|
|
||||||
} catch {
|
|
||||||
found = [];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const best = found[0] ?? null;
|
|
||||||
cameraCache.set(camera, best);
|
|
||||||
return best;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ---------------------------------------------------------- correction maps */
|
|
||||||
|
|
||||||
export function autoScaleFor(geometry: LensMap): number {
|
|
||||||
const sample = (x: number, y: number) => {
|
|
||||||
const px = x * (geometry.width - 1);
|
|
||||||
const py = y * (geometry.height - 1);
|
|
||||||
const x0 = Math.max(0, Math.min(geometry.width - 1, Math.floor(px)));
|
|
||||||
const y0 = Math.max(0, Math.min(geometry.height - 1, Math.floor(py)));
|
|
||||||
const x1 = Math.min(geometry.width - 1, x0 + 1);
|
|
||||||
const y1 = Math.min(geometry.height - 1, y0 + 1);
|
|
||||||
const fx = px - x0;
|
|
||||||
const fy = py - y0;
|
|
||||||
const at = (xx: number, yy: number) => (yy * geometry.width + xx) * 4;
|
|
||||||
const a = at(x0, y0);
|
|
||||||
const b = at(x1, y0);
|
|
||||||
const c = at(x0, y1);
|
|
||||||
const d = at(x1, y1);
|
|
||||||
return {
|
|
||||||
x: (geometry.data[a] * (1 - fx) + geometry.data[b] * fx) * (1 - fy) +
|
|
||||||
(geometry.data[c] * (1 - fx) + geometry.data[d] * fx) * fy,
|
|
||||||
y: (geometry.data[a + 1] * (1 - fx) + geometry.data[b + 1] * fx) * (1 - fy) +
|
|
||||||
(geometry.data[c + 1] * (1 - fx) + geometry.data[d + 1] * fx) * fy,
|
|
||||||
};
|
|
||||||
};
|
|
||||||
const inside = (scale: number) => {
|
|
||||||
for (let iy = 0; iy <= 24; iy++) {
|
|
||||||
for (let ix = 0; ix <= 24; ix++) {
|
|
||||||
const x = 0.5 + (ix / 24 - 0.5) / scale;
|
|
||||||
const y = 0.5 + (iy / 24 - 0.5) / scale;
|
|
||||||
const p = sample(x, y);
|
|
||||||
if (p.x < 0.001 || p.y < 0.001 || p.x > 0.999 || p.y > 0.999) return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
};
|
|
||||||
if (inside(1)) return 1;
|
|
||||||
let lo = 1;
|
|
||||||
let hi = 2.5;
|
|
||||||
for (let i = 0; i < 12; i++) {
|
|
||||||
const mid = (lo + hi) / 2;
|
|
||||||
if (inside(mid)) hi = mid;
|
|
||||||
else lo = mid;
|
|
||||||
}
|
|
||||||
return hi;
|
|
||||||
}
|
|
||||||
|
|
||||||
function bilinear(values: Float32Array, w: number, h: number, x: number, y: number, stride: number, offset: number) {
|
|
||||||
const px = Math.max(0, Math.min(w - 1, x * (w - 1)));
|
|
||||||
const py = Math.max(0, Math.min(h - 1, y * (h - 1)));
|
|
||||||
const x0 = Math.floor(px);
|
|
||||||
const y0 = Math.floor(py);
|
|
||||||
const x1 = Math.min(w - 1, x0 + 1);
|
|
||||||
const y1 = Math.min(h - 1, y0 + 1);
|
|
||||||
const fx = px - x0;
|
|
||||||
const fy = py - y0;
|
|
||||||
const at = (xx: number, yy: number) => (yy * w + xx) * stride + offset;
|
|
||||||
const a = values[at(x0, y0)];
|
|
||||||
const b = values[at(x1, y0)];
|
|
||||||
const c = values[at(x0, y1)];
|
|
||||||
const d = values[at(x1, y1)];
|
|
||||||
return (a * (1 - fx) + b * fx) * (1 - fy) + (c * (1 - fx) + d * fx) * fy;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function buildLensCorrection(
|
|
||||||
profile: LensProfile,
|
|
||||||
photo: { width: number; height: number; meta: Pick<PhotoMeta, 'focal' | 'aperture'> },
|
|
||||||
): Promise<LensCorrection> {
|
|
||||||
const key = `${profileKey(profile)}|${profile.crop}|${photo.width}x${photo.height}|${photo.meta.focal ?? 0}|${
|
|
||||||
photo.meta.aperture ?? 0
|
|
||||||
}|${profile.corrections.distortion ? 1 : 0}${profile.corrections.tca ? 1 : 0}${
|
|
||||||
profile.corrections.vignetting ? 1 : 0
|
|
||||||
}|${profile.distance ?? 1000}`;
|
|
||||||
const cached = correctionCache.get(key);
|
|
||||||
if (cached) return cached;
|
|
||||||
|
|
||||||
const match = await resolveLens(profile);
|
|
||||||
if (!match) throw new Error('Lens profile not found in the Lensfun database');
|
|
||||||
const focal = Number(photo.meta.focal) || 0;
|
|
||||||
if (!focal) throw new Error('This photo has no focal length in its EXIF data');
|
|
||||||
const lf = await getLensfun();
|
|
||||||
const available = lf.getAvailableModifications(match.handle, profile.crop);
|
|
||||||
const useDistortion =
|
|
||||||
profile.corrections.distortion && (available & FLAG_DISTORTION) !== 0;
|
|
||||||
const useTca = profile.corrections.tca && (available & FLAG_TCA) !== 0;
|
|
||||||
const useVignetting =
|
|
||||||
profile.corrections.vignetting &&
|
|
||||||
(available & FLAG_VIGNETTING) !== 0 &&
|
|
||||||
Number(photo.meta.aperture) > 0;
|
|
||||||
const long = 640;
|
|
||||||
const aspect = Math.max(0.1, photo.width / Math.max(1, photo.height));
|
|
||||||
const mapW = aspect >= 1 ? long : Math.max(8, Math.round(long * aspect));
|
|
||||||
const mapH = aspect >= 1 ? Math.max(8, Math.round(long / aspect)) : long;
|
|
||||||
|
|
||||||
const maps: CorrectionMaps = lf.buildCorrectionMaps({
|
|
||||||
lensHandle: match.handle,
|
|
||||||
width: mapW,
|
|
||||||
height: mapH,
|
|
||||||
focal,
|
|
||||||
crop: profile.crop,
|
|
||||||
step: 1,
|
|
||||||
includeTca: useTca,
|
|
||||||
includeVignetting: useVignetting,
|
|
||||||
aperture: Number(photo.meta.aperture) || 1,
|
|
||||||
distance: profile.distance ?? 1000,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Textures are RGBA32F so the renderer can use one upload path for all three
|
|
||||||
// maps. Geometry and TCA only need the first channels, but keeping four
|
|
||||||
// channels also means the texture is always fully specified.
|
|
||||||
const geometry = new Float32Array(mapW * mapH * 4);
|
|
||||||
for (let i = 0; i < mapW * mapH; i++) {
|
|
||||||
if (useDistortion) {
|
|
||||||
geometry[i * 4] = maps.geometry[i * 2] / Math.max(1, mapW - 1);
|
|
||||||
geometry[i * 4 + 1] = maps.geometry[i * 2 + 1] / Math.max(1, mapH - 1);
|
|
||||||
} else {
|
|
||||||
geometry[i * 4] = (i % mapW) / Math.max(1, mapW - 1);
|
|
||||||
geometry[i * 4 + 1] = Math.floor(i / mapW) / Math.max(1, mapH - 1);
|
|
||||||
}
|
|
||||||
geometry[i * 4 + 3] = 1;
|
|
||||||
}
|
|
||||||
const geometryMap: LensMap = { data: geometry, width: mapW, height: mapH };
|
|
||||||
let tca: LensMap | undefined;
|
|
||||||
if (useTca && maps.tca) {
|
|
||||||
tca = { data: new Float32Array(mapW * mapH * 4), width: mapW, height: mapH };
|
|
||||||
for (let i = 0; i < mapW * mapH; i++) {
|
|
||||||
const x = (i % mapW) / Math.max(1, mapW - 1);
|
|
||||||
const y = Math.floor(i / mapW) / Math.max(1, mapH - 1);
|
|
||||||
const gx = useDistortion ? geometry[i * 4] : x;
|
|
||||||
const gy = useDistortion ? geometry[i * 4 + 1] : y;
|
|
||||||
const rx = bilinear(maps.tca, mapW, mapH, gx, gy, 6, 0) / Math.max(1, mapW - 1);
|
|
||||||
const ry = bilinear(maps.tca, mapW, mapH, gx, gy, 6, 1) / Math.max(1, mapH - 1);
|
|
||||||
const bx = bilinear(maps.tca, mapW, mapH, gx, gy, 6, 4) / Math.max(1, mapW - 1);
|
|
||||||
const by = bilinear(maps.tca, mapW, mapH, gx, gy, 6, 5) / Math.max(1, mapH - 1);
|
|
||||||
tca.data[i * 4] = rx - gx;
|
|
||||||
tca.data[i * 4 + 1] = ry - gy;
|
|
||||||
tca.data[i * 4 + 2] = bx - gx;
|
|
||||||
tca.data[i * 4 + 3] = by - gy;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let vignette: LensMap | undefined;
|
|
||||||
if (useVignetting && maps.vignetting) {
|
|
||||||
vignette = { data: new Float32Array(mapW * mapH * 4), width: mapW, height: mapH };
|
|
||||||
for (let i = 0; i < mapW * mapH; i++) {
|
|
||||||
vignette.data[i * 4] = maps.vignetting[i * 3];
|
|
||||||
vignette.data[i * 4 + 1] = maps.vignetting[i * 3 + 1];
|
|
||||||
vignette.data[i * 4 + 2] = maps.vignetting[i * 3 + 2];
|
|
||||||
vignette.data[i * 4 + 3] = 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const correction: LensCorrection = {
|
|
||||||
key,
|
|
||||||
geometry: geometryMap,
|
|
||||||
tca,
|
|
||||||
vignette,
|
|
||||||
scale: useDistortion ? autoScaleFor(geometryMap) : 1,
|
|
||||||
};
|
|
||||||
correctionCache.set(key, correction);
|
|
||||||
return correction;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ------------------------------------------------------------- CPU map math */
|
|
||||||
|
|
||||||
export function sampleLensMap(map: LensMap, x: number, y: number): { x: number; y: number } {
|
|
||||||
return {
|
|
||||||
x: bilinear(map.data, map.width, map.height, x, y, 4, 0),
|
|
||||||
y: bilinear(map.data, map.width, map.height, x, y, 4, 1),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export function correctLensPoint(
|
|
||||||
correction: LensCorrection | null,
|
|
||||||
x: number,
|
|
||||||
y: number,
|
|
||||||
): { x: number; y: number } {
|
|
||||||
if (!correction) return { x, y };
|
|
||||||
const sx = 0.5 + (x - 0.5) / Math.max(1e-5, correction.scale);
|
|
||||||
const sy = 0.5 + (y - 0.5) / Math.max(1e-5, correction.scale);
|
|
||||||
return sampleLensMap(correction.geometry, sx, sy);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function uncorrectLensPoint(
|
|
||||||
correction: LensCorrection | null,
|
|
||||||
x: number,
|
|
||||||
y: number,
|
|
||||||
): { x: number; y: number } {
|
|
||||||
if (!correction) return { x, y };
|
|
||||||
let px = x;
|
|
||||||
let py = y;
|
|
||||||
for (let i = 0; i < 10; i++) {
|
|
||||||
const mapped = correctLensPoint(correction, px, py);
|
|
||||||
px += x - mapped.x;
|
|
||||||
py += y - mapped.y;
|
|
||||||
}
|
|
||||||
return { x: px, y: py };
|
|
||||||
}
|
|
||||||
+3
-1
@@ -115,7 +115,9 @@ export interface LensCorrections {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface LensProfile {
|
export interface LensProfile {
|
||||||
/** Lensfun maker/model and the sensor crop used for calibration. */
|
/** Profile id in the bundled lens database, when it came from a search. */
|
||||||
|
id?: string;
|
||||||
|
/** Maker/model and the sensor crop used for calibration. */
|
||||||
maker: string;
|
maker: string;
|
||||||
model: string;
|
model: string;
|
||||||
crop: number;
|
crop: number;
|
||||||
|
|||||||
Reference in New Issue
Block a user