Compare commits
20 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| fb43ca8e99 | |||
| 46dcc231a7 | |||
| c05dbce580 | |||
| 69a327cd45 | |||
| 5c2903eeef | |||
| be8cf3c88a | |||
| b884616889 | |||
| acf582251f | |||
| 00e6fee9bd | |||
| 24deb8e69b | |||
| 4b17ca00db | |||
| 6e80699829 | |||
| a67e9ef458 | |||
| a6491f6ef6 | |||
| fe9d2aff3f | |||
| 1e7ec0cf15 | |||
| c10ff97670 | |||
| 2dc569256c | |||
| c7b01b31cb | |||
| 32616d5404 |
@@ -281,6 +281,22 @@ npm run build # type-checks and bundles dist/
|
|||||||
npm start # serves dist/ and /api from one Node process
|
npm start # serves dist/ and /api from one Node process
|
||||||
```
|
```
|
||||||
|
|
||||||
|
To push a running install over ssh, `npm run deploy` runs the whole predeploy gate
|
||||||
|
first — a type error, a failing test or a clipping-overlay regression stops it before
|
||||||
|
anything is copied — then rsyncs the source, rebuilds, restarts the service and checks
|
||||||
|
that the server is serving the same bundle hashes. npm runs the `predeploy` script
|
||||||
|
before `deploy` on its own, so the gate runs exactly once; calling `node
|
||||||
|
scripts/deploy.mjs` directly runs the gate itself:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
LUMINARY_DEPLOY_HOST=bhursey@photos.example.org \
|
||||||
|
LUMINARY_DEPLOY_SUDO_PASS=… npm run deploy
|
||||||
|
```
|
||||||
|
|
||||||
|
`LUMINARY_DEPLOY_PATH` (default `/srv/luminary`), `LUMINARY_DEPLOY_SERVICE` (default
|
||||||
|
`luminary`) and `LUMINARY_DEPLOY_SSH_PASS` cover a different layout; without the
|
||||||
|
password variables it uses your ssh key and passwordless sudo.
|
||||||
|
|
||||||
The server serves the built UI with an SPA fallback (unknown non-API paths return
|
The server serves the built UI with an SPA fallback (unknown non-API paths return
|
||||||
`index.html`), caches `/assets/*` for a year as immutable, and returns `503` with a
|
`index.html`), caches `/assets/*` for a year as immutable, and returns `503` with a
|
||||||
build hint if `dist/index.html` is missing. JSON responses are `no-store`; image bytes
|
build hint if `dist/index.html` is missing. JSON responses are `no-store`; image bytes
|
||||||
@@ -956,6 +972,9 @@ positions. Camera-lens defaults require both a normalised camera and lens name t
|
|||||||
| `npm run dev` | Vite HMR on 5173 |
|
| `npm run dev` | Vite HMR on 5173 |
|
||||||
| `npm run typecheck` | `tsc --noEmit` |
|
| `npm run typecheck` | `tsc --noEmit` |
|
||||||
| `npm test` | Vitest, one pass then exit |
|
| `npm test` | Vitest, one pass then exit |
|
||||||
|
| `npm run check:render` | Headless Chrome check that the 16-bit sidecar and JPEG proxy upload in the same row order |
|
||||||
|
| `npm run predeploy` | Typecheck, unit suite, render check, then build — run this before pushing a deploy; the build is skipped when only test files changed since the last build |
|
||||||
|
| `npm run deploy` | Predeploy gate, then rsync, remote build, restart and bundle-hash check (see [Production deployment](#production-deployment)) |
|
||||||
|
|
||||||
Conventions worth knowing before changing code:
|
Conventions worth knowing before changing code:
|
||||||
|
|
||||||
@@ -984,13 +1003,25 @@ Conventions worth knowing before changing code:
|
|||||||
| `src/lib/lensNames.test.ts` | EXIF lens-name normalisation, search variants and match scoring |
|
| `src/lib/lensNames.test.ts` | EXIF lens-name normalisation, search variants and match scoring |
|
||||||
| `src/lib/lensDefaults.test.ts` | Camera + lens default selection and rejection rules |
|
| `src/lib/lensDefaults.test.ts` | Camera + lens default selection and rejection rules |
|
||||||
| `src/lib/editSections.test.ts` | Selective settings copy and the ISO-aware auto-noise curve |
|
| `src/lib/editSections.test.ts` | Selective settings copy and the ISO-aware auto-noise curve |
|
||||||
| `src/lib/preview16.test.ts` | 16-bit PNG proxy parsing, row flip, half-float encoding and the camera matrix chunk |
|
| `src/lib/preview16.test.ts` | 16-bit PNG proxy parsing, row order, half-float encoding and the camera matrix chunk |
|
||||||
| `src/lib/dcp.test.ts` | DCP tag parsing and the camera matrix recipe against LibRaw's own values |
|
| `src/lib/dcp.test.ts` | DCP tag parsing and the camera matrix recipe against LibRaw's own values |
|
||||||
| `src/lib/softProof.test.ts` | ICC parsing (including counted lut16 tables), the printer round trip, gamut threshold, rendering-intent selection and CMYK profiles |
|
| `src/lib/softProof.test.ts` | ICC parsing (including counted lut16 tables), the printer round trip, gamut threshold, rendering-intent selection and CMYK profiles |
|
||||||
| `src/lib/dcpLibrary.test.ts` | Per-camera DCP library: validation, replacement, forgetting and camera matching |
|
| `src/lib/dcpLibrary.test.ts` | Per-camera DCP library: validation, replacement, forgetting and camera matching |
|
||||||
|
|
||||||
There are no server integration tests; the API is exercised through the UI.
|
There are no server integration tests; the API is exercised through the UI.
|
||||||
|
|
||||||
|
`npm run check:render` covers the one thing the unit suite cannot: what a shader does to
|
||||||
|
real GPU pixels. It encodes a 16-bit sidecar with the server's own encoder, serves it
|
||||||
|
beside the matching JPEG proxy and measures the rows that reach a WebGL2 texture in
|
||||||
|
headless Chrome. Then it renders that image through the real `Renderer` with the Ctrl
|
||||||
|
clipping preview on, so the overlay has to paint red for one clipped channel and yellow
|
||||||
|
for two instead of collapsing to white, and an unclipped band has to turn white once
|
||||||
|
Exposure is pushed past the top of the range. The same run checks the shadow warning:
|
||||||
|
red for one channel at black, yellow for red+green, cyan for green+blue. `npm run
|
||||||
|
predeploy` chains it with the typecheck, unit suite and build. It fails on either regression, printing the
|
||||||
|
measured values, needs Chrome (`CHROME_PATH` overrides discovery) and skips with a notice
|
||||||
|
when none is installed.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Troubleshooting
|
## Troubleshooting
|
||||||
|
|||||||
@@ -13,6 +13,9 @@
|
|||||||
"preview": "vite preview",
|
"preview": "vite preview",
|
||||||
"typecheck": "tsc --noEmit",
|
"typecheck": "tsc --noEmit",
|
||||||
"test": "vitest run",
|
"test": "vitest run",
|
||||||
|
"check:render": "node scripts/render-check.mjs",
|
||||||
|
"predeploy": "node scripts/predeploy.mjs",
|
||||||
|
"deploy": "node scripts/deploy.mjs",
|
||||||
"build:lens-db": "node scripts/build-lens-db.mjs"
|
"build:lens-db": "node scripts/build-lens-db.mjs"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
|||||||
@@ -0,0 +1,166 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
/**
|
||||||
|
* Deploy Luminary: run the predeploy gate, then copy the source to the server,
|
||||||
|
* rebuild it there and restart the service.
|
||||||
|
*
|
||||||
|
* The gate runs first and a failure exits before anything touches the server,
|
||||||
|
* so a type error, a failing test or a shader regression caught by the render
|
||||||
|
* check cannot reach production. The local bundle is compared with the one the
|
||||||
|
* server just built, so a deploy that silently ships stale assets is visible.
|
||||||
|
*
|
||||||
|
* Exits via process.exitCode rather than process.exit(): stdout/stderr are
|
||||||
|
* async when piped, and exiting early truncates the very lines that explain
|
||||||
|
* why a deploy stopped.
|
||||||
|
*
|
||||||
|
* Environment:
|
||||||
|
* LUMINARY_DEPLOY_HOST ssh target, e.g. bhursey@photos.example.org (required)
|
||||||
|
* LUMINARY_DEPLOY_PATH remote checkout of this repo (default /srv/luminary)
|
||||||
|
* LUMINARY_DEPLOY_SERVICE systemd unit to restart (default luminary)
|
||||||
|
* LUMINARY_DEPLOY_SSH_PASS optional ssh password, passed to sshpass via env
|
||||||
|
* LUMINARY_DEPLOY_SUDO_PASS optional sudo password for the remote build/restart
|
||||||
|
*/
|
||||||
|
import { execFileSync } from 'node:child_process';
|
||||||
|
import { existsSync, readdirSync } from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
|
||||||
|
const env = process.env;
|
||||||
|
const HOST = env.LUMINARY_DEPLOY_HOST;
|
||||||
|
const REMOTE_PATH = env.LUMINARY_DEPLOY_PATH || '/srv/luminary';
|
||||||
|
const SERVICE = env.LUMINARY_DEPLOY_SERVICE || 'luminary';
|
||||||
|
const SSH_PASS = env.LUMINARY_DEPLOY_SSH_PASS || '';
|
||||||
|
const SUDO_PASS = env.LUMINARY_DEPLOY_SUDO_PASS || '';
|
||||||
|
|
||||||
|
/** Local-only state that must never be copied over the server's copy. */
|
||||||
|
const EXCLUDES = [
|
||||||
|
'node_modules',
|
||||||
|
'dist',
|
||||||
|
'data',
|
||||||
|
'.git',
|
||||||
|
'.freebuff',
|
||||||
|
'.check',
|
||||||
|
'.smoke',
|
||||||
|
'logo.png',
|
||||||
|
'*.log',
|
||||||
|
];
|
||||||
|
|
||||||
|
function run(command, args, extraEnv) {
|
||||||
|
execFileSync(command, args, {
|
||||||
|
stdio: 'inherit',
|
||||||
|
env: extraEnv ? { ...process.env, ...extraEnv } : process.env,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function sshArgs(script) {
|
||||||
|
return ['-o', 'StrictHostKeyChecking=accept-new', HOST, script];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Runs a remote script with stdout echoed, returning what it printed. */
|
||||||
|
function sshCapture(script, input) {
|
||||||
|
const piped = input !== undefined;
|
||||||
|
const output = execFileSync(
|
||||||
|
SSH_PASS ? 'sshpass' : 'ssh',
|
||||||
|
SSH_PASS ? ['-e', 'ssh', ...sshArgs(script)] : sshArgs(script),
|
||||||
|
{
|
||||||
|
stdio: [piped ? 'pipe' : 'inherit', 'pipe', 'inherit'],
|
||||||
|
input,
|
||||||
|
encoding: 'utf8',
|
||||||
|
env: SSH_PASS ? { ...process.env, SSHPASS: SSH_PASS } : process.env,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
process.stdout.write(output);
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
|
||||||
|
function localBundles() {
|
||||||
|
const dir = path.join(process.cwd(), 'dist', 'assets');
|
||||||
|
if (!existsSync(dir)) return [];
|
||||||
|
return readdirSync(dir)
|
||||||
|
.filter((file) => /^index-.*\.(js|css)$/.test(file))
|
||||||
|
.sort();
|
||||||
|
}
|
||||||
|
|
||||||
|
function main() {
|
||||||
|
if (!HOST) {
|
||||||
|
console.error('deploy: set LUMINARY_DEPLOY_HOST to the ssh target, e.g. user@server.');
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. Gate. Nothing below this line may run if the gate fails.
|
||||||
|
// npm runs a script called "predeploy" before "deploy", so under `npm run
|
||||||
|
// deploy` the gate has already passed before this process starts; running it
|
||||||
|
// again would typecheck and render-check the same source twice. Invoked
|
||||||
|
// directly, this script has to run the gate itself.
|
||||||
|
if (env.npm_lifecycle_event === 'deploy') {
|
||||||
|
console.log('deploy: predeploy gate passed (npm predeploy hook)');
|
||||||
|
} else {
|
||||||
|
console.log('deploy: predeploy gate');
|
||||||
|
try {
|
||||||
|
run(process.execPath, [path.join('scripts', 'predeploy.mjs')]);
|
||||||
|
} catch {
|
||||||
|
console.error('deploy: aborted - predeploy failed, nothing was sent to the server.');
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Copy the source, keeping server-side data and build output.
|
||||||
|
console.log(`\ndeploy: rsync to ${HOST}:${REMOTE_PATH}`);
|
||||||
|
const rsyncArgs = ['-az'];
|
||||||
|
for (const item of EXCLUDES) rsyncArgs.push(`--exclude=${item}`);
|
||||||
|
const remoteShell = SSH_PASS
|
||||||
|
? `sshpass -e ssh -o StrictHostKeyChecking=accept-new`
|
||||||
|
: `ssh -o StrictHostKeyChecking=accept-new`;
|
||||||
|
rsyncArgs.push('-e', remoteShell, './', `${HOST}:${REMOTE_PATH}/`);
|
||||||
|
try {
|
||||||
|
run('rsync', rsyncArgs, SSH_PASS ? { SSHPASS: SSH_PASS } : undefined);
|
||||||
|
} catch {
|
||||||
|
console.error('deploy: aborted - rsync failed.');
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Rebuild and restart there, then report what is actually being served.
|
||||||
|
const sudo = SUDO_PASS ? `sudo -S -p '' ` : '';
|
||||||
|
const sudoLines = SUDO_PASS ? `${SUDO_PASS}\n${SUDO_PASS}\n` : undefined;
|
||||||
|
const script = [
|
||||||
|
`cd ${REMOTE_PATH} || exit 3`,
|
||||||
|
`${sudo}npm run build`,
|
||||||
|
'build=$?',
|
||||||
|
'[ "$build" -eq 0 ] || { echo "deploy: remote build failed ($build)"; exit "$build"; }',
|
||||||
|
`${sudo}systemctl restart ${SERVICE}`,
|
||||||
|
'sleep 2',
|
||||||
|
`systemctl is-active ${SERVICE}`,
|
||||||
|
'sha256sum dist/assets/*.js dist/assets/*.css',
|
||||||
|
].join('\n');
|
||||||
|
|
||||||
|
console.log(`\ndeploy: build and restart ${SERVICE} on ${HOST}`);
|
||||||
|
let output;
|
||||||
|
try {
|
||||||
|
output = sshCapture(script, sudoLines);
|
||||||
|
} catch {
|
||||||
|
console.error('deploy: aborted - the remote build or restart failed.');
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. The server must be serving the bundle the gate just reviewed.
|
||||||
|
const remoteHashes = new Map();
|
||||||
|
for (const line of output.split('\n')) {
|
||||||
|
const match = /^([0-9a-f]{64})\s+dist\/assets\/(index-[^/\s]+)$/.exec(line.trim());
|
||||||
|
if (match) remoteHashes.set(match[2], match[1]);
|
||||||
|
}
|
||||||
|
const missing = localBundles().filter((file) => !remoteHashes.has(file));
|
||||||
|
if (missing.length) {
|
||||||
|
console.error(
|
||||||
|
`\ndeploy: FAILED - the server is not serving ${missing.join(', ')}; check the remote build.`,
|
||||||
|
);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
const served = [...remoteHashes.entries()];
|
||||||
|
console.log(
|
||||||
|
`\ndeploy PASSED: ${SERVICE} is active on ${HOST} serving ${served
|
||||||
|
.map(([file, hash]) => `${file} (${hash.slice(0, 12)})`)
|
||||||
|
.join(', ')}.`,
|
||||||
|
);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
process.exitCode = main();
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
/**
|
||||||
|
* Pre-deploy gate: typecheck, unit suite, render check, then the production
|
||||||
|
* build -- skipped when nothing that feeds the bundle has changed since the
|
||||||
|
* last successful build, so editing only a test file does not rebuild dist.
|
||||||
|
*
|
||||||
|
* The signature is stored under node_modules/.cache: that directory is
|
||||||
|
* gitignored and excluded from the deploy rsync, so it is per-checkout state
|
||||||
|
* and never travels to the server.
|
||||||
|
*
|
||||||
|
* Exits via process.exitCode rather than process.exit(): piped stdout is async
|
||||||
|
* and exiting early truncates the failure message.
|
||||||
|
*/
|
||||||
|
import { createHash } from 'node:crypto';
|
||||||
|
import { execFileSync } from 'node:child_process';
|
||||||
|
import {
|
||||||
|
existsSync,
|
||||||
|
mkdirSync,
|
||||||
|
readFileSync,
|
||||||
|
readdirSync,
|
||||||
|
statSync,
|
||||||
|
writeFileSync,
|
||||||
|
} from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
|
||||||
|
const ROOT = process.cwd();
|
||||||
|
const CACHE = path.join(ROOT, 'node_modules', '.cache', 'luminary-predeploy.json');
|
||||||
|
|
||||||
|
/** Vite inputs: everything the bundle is built from, plus the config it reads. */
|
||||||
|
const INPUTS = [
|
||||||
|
'src',
|
||||||
|
'public',
|
||||||
|
'index.html',
|
||||||
|
'vite.config.ts',
|
||||||
|
'tsconfig.json',
|
||||||
|
'package.json',
|
||||||
|
'package-lock.json',
|
||||||
|
];
|
||||||
|
|
||||||
|
/** Test files never reach the bundle, so their edits must not force a rebuild. */
|
||||||
|
const NOT_BUNDLED = /(^|\/)(__tests__|__mocks__|__fixtures__)(\/|$)|\.(test|spec)\.[cm]?[jt]sx?$/;
|
||||||
|
|
||||||
|
class StepFailed extends Error {}
|
||||||
|
|
||||||
|
function walk(target) {
|
||||||
|
if (!existsSync(target)) return [];
|
||||||
|
if (statSync(target).isFile()) return [target];
|
||||||
|
return readdirSync(target, { withFileTypes: true }).flatMap((entry) =>
|
||||||
|
walk(path.join(target, entry.name)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function inputSignature() {
|
||||||
|
const files = INPUTS.flatMap((entry) => walk(entry))
|
||||||
|
.map((file) => path.relative(ROOT, file).split(path.sep).join('/'))
|
||||||
|
.filter((file) => !NOT_BUNDLED.test(file))
|
||||||
|
.sort();
|
||||||
|
const hash = createHash('sha256');
|
||||||
|
for (const file of files) {
|
||||||
|
hash.update(file);
|
||||||
|
hash.update('\0');
|
||||||
|
hash.update(readFileSync(path.join(ROOT, file)));
|
||||||
|
hash.update('\0');
|
||||||
|
}
|
||||||
|
return { count: files.length, digest: hash.digest('hex') };
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(name, args) {
|
||||||
|
console.log(`\npredeploy: ${name}`);
|
||||||
|
try {
|
||||||
|
execFileSync('npm', args, { cwd: ROOT, stdio: 'inherit' });
|
||||||
|
} catch {
|
||||||
|
throw new StepFailed(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function main() {
|
||||||
|
const signature = inputSignature();
|
||||||
|
const previous = existsSync(CACHE) ? JSON.parse(readFileSync(CACHE, 'utf8')) : null;
|
||||||
|
const upToDate =
|
||||||
|
existsSync(path.join(ROOT, 'dist', 'index.html')) && previous?.digest === signature.digest;
|
||||||
|
|
||||||
|
try {
|
||||||
|
run('typecheck', ['run', 'typecheck']);
|
||||||
|
run('tests', ['run', 'test']);
|
||||||
|
run('render check', ['run', 'check:render']);
|
||||||
|
if (upToDate) {
|
||||||
|
console.log(
|
||||||
|
`\npredeploy: build skipped - the ${signature.count} bundle inputs are unchanged since the last build.`,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
run('build', ['run', 'build']);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
if (!(err instanceof StepFailed)) throw err;
|
||||||
|
console.error(`\npredeploy FAILED at ${err.message}.`);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!upToDate) {
|
||||||
|
mkdirSync(path.dirname(CACHE), { recursive: true });
|
||||||
|
writeFileSync(
|
||||||
|
CACHE,
|
||||||
|
`${JSON.stringify({ digest: signature.digest, count: signature.count, at: new Date().toISOString() }, null, 2)}\n`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('\npredeploy PASSED.');
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
process.exitCode = main();
|
||||||
@@ -0,0 +1,740 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
/**
|
||||||
|
* Headless render check for the 16-bit proxy swap.
|
||||||
|
*
|
||||||
|
* The editor shows the JPEG proxy first and swaps in the 16-bit sidecar a few
|
||||||
|
* seconds later. Both uploads go through `Renderer.setImage`, and whether they
|
||||||
|
* agree depends on a WebGL detail that no unit test can cover: `UNPACK_FLIP_Y_WEBGL`
|
||||||
|
* is ignored for `ImageBitmap` sources (the proxy) but honoured for typed arrays
|
||||||
|
* (the sidecar). If the two disagree, the picture jumps upside down at the swap.
|
||||||
|
*
|
||||||
|
* This script builds a two-tone 16-bit PNG with the server's own encoder plus the
|
||||||
|
* matching JPEG, serves `parsePreview16` through Vite, and measures the rows that
|
||||||
|
* actually reach the GPU in headless Chrome. It fails if the top row of the proxy
|
||||||
|
* is not the top row of the sidecar.
|
||||||
|
*
|
||||||
|
* Runs outside `npm test` because it needs a WebGL2-capable Chrome:
|
||||||
|
* npm run check:render
|
||||||
|
*/
|
||||||
|
import { spawn } from 'node:child_process';
|
||||||
|
import { existsSync } from 'node:fs';
|
||||||
|
import { mkdir, rm, writeFile } from 'node:fs/promises';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
import sharp from 'sharp';
|
||||||
|
import { createServer } from 'vite';
|
||||||
|
import { encodePng16 } from '../server/imaging.mjs';
|
||||||
|
|
||||||
|
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
|
const DIR = path.join(ROOT, '.render-check');
|
||||||
|
const PAGE = path.join(DIR, 'index.html');
|
||||||
|
const W = 96;
|
||||||
|
const H = 64;
|
||||||
|
|
||||||
|
const CHROME_CANDIDATES = [
|
||||||
|
process.env.CHROME_PATH,
|
||||||
|
'google-chrome',
|
||||||
|
'google-chrome-stable',
|
||||||
|
'chromium',
|
||||||
|
'chromium-browser',
|
||||||
|
].filter(Boolean);
|
||||||
|
|
||||||
|
async function findChrome() {
|
||||||
|
for (const candidate of CHROME_CANDIDATES) {
|
||||||
|
if (candidate.includes(path.sep)) {
|
||||||
|
if (existsSync(candidate)) return candidate;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (await spawnSyncOk(candidate)) return candidate;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function spawnSyncOk(bin) {
|
||||||
|
const probe = spawn(bin, ['--version'], { stdio: 'ignore' });
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
probe.on('error', () => resolve(false));
|
||||||
|
probe.on('exit', (code) => resolve(code === 0));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Horizontal bands that exercise both ends of the range: one and two channels
|
||||||
|
* blown, one clean band, then one and two channels crushed, plus a green+blue
|
||||||
|
* crush to check the secondary colour. The same image proves the clipping
|
||||||
|
* overlay names the channels instead of painting every warning one colour.
|
||||||
|
*/
|
||||||
|
const BANDS = [
|
||||||
|
[1.0, 0.55, 0.08], // highlight: red only
|
||||||
|
[1.0, 1.0, 0.08], // highlight: red + green (yellow)
|
||||||
|
[0.24, 0.28, 0.35], // nothing clipped
|
||||||
|
[0.0, 0.3, 0.35], // shadow: red only
|
||||||
|
[0.0, 0.0, 0.35], // shadow: red + green (yellow)
|
||||||
|
[0.3, 0.0, 0.0], // shadow: green + blue (cyan)
|
||||||
|
];
|
||||||
|
|
||||||
|
function buildSource() {
|
||||||
|
const rgb16 = new Uint16Array(W * H * 3);
|
||||||
|
const rgb8 = new Uint8Array(W * H * 3);
|
||||||
|
const bands = BANDS;
|
||||||
|
for (let y = 0; y < H; y++) {
|
||||||
|
const band = bands[Math.min(bands.length - 1, Math.floor((y / H) * bands.length))];
|
||||||
|
for (let x = 0; x < W; x++) {
|
||||||
|
const i = (y * W + x) * 3;
|
||||||
|
for (let c = 0; c < 3; c++) {
|
||||||
|
rgb16[i + c] = Math.round(band[c] * 65535);
|
||||||
|
rgb8[i + c] = Math.round(band[c] * 255);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { rgb8, rgb16 };
|
||||||
|
}
|
||||||
|
|
||||||
|
const PAGE_HTML = `<!doctype html>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<pre id="out">boot</pre>
|
||||||
|
<script type="module">
|
||||||
|
import { parsePreview16 } from '/src/lib/preview16.ts';
|
||||||
|
import { Renderer } from '/src/gl/renderer.ts';
|
||||||
|
import { defaultEdits, defaultLocalComponent, defaultLocalLayer } from '/src/lib/edits.ts';
|
||||||
|
const pre = document.getElementById('out');
|
||||||
|
const half = (bits) => {
|
||||||
|
const s = bits >> 15 ? -1 : 1;
|
||||||
|
const e = (bits >> 10) & 0x1f;
|
||||||
|
const m = bits & 0x3ff;
|
||||||
|
if (e === 0) return s * m * Math.pow(2, -24);
|
||||||
|
if (e === 31) return m ? NaN : s * Infinity;
|
||||||
|
return s * (1 + m / 1024) * Math.pow(2, e - 15);
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
const canvas = document.createElement('canvas');
|
||||||
|
const gl = canvas.getContext('webgl2', { alpha: false, antialias: false });
|
||||||
|
if (!gl) { pre.textContent = 'ERROR no WebGL2 in this Chrome'; throw new Error('no webgl2'); }
|
||||||
|
const makeTex = () => {
|
||||||
|
const t = gl.createTexture();
|
||||||
|
gl.bindTexture(gl.TEXTURE_2D, t);
|
||||||
|
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
|
||||||
|
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
|
||||||
|
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
|
||||||
|
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
|
||||||
|
return t;
|
||||||
|
};
|
||||||
|
// readPixels rows start at the framebuffer's bottom row, which is texel row 0.
|
||||||
|
const rowLuma = (tex, y, w) => {
|
||||||
|
gl.bindTexture(gl.TEXTURE_2D, tex);
|
||||||
|
const fb = gl.createFramebuffer();
|
||||||
|
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
|
||||||
|
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
|
||||||
|
if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) {
|
||||||
|
throw new Error('framebuffer incomplete');
|
||||||
|
}
|
||||||
|
const buf = new Uint8Array(w * 4);
|
||||||
|
gl.readPixels(0, y, w, 1, gl.RGBA, gl.UNSIGNED_BYTE, buf);
|
||||||
|
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
|
||||||
|
gl.deleteFramebuffer(fb);
|
||||||
|
let sum = 0;
|
||||||
|
for (let i = 0; i < w; i++) {
|
||||||
|
sum += 0.2126 * buf[i * 4] + 0.7152 * buf[i * 4 + 1] + 0.0722 * buf[i * 4 + 2];
|
||||||
|
}
|
||||||
|
return sum / w / 255;
|
||||||
|
};
|
||||||
|
|
||||||
|
const blob = await (await fetch('/.render-check/proxy.jpg')).blob();
|
||||||
|
const bitmap = await createImageBitmap(blob, { imageOrientation: 'from-image' });
|
||||||
|
const w = bitmap.width;
|
||||||
|
const h = bitmap.height;
|
||||||
|
|
||||||
|
// Exactly what Renderer.setImage does for the JPEG proxy.
|
||||||
|
const texFlip = makeTex();
|
||||||
|
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
|
||||||
|
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, gl.RGBA, gl.UNSIGNED_BYTE, bitmap);
|
||||||
|
const texNoFlip = makeTex();
|
||||||
|
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
|
||||||
|
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, gl.RGBA, gl.UNSIGNED_BYTE, bitmap);
|
||||||
|
|
||||||
|
const png = await (await fetch('/.render-check/side.p16.png')).arrayBuffer();
|
||||||
|
const parsed = await parsePreview16(png);
|
||||||
|
if (!parsed) throw new Error('parsePreview16 returned null');
|
||||||
|
if (parsed.width !== w || parsed.height !== h) {
|
||||||
|
throw new Error('sidecar ' + parsed.width + 'x' + parsed.height + ' vs proxy ' + w + 'x' + h);
|
||||||
|
}
|
||||||
|
// Exactly what Renderer.setImage does for the sidecar: rows in parser order, unflipped.
|
||||||
|
const sideRow = (y) => {
|
||||||
|
const out = new Uint8Array(w * 4);
|
||||||
|
for (let x = 0; x < w; x++) {
|
||||||
|
const i = (y * w + x) * 4;
|
||||||
|
const toByte = (bits) => Math.round(Math.min(1, Math.max(0, half(bits))) * 255);
|
||||||
|
out[x * 4] = toByte(parsed.rgba[i]);
|
||||||
|
out[x * 4 + 1] = toByte(parsed.rgba[i + 1]);
|
||||||
|
out[x * 4 + 2] = toByte(parsed.rgba[i + 2]);
|
||||||
|
out[x * 4 + 3] = 255;
|
||||||
|
}
|
||||||
|
const tex = makeTex();
|
||||||
|
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
|
||||||
|
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, w, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, out);
|
||||||
|
return tex;
|
||||||
|
};
|
||||||
|
const sideTopTex = sideRow(0);
|
||||||
|
const sideBottomTex = sideRow(h - 1);
|
||||||
|
|
||||||
|
const proxyTop = rowLuma(texFlip, 0, w);
|
||||||
|
const proxyBottom = rowLuma(texFlip, h - 1, w);
|
||||||
|
const proxyNoFlipTop = rowLuma(texNoFlip, 0, w);
|
||||||
|
const sideTop = rowLuma(sideTopTex, 0, w);
|
||||||
|
const sideBottom = rowLuma(sideBottomTex, 0, w);
|
||||||
|
const same = (a, b) => Math.abs(a - b) < 0.02;
|
||||||
|
|
||||||
|
// Clipping overlay: red for one clipped channel, yellow for two. This renders
|
||||||
|
// through the real Renderer, so a shader that collapses the warning to white
|
||||||
|
// (or loses the shadow/highlight bit) fails here.
|
||||||
|
const view = document.createElement('canvas');
|
||||||
|
const renderer = new Renderer(view);
|
||||||
|
renderer.setImage(bitmap, parsed);
|
||||||
|
renderer.render(defaultEdits(), { width: w, height: h, clipPreview: true });
|
||||||
|
const viewGl = view.getContext('webgl2');
|
||||||
|
const sampleBand = (index) => {
|
||||||
|
// readPixels rows start at the bottom, so flip the band centre.
|
||||||
|
const py = h - 1 - Math.floor((h * (index + 0.5)) / ${BANDS.length});
|
||||||
|
const px = new Uint8Array(4);
|
||||||
|
viewGl.readPixels(Math.floor(w / 2), py, 1, 1, viewGl.RGBA, viewGl.UNSIGNED_BYTE, px);
|
||||||
|
return [px[0], px[1], px[2]];
|
||||||
|
};
|
||||||
|
const clipPixels = [0, 1, 2].map(sampleBand);
|
||||||
|
const near = (pixel, target) =>
|
||||||
|
Math.abs(pixel[0] - target[0]) < 14 &&
|
||||||
|
Math.abs(pixel[1] - target[1]) < 14 &&
|
||||||
|
Math.abs(pixel[2] - target[2]) < 14;
|
||||||
|
const RED_MARK = [255, 31, 31];
|
||||||
|
const YELLOW_MARK = [255, 230, 26];
|
||||||
|
// The preview has to follow the sliders it is shown for: +6 EV blows every
|
||||||
|
// channel of the unclipped band, so it must turn white, not stay clear.
|
||||||
|
const brightEdits = defaultEdits();
|
||||||
|
brightEdits.exposure = 6;
|
||||||
|
renderer.render(brightEdits, { width: w, height: h, clipPreview: true });
|
||||||
|
const brightPixel = sampleBand(2);
|
||||||
|
|
||||||
|
// Shadow clipping: same palette at the other end of the histogram.
|
||||||
|
renderer.render(defaultEdits(), { width: w, height: h, clipping: 'shadows' });
|
||||||
|
const shadowPixels = [2, 3, 4, 5].map(sampleBand);
|
||||||
|
|
||||||
|
// And it has to move with the sliders, not just exist: -9 EV drives every
|
||||||
|
// channel of the clean band to black, so that band must turn white in shadow
|
||||||
|
// mode, just as it turns white at +6 EV in highlight mode.
|
||||||
|
const shadowEdits = defaultEdits();
|
||||||
|
shadowEdits.exposure = -9;
|
||||||
|
renderer.render(shadowEdits, { width: w, height: h, clipping: 'shadows' });
|
||||||
|
const shadowDarkPixel = sampleBand(2);
|
||||||
|
|
||||||
|
// Per-mask curve: a radial covering the whole frame, first with an identity
|
||||||
|
// curve and then with one that halves the output. The mask must leave the
|
||||||
|
// frame alone with the identity curve and darken it with the real one.
|
||||||
|
const maskLayer = defaultLocalLayer('radial', 0);
|
||||||
|
const maskShape = maskLayer.components[0];
|
||||||
|
maskShape.feather = 0;
|
||||||
|
maskShape.radial = { cx: 0.5, cy: 0.5, rx: 1.2, ry: 1.2 };
|
||||||
|
const darkCurve = [
|
||||||
|
{ x: 0, y: 0 },
|
||||||
|
{ x: 1, y: 0.4 },
|
||||||
|
];
|
||||||
|
const maskedEdits = defaultEdits();
|
||||||
|
maskedEdits.local = [{ ...maskLayer, curve: [{ x: 0, y: 0 }, { x: 1, y: 1 }] }];
|
||||||
|
renderer.render(maskedEdits, { width: w, height: h });
|
||||||
|
const maskIdentityPixel = sampleBand(2);
|
||||||
|
maskedEdits.local = [{ ...maskLayer, curve: darkCurve }];
|
||||||
|
renderer.render(maskedEdits, { width: w, height: h });
|
||||||
|
const maskCurvePixel = sampleBand(2);
|
||||||
|
|
||||||
|
// Mask groups: a second shape has to composite into the layer's own mask.
|
||||||
|
// Subtracting a frame-wide shape from an equally wide add shape clears the
|
||||||
|
// group, so the darkened curve must stop touching the frame; intersecting
|
||||||
|
// with the same shape keeps full coverage, so it must still darken.
|
||||||
|
const groupShape = defaultLocalComponent('radial');
|
||||||
|
groupShape.feather = 0;
|
||||||
|
groupShape.radial = { cx: 0.5, cy: 0.5, rx: 1.2, ry: 1.2 };
|
||||||
|
const groupEdits = defaultEdits();
|
||||||
|
groupEdits.local = [
|
||||||
|
{
|
||||||
|
...maskLayer,
|
||||||
|
curve: darkCurve,
|
||||||
|
components: [maskShape, { ...groupShape, mode: 'subtract' }],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
renderer.render(groupEdits, { width: w, height: h });
|
||||||
|
const maskGroupSubtractPixel = sampleBand(2);
|
||||||
|
groupEdits.local = [
|
||||||
|
{
|
||||||
|
...maskLayer,
|
||||||
|
curve: darkCurve,
|
||||||
|
components: [maskShape, { ...groupShape, mode: 'intersect' }],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
renderer.render(groupEdits, { width: w, height: h });
|
||||||
|
const maskGroupIntersectPixel = sampleBand(2);
|
||||||
|
|
||||||
|
// Brush masks are source-space and feather softens the rim inside the brush
|
||||||
|
// circle. The dab below has a radius of 0.08 of the frame width, so it spans
|
||||||
|
// 0.12 of the frame height; nothing outside that may be touched, even at a
|
||||||
|
// high feather, and the rim itself must be a gradient rather than a step.
|
||||||
|
const pixelAt = (fx, fy) => {
|
||||||
|
const px = new Uint8Array(4);
|
||||||
|
const py = h - 1 - Math.min(h - 1, Math.floor(fy * h));
|
||||||
|
viewGl.readPixels(Math.min(w - 1, Math.floor(fx * w)), py, 1, 1, viewGl.RGBA, viewGl.UNSIGNED_BYTE, px);
|
||||||
|
return [px[0], px[1], px[2]];
|
||||||
|
};
|
||||||
|
const dabRadiusY = 0.08 * (w / h);
|
||||||
|
const brushEdits = (feather) => {
|
||||||
|
const layer = defaultLocalLayer('brush', 0);
|
||||||
|
const shape = layer.components[0];
|
||||||
|
shape.feather = feather;
|
||||||
|
shape.brush.strokes = [{ points: [{ x: 0.25, y: 0.2 }], size: 0.08, erase: false }];
|
||||||
|
return { ...defaultEdits(), local: [{ ...layer, curve: darkCurve }] };
|
||||||
|
};
|
||||||
|
renderer.render(brushEdits(0), { width: w, height: h });
|
||||||
|
const dabHard = pixelAt(0.25, 0.2);
|
||||||
|
const dabOutsideHard = pixelAt(0.25, 0.2 + dabRadiusY * 1.15);
|
||||||
|
renderer.render(brushEdits(80), { width: w, height: h });
|
||||||
|
const dabSoft = pixelAt(0.25, 0.2);
|
||||||
|
const dabRimSoft = pixelAt(0.25, 0.2 + dabRadiusY * 0.75);
|
||||||
|
const dabOutsideSoft = pixelAt(0.25, 0.2 + dabRadiusY * 1.15);
|
||||||
|
// The develop view tints the baked mask instead of redrawing the stroke, so
|
||||||
|
// the overlay has to follow the same coverage: strong in the core, a real
|
||||||
|
// gradient at the rim, and nothing at all outside the brush circle.
|
||||||
|
renderer.render(brushEdits(80), { width: w, height: h, maskView: 0 });
|
||||||
|
const tintCore = pixelAt(0.25, 0.2);
|
||||||
|
const tintRim = pixelAt(0.25, 0.2 + dabRadiusY * 0.75);
|
||||||
|
const tintOutside = pixelAt(0.25, 0.2 + dabRadiusY * 1.15);
|
||||||
|
|
||||||
|
// Source-space alignment. Masks are baked over the whole source, so a crop
|
||||||
|
// that keeps a dab in frame but moves it on screen must move its tint and
|
||||||
|
// its local detail with it: source (0.6, 0.4) inside a quarter-frame crop
|
||||||
|
// lands at screen (0.4, 0.6), and nothing may be tinted at (0.6, 0.4).
|
||||||
|
const cropRect = {
|
||||||
|
x: 0.5,
|
||||||
|
y: 0.25,
|
||||||
|
w: 0.25,
|
||||||
|
h: 0.25,
|
||||||
|
angle: 0,
|
||||||
|
quarter: 0,
|
||||||
|
aspect: 'original',
|
||||||
|
flipH: false,
|
||||||
|
flipV: false,
|
||||||
|
};
|
||||||
|
const dabEdits = (at, size, adjust) => {
|
||||||
|
const layer = defaultLocalLayer('brush', 0);
|
||||||
|
const shape = layer.components[0];
|
||||||
|
shape.feather = 0;
|
||||||
|
shape.brush.strokes = [{ points: [at], size, erase: false }];
|
||||||
|
return {
|
||||||
|
...defaultEdits(),
|
||||||
|
local: [{ ...layer, adjust: { ...layer.adjust, ...(adjust || {}) } }],
|
||||||
|
};
|
||||||
|
};
|
||||||
|
const cropped = { ...defaultEdits(), crop: cropRect };
|
||||||
|
renderer.render(cropped, { width: w, height: h });
|
||||||
|
const cropRef = pixelAt(0.4, 0.6);
|
||||||
|
const cropRefOff = pixelAt(0.6, 0.4);
|
||||||
|
const cropDab = dabEdits({ x: 0.6, y: 0.4 }, 0.02);
|
||||||
|
cropDab.crop = cropRect;
|
||||||
|
renderer.render(cropDab, { width: w, height: h, maskView: 0 });
|
||||||
|
const cropTintOn = pixelAt(0.4, 0.6);
|
||||||
|
const cropTintOff = pixelAt(0.6, 0.4);
|
||||||
|
// Same crop and dab, but as a local detail amount instead of a tint: the
|
||||||
|
// finish pass has to read the mask through the same source coordinate.
|
||||||
|
const cropDetail = dabEdits({ x: 0.6, y: 0.4 }, 0.02, { dehaze: 100 });
|
||||||
|
cropDetail.crop = cropRect;
|
||||||
|
renderer.render(cropDetail, { width: w, height: h });
|
||||||
|
const cropDetailOn = pixelAt(0.4, 0.6);
|
||||||
|
const cropDetailOff = pixelAt(0.6, 0.4);
|
||||||
|
|
||||||
|
// Tint strength and toggle: full strength must read stronger than the default
|
||||||
|
// half, and no maskView at all must leave the photo untouched.
|
||||||
|
renderer.render(brushEdits(80), { width: w, height: h, maskView: 0, maskStrength: 1 });
|
||||||
|
const tintFull = pixelAt(0.25, 0.2);
|
||||||
|
renderer.render(brushEdits(80), { width: w, height: h });
|
||||||
|
const tintOffPixel = pixelAt(0.25, 0.2);
|
||||||
|
|
||||||
|
// Lens warp: a geometry map that magnifies the centre by 1.6 puts the dab at
|
||||||
|
// source (0.7, 0.45) at screen (0.625, 0.469); its source uv must be clear.
|
||||||
|
const lensN = 33;
|
||||||
|
const lensData = new Float32Array(lensN * lensN * 4);
|
||||||
|
for (let ly = 0; ly < lensN; ly++) {
|
||||||
|
for (let lx = 0; lx < lensN; lx++) {
|
||||||
|
const i = (ly * lensN + lx) * 4;
|
||||||
|
lensData[i] = 0.5 + ((lx + 0.5) / lensN - 0.5) * 1.6;
|
||||||
|
lensData[i + 1] = 0.5 + ((ly + 0.5) / lensN - 0.5) * 1.6;
|
||||||
|
lensData[i + 2] = 0;
|
||||||
|
lensData[i + 3] = 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const lensWarp = {
|
||||||
|
key: 'render-check-warp',
|
||||||
|
scale: 1,
|
||||||
|
geometry: { data: lensData, width: lensN, height: lensN },
|
||||||
|
};
|
||||||
|
renderer.render(defaultEdits(), { width: w, height: h, lens: lensWarp });
|
||||||
|
const lensRef = pixelAt(0.625, 0.469);
|
||||||
|
const lensRefOff = pixelAt(0.7, 0.469);
|
||||||
|
const lensDab = dabEdits({ x: 0.7, y: 0.45 }, 0.04);
|
||||||
|
renderer.render(lensDab, { width: w, height: h, lens: lensWarp, maskView: 0 });
|
||||||
|
const lensTintOn = pixelAt(0.625, 0.469);
|
||||||
|
const lensTintOff = pixelAt(0.7, 0.469);
|
||||||
|
|
||||||
|
pre.textContent = 'RESULT ' + JSON.stringify({
|
||||||
|
clipPixels,
|
||||||
|
clipRed: near(clipPixels[0], RED_MARK),
|
||||||
|
clipYellow: near(clipPixels[1], YELLOW_MARK),
|
||||||
|
clipClear:
|
||||||
|
!near(clipPixels[2], RED_MARK) &&
|
||||||
|
!near(clipPixels[2], YELLOW_MARK) &&
|
||||||
|
!near(clipPixels[2], [255, 255, 255]),
|
||||||
|
clipFollowsExposure: near(brightPixel, [255, 255, 255]),
|
||||||
|
brightPixel,
|
||||||
|
shadowPixels,
|
||||||
|
shadowClear:
|
||||||
|
!near(shadowPixels[0], RED_MARK) && !near(shadowPixels[0], YELLOW_MARK),
|
||||||
|
shadowRed: near(shadowPixels[1], RED_MARK),
|
||||||
|
shadowYellow: near(shadowPixels[2], YELLOW_MARK),
|
||||||
|
shadowCyan: near(shadowPixels[3], [26, 217, 255]),
|
||||||
|
shadowFollowsExposure: near(shadowDarkPixel, [255, 255, 255]),
|
||||||
|
shadowDarkPixel,
|
||||||
|
maskIdentityPixel,
|
||||||
|
maskCurvePixel,
|
||||||
|
maskIdentityFlat: near(maskIdentityPixel, [61, 71, 89]),
|
||||||
|
maskCurveDarkens: maskCurvePixel[0] < maskIdentityPixel[0] * 0.75,
|
||||||
|
maskGroupSubtractPixel,
|
||||||
|
maskGroupSubtractCleared: near(maskGroupSubtractPixel, maskIdentityPixel),
|
||||||
|
maskGroupIntersectPixel,
|
||||||
|
maskGroupIntersectDarkens: maskGroupIntersectPixel[0] < maskIdentityPixel[0] * 0.75,
|
||||||
|
dabHard,
|
||||||
|
dabOutsideHard,
|
||||||
|
dabSoft,
|
||||||
|
dabRimSoft,
|
||||||
|
dabOutsideSoft,
|
||||||
|
tintCore,
|
||||||
|
tintRim,
|
||||||
|
tintOutside,
|
||||||
|
// Orange tint: blue is the channel the overlay pushes up, so it ranks the
|
||||||
|
// coverage without depending on how dark the adjustment left the pixels.
|
||||||
|
tintFollowsMask: tintCore[2] > tintRim[2] && tintRim[2] > tintOutside[2] + 5,
|
||||||
|
tintBounded: Math.abs(tintOutside[2] - dabOutsideSoft[2]) <= 1,
|
||||||
|
cropRef,
|
||||||
|
cropRefOff,
|
||||||
|
cropTintOn,
|
||||||
|
cropTintOff,
|
||||||
|
cropDetailOn,
|
||||||
|
cropDetailOff,
|
||||||
|
lensRef,
|
||||||
|
lensRefOff,
|
||||||
|
lensTintOn,
|
||||||
|
lensTintOff,
|
||||||
|
tintFull,
|
||||||
|
tintOffPixel,
|
||||||
|
// The tint pushes red up hard on the dark mid band, so red ranks coverage.
|
||||||
|
cropTintAligned: cropTintOn[0] > cropRef[0] + 40,
|
||||||
|
cropTintBounded: Math.abs(cropTintOff[0] - cropRefOff[0]) <= 2,
|
||||||
|
// Local dehaze lifts the blue of that band, so blue marks where it landed.
|
||||||
|
cropDetailAligned: cropDetailOn[2] > cropDetailOff[2] + 10,
|
||||||
|
cropDetailBounded: Math.abs(cropDetailOff[2] - cropRefOff[2]) <= 3,
|
||||||
|
lensTintAligned: lensTintOn[0] > lensRef[0] + 40,
|
||||||
|
lensTintBounded: Math.abs(lensTintOff[0] - lensRefOff[0]) <= 2,
|
||||||
|
tintStrengthWorks: tintFull[2] > tintCore[2] + 8,
|
||||||
|
tintOffMatches: Math.abs(tintOffPixel[2] - dabSoft[2]) <= 1,
|
||||||
|
// A hard dab covers the core, and even an 80 % feather stops at the rim.
|
||||||
|
dabCoreDarkened: dabHard[0] < 140,
|
||||||
|
dabSoftCoreDarkened: dabSoft[0] < 140,
|
||||||
|
dabRimSmooth: dabRimSoft[0] > 140 && dabRimSoft[0] < 240,
|
||||||
|
dabBoundedHard: dabOutsideHard[0] > 240,
|
||||||
|
dabBoundedSoft: dabOutsideSoft[0] > 240,
|
||||||
|
flagHonouredForBitmap: !same(proxyTop, proxyNoFlipTop),
|
||||||
|
proxyTop: +proxyTop.toFixed(4),
|
||||||
|
sidecarTop: +sideTop.toFixed(4),
|
||||||
|
proxyBottom: +proxyBottom.toFixed(4),
|
||||||
|
sidecarBottom: +sideBottom.toFixed(4),
|
||||||
|
matchTop: same(proxyTop, sideTop),
|
||||||
|
matchBottom: same(proxyBottom, sideBottom),
|
||||||
|
reversed: same(proxyTop, sideBottom) && same(proxyBottom, sideTop),
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
if (!String(pre.textContent).startsWith('ERROR')) {
|
||||||
|
pre.textContent = 'ERROR ' + (err && err.message ? err.message : String(err));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>`;
|
||||||
|
|
||||||
|
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||||
|
|
||||||
|
async function drive(chromeBin, url) {
|
||||||
|
const port = 9333 + Math.floor(Math.random() * 200);
|
||||||
|
const child = spawn(
|
||||||
|
chromeBin,
|
||||||
|
[
|
||||||
|
'--headless=new',
|
||||||
|
'--no-sandbox',
|
||||||
|
'--disable-gpu-sandbox',
|
||||||
|
'--use-gl=angle',
|
||||||
|
'--use-angle=swiftshader',
|
||||||
|
'--enable-unsafe-swiftshader',
|
||||||
|
`--remote-debugging-port=${port}`,
|
||||||
|
`--user-data-dir=${path.join(DIR, 'profile')}`,
|
||||||
|
'about:blank',
|
||||||
|
],
|
||||||
|
{ stdio: 'ignore' },
|
||||||
|
);
|
||||||
|
|
||||||
|
try {
|
||||||
|
let target = null;
|
||||||
|
for (let i = 0; i < 120 && !target; i++) {
|
||||||
|
try {
|
||||||
|
const res = await fetch(`http://127.0.0.1:${port}/json/list`);
|
||||||
|
target = (await res.json()).find((t) => t.type === 'page') ?? null;
|
||||||
|
} catch {
|
||||||
|
/* devtools not up yet */
|
||||||
|
}
|
||||||
|
if (!target) await sleep(250);
|
||||||
|
}
|
||||||
|
if (!target) throw new Error('Chrome DevTools endpoint never came up');
|
||||||
|
|
||||||
|
const ws = new WebSocket(target.webSocketDebuggerUrl);
|
||||||
|
await new Promise((resolve, reject) => {
|
||||||
|
ws.onopen = resolve;
|
||||||
|
ws.onerror = () => reject(new Error('DevTools websocket failed'));
|
||||||
|
});
|
||||||
|
let nextId = 1;
|
||||||
|
const pending = new Map();
|
||||||
|
ws.onmessage = (event) => {
|
||||||
|
const message = JSON.parse(event.data);
|
||||||
|
if (message.id && pending.has(message.id)) {
|
||||||
|
pending.get(message.id)(message);
|
||||||
|
pending.delete(message.id);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const send = (method, params = {}) => {
|
||||||
|
const id = nextId++;
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
pending.set(id, resolve);
|
||||||
|
ws.send(JSON.stringify({ id, method, params }));
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
await send('Page.enable');
|
||||||
|
await send('Runtime.enable');
|
||||||
|
await send('Page.navigate', { url });
|
||||||
|
|
||||||
|
let text = '';
|
||||||
|
const deadline = Date.now() + 90000;
|
||||||
|
while (Date.now() < deadline) {
|
||||||
|
const res = await send('Runtime.evaluate', {
|
||||||
|
expression: "document.getElementById('out')?.textContent ?? ''",
|
||||||
|
returnByValue: true,
|
||||||
|
});
|
||||||
|
text = res.result?.result?.value ?? '';
|
||||||
|
if (text.includes('RESULT') || text.startsWith('ERROR')) break;
|
||||||
|
await sleep(500);
|
||||||
|
}
|
||||||
|
ws.close();
|
||||||
|
return text;
|
||||||
|
} finally {
|
||||||
|
child.kill('SIGKILL');
|
||||||
|
// Chrome writes its profile until the process is gone; give it a moment so
|
||||||
|
// the cleanup below does not race the file handles it still holds.
|
||||||
|
await sleep(500);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const chromeBin = await findChrome();
|
||||||
|
const { rgb8, rgb16 } = buildSource();
|
||||||
|
await mkdir(DIR, { recursive: true });
|
||||||
|
await writeFile(path.join(DIR, 'proxy.jpg'), await sharp(rgb8, { raw: { width: W, height: H, channels: 3 } })
|
||||||
|
.jpeg({ quality: 96, chromaSubsampling: '4:4:4' })
|
||||||
|
.toBuffer());
|
||||||
|
await writeFile(path.join(DIR, 'side.p16.png'), encodePng16(rgb16, W, H));
|
||||||
|
await writeFile(PAGE, PAGE_HTML);
|
||||||
|
|
||||||
|
const server = await createServer({
|
||||||
|
root: ROOT,
|
||||||
|
logLevel: 'error',
|
||||||
|
server: { host: '127.0.0.1', port: 5199, strictPort: false },
|
||||||
|
});
|
||||||
|
await server.listen();
|
||||||
|
const base = server.resolvedUrls?.local?.[0] ?? 'http://127.0.0.1:5199/';
|
||||||
|
|
||||||
|
let text = '';
|
||||||
|
try {
|
||||||
|
if (!chromeBin) {
|
||||||
|
console.log('render check SKIPPED: no Chrome/Chromium found (set CHROME_PATH to run it).');
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
text = await drive(chromeBin, `${base.replace(/\/$/, '')}/.render-check/`);
|
||||||
|
} finally {
|
||||||
|
await server.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (text.startsWith('ERROR')) {
|
||||||
|
console.error(`render check FAILED: ${text.slice(6)}`);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
const marker = text.indexOf('RESULT');
|
||||||
|
if (marker < 0) {
|
||||||
|
console.error('render check FAILED: the probe never reported a result.');
|
||||||
|
console.error(text.slice(0, 500));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
const result = JSON.parse(text.slice(marker + 7));
|
||||||
|
console.log(
|
||||||
|
`render check: proxy top=${result.proxyTop} bottom=${result.proxyBottom}` +
|
||||||
|
` | sidecar top=${result.sidecarTop} bottom=${result.sidecarBottom}` +
|
||||||
|
` | flip flag honoured for ImageBitmap=${result.flagHonouredForBitmap}`,
|
||||||
|
);
|
||||||
|
console.log(
|
||||||
|
`render check: clipping overlay red=${JSON.stringify(result.clipPixels[0])}` +
|
||||||
|
` yellow=${JSON.stringify(result.clipPixels[1])}` +
|
||||||
|
` clear=${JSON.stringify(result.clipPixels[2])}` +
|
||||||
|
` | at +6EV the clear band is ${JSON.stringify(result.brightPixel)}`,
|
||||||
|
);
|
||||||
|
console.log(
|
||||||
|
`render check: shadow overlay clear=${JSON.stringify(result.shadowPixels[0])}` +
|
||||||
|
` red=${JSON.stringify(result.shadowPixels[1])}` +
|
||||||
|
` yellow=${JSON.stringify(result.shadowPixels[2])}` +
|
||||||
|
` cyan=${JSON.stringify(result.shadowPixels[3])}` +
|
||||||
|
` | at -9EV the clean band is ${JSON.stringify(result.shadowDarkPixel)}`,
|
||||||
|
);
|
||||||
|
console.log(
|
||||||
|
`render check: mask curve identity=${JSON.stringify(result.maskIdentityPixel)}` +
|
||||||
|
` darkened=${JSON.stringify(result.maskCurvePixel)}`,
|
||||||
|
);
|
||||||
|
console.log(
|
||||||
|
`render check: mask group subtract=${JSON.stringify(result.maskGroupSubtractPixel)}` +
|
||||||
|
` intersect=${JSON.stringify(result.maskGroupIntersectPixel)}`,
|
||||||
|
);
|
||||||
|
if (!result.matchTop || !result.matchBottom) {
|
||||||
|
console.error(
|
||||||
|
result.reversed
|
||||||
|
? 'render check FAILED: the sidecar lands upside down against the proxy.'
|
||||||
|
: 'render check FAILED: proxy and sidecar rows do not line up.',
|
||||||
|
);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
if (!result.clipRed || !result.clipYellow || !result.clipClear) {
|
||||||
|
console.error(
|
||||||
|
'render check FAILED: the clipping overlay lost its channel colours ' +
|
||||||
|
`(red=${result.clipRed}, yellow=${result.clipYellow}, clear=${result.clipClear}).`,
|
||||||
|
);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
if (!result.shadowClear || !result.shadowRed || !result.shadowYellow || !result.shadowCyan) {
|
||||||
|
console.error(
|
||||||
|
'render check FAILED: the shadow clipping overlay lost its channel colours ' +
|
||||||
|
`(clear=${result.shadowClear}, red=${result.shadowRed}, ` +
|
||||||
|
`yellow=${result.shadowYellow}, cyan=${result.shadowCyan}).`,
|
||||||
|
);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
if (!result.maskIdentityFlat || !result.maskCurveDarkens) {
|
||||||
|
console.error(
|
||||||
|
'render check FAILED: the per-mask curve is not reaching the grade ' +
|
||||||
|
`(identity=${JSON.stringify(result.maskIdentityPixel)}, ` +
|
||||||
|
`curve=${JSON.stringify(result.maskCurvePixel)}).`,
|
||||||
|
);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
if (!result.maskGroupSubtractCleared || !result.maskGroupIntersectDarkens) {
|
||||||
|
console.error(
|
||||||
|
'render check FAILED: mask group shapes are not compositing ' +
|
||||||
|
`(subtract=${JSON.stringify(result.maskGroupSubtractPixel)}, ` +
|
||||||
|
`intersect=${JSON.stringify(result.maskGroupIntersectPixel)}).`,
|
||||||
|
);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
if (!result.shadowFollowsExposure) {
|
||||||
|
console.error(
|
||||||
|
'render check FAILED: the shadow clipping overlay does not follow Exposure; ' +
|
||||||
|
`at -9EV the clean band stayed ${JSON.stringify(result.shadowDarkPixel)}.`,
|
||||||
|
);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
if (!result.clipFollowsExposure) {
|
||||||
|
console.error(
|
||||||
|
'render check FAILED: the clipping overlay does not follow Exposure; ' +
|
||||||
|
`the unclipped band stayed ${JSON.stringify(result.brightPixel)} at +6 EV.`,
|
||||||
|
);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
console.log(
|
||||||
|
`render check: brush dab hard=${JSON.stringify(result.dabHard)}` +
|
||||||
|
` outsideHard=${JSON.stringify(result.dabOutsideHard)} soft=${JSON.stringify(result.dabSoft)}` +
|
||||||
|
` rimSoft=${JSON.stringify(result.dabRimSoft)} outsideSoft=${JSON.stringify(result.dabOutsideSoft)}`,
|
||||||
|
);
|
||||||
|
console.log(
|
||||||
|
`render check: mask overlay core=${JSON.stringify(result.tintCore)}` +
|
||||||
|
` rim=${JSON.stringify(result.tintRim)} outside=${JSON.stringify(result.tintOutside)}`,
|
||||||
|
);
|
||||||
|
console.log(
|
||||||
|
`render check: crop mask tint on=${JSON.stringify(result.cropTintOn)}` +
|
||||||
|
` off=${JSON.stringify(result.cropTintOff)} ref=${JSON.stringify(result.cropRef)}` +
|
||||||
|
` | local detail on=${JSON.stringify(result.cropDetailOn)}` +
|
||||||
|
` off=${JSON.stringify(result.cropDetailOff)}`,
|
||||||
|
);
|
||||||
|
console.log(
|
||||||
|
`render check: lens mask tint on=${JSON.stringify(result.lensTintOn)}` +
|
||||||
|
` off=${JSON.stringify(result.lensTintOff)} ref=${JSON.stringify(result.lensRef)}` +
|
||||||
|
` | tint strength full=${JSON.stringify(result.tintFull)}` +
|
||||||
|
` half=${JSON.stringify(result.tintCore)}`,
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
!result.cropTintAligned ||
|
||||||
|
!result.cropTintBounded ||
|
||||||
|
!result.cropDetailAligned ||
|
||||||
|
!result.cropDetailBounded ||
|
||||||
|
!result.lensTintAligned ||
|
||||||
|
!result.lensTintBounded ||
|
||||||
|
!result.tintStrengthWorks ||
|
||||||
|
!result.tintOffMatches
|
||||||
|
) {
|
||||||
|
console.error(
|
||||||
|
'render check FAILED: the local mask does not stay on its source pixels ' +
|
||||||
|
'through a crop or a lens warp ' +
|
||||||
|
`(crop tint ${JSON.stringify(result.cropTintOn)}/${JSON.stringify(result.cropTintOff)}` +
|
||||||
|
` vs ${JSON.stringify(result.cropRef)}, detail ` +
|
||||||
|
`${JSON.stringify(result.cropDetailOn)}/${JSON.stringify(result.cropDetailOff)}` +
|
||||||
|
`, lens tint ${JSON.stringify(result.lensTintOn)}/${JSON.stringify(result.lensTintOff)}` +
|
||||||
|
` vs ${JSON.stringify(result.lensRef)}).`,
|
||||||
|
);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
!result.dabCoreDarkened ||
|
||||||
|
!result.dabSoftCoreDarkened ||
|
||||||
|
!result.dabRimSmooth ||
|
||||||
|
!result.dabBoundedHard ||
|
||||||
|
!result.dabBoundedSoft ||
|
||||||
|
!result.tintFollowsMask ||
|
||||||
|
!result.tintBounded
|
||||||
|
) {
|
||||||
|
console.error(
|
||||||
|
'render check FAILED: the brush mask does not follow the brush circle ' +
|
||||||
|
`(hard=${JSON.stringify(result.dabHard)}, rim=${JSON.stringify(result.dabRimSoft)}, ` +
|
||||||
|
`outsideHard=${JSON.stringify(result.dabOutsideHard)}, ` +
|
||||||
|
`outsideSoft=${JSON.stringify(result.dabOutsideSoft)}, ` +
|
||||||
|
`tint=${JSON.stringify(result.tintCore)}/${JSON.stringify(result.tintRim)}/` +
|
||||||
|
`${JSON.stringify(result.tintOutside)}).`,
|
||||||
|
);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
console.log(
|
||||||
|
'render check PASSED: proxy and sidecar share a row order and the clipping overlay names the channels.',
|
||||||
|
);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
let code = 1;
|
||||||
|
try {
|
||||||
|
code = await main();
|
||||||
|
} catch (err) {
|
||||||
|
console.error(`render check FAILED: ${err instanceof Error ? err.message : String(err)}`);
|
||||||
|
} finally {
|
||||||
|
await rm(DIR, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 }).catch(() => {
|
||||||
|
/* a stray Chrome profile is not worth failing the check over */
|
||||||
|
});
|
||||||
|
}
|
||||||
|
process.exit(code);
|
||||||
@@ -281,6 +281,56 @@ if (!immichAlbumColumns.includes('kind')) {
|
|||||||
db.exec("ALTER TABLE immich_albums ADD COLUMN kind TEXT NOT NULL DEFAULT 'import'");
|
db.exec("ALTER TABLE immich_albums ADD COLUMN kind TEXT NOT NULL DEFAULT 'import'");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Applying a lens profile used to enable its vignetting correction, and that
|
||||||
|
* flat-field gain over-exposed the edges. The correction is opt-in now, so the
|
||||||
|
* flag older edits stored is cleared once, here, before anything reads the
|
||||||
|
* catalogue. Matching on the JSON text keeps the scan to the few rows that ever
|
||||||
|
* carried it, and the rows it rewrites no longer match, so it is idempotent.
|
||||||
|
*/
|
||||||
|
const legacyVignetting = db
|
||||||
|
.prepare(`SELECT id, data FROM photos WHERE instr(data, '"vignetting":true') > 0`)
|
||||||
|
.all();
|
||||||
|
if (legacyVignetting.length) {
|
||||||
|
const updateData = db.prepare('UPDATE photos SET data = ?, updated_at = ? WHERE id = ?');
|
||||||
|
const clear = (edits) => {
|
||||||
|
const lens = edits && edits.lens;
|
||||||
|
if (!lens || !lens.corrections || lens.corrections.vignetting !== true) return edits;
|
||||||
|
return { ...edits, lens: { ...lens, corrections: { ...lens.corrections, vignetting: false } } };
|
||||||
|
};
|
||||||
|
let cleared = 0;
|
||||||
|
for (const row of legacyVignetting) {
|
||||||
|
let record;
|
||||||
|
try {
|
||||||
|
record = JSON.parse(row.data);
|
||||||
|
} catch {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!record || typeof record !== 'object') continue;
|
||||||
|
let changed = false;
|
||||||
|
const strip = (edits) => {
|
||||||
|
const next = clear(edits);
|
||||||
|
if (next !== edits) changed = true;
|
||||||
|
return next;
|
||||||
|
};
|
||||||
|
record.edits = strip(record.edits);
|
||||||
|
if (Array.isArray(record.snapshots)) {
|
||||||
|
record.snapshots = record.snapshots.map((snap) =>
|
||||||
|
snap && snap.edits ? { ...snap, edits: strip(snap.edits) } : snap,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (Array.isArray(record.history)) {
|
||||||
|
record.history = record.history.map((entry) =>
|
||||||
|
entry && entry.edits ? { ...entry, edits: strip(entry.edits) } : entry,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (!changed) continue;
|
||||||
|
updateData.run(JSON.stringify(record), Date.now(), row.id);
|
||||||
|
cleared += 1;
|
||||||
|
}
|
||||||
|
if (cleared) console.log(`lens vignetting: cleared the stored corner gain on ${cleared} photo(s)`);
|
||||||
|
}
|
||||||
|
|
||||||
const q = {
|
const q = {
|
||||||
upsertEvent: db.prepare(`
|
upsertEvent: db.prepare(`
|
||||||
INSERT INTO events (id, owner_id, sort_index, created_at, data) VALUES (?, ?, ?, ?, ?)
|
INSERT INTO events (id, owner_id, sort_index, created_at, data) VALUES (?, ?, ?, ?, ?)
|
||||||
|
|||||||
+52
-5
@@ -974,6 +974,55 @@ route('PUT', '/api/admin/storage', async ({ req, res }) => {
|
|||||||
|
|
||||||
let previewRebuild = null;
|
let previewRebuild = null;
|
||||||
|
|
||||||
|
/** Progress file, so a restart resumes a run instead of starting it over. */
|
||||||
|
function previewRebuildFile() {
|
||||||
|
return path.join(storageRoot(), 'preview-rebuild.json');
|
||||||
|
}
|
||||||
|
|
||||||
|
function savePreviewRebuild(state) {
|
||||||
|
try {
|
||||||
|
fs.writeFileSync(previewRebuildFile(), JSON.stringify(state));
|
||||||
|
} catch {
|
||||||
|
/* Progress is a convenience; a read-only storage root must not stop a run. */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs the job and mirrors its progress to disk after every photo. The proxy
|
||||||
|
* rebuild takes hours on a full library, so losing it to a deploy means
|
||||||
|
* starting from the first photo again.
|
||||||
|
*/
|
||||||
|
function beginPreviewRebuild(targets) {
|
||||||
|
const job = startPreviewRebuild({
|
||||||
|
targets,
|
||||||
|
regenerate: (photo) => regenerateRawPreview(photo.id, photo, photoOwner(photo.id) ?? ''),
|
||||||
|
onProgress: (snapshot, pending) =>
|
||||||
|
savePreviewRebuild({ ...snapshot, pending: pending.map((photo) => photo.id) }),
|
||||||
|
});
|
||||||
|
savePreviewRebuild({ ...job.snapshot(), pending: targets.map((photo) => photo.id) });
|
||||||
|
void job.finished.then(() => savePreviewRebuild({ ...job.snapshot(), pending: [] }));
|
||||||
|
previewRebuild = job;
|
||||||
|
return job;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Restarts a run that a restart interrupted, skipping finished photos. */
|
||||||
|
function resumePreviewRebuild() {
|
||||||
|
let saved = null;
|
||||||
|
try {
|
||||||
|
saved = JSON.parse(fs.readFileSync(previewRebuildFile(), 'utf8'));
|
||||||
|
} catch {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (saved?.state !== 'running' || !Array.isArray(saved.pending) || saved.pending.length === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const byId = new Map(listPhotos().map((photo) => [photo.id, photo]));
|
||||||
|
const targets = saved.pending.map((id) => byId.get(id)).filter(Boolean);
|
||||||
|
if (targets.length === 0) return;
|
||||||
|
console.log(` previews: resuming rebuild, ${targets.length} photo(s) left`);
|
||||||
|
beginPreviewRebuild(targets);
|
||||||
|
}
|
||||||
|
|
||||||
function previewRebuildStatus() {
|
function previewRebuildStatus() {
|
||||||
return (
|
return (
|
||||||
previewRebuild?.snapshot() ?? {
|
previewRebuild?.snapshot() ?? {
|
||||||
@@ -1005,11 +1054,8 @@ route('POST', '/api/admin/previews/rebuild', async ({ req, res }) => {
|
|||||||
const current = previewRebuildStatus();
|
const current = previewRebuildStatus();
|
||||||
if (current.state === 'running') return json(res, 202, { rebuild: current });
|
if (current.state === 'running') return json(res, 202, { rebuild: current });
|
||||||
const targets = previewRebuildTargets(listPhotos());
|
const targets = previewRebuildTargets(listPhotos());
|
||||||
previewRebuild = startPreviewRebuild({
|
const rebuild = beginPreviewRebuild(targets);
|
||||||
targets,
|
json(res, 202, { rebuild: rebuild.snapshot() });
|
||||||
regenerate: (photo) => regenerateRawPreview(photo.id, photo, photoOwner(photo.id) ?? ''),
|
|
||||||
});
|
|
||||||
json(res, 202, { rebuild: previewRebuild.snapshot() });
|
|
||||||
});
|
});
|
||||||
|
|
||||||
route('GET', '/api/quota', async ({ req, res }) => {
|
route('GET', '/api/quota', async ({ req, res }) => {
|
||||||
@@ -2531,6 +2577,7 @@ server.listen(PORT, HOST, async () => {
|
|||||||
);
|
);
|
||||||
console.log(` users: ${users.count()} account(s)${users.count() === 0 ? ' — first signup becomes admin' : ''}`);
|
console.log(` users: ${users.count()} account(s)${users.count() === 0 ? ' — first signup becomes admin' : ''}`);
|
||||||
if (!raw.libraw) console.log(' note: install libraw-wasm for full raw demosaic (embedded previews still work)');
|
if (!raw.libraw) console.log(' note: install libraw-wasm for full raw demosaic (embedded previews still work)');
|
||||||
|
resumePreviewRebuild();
|
||||||
});
|
});
|
||||||
|
|
||||||
setInterval(() => {
|
setInterval(() => {
|
||||||
|
|||||||
@@ -3,8 +3,9 @@
|
|||||||
*
|
*
|
||||||
* A decode is CPU bound and holds a LibRaw worker for seconds, so the work runs
|
* A decode is CPU bound and holds a LibRaw worker for seconds, so the work runs
|
||||||
* one photo at a time behind a snapshot: a request that blocked for an hour
|
* one photo at a time behind a snapshot: a request that blocked for an hour
|
||||||
* would time out, and decoding in parallel would starve the editor. Progress
|
* would time out, and decoding in parallel would starve the editor. The job
|
||||||
* lives in memory only, so an interrupted rebuild simply starts again.
|
* itself keeps progress in memory; `onProgress` lets the caller persist it so a
|
||||||
|
* restart can pick the run up where it stopped.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
/** Photos that have a proxy worth regenerating: camera raws that still exist. */
|
/** Photos that have a proxy worth regenerating: camera raws that still exist. */
|
||||||
@@ -18,7 +19,7 @@ export function previewRebuildTargets(photos) {
|
|||||||
* A photo that fails is counted and recorded, and the run continues: one
|
* A photo that fails is counted and recorded, and the run continues: one
|
||||||
* unreadable original must not strand the rest of the library.
|
* unreadable original must not strand the rest of the library.
|
||||||
*/
|
*/
|
||||||
export function startPreviewRebuild({ targets, regenerate, now = Date.now }) {
|
export function startPreviewRebuild({ targets, regenerate, now = Date.now, onProgress }) {
|
||||||
const job = {
|
const job = {
|
||||||
state: 'running',
|
state: 'running',
|
||||||
total: targets.length,
|
total: targets.length,
|
||||||
@@ -31,7 +32,7 @@ export function startPreviewRebuild({ targets, regenerate, now = Date.now }) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const finished = (async () => {
|
const finished = (async () => {
|
||||||
for (const photo of targets) {
|
for (const [index, photo] of targets.entries()) {
|
||||||
try {
|
try {
|
||||||
const result = await regenerate(photo);
|
const result = await regenerate(photo);
|
||||||
if (result?.sidecar) job.sidecars += 1;
|
if (result?.sidecar) job.sidecars += 1;
|
||||||
@@ -43,6 +44,7 @@ export function startPreviewRebuild({ targets, regenerate, now = Date.now }) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
job.done += 1;
|
job.done += 1;
|
||||||
|
onProgress?.({ ...job, errors: [...job.errors] }, targets.slice(index + 1));
|
||||||
}
|
}
|
||||||
job.state = 'done';
|
job.state = 'done';
|
||||||
job.finishedAt = now();
|
job.finishedAt = now();
|
||||||
|
|||||||
@@ -63,6 +63,22 @@ describe('preview rebuild job', () => {
|
|||||||
expect(job.snapshot().errors).toEqual([]);
|
expect(job.snapshot().errors).toEqual([]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('reports progress and what is still pending after each photo', async () => {
|
||||||
|
const steps = [];
|
||||||
|
const job = startPreviewRebuild({
|
||||||
|
targets: [{ id: 'a' }, { id: 'b' }, { id: 'c' }],
|
||||||
|
regenerate: async () => ({ sidecar: false }),
|
||||||
|
onProgress: (snapshot, pending) =>
|
||||||
|
steps.push({ done: snapshot.done, pending: pending.map((photo) => photo.id) }),
|
||||||
|
});
|
||||||
|
await job.finished;
|
||||||
|
expect(steps).toEqual([
|
||||||
|
{ done: 1, pending: ['b', 'c'] },
|
||||||
|
{ done: 2, pending: ['c'] },
|
||||||
|
{ done: 3, pending: [] },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
it('finishes immediately when there is nothing to rebuild', async () => {
|
it('finishes immediately when there is nothing to rebuild', async () => {
|
||||||
const job = startPreviewRebuild({ targets: [], regenerate: async () => ({ sidecar: false }) });
|
const job = startPreviewRebuild({ targets: [], regenerate: async () => ({ sidecar: false }) });
|
||||||
await job.finished;
|
await job.finished;
|
||||||
|
|||||||
+368
-103
@@ -2,8 +2,10 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
|||||||
import {
|
import {
|
||||||
ASPECTS,
|
ASPECTS,
|
||||||
defaultEdits,
|
defaultEdits,
|
||||||
|
defaultLocalComponent,
|
||||||
defaultLocalLayer,
|
defaultLocalLayer,
|
||||||
MAX_HEAL_SPOTS,
|
MAX_HEAL_SPOTS,
|
||||||
|
MAX_LOCAL_COMPONENTS,
|
||||||
MAX_LOCAL_LAYERS,
|
MAX_LOCAL_LAYERS,
|
||||||
} from '../lib/edits';
|
} from '../lib/edits';
|
||||||
import { subscribeClipPreview } from '../lib/clipPreview';
|
import { subscribeClipPreview } from '../lib/clipPreview';
|
||||||
@@ -35,6 +37,7 @@ import type {
|
|||||||
EventRecord,
|
EventRecord,
|
||||||
Flag,
|
Flag,
|
||||||
HealSpot,
|
HealSpot,
|
||||||
|
LocalComponent,
|
||||||
LocalLayer,
|
LocalLayer,
|
||||||
LocalMaskKind,
|
LocalMaskKind,
|
||||||
LocalStroke,
|
LocalStroke,
|
||||||
@@ -105,16 +108,21 @@ const EMPTY_GEO: Geometry = {
|
|||||||
function cloneLocalLayer(layer: LocalLayer): LocalLayer {
|
function cloneLocalLayer(layer: LocalLayer): LocalLayer {
|
||||||
return {
|
return {
|
||||||
...layer,
|
...layer,
|
||||||
brush: {
|
components: layer.components.map((component) => ({
|
||||||
strokes: layer.brush.strokes.map((stroke) => ({
|
...component,
|
||||||
...stroke,
|
brush: {
|
||||||
points: stroke.points.map((point) => ({ ...point })),
|
strokes: component.brush.strokes.map((stroke) => ({
|
||||||
})),
|
...stroke,
|
||||||
},
|
points: stroke.points.map((point) => ({ ...point })),
|
||||||
linear: { ...layer.linear },
|
})),
|
||||||
radial: { ...layer.radial },
|
},
|
||||||
|
linear: { ...component.linear },
|
||||||
|
radial: { ...component.radial },
|
||||||
|
...(component.raster ? { raster: { ...component.raster } } : {}),
|
||||||
|
})),
|
||||||
adjust: { ...layer.adjust },
|
adjust: { ...layer.adjust },
|
||||||
range: { ...layer.range },
|
range: { ...layer.range },
|
||||||
|
curve: layer.curve.map((point) => ({ ...point })),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -253,11 +261,18 @@ export default function Develop({
|
|||||||
const healDrag = useRef<{ index: number; mode: 'target' | 'source'; spot: HealSpot } | null>(null);
|
const healDrag = useRef<{ index: number; mode: 'target' | 'source'; spot: HealSpot } | null>(null);
|
||||||
|
|
||||||
const [localSelected, setLocalSelected] = useState<string | null>(null);
|
const [localSelected, setLocalSelected] = useState<string | null>(null);
|
||||||
|
const [localComponentSelected, setLocalComponentSelected] = useState<string | null>(null);
|
||||||
const [localMode, setLocalMode] = useState(false);
|
const [localMode, setLocalMode] = useState(false);
|
||||||
const [autoMaskBusy, setAutoMaskBusy] = useState(false);
|
const [autoMaskBusy, setAutoMaskBusy] = useState(false);
|
||||||
const [localBrush, setLocalBrush] = useState(72);
|
const [localBrush, setLocalBrush] = useState(72);
|
||||||
const [localHover, setLocalHover] = useState<{ x: number; y: number } | null>(null);
|
const [localHover, setLocalHover] = useState<{ x: number; y: number } | null>(null);
|
||||||
const [localDraft, setLocalDraft] = useState<LocalStroke | null>(null);
|
const [localDraft, setLocalDraft] = useState<LocalStroke | null>(null);
|
||||||
|
// The mask tint is a view aid, not an edit: it has its own toggle (O) and
|
||||||
|
// strength, and both are display preferences rather than catalog data.
|
||||||
|
const [maskOverlay, setMaskOverlay] = usePersistentState('develop.maskOverlay', true);
|
||||||
|
const [maskStrength, setMaskStrength] = usePersistentState('develop.maskStrength', 50);
|
||||||
|
// How the next mask gesture combines with the group: paint or erase.
|
||||||
|
const [localErase, setLocalErase] = useState(false);
|
||||||
const [lensCorrection, setLensCorrection] = useState<LensCorrection | null>(null);
|
const [lensCorrection, setLensCorrection] = useState<LensCorrection | null>(null);
|
||||||
const [lensSplit, setLensSplit] = useState(false);
|
const [lensSplit, setLensSplit] = useState(false);
|
||||||
const [lensSplitAt, setLensSplitAt] = useState(0.5);
|
const [lensSplitAt, setLensSplitAt] = useState(0.5);
|
||||||
@@ -266,7 +281,8 @@ export default function Develop({
|
|||||||
error: null,
|
error: null,
|
||||||
});
|
});
|
||||||
const localDrag = useRef<{
|
const localDrag = useRef<{
|
||||||
id: string;
|
layerId: string;
|
||||||
|
componentId: string;
|
||||||
mode: 'brush' | 'center' | 'edge' | 'edgeX' | 'edgeY' | 'start' | 'end';
|
mode: 'brush' | 'center' | 'edge' | 'edgeX' | 'edgeY' | 'start' | 'end';
|
||||||
stroke: LocalStroke | null;
|
stroke: LocalStroke | null;
|
||||||
} | null>(null);
|
} | null>(null);
|
||||||
@@ -280,6 +296,10 @@ export default function Develop({
|
|||||||
[photos, photo.meta?.camera],
|
[photos, photo.meta?.camera],
|
||||||
);
|
);
|
||||||
const activeLocal = (edits.local ?? []).find((layer) => layer.id === localSelected) ?? null;
|
const activeLocal = (edits.local ?? []).find((layer) => layer.id === localSelected) ?? null;
|
||||||
|
const activeComponent =
|
||||||
|
activeLocal?.components.find((component) => component.id === localComponentSelected) ??
|
||||||
|
activeLocal?.components[0] ??
|
||||||
|
null;
|
||||||
const zoomed = zoom.pct !== 'fit';
|
const zoomed = zoom.pct !== 'fit';
|
||||||
|
|
||||||
// The filmstrip has its own Lightroom-style cull filter so you can narrow the
|
// The filmstrip has its own Lightroom-style cull filter so you can narrow the
|
||||||
@@ -583,6 +603,15 @@ export default function Develop({
|
|||||||
: view,
|
: view,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// The mask overlay is the baked mask itself, and it is a view toggle: off
|
||||||
|
// while holding \\ (before/after), while the mask tool is closed, or when
|
||||||
|
// the user hides it. The histogram ignores it: a tinted chart is not a
|
||||||
|
// measurement of the photo.
|
||||||
|
const maskView =
|
||||||
|
showOriginal || !localMode || !maskOverlay
|
||||||
|
? -1
|
||||||
|
: (edits.local ?? []).findIndex((layer) => layer.id === localSelected);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
renderer.setImage(bitmap, hdrSource);
|
renderer.setImage(bitmap, hdrSource);
|
||||||
// "Show original" must show the untouched source, not the cleaned proxy.
|
// "Show original" must show the untouched source, not the cleaned proxy.
|
||||||
@@ -592,7 +621,7 @@ export default function Develop({
|
|||||||
height: pxH,
|
height: pxH,
|
||||||
cropPreview: cropMode,
|
cropPreview: cropMode,
|
||||||
// The histogram describes the whole photo, so it is only refreshed at fit.
|
// The histogram describes the whole photo, so it is only refreshed at fit.
|
||||||
histogram: !cropMode && !showOriginal && zoomFactor <= 1.0001,
|
histogram: !cropMode && !showOriginal && zoomFactor <= 1.0001 && maskView < 0,
|
||||||
view: zoomFactor <= 1.0001 ? undefined : view,
|
view: zoomFactor <= 1.0001 ? undefined : view,
|
||||||
// Holding the grain still keeps the noise from crawling while a crop
|
// Holding the grain still keeps the noise from crawling while a crop
|
||||||
// handle moves; the new crop-relative scale applies on release.
|
// handle moves; the new crop-relative scale applies on release.
|
||||||
@@ -604,6 +633,8 @@ export default function Develop({
|
|||||||
clipping: clipping ?? undefined,
|
clipping: clipping ?? undefined,
|
||||||
lens: showOriginal ? null : lensCorrection,
|
lens: showOriginal ? null : lensCorrection,
|
||||||
lensSplit: lensSplit && !showOriginal ? lensSplitAt : undefined,
|
lensSplit: lensSplit && !showOriginal ? lensSplitAt : undefined,
|
||||||
|
maskView,
|
||||||
|
maskStrength: maskStrength / 100,
|
||||||
});
|
});
|
||||||
histRef.current = renderer.histogram;
|
histRef.current = renderer.histogram;
|
||||||
setHistVersion((v) => v + 1);
|
setHistVersion((v) => v + 1);
|
||||||
@@ -625,6 +656,10 @@ export default function Develop({
|
|||||||
lensCorrection,
|
lensCorrection,
|
||||||
lensSplit,
|
lensSplit,
|
||||||
lensSplitAt,
|
lensSplitAt,
|
||||||
|
localMode,
|
||||||
|
localSelected,
|
||||||
|
maskOverlay,
|
||||||
|
maskStrength,
|
||||||
// Loading or clearing a printer profile changes the finish pass, and the
|
// Loading or clearing a printer profile changes the finish pass, and the
|
||||||
// cube lives outside the edit record, so the redraw is keyed on it here.
|
// cube lives outside the edit record, so the redraw is keyed on it here.
|
||||||
proofProfile,
|
proofProfile,
|
||||||
@@ -740,7 +775,7 @@ export default function Develop({
|
|||||||
if ((e.target as HTMLElement | null)?.closest('.loupe-adjust')) return;
|
if ((e.target as HTMLElement | null)?.closest('.loupe-adjust')) return;
|
||||||
if (cropMode) return;
|
if (cropMode) return;
|
||||||
// While painting a mask, the wheel sizes the brush instead of zooming.
|
// While painting a mask, the wheel sizes the brush instead of zooming.
|
||||||
if (localMode && activeLocal?.kind === 'brush') {
|
if (localMode && activeComponent?.kind === 'brush') {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
setLocalBrush((v) => clampNum(v * Math.exp(-e.deltaY * 0.0015), 8, 320));
|
setLocalBrush((v) => clampNum(v * Math.exp(-e.deltaY * 0.0015), 8, 320));
|
||||||
return;
|
return;
|
||||||
@@ -760,7 +795,7 @@ export default function Develop({
|
|||||||
};
|
};
|
||||||
el.addEventListener('wheel', onWheel, { passive: false });
|
el.addEventListener('wheel', onWheel, { passive: false });
|
||||||
return () => el.removeEventListener('wheel', onWheel);
|
return () => el.removeEventListener('wheel', onWheel);
|
||||||
}, [cropMode, applyZoom, healMode, localMode, activeLocal]);
|
}, [cropMode, applyZoom, healMode, localMode, activeComponent]);
|
||||||
|
|
||||||
const beginPan = (e: React.PointerEvent<HTMLCanvasElement>) => {
|
const beginPan = (e: React.PointerEvent<HTMLCanvasElement>) => {
|
||||||
if (picking || rangePicking || cropMode || healMode || localMode || !zoomed || e.button !== 0) return;
|
if (picking || rangePicking || cropMode || healMode || localMode || !zoomed || e.button !== 0) return;
|
||||||
@@ -1013,6 +1048,26 @@ export default function Develop({
|
|||||||
[commitLocal, photo.edits.local],
|
[commitLocal, photo.edits.local],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
/** Updates one shape inside a layer's mask group. */
|
||||||
|
const patchComponent = useCallback(
|
||||||
|
(layerId: string, componentId: string, patch: Partial<LocalComponent>, label = 'Local adjustment') => {
|
||||||
|
commitLocal(
|
||||||
|
(photo.edits.local ?? []).map((layer) =>
|
||||||
|
layer.id === layerId
|
||||||
|
? {
|
||||||
|
...layer,
|
||||||
|
components: layer.components.map((component) =>
|
||||||
|
component.id === componentId ? { ...component, ...patch } : component,
|
||||||
|
),
|
||||||
|
}
|
||||||
|
: layer,
|
||||||
|
),
|
||||||
|
label,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
[commitLocal, photo.edits.local],
|
||||||
|
);
|
||||||
|
|
||||||
const addLocalLayer = useCallback(
|
const addLocalLayer = useCallback(
|
||||||
(kind: LocalMaskKind) => {
|
(kind: LocalMaskKind) => {
|
||||||
const layers = edits.local ?? [];
|
const layers = edits.local ?? [];
|
||||||
@@ -1020,6 +1075,7 @@ export default function Develop({
|
|||||||
const layer = defaultLocalLayer(kind, layers.length);
|
const layer = defaultLocalLayer(kind, layers.length);
|
||||||
commitLocal([...layers, layer], 'Add local adjustment');
|
commitLocal([...layers, layer], 'Add local adjustment');
|
||||||
setLocalSelected(layer.id);
|
setLocalSelected(layer.id);
|
||||||
|
setLocalComponentSelected(layer.components[0]?.id ?? null);
|
||||||
setLocalMode(true);
|
setLocalMode(true);
|
||||||
setCropMode(false);
|
setCropMode(false);
|
||||||
setHealMode(false);
|
setHealMode(false);
|
||||||
@@ -1037,10 +1093,14 @@ export default function Develop({
|
|||||||
const raster = await buildAutoMask(source, kind);
|
const raster = await buildAutoMask(source, kind);
|
||||||
const layer = defaultLocalLayer('raster', layers.length);
|
const layer = defaultLocalLayer('raster', layers.length);
|
||||||
layer.name = `Auto ${kind}`;
|
layer.name = `Auto ${kind}`;
|
||||||
layer.raster = raster;
|
const shape = layer.components[0];
|
||||||
layer.feather = 30;
|
if (shape) {
|
||||||
|
shape.raster = raster;
|
||||||
|
shape.feather = 30;
|
||||||
|
}
|
||||||
commitLocal([...layers, layer], `Auto ${kind} mask`);
|
commitLocal([...layers, layer], `Auto ${kind} mask`);
|
||||||
setLocalSelected(layer.id);
|
setLocalSelected(layer.id);
|
||||||
|
setLocalComponentSelected(layer.components[0]?.id ?? null);
|
||||||
setLocalMode(false);
|
setLocalMode(false);
|
||||||
setCropMode(false);
|
setCropMode(false);
|
||||||
setHealMode(false);
|
setHealMode(false);
|
||||||
@@ -1109,6 +1169,7 @@ export default function Develop({
|
|||||||
(id: string) => {
|
(id: string) => {
|
||||||
commitLocal((edits.local ?? []).filter((layer) => layer.id !== id), 'Delete local adjustment');
|
commitLocal((edits.local ?? []).filter((layer) => layer.id !== id), 'Delete local adjustment');
|
||||||
setLocalSelected(null);
|
setLocalSelected(null);
|
||||||
|
setLocalComponentSelected(null);
|
||||||
setLocalMode(false);
|
setLocalMode(false);
|
||||||
},
|
},
|
||||||
[commitLocal, edits.local],
|
[commitLocal, edits.local],
|
||||||
@@ -1127,6 +1188,7 @@ export default function Develop({
|
|||||||
};
|
};
|
||||||
commitLocal([...layers, copy], 'Duplicate local adjustment');
|
commitLocal([...layers, copy], 'Duplicate local adjustment');
|
||||||
setLocalSelected(copy.id);
|
setLocalSelected(copy.id);
|
||||||
|
setLocalComponentSelected(copy.components[0]?.id ?? null);
|
||||||
},
|
},
|
||||||
[commitLocal, edits.local],
|
[commitLocal, edits.local],
|
||||||
);
|
);
|
||||||
@@ -1146,11 +1208,39 @@ export default function Develop({
|
|||||||
};
|
};
|
||||||
commitLocal([...layers, copy], 'Paste local adjustment');
|
commitLocal([...layers, copy], 'Paste local adjustment');
|
||||||
setLocalSelected(copy.id);
|
setLocalSelected(copy.id);
|
||||||
|
setLocalComponentSelected(copy.components[0]?.id ?? null);
|
||||||
setLocalMode(true);
|
setLocalMode(true);
|
||||||
setCropMode(false);
|
setCropMode(false);
|
||||||
setHealMode(false);
|
setHealMode(false);
|
||||||
}, [commitLocal, edits.local, localClipboard]);
|
}, [commitLocal, edits.local, localClipboard]);
|
||||||
|
|
||||||
|
const addLocalComponent = useCallback(
|
||||||
|
(kind: LocalMaskKind) => {
|
||||||
|
if (!activeLocal) return;
|
||||||
|
if (activeLocal.components.length >= MAX_LOCAL_COMPONENTS) return;
|
||||||
|
const component = defaultLocalComponent(kind);
|
||||||
|
patchLocal(activeLocal.id, { components: [...activeLocal.components, component] }, 'Add mask shape');
|
||||||
|
setLocalComponentSelected(component.id);
|
||||||
|
setLocalMode(true);
|
||||||
|
setCropMode(false);
|
||||||
|
setHealMode(false);
|
||||||
|
setPicking(false);
|
||||||
|
},
|
||||||
|
[activeLocal, patchLocal],
|
||||||
|
);
|
||||||
|
|
||||||
|
const deleteLocalComponent = useCallback(
|
||||||
|
(componentId: string) => {
|
||||||
|
// A layer is its group: removing the last shape would leave an adjustment
|
||||||
|
// with no mask, so Delete layer is the way to remove it.
|
||||||
|
if (!activeLocal || activeLocal.components.length <= 1) return;
|
||||||
|
const remaining = activeLocal.components.filter((component) => component.id !== componentId);
|
||||||
|
patchLocal(activeLocal.id, { components: remaining }, 'Delete mask shape');
|
||||||
|
setLocalComponentSelected(remaining[0]?.id ?? null);
|
||||||
|
},
|
||||||
|
[activeLocal, patchLocal],
|
||||||
|
);
|
||||||
|
|
||||||
const toggleLocalMode = useCallback(() => {
|
const toggleLocalMode = useCallback(() => {
|
||||||
if (!activeLocal) return;
|
if (!activeLocal) return;
|
||||||
setLocalMode((v) => !v);
|
setLocalMode((v) => !v);
|
||||||
@@ -1160,21 +1250,25 @@ export default function Develop({
|
|||||||
}, [activeLocal]);
|
}, [activeLocal]);
|
||||||
|
|
||||||
const startLocalMask = (e: React.PointerEvent<HTMLCanvasElement>) => {
|
const startLocalMask = (e: React.PointerEvent<HTMLCanvasElement>) => {
|
||||||
if (!localMode || !activeLocal || !bitmap) return;
|
if (!localMode || !activeLocal || !activeComponent || !bitmap) return;
|
||||||
const p = sourcePointFromEvent(e);
|
const p = sourcePointFromEvent(e);
|
||||||
if (!p) return;
|
if (!p) return;
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
e.currentTarget.setPointerCapture(e.pointerId);
|
e.currentTarget.setPointerCapture(e.pointerId);
|
||||||
if (activeLocal.kind === 'brush') {
|
if (activeComponent.kind === 'brush') {
|
||||||
const stroke: LocalStroke = { points: [p], size: localRadius(), erase: e.altKey };
|
const stroke: LocalStroke = {
|
||||||
localDrag.current = { id: activeLocal.id, mode: 'brush', stroke };
|
points: [p],
|
||||||
|
size: localRadius(),
|
||||||
|
erase: e.altKey || localErase,
|
||||||
|
};
|
||||||
|
localDrag.current = { layerId: activeLocal.id, componentId: activeComponent.id, mode: 'brush', stroke };
|
||||||
setLocalDraft(stroke);
|
setLocalDraft(stroke);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (activeLocal.kind === 'radial') {
|
if (activeComponent.kind === 'radial') {
|
||||||
const aspect = bitmap.height / bitmap.width;
|
const aspect = bitmap.height / bitmap.width;
|
||||||
const nx = (p.x - activeLocal.radial.cx) / Math.max(0.001, activeLocal.radial.rx);
|
const nx = (p.x - activeComponent.radial.cx) / Math.max(0.001, activeComponent.radial.rx);
|
||||||
const ny = ((p.y - activeLocal.radial.cy) * aspect) / Math.max(0.001, activeLocal.radial.ry);
|
const ny = ((p.y - activeComponent.radial.cy) * aspect) / Math.max(0.001, activeComponent.radial.ry);
|
||||||
const mode =
|
const mode =
|
||||||
Math.abs(nx) > 0.82 && Math.abs(ny) < 0.65
|
Math.abs(nx) > 0.82 && Math.abs(ny) < 0.65
|
||||||
? 'edgeX'
|
? 'edgeX'
|
||||||
@@ -1183,12 +1277,23 @@ export default function Develop({
|
|||||||
: Math.hypot(nx, ny) > 0.82
|
: Math.hypot(nx, ny) > 0.82
|
||||||
? 'edge'
|
? 'edge'
|
||||||
: 'center';
|
: 'center';
|
||||||
localDrag.current = { id: activeLocal.id, mode, stroke: null };
|
localDrag.current = { layerId: activeLocal.id, componentId: activeComponent.id, mode, stroke: null };
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const ds = Math.hypot(p.x - activeLocal.linear.x1, (p.y - activeLocal.linear.y1) * (bitmap.height / bitmap.width));
|
const ds = Math.hypot(
|
||||||
const de = Math.hypot(p.x - activeLocal.linear.x2, (p.y - activeLocal.linear.y2) * (bitmap.height / bitmap.width));
|
p.x - activeComponent.linear.x1,
|
||||||
localDrag.current = { id: activeLocal.id, mode: ds <= de ? 'start' : 'end', stroke: null };
|
(p.y - activeComponent.linear.y1) * (bitmap.height / bitmap.width),
|
||||||
|
);
|
||||||
|
const de = Math.hypot(
|
||||||
|
p.x - activeComponent.linear.x2,
|
||||||
|
(p.y - activeComponent.linear.y2) * (bitmap.height / bitmap.width),
|
||||||
|
);
|
||||||
|
localDrag.current = {
|
||||||
|
layerId: activeLocal.id,
|
||||||
|
componentId: activeComponent.id,
|
||||||
|
mode: ds <= de ? 'start' : 'end',
|
||||||
|
stroke: null,
|
||||||
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
const moveLocalMask = (e: React.PointerEvent<HTMLCanvasElement>) => {
|
const moveLocalMask = (e: React.PointerEvent<HTMLCanvasElement>) => {
|
||||||
@@ -1198,8 +1303,9 @@ export default function Develop({
|
|||||||
setLocalHover(p);
|
setLocalHover(p);
|
||||||
const drag = localDrag.current;
|
const drag = localDrag.current;
|
||||||
if (!drag) return;
|
if (!drag) return;
|
||||||
const layer = (photo.edits.local ?? []).find((item) => item.id === drag.id);
|
const layer = (photo.edits.local ?? []).find((item) => item.id === drag.layerId);
|
||||||
if (!layer) return;
|
const shape = layer?.components.find((item) => item.id === drag.componentId);
|
||||||
|
if (!layer || !shape) return;
|
||||||
if (drag.mode === 'brush' && drag.stroke) {
|
if (drag.mode === 'brush' && drag.stroke) {
|
||||||
const last = drag.stroke.points[drag.stroke.points.length - 1];
|
const last = drag.stroke.points[drag.stroke.points.length - 1];
|
||||||
if (last && Math.hypot((p.x - last.x) * bitmap.width, (p.y - last.y) * bitmap.height) < 1.2) return;
|
if (last && Math.hypot((p.x - last.x) * bitmap.width, (p.y - last.y) * bitmap.height) < 1.2) return;
|
||||||
@@ -1209,46 +1315,51 @@ export default function Develop({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (drag.mode === 'center') {
|
if (drag.mode === 'center') {
|
||||||
patchLocal(layer.id, { radial: { ...layer.radial, cx: p.x, cy: p.y } }, 'Move local mask');
|
patchComponent(layer.id, shape.id, { radial: { ...shape.radial, cx: p.x, cy: p.y } }, 'Move local mask');
|
||||||
} else if (drag.mode === 'edgeX') {
|
} else if (drag.mode === 'edgeX') {
|
||||||
patchLocal(
|
patchComponent(
|
||||||
layer.id,
|
layer.id,
|
||||||
{ radial: { ...layer.radial, rx: clampNum(Math.abs(p.x - layer.radial.cx), 0.01, 1.5) } },
|
shape.id,
|
||||||
|
{ radial: { ...shape.radial, rx: clampNum(Math.abs(p.x - shape.radial.cx), 0.01, 1.5) } },
|
||||||
'Resize local mask',
|
'Resize local mask',
|
||||||
);
|
);
|
||||||
} else if (drag.mode === 'edgeY') {
|
} else if (drag.mode === 'edgeY') {
|
||||||
patchLocal(
|
patchComponent(
|
||||||
layer.id,
|
layer.id,
|
||||||
{ radial: { ...layer.radial, ry: clampNum(Math.abs(p.y - layer.radial.cy), 0.01, 1.5) } },
|
shape.id,
|
||||||
|
{ radial: { ...shape.radial, ry: clampNum(Math.abs(p.y - shape.radial.cy), 0.01, 1.5) } },
|
||||||
'Resize local mask',
|
'Resize local mask',
|
||||||
);
|
);
|
||||||
} else if (drag.mode === 'edge') {
|
} else if (drag.mode === 'edge') {
|
||||||
patchLocal(
|
patchComponent(
|
||||||
layer.id,
|
layer.id,
|
||||||
|
shape.id,
|
||||||
{
|
{
|
||||||
radial: {
|
radial: {
|
||||||
...layer.radial,
|
...shape.radial,
|
||||||
rx: clampNum(Math.abs(p.x - layer.radial.cx), 0.01, 1.5),
|
rx: clampNum(Math.abs(p.x - shape.radial.cx), 0.01, 1.5),
|
||||||
ry: clampNum(Math.abs(p.y - layer.radial.cy), 0.01, 1.5),
|
ry: clampNum(Math.abs(p.y - shape.radial.cy), 0.01, 1.5),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
'Resize local mask',
|
'Resize local mask',
|
||||||
);
|
);
|
||||||
} else if (drag.mode === 'start') {
|
} else if (drag.mode === 'start') {
|
||||||
patchLocal(layer.id, { linear: { ...layer.linear, x1: p.x, y1: p.y } }, 'Move local gradient');
|
patchComponent(layer.id, shape.id, { linear: { ...shape.linear, x1: p.x, y1: p.y } }, 'Move local gradient');
|
||||||
} else if (drag.mode === 'end') {
|
} else if (drag.mode === 'end') {
|
||||||
patchLocal(layer.id, { linear: { ...layer.linear, x2: p.x, y2: p.y } }, 'Move local gradient');
|
patchComponent(layer.id, shape.id, { linear: { ...shape.linear, x2: p.x, y2: p.y } }, 'Move local gradient');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const endLocalMask = (e: React.PointerEvent<HTMLCanvasElement>) => {
|
const endLocalMask = (e: React.PointerEvent<HTMLCanvasElement>) => {
|
||||||
const drag = localDrag.current;
|
const drag = localDrag.current;
|
||||||
if (drag?.mode === 'brush' && drag.stroke?.points.length) {
|
if (drag?.mode === 'brush' && drag.stroke?.points.length) {
|
||||||
const layer = (photo.edits.local ?? []).find((item) => item.id === drag.id);
|
const layer = (photo.edits.local ?? []).find((item) => item.id === drag.layerId);
|
||||||
if (layer) {
|
const shape = layer?.components.find((item) => item.id === drag.componentId);
|
||||||
patchLocal(
|
if (layer && shape) {
|
||||||
|
patchComponent(
|
||||||
layer.id,
|
layer.id,
|
||||||
{ brush: { strokes: [...layer.brush.strokes, drag.stroke].slice(-300) } },
|
shape.id,
|
||||||
|
{ brush: { strokes: [...shape.brush.strokes, drag.stroke].slice(-300) } },
|
||||||
drag.stroke.erase ? 'Erase local mask' : 'Paint local mask',
|
drag.stroke.erase ? 'Erase local mask' : 'Paint local mask',
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1281,18 +1392,35 @@ export default function Develop({
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setLocalSelected(null);
|
setLocalSelected(null);
|
||||||
|
setLocalComponentSelected(null);
|
||||||
setLocalMode(false);
|
setLocalMode(false);
|
||||||
setLocalDraft(null);
|
setLocalDraft(null);
|
||||||
|
setLocalErase(false);
|
||||||
localDrag.current = null;
|
localDrag.current = null;
|
||||||
}, [photo.id]);
|
}, [photo.id]);
|
||||||
|
|
||||||
|
// Leaving the mask tool drops the erase mode, so the next visit starts by
|
||||||
|
// painting rather than cutting holes into the mask.
|
||||||
|
useEffect(() => {
|
||||||
|
if (!localMode) setLocalErase(false);
|
||||||
|
}, [localMode]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!(edits.local ?? []).some((layer) => layer.id === localSelected)) {
|
if (!(edits.local ?? []).some((layer) => layer.id === localSelected)) {
|
||||||
setLocalSelected(null);
|
setLocalSelected(null);
|
||||||
|
setLocalComponentSelected(null);
|
||||||
setLocalMode(false);
|
setLocalMode(false);
|
||||||
}
|
}
|
||||||
}, [edits.local, localSelected]);
|
}, [edits.local, localSelected]);
|
||||||
|
|
||||||
|
// Keep a shape selected, so Edit mask always has something to route the
|
||||||
|
// pointer to after a layer switch or a shape delete.
|
||||||
|
useEffect(() => {
|
||||||
|
if (!activeLocal) return;
|
||||||
|
if (activeLocal.components.some((component) => component.id === localComponentSelected)) return;
|
||||||
|
setLocalComponentSelected(activeLocal.components[0]?.id ?? null);
|
||||||
|
}, [activeLocal, localComponentSelected]);
|
||||||
|
|
||||||
// Escape cancels the picker without touching the edit.
|
// Escape cancels the picker without touching the edit.
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!picking) return;
|
if (!picking) return;
|
||||||
@@ -1422,6 +1550,13 @@ export default function Develop({
|
|||||||
toggleLocalMode();
|
toggleLocalMode();
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
}
|
}
|
||||||
|
} else if (e.key.toLowerCase() === 'o' && !e.metaKey && !e.ctrlKey && !e.altKey) {
|
||||||
|
// The mask tint is a view, so it can be hidden while painting or
|
||||||
|
// checking the photo underneath without leaving the mask tool.
|
||||||
|
if (localMode) {
|
||||||
|
setMaskOverlay((v) => !v);
|
||||||
|
e.preventDefault();
|
||||||
|
}
|
||||||
} else if (e.key === 'Enter' && cropMode) {
|
} else if (e.key === 'Enter' && cropMode) {
|
||||||
setCropMode(false);
|
setCropMode(false);
|
||||||
} else if (e.key === 'Escape') {
|
} else if (e.key === 'Escape') {
|
||||||
@@ -1528,6 +1663,10 @@ export default function Develop({
|
|||||||
set={setEdits}
|
set={setEdits}
|
||||||
activeId={localSelected}
|
activeId={localSelected}
|
||||||
onSelect={(id) => setLocalSelected(id)}
|
onSelect={(id) => setLocalSelected(id)}
|
||||||
|
componentId={localComponentSelected}
|
||||||
|
onSelectComponent={setLocalComponentSelected}
|
||||||
|
onAddComponent={addLocalComponent}
|
||||||
|
onDeleteComponent={deleteLocalComponent}
|
||||||
onAdd={addLocalLayer}
|
onAdd={addLocalLayer}
|
||||||
onDelete={deleteLocalLayer}
|
onDelete={deleteLocalLayer}
|
||||||
onDuplicate={duplicateLocalLayer}
|
onDuplicate={duplicateLocalLayer}
|
||||||
@@ -2074,7 +2213,7 @@ export default function Develop({
|
|||||||
</svg>
|
</svg>
|
||||||
);
|
);
|
||||||
})()}
|
})()}
|
||||||
{localMode && bitmap && activeLocal && (() => {
|
{localMode && bitmap && activeComponent && (() => {
|
||||||
const geo = geoRef.current;
|
const geo = geoRef.current;
|
||||||
const view = geo.view;
|
const view = geo.view;
|
||||||
const marker = (p: { x: number; y: number }) => {
|
const marker = (p: { x: number; y: number }) => {
|
||||||
@@ -2098,47 +2237,66 @@ export default function Develop({
|
|||||||
y: ((f.y - view.y) / view.h) * 100,
|
y: ((f.y - view.y) / view.h) * 100,
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
const xScale = bitmap.width / (frame.w * view.w);
|
|
||||||
const canvasEl = canvasRef.current;
|
const canvasEl = canvasRef.current;
|
||||||
const canvasW = canvasEl?.clientWidth || 1;
|
const canvasW = canvasEl?.clientWidth || 1;
|
||||||
const canvasH = canvasEl?.clientHeight || 1;
|
// A brush radius is a fraction of the source width, but the
|
||||||
const strokes = localDraft
|
// overlay's 100×100 box is stretched over the canvas, so the
|
||||||
? [...activeLocal.brush.strokes, localDraft]
|
// two axes are converted separately. Using one frame term for
|
||||||
: activeLocal.brush.strokes;
|
// both (or the canvas aspect) turns the circle into an oval as
|
||||||
|
// soon as the photo is cropped or zoomed.
|
||||||
|
const radiusU = (r: number) => (r * bitmap.width * 100) / (frame.w * view.w);
|
||||||
|
const radiusV = (r: number) => (r * bitmap.width * 100) / (frame.h * view.h);
|
||||||
|
/** Brush diameter in canvas pixels, for the stroke preview. */
|
||||||
|
const diameterPx = (r: number) => (r * 2 * bitmap.width * canvasW) / (frame.w * view.w);
|
||||||
|
const feather = Math.max(0, Math.min(1, activeComponent.feather / 100));
|
||||||
|
// Committed strokes are not redrawn here: the shader tints the
|
||||||
|
// baked mask, which is the real feathered shape. Only the stroke
|
||||||
|
// in progress is drawn, as a preview of what will be baked.
|
||||||
|
const draft = localDraft && localDraft.points.length ? localDraft : null;
|
||||||
return (
|
return (
|
||||||
<svg className="local-layer" viewBox="0 0 100 100" preserveAspectRatio="none">
|
<svg className="local-layer" viewBox="0 0 100 100" preserveAspectRatio="none">
|
||||||
{activeLocal.kind === 'brush' &&
|
{activeComponent.kind === 'brush' &&
|
||||||
strokes.map((stroke, i) => {
|
(() => {
|
||||||
if (!stroke.points.length) return null;
|
if (!draft) return null;
|
||||||
const points = stroke.points.map(marker).map((p) => `${p.x},${p.y}`).join(' ');
|
const points = draft.points.map(marker).map((p) => `${p.x},${p.y}`).join(' ');
|
||||||
const width = Math.max(1, stroke.size * 2 * canvasW);
|
const width = Math.max(1, diameterPx(draft.size));
|
||||||
|
const core = Math.max(1, width * (1 - feather));
|
||||||
return (
|
return (
|
||||||
<polyline
|
<g>
|
||||||
key={i}
|
{core < width - 0.5 && (
|
||||||
points={points}
|
<polyline
|
||||||
className={`local-brush ${stroke.erase ? 'erase' : ''}`}
|
points={points}
|
||||||
strokeWidth={width}
|
className={`local-brush band ${draft.erase ? 'erase' : ''}`}
|
||||||
vectorEffect="non-scaling-stroke"
|
strokeWidth={width}
|
||||||
/>
|
vectorEffect="non-scaling-stroke"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<polyline
|
||||||
|
points={points}
|
||||||
|
className={`local-brush ${draft.erase ? 'erase' : ''}`}
|
||||||
|
strokeWidth={core}
|
||||||
|
vectorEffect="non-scaling-stroke"
|
||||||
|
/>
|
||||||
|
</g>
|
||||||
);
|
);
|
||||||
})}
|
})()}
|
||||||
{activeLocal.kind === 'radial' && (() => {
|
{activeComponent.kind === 'radial' && (() => {
|
||||||
const c = marker({ x: activeLocal.radial.cx, y: activeLocal.radial.cy });
|
const c = marker({ x: activeComponent.radial.cx, y: activeComponent.radial.cy });
|
||||||
const edge = marker({
|
const edge = marker({
|
||||||
x: activeLocal.radial.cx + activeLocal.radial.rx,
|
x: activeComponent.radial.cx + activeComponent.radial.rx,
|
||||||
y: activeLocal.radial.cy,
|
y: activeComponent.radial.cy,
|
||||||
});
|
});
|
||||||
const edgeY = marker({
|
const edgeY = marker({
|
||||||
x: activeLocal.radial.cx,
|
x: activeComponent.radial.cx,
|
||||||
y: activeLocal.radial.cy + activeLocal.radial.ry,
|
y: activeComponent.radial.cy + activeComponent.radial.ry,
|
||||||
});
|
});
|
||||||
// Sample the perimeter so the guide follows the same warp
|
// Sample the perimeter so the guide follows the same warp
|
||||||
// as the picture instead of staying a screen-space ellipse.
|
// as the picture instead of staying a screen-space ellipse.
|
||||||
const ring = Array.from({ length: 72 }, (_, i) => {
|
const ring = Array.from({ length: 72 }, (_, i) => {
|
||||||
const angle = (i / 72) * Math.PI * 2;
|
const angle = (i / 72) * Math.PI * 2;
|
||||||
const p = marker({
|
const p = marker({
|
||||||
x: activeLocal.radial.cx + Math.cos(angle) * activeLocal.radial.rx,
|
x: activeComponent.radial.cx + Math.cos(angle) * activeComponent.radial.rx,
|
||||||
y: activeLocal.radial.cy + Math.sin(angle) * activeLocal.radial.ry,
|
y: activeComponent.radial.cy + Math.sin(angle) * activeComponent.radial.ry,
|
||||||
});
|
});
|
||||||
return `${p.x},${p.y}`;
|
return `${p.x},${p.y}`;
|
||||||
}).join(' ');
|
}).join(' ');
|
||||||
@@ -2155,9 +2313,9 @@ export default function Develop({
|
|||||||
</g>
|
</g>
|
||||||
);
|
);
|
||||||
})()}
|
})()}
|
||||||
{activeLocal.kind === 'linear' && (() => {
|
{activeComponent.kind === 'linear' && (() => {
|
||||||
const a = marker({ x: activeLocal.linear.x1, y: activeLocal.linear.y1 });
|
const a = marker({ x: activeComponent.linear.x1, y: activeComponent.linear.y1 });
|
||||||
const b = marker({ x: activeLocal.linear.x2, y: activeLocal.linear.y2 });
|
const b = marker({ x: activeComponent.linear.x2, y: activeComponent.linear.y2 });
|
||||||
return (
|
return (
|
||||||
<g>
|
<g>
|
||||||
<line x1={a.x} y1={a.y} x2={b.x} y2={b.y} className="local-line" vectorEffect="non-scaling-stroke" />
|
<line x1={a.x} y1={a.y} x2={b.x} y2={b.y} className="local-line" vectorEffect="non-scaling-stroke" />
|
||||||
@@ -2166,16 +2324,34 @@ export default function Develop({
|
|||||||
</g>
|
</g>
|
||||||
);
|
);
|
||||||
})()}
|
})()}
|
||||||
{activeLocal.kind === 'brush' && localHover && !localDrag.current && (
|
{activeComponent.kind === 'brush' && localHover && !localDrag.current && (() => {
|
||||||
<ellipse
|
const c = marker(localHover);
|
||||||
cx={marker(localHover).x}
|
const r = localRadius();
|
||||||
cy={marker(localHover).y}
|
// Feather is the soft band inside the rim, so the inner
|
||||||
rx={localRadius() * xScale * 100}
|
// ring marks where the dab is still at full strength.
|
||||||
ry={localRadius() * 100 * (canvasW / canvasH)}
|
return (
|
||||||
className="local-cursor"
|
<g>
|
||||||
vectorEffect="non-scaling-stroke"
|
<ellipse
|
||||||
/>
|
cx={c.x}
|
||||||
)}
|
cy={c.y}
|
||||||
|
rx={radiusU(r)}
|
||||||
|
ry={radiusV(r)}
|
||||||
|
className="local-cursor"
|
||||||
|
vectorEffect="non-scaling-stroke"
|
||||||
|
/>
|
||||||
|
{feather > 0.02 && (
|
||||||
|
<ellipse
|
||||||
|
cx={c.x}
|
||||||
|
cy={c.y}
|
||||||
|
rx={radiusU(r * (1 - feather))}
|
||||||
|
ry={radiusV(r * (1 - feather))}
|
||||||
|
className="local-cursor inner"
|
||||||
|
vectorEffect="non-scaling-stroke"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</g>
|
||||||
|
);
|
||||||
|
})()}
|
||||||
</svg>
|
</svg>
|
||||||
);
|
);
|
||||||
})()}
|
})()}
|
||||||
@@ -2192,10 +2368,10 @@ export default function Develop({
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{localMode && activeLocal && !error && (
|
{localMode && activeLocal && activeComponent && !error && (
|
||||||
<div className="heal-hud local-hud">
|
<div className="heal-hud local-hud">
|
||||||
<span className="heal-hud-title">Local · {activeLocal.kind}</span>
|
<span className="heal-hud-title">Local · {activeComponent.kind}</span>
|
||||||
{activeLocal.kind === 'brush' && (
|
{activeComponent.kind === 'brush' && (
|
||||||
<>
|
<>
|
||||||
<label className="heal-field">
|
<label className="heal-field">
|
||||||
Size
|
Size
|
||||||
@@ -2211,7 +2387,7 @@ export default function Develop({
|
|||||||
<span className="heal-read">{Math.round(localBrush)}px</span>
|
<span className="heal-read">{Math.round(localBrush)}px</span>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
{activeLocal.kind !== 'linear' && (
|
{activeComponent.kind !== 'linear' && (
|
||||||
<>
|
<>
|
||||||
<label className="heal-field">
|
<label className="heal-field">
|
||||||
Feather
|
Feather
|
||||||
@@ -2220,27 +2396,77 @@ export default function Develop({
|
|||||||
min={0}
|
min={0}
|
||||||
max={100}
|
max={100}
|
||||||
step={1}
|
step={1}
|
||||||
value={activeLocal.feather}
|
value={activeComponent.feather}
|
||||||
onChange={(e) => patchLocal(activeLocal.id, { feather: Number(e.target.value) }, 'Local feather')}
|
onChange={(e) =>
|
||||||
|
patchComponent(
|
||||||
|
activeLocal.id,
|
||||||
|
activeComponent.id,
|
||||||
|
{ feather: Number(e.target.value) },
|
||||||
|
'Local feather',
|
||||||
|
)
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
<span className="heal-read">{Math.round(activeLocal.feather)}%</span>
|
<span className="heal-read">{Math.round(activeComponent.feather)}%</span>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
<button
|
||||||
|
className={`heal-act ${(activeComponent.kind === 'brush' ? !localErase : activeComponent.mode !== 'subtract') ? 'on' : ''}`}
|
||||||
|
onClick={() => {
|
||||||
|
if (activeComponent.kind === 'brush') {
|
||||||
|
setLocalErase(false);
|
||||||
|
} else if (activeComponent.mode === 'subtract') {
|
||||||
|
patchComponent(activeLocal.id, activeComponent.id, { mode: 'add' }, 'Shape add');
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
title="Add to the mask (+)"
|
||||||
|
>
|
||||||
|
+
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className={`heal-act ${(activeComponent.kind === 'brush' ? localErase : activeComponent.mode === 'subtract') ? 'on' : ''}`}
|
||||||
|
onClick={() => {
|
||||||
|
if (activeComponent.kind === 'brush') {
|
||||||
|
setLocalErase(true);
|
||||||
|
} else {
|
||||||
|
patchComponent(activeLocal.id, activeComponent.id, { mode: 'subtract' }, 'Shape subtract');
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
disabled={
|
||||||
|
activeComponent.kind !== 'brush' &&
|
||||||
|
activeLocal.components[0]?.id === activeComponent.id
|
||||||
|
}
|
||||||
|
title={
|
||||||
|
activeComponent.kind === 'brush'
|
||||||
|
? 'Erase from the mask (−)'
|
||||||
|
: activeLocal.components[0]?.id === activeComponent.id
|
||||||
|
? 'The first shape starts the mask, so it always adds'
|
||||||
|
: 'Subtract this shape from the mask (−)'
|
||||||
|
}
|
||||||
|
>
|
||||||
|
−
|
||||||
|
</button>
|
||||||
<button
|
<button
|
||||||
className="heal-act"
|
className="heal-act"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
if (activeLocal.kind === 'brush') {
|
if (activeComponent.kind === 'brush') {
|
||||||
patchLocal(activeLocal.id, { brush: { strokes: [] } }, 'Clear local mask');
|
patchComponent(
|
||||||
} else if (activeLocal.kind === 'radial') {
|
|
||||||
patchLocal(
|
|
||||||
activeLocal.id,
|
activeLocal.id,
|
||||||
|
activeComponent.id,
|
||||||
|
{ brush: { strokes: [] } },
|
||||||
|
'Clear local mask',
|
||||||
|
);
|
||||||
|
} else if (activeComponent.kind === 'radial') {
|
||||||
|
patchComponent(
|
||||||
|
activeLocal.id,
|
||||||
|
activeComponent.id,
|
||||||
{ radial: { cx: 0.5, cy: 0.5, rx: 0.25, ry: 0.3 } },
|
{ radial: { cx: 0.5, cy: 0.5, rx: 0.25, ry: 0.3 } },
|
||||||
'Reset local mask',
|
'Reset local mask',
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
patchLocal(
|
patchComponent(
|
||||||
activeLocal.id,
|
activeLocal.id,
|
||||||
|
activeComponent.id,
|
||||||
{ linear: { x1: 0.5, y1: 0.2, x2: 0.5, y2: 0.8 } },
|
{ linear: { x1: 0.5, y1: 0.2, x2: 0.5, y2: 0.8 } },
|
||||||
'Reset local mask',
|
'Reset local mask',
|
||||||
);
|
);
|
||||||
@@ -2249,13 +2475,36 @@ export default function Develop({
|
|||||||
>
|
>
|
||||||
Clear
|
Clear
|
||||||
</button>
|
</button>
|
||||||
|
<button
|
||||||
|
className={`heal-act ${maskOverlay ? 'on' : ''}`}
|
||||||
|
onClick={() => setMaskOverlay((v) => !v)}
|
||||||
|
title="Show or hide the mask tint (O)"
|
||||||
|
>
|
||||||
|
Mask
|
||||||
|
</button>
|
||||||
|
{maskOverlay && (
|
||||||
|
<>
|
||||||
|
<label className="heal-field">
|
||||||
|
Tint
|
||||||
|
<input
|
||||||
|
type="range"
|
||||||
|
min={10}
|
||||||
|
max={100}
|
||||||
|
step={1}
|
||||||
|
value={maskStrength}
|
||||||
|
onChange={(e) => setMaskStrength(Number(e.target.value))}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<span className="heal-read">{Math.round(maskStrength)}%</span>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
<button className="heal-act on" onClick={() => setLocalMode(false)}>
|
<button className="heal-act on" onClick={() => setLocalMode(false)}>
|
||||||
Done
|
Done
|
||||||
</button>
|
</button>
|
||||||
<span className="heal-tip">
|
<span className="heal-tip">
|
||||||
{activeLocal.kind === 'brush'
|
{activeComponent.kind === 'brush'
|
||||||
? 'Paint the mask · Alt paints an erase stroke · wheel sizes the brush'
|
? 'Paint the mask · − erases · Alt erases one stroke · wheel sizes the brush'
|
||||||
: activeLocal.kind === 'radial'
|
: activeComponent.kind === 'radial'
|
||||||
? 'Drag the centre or the edge handle · wheel zooms'
|
? 'Drag the centre or the edge handle · wheel zooms'
|
||||||
: 'Drag either end of the gradient'}
|
: 'Drag either end of the gradient'}
|
||||||
</span>
|
</span>
|
||||||
@@ -2381,13 +2630,29 @@ export default function Develop({
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{clipPreview && (
|
{(clipPreview || clipping === 'shadows') && (
|
||||||
<div className="clip-legend">
|
<div className="clip-legend">
|
||||||
<span className="clip-dot r" /> red
|
{clipPreview ? (
|
||||||
<span className="clip-dot g" /> green
|
<>
|
||||||
<span className="clip-dot b" /> blue
|
<span className="clip-dot r" /> red
|
||||||
<span className="clip-dot y" /> two channels
|
<span className="clip-dot g" /> green
|
||||||
<span className="clip-dot w" /> all three
|
<span className="clip-dot b" /> blue
|
||||||
|
<span className="clip-dot y" /> two channels
|
||||||
|
<span className="clip-dot w" /> all three
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<span className="clip-dot r" />
|
||||||
|
<span className="clip-dot g" />
|
||||||
|
<span className="clip-dot b" />
|
||||||
|
<span className="clip-label">one channel</span>
|
||||||
|
<span className="clip-dot y" />
|
||||||
|
<span className="clip-dot m" />
|
||||||
|
<span className="clip-dot c" />
|
||||||
|
<span className="clip-label">two channels</span>
|
||||||
|
<span className="clip-dot w" /> all three
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{loupe && !adjustOpen && (
|
{loupe && !adjustOpen && (
|
||||||
|
|||||||
+143
-21
@@ -1,5 +1,5 @@
|
|||||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||||
import { ASPECTS, BW_FILTERS, HUE_BANDS, identityCurve, MAX_LOCAL_LAYERS } from '../lib/edits';
|
import { ASPECTS, BW_FILTERS, HUE_BANDS, identityCurve, MAX_LOCAL_COMPONENTS, MAX_LOCAL_LAYERS } from '../lib/edits';
|
||||||
import { computeAutoEdits, computeAutoWhiteBalance } from '../lib/auto';
|
import { computeAutoEdits, computeAutoWhiteBalance } from '../lib/auto';
|
||||||
import { autoNoiseFor } from '../lib/noiseProfile';
|
import { autoNoiseFor } from '../lib/noiseProfile';
|
||||||
import { clearDenoised, getDenoiseJob, startDenoise } from '../lib/api';
|
import { clearDenoised, getDenoiseJob, startDenoise } from '../lib/api';
|
||||||
@@ -9,6 +9,7 @@ import type {
|
|||||||
Edits,
|
Edits,
|
||||||
EventRecord,
|
EventRecord,
|
||||||
HistoryEntry,
|
HistoryEntry,
|
||||||
|
LocalComponent,
|
||||||
LocalLayer,
|
LocalLayer,
|
||||||
LocalMaskKind,
|
LocalMaskKind,
|
||||||
MetadataPreset,
|
MetadataPreset,
|
||||||
@@ -94,10 +95,15 @@ export function BasicPanel({
|
|||||||
const [autoBusy, setAutoBusy] = useState(false);
|
const [autoBusy, setAutoBusy] = useState(false);
|
||||||
const [wbBusy, setWbBusy] = useState(false);
|
const [wbBusy, setWbBusy] = useState(false);
|
||||||
|
|
||||||
|
// Raws carry their pixels as a URL, with `thumb` empty; handing the empty
|
||||||
|
// string to the analysis made the decode fail and both Auto buttons quietly
|
||||||
|
// come back with neutral values, so Auto WB matched As shot exactly.
|
||||||
|
const thumbSrc = photo.thumbUrl ?? photo.thumb;
|
||||||
|
|
||||||
const auto = async () => {
|
const auto = async () => {
|
||||||
setAutoBusy(true);
|
setAutoBusy(true);
|
||||||
try {
|
try {
|
||||||
const partial = await computeAutoEdits(photo.thumb);
|
const partial = await computeAutoEdits(thumbSrc);
|
||||||
set(partial, 'Auto tone');
|
set(partial, 'Auto tone');
|
||||||
} finally {
|
} finally {
|
||||||
setAutoBusy(false);
|
setAutoBusy(false);
|
||||||
@@ -107,7 +113,7 @@ export function BasicPanel({
|
|||||||
const autoWb = async () => {
|
const autoWb = async () => {
|
||||||
setWbBusy(true);
|
setWbBusy(true);
|
||||||
try {
|
try {
|
||||||
set(await computeAutoWhiteBalance(photo.thumb), 'Auto white balance');
|
set(await computeAutoWhiteBalance(thumbSrc), 'Auto white balance');
|
||||||
} finally {
|
} finally {
|
||||||
setWbBusy(false);
|
setWbBusy(false);
|
||||||
}
|
}
|
||||||
@@ -1489,6 +1495,10 @@ export function LocalPanel({
|
|||||||
set,
|
set,
|
||||||
activeId,
|
activeId,
|
||||||
onSelect,
|
onSelect,
|
||||||
|
componentId,
|
||||||
|
onSelectComponent,
|
||||||
|
onAddComponent,
|
||||||
|
onDeleteComponent,
|
||||||
onAdd,
|
onAdd,
|
||||||
onDelete,
|
onDelete,
|
||||||
onDuplicate,
|
onDuplicate,
|
||||||
@@ -1505,6 +1515,11 @@ export function LocalPanel({
|
|||||||
}: PanelSetProps & {
|
}: PanelSetProps & {
|
||||||
activeId: string | null;
|
activeId: string | null;
|
||||||
onSelect: (id: string) => void;
|
onSelect: (id: string) => void;
|
||||||
|
/** Shape inside the active layer that the mask controls edit. */
|
||||||
|
componentId: string | null;
|
||||||
|
onSelectComponent: (id: string) => void;
|
||||||
|
onAddComponent: (kind: LocalMaskKind) => void;
|
||||||
|
onDeleteComponent: (id: string) => void;
|
||||||
onAdd: (kind: LocalMaskKind) => void;
|
onAdd: (kind: LocalMaskKind) => void;
|
||||||
onDelete: (id: string) => void;
|
onDelete: (id: string) => void;
|
||||||
onDuplicate: (id: string) => void;
|
onDuplicate: (id: string) => void;
|
||||||
@@ -1522,11 +1537,31 @@ export function LocalPanel({
|
|||||||
}) {
|
}) {
|
||||||
const layers = edits.local ?? [];
|
const layers = edits.local ?? [];
|
||||||
const active = layers.find((layer) => layer.id === activeId) ?? null;
|
const active = layers.find((layer) => layer.id === activeId) ?? null;
|
||||||
|
const shapes = active?.components ?? [];
|
||||||
|
const shape = shapes.find((component) => component.id === componentId) ?? shapes[0] ?? null;
|
||||||
|
|
||||||
const patch = (next: Partial<LocalLayer>, label: string) => {
|
const patch = (next: Partial<LocalLayer>, label: string) => {
|
||||||
if (!active) return;
|
if (!active) return;
|
||||||
set({ local: layers.map((layer) => (layer.id === active.id ? { ...layer, ...next } : layer)) }, label);
|
set({ local: layers.map((layer) => (layer.id === active.id ? { ...layer, ...next } : layer)) }, label);
|
||||||
};
|
};
|
||||||
|
const patchShape = (next: Partial<LocalComponent>, label: string) => {
|
||||||
|
if (!active || !shape) return;
|
||||||
|
set(
|
||||||
|
{
|
||||||
|
local: layers.map((layer) =>
|
||||||
|
layer.id === active.id
|
||||||
|
? {
|
||||||
|
...layer,
|
||||||
|
components: layer.components.map((component) =>
|
||||||
|
component.id === shape.id ? { ...component, ...next } : component,
|
||||||
|
),
|
||||||
|
}
|
||||||
|
: layer,
|
||||||
|
),
|
||||||
|
},
|
||||||
|
label,
|
||||||
|
);
|
||||||
|
};
|
||||||
const adjust = (key: keyof LocalLayer['adjust'], value: number) =>
|
const adjust = (key: keyof LocalLayer['adjust'], value: number) =>
|
||||||
active && patch({ adjust: { ...active.adjust, [key]: value } }, `Local ${key}`);
|
active && patch({ adjust: { ...active.adjust, [key]: value } }, `Local ${key}`);
|
||||||
const range = (key: keyof LocalLayer['range'], value: number | boolean) =>
|
const range = (key: keyof LocalLayer['range'], value: number | boolean) =>
|
||||||
@@ -1589,21 +1624,55 @@ export function LocalPanel({
|
|||||||
className={`local-item ${layer.id === activeId ? 'on' : ''}`}
|
className={`local-item ${layer.id === activeId ? 'on' : ''}`}
|
||||||
onClick={() => onSelect(layer.id)}
|
onClick={() => onSelect(layer.id)}
|
||||||
>
|
>
|
||||||
<span className="local-icon">{LOCAL_ICON[layer.kind]}</span>
|
<span className="local-icon">{LOCAL_ICON[layer.components[0]?.kind ?? 'brush']}</span>
|
||||||
<span className="local-name">{layer.name}</span>
|
<span className="local-name">{layer.name}</span>
|
||||||
<span className="local-kind">{layer.kind}</span>
|
<span className="local-kind">
|
||||||
|
{layer.components.length > 1
|
||||||
|
? `${layer.components.length} shapes`
|
||||||
|
: (layer.components[0]?.kind ?? 'mask')}
|
||||||
|
</span>
|
||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{active && (
|
<div className="local-subhead">Mask shapes</div>
|
||||||
|
<div className="local-list shapes">
|
||||||
|
{shapes.map((component, index) => (
|
||||||
|
<button
|
||||||
|
key={component.id}
|
||||||
|
className={`local-item ${component.id === shape?.id ? 'on' : ''}`}
|
||||||
|
onClick={() => onSelectComponent(component.id)}
|
||||||
|
>
|
||||||
|
<span className="local-icon">{LOCAL_ICON[component.kind]}</span>
|
||||||
|
<span className="local-name">Shape {index + 1}</span>
|
||||||
|
<span className="local-kind">
|
||||||
|
{component.mode === 'add' ? component.kind : `${component.kind} · ${component.mode}`}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<div className="btn-row local-add">
|
||||||
|
{(['brush', 'linear', 'radial'] as const).map((kind) => (
|
||||||
|
<button
|
||||||
|
key={kind}
|
||||||
|
className="btn ghost small"
|
||||||
|
onClick={() => onAddComponent(kind)}
|
||||||
|
disabled={shapes.length >= MAX_LOCAL_COMPONENTS}
|
||||||
|
title="Add a shape to this mask group"
|
||||||
|
>
|
||||||
|
+ {LOCAL_ICON[kind]} {kind}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{active && shape && (
|
||||||
<>
|
<>
|
||||||
<div className="btn-row local-actions">
|
<div className="btn-row local-actions">
|
||||||
<button
|
<button
|
||||||
className={`btn ghost small ${maskMode ? 'on' : ''}`}
|
className={`btn ghost small ${maskMode ? 'on' : ''}`}
|
||||||
onClick={onEditMask}
|
onClick={onEditMask}
|
||||||
disabled={active.kind === 'raster'}
|
disabled={shape.kind === 'raster'}
|
||||||
title={active.kind === 'raster' ? 'Auto masks are generated, not painted' : undefined}
|
title={shape.kind === 'raster' ? 'Auto masks are generated, not painted' : undefined}
|
||||||
>
|
>
|
||||||
{maskMode ? 'Done mask' : 'Edit mask'}
|
{maskMode ? 'Done mask' : 'Edit mask'}
|
||||||
</button>
|
</button>
|
||||||
@@ -1615,13 +1684,13 @@ export function LocalPanel({
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{active.kind === 'raster' && (
|
{shape.kind === 'raster' && (
|
||||||
<p className="muted small panel-hint">
|
<p className="muted small panel-hint">
|
||||||
Auto mask · adjust the feather, invert it, paint it away by adding a brush layer, or regenerate from the buttons above.
|
Auto mask · adjust the feather, invert it, paint it away by adding a brush layer, or regenerate from the buttons above.
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{active.kind === 'brush' && (
|
{shape.kind === 'brush' && (
|
||||||
<Slider
|
<Slider
|
||||||
label="Brush size"
|
label="Brush size"
|
||||||
min={8}
|
min={8}
|
||||||
@@ -1633,19 +1702,56 @@ export function LocalPanel({
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{active.kind !== 'linear' && (
|
{shape.kind !== 'linear' && (
|
||||||
<Slider
|
<Slider
|
||||||
label="Feather"
|
label="Feather"
|
||||||
min={0}
|
min={0}
|
||||||
max={100}
|
max={100}
|
||||||
value={active.feather}
|
value={shape.feather}
|
||||||
def={50}
|
def={50}
|
||||||
onChange={(v) => patch({ feather: v }, 'Local feather')}
|
onChange={(v) => patchShape({ feather: v }, 'Local feather')}
|
||||||
format={(v) => `${Math.round(v)}%`}
|
format={(v) => `${Math.round(v)}%`}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div className="local-subhead">Combine</div>
|
<div className="local-subhead">Shape blend</div>
|
||||||
|
<div className="btn-row local-modes">
|
||||||
|
{(['add', 'subtract', 'intersect'] as const).map((mode) => (
|
||||||
|
<button
|
||||||
|
key={mode}
|
||||||
|
className={`chip tiny ${shape.mode === mode ? 'on' : ''}`}
|
||||||
|
disabled={shapes[0]?.id === shape.id && mode !== 'add'}
|
||||||
|
title={
|
||||||
|
shapes[0]?.id === shape.id
|
||||||
|
? 'The first shape starts the group, so it always adds'
|
||||||
|
: mode === 'add'
|
||||||
|
? 'Union this shape into the group'
|
||||||
|
: mode === 'subtract'
|
||||||
|
? 'Cut this shape out of the shapes before it'
|
||||||
|
: 'Keep only where this shape overlaps the shapes before it'
|
||||||
|
}
|
||||||
|
onClick={() => patchShape({ mode }, `Shape ${mode}`)}
|
||||||
|
>
|
||||||
|
{mode === 'add' ? 'Add' : mode === 'subtract' ? 'Subtract' : 'Intersect'}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<div className="btn-row">
|
||||||
|
<button
|
||||||
|
className="btn ghost small danger"
|
||||||
|
onClick={() => onDeleteComponent(shape.id)}
|
||||||
|
disabled={shapes.length <= 1}
|
||||||
|
title={
|
||||||
|
shapes.length <= 1
|
||||||
|
? 'A layer needs one shape; delete the layer instead'
|
||||||
|
: 'Remove this shape from the group'
|
||||||
|
}
|
||||||
|
>
|
||||||
|
Delete shape
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="local-subhead">Layer blend</div>
|
||||||
<div className="btn-row local-modes">
|
<div className="btn-row local-modes">
|
||||||
{(['add', 'subtract', 'intersect'] as const).map((mode) => (
|
{(['add', 'subtract', 'intersect'] as const).map((mode) => (
|
||||||
<button
|
<button
|
||||||
@@ -1653,18 +1759,25 @@ export function LocalPanel({
|
|||||||
className={`chip tiny ${active.mode === mode ? 'on' : ''}`}
|
className={`chip tiny ${active.mode === mode ? 'on' : ''}`}
|
||||||
title={
|
title={
|
||||||
mode === 'add'
|
mode === 'add'
|
||||||
? 'Apply this adjustment inside the mask'
|
? 'Apply this layer inside its mask'
|
||||||
: mode === 'subtract'
|
: mode === 'subtract'
|
||||||
? 'Apply it outside this mask, within the layer above'
|
? 'Apply it outside its mask, within the layer above'
|
||||||
: 'Apply it only where this mask overlaps the layer above'
|
: 'Apply it only where the mask overlaps the layer above'
|
||||||
}
|
}
|
||||||
onClick={() => patch({ mode }, `Mask ${mode}`)}
|
onClick={() => patch({ mode }, `Layer ${mode}`)}
|
||||||
>
|
>
|
||||||
{mode === 'add' ? 'Add' : mode === 'subtract' ? 'Subtract' : 'Intersect'}
|
{mode === 'add' ? 'Add' : mode === 'subtract' ? 'Subtract' : 'Intersect'}
|
||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div className="local-subhead">Mask curve</div>
|
||||||
|
<CurveEditor
|
||||||
|
points={active.curve}
|
||||||
|
onChange={(points) => patch({ curve: points }, 'Mask curve')}
|
||||||
|
color="#f2f4f8"
|
||||||
|
/>
|
||||||
|
|
||||||
<div className="local-subhead">Light</div>
|
<div className="local-subhead">Light</div>
|
||||||
<Slider
|
<Slider
|
||||||
label="Exposure"
|
label="Exposure"
|
||||||
@@ -1811,8 +1924,8 @@ export function LocalPanel({
|
|||||||
|
|
||||||
<div className="btn-row">
|
<div className="btn-row">
|
||||||
<button
|
<button
|
||||||
className={`btn ghost small ${active.inverted ? 'on' : ''}`}
|
className={`btn ghost small ${shape.inverted ? 'on' : ''}`}
|
||||||
onClick={() => patch({ inverted: !active.inverted }, 'Invert mask')}
|
onClick={() => patchShape({ inverted: !shape.inverted }, 'Invert mask')}
|
||||||
>
|
>
|
||||||
Invert mask
|
Invert mask
|
||||||
</button>
|
</button>
|
||||||
@@ -1915,7 +2028,10 @@ export function OpticsPanel({
|
|||||||
model: result.model,
|
model: result.model,
|
||||||
crop: result.crop,
|
crop: result.crop,
|
||||||
cameraModel: photo.meta.camera ?? undefined,
|
cameraModel: photo.meta.camera ?? undefined,
|
||||||
corrections: { distortion: true, tca: true, vignetting: true },
|
// Geometry and CA are safe to correct on their own; the vignetting gain
|
||||||
|
// lifts the corners above the frame centre, so it is left for the user to
|
||||||
|
// enable on the profile they applied.
|
||||||
|
corrections: { distortion: true, tca: true, vignetting: false },
|
||||||
distance: 1000,
|
distance: 1000,
|
||||||
};
|
};
|
||||||
set({ lens: next }, 'Lens profile');
|
set({ lens: next }, 'Lens profile');
|
||||||
@@ -2110,6 +2226,12 @@ export function OpticsPanel({
|
|||||||
</label>
|
</label>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
{!profile.corrections.vignetting && (
|
||||||
|
<p className="muted small lens-msg">
|
||||||
|
Vignetting correction is off, so the corners keep the lens's own falloff.
|
||||||
|
Tick Vignetting to lift them back to the centre.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
{lensState?.loading && <p className="muted small lens-msg">Building correction maps…</p>}
|
{lensState?.loading && <p className="muted small lens-msg">Building correction maps…</p>}
|
||||||
{lensState?.error && <p className="small lens-error">{lensState.error}</p>}
|
{lensState?.error && <p className="small lens-error">{lensState.error}</p>}
|
||||||
{onLensSplit && (
|
{onLensSplit && (
|
||||||
|
|||||||
@@ -36,6 +36,7 @@ const GROUPS: { title: string; rows: [string, string][] }[] = [
|
|||||||
['C', 'Crop & straighten'],
|
['C', 'Crop & straighten'],
|
||||||
['Q', 'Spot healing brush'],
|
['Q', 'Spot healing brush'],
|
||||||
['M', 'Edit the selected local mask'],
|
['M', 'Edit the selected local mask'],
|
||||||
|
['O', 'Show or hide the mask tint'],
|
||||||
['Enter', 'Apply the crop'],
|
['Enter', 'Apply the crop'],
|
||||||
['\\ (hold)', 'Before / after'],
|
['\\ (hold)', 'Before / after'],
|
||||||
['1 – 5', 'Star rating'],
|
['1 – 5', 'Star rating'],
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { blendCoverage, maskSize } from './masks';
|
||||||
|
|
||||||
|
/** Coverage values are 0–1 inside the baker, which this keeps readable. */
|
||||||
|
describe('mask texture size', () => {
|
||||||
|
it('keeps square mask pixels so a round brush stays round', () => {
|
||||||
|
const tall = maskSize(3000, 9000);
|
||||||
|
expect(tall.h).toBeLessThanOrEqual(1400);
|
||||||
|
expect(tall.w / tall.h).toBeCloseTo(1 / 3, 2);
|
||||||
|
const wide = maskSize(15000, 1000);
|
||||||
|
expect(wide.h).toBeGreaterThanOrEqual(120);
|
||||||
|
expect(wide.w / wide.h).toBeCloseTo(15, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses the full width for a normal photo', () => {
|
||||||
|
expect(maskSize(3464, 5202)).toEqual({ w: 800, h: 1201 });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('mask group compositing', () => {
|
||||||
|
it('starts a group with the first shape whatever its mode says', () => {
|
||||||
|
expect(blendCoverage(0, 0.6, 'subtract', true)).toBe(0.6);
|
||||||
|
expect(blendCoverage(0, 0.6, 'intersect', true)).toBe(0.6);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('unions added shapes instead of stacking them', () => {
|
||||||
|
expect(blendCoverage(0.4, 0.7, 'add', false)).toBe(0.7);
|
||||||
|
expect(blendCoverage(0.7, 0.4, 'add', false)).toBe(0.7);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('subtracts coverage from the group', () => {
|
||||||
|
expect(blendCoverage(1, 0.25, 'subtract', false)).toBeCloseTo(0.75, 6);
|
||||||
|
expect(blendCoverage(1, 1, 'subtract', false)).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps only the overlap for an intersect shape', () => {
|
||||||
|
expect(blendCoverage(0.8, 0.5, 'intersect', false)).toBeCloseTo(0.4, 6);
|
||||||
|
expect(blendCoverage(0.8, 0, 'intersect', false)).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
+140
-70
@@ -1,11 +1,13 @@
|
|||||||
import type { LocalLayer } from '../types';
|
import type { LocalComponent, LocalLayer } from '../types';
|
||||||
import { MAX_LOCAL_LAYERS } from '../lib/edits';
|
import { MAX_LOCAL_LAYERS } from '../lib/edits';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Local masks are baked on the CPU into two RGBA textures, one layer per
|
* Local masks are baked on the CPU into two RGBA textures, one layer per
|
||||||
* channel, so the grade shader can apply up to eight adjustments in a single
|
* channel, so the grade shader can apply up to eight adjustments in a single
|
||||||
* pass. The mask is source-space, which keeps brushes and gradients attached to
|
* pass. A layer's mask is a group of shapes composited in order: add unions,
|
||||||
* the picture through crops, straightening, zoom and lens correction.
|
* subtract cuts a hole, intersect keeps the overlap. The mask is source-space,
|
||||||
|
* which keeps brushes and gradients attached to the picture through crops,
|
||||||
|
* straightening, zoom and lens correction.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
export interface PackedMasks {
|
export interface PackedMasks {
|
||||||
@@ -23,19 +25,22 @@ export function maskSignature(layers: LocalLayer[], srcW: number, srcH: number)
|
|||||||
srcW,
|
srcW,
|
||||||
srcH,
|
srcH,
|
||||||
layers: layers.slice(0, MAX_LOCAL_LAYERS).map((layer) => ({
|
layers: layers.slice(0, MAX_LOCAL_LAYERS).map((layer) => ({
|
||||||
kind: layer.kind,
|
components: (layer.components ?? []).map((component) => ({
|
||||||
inverted: layer.inverted,
|
kind: component.kind,
|
||||||
feather: layer.feather,
|
mode: component.mode,
|
||||||
brush: layer.brush,
|
inverted: component.inverted,
|
||||||
linear: layer.linear,
|
feather: component.feather,
|
||||||
radial: layer.radial,
|
brush: component.brush,
|
||||||
raster: layer.raster
|
linear: component.linear,
|
||||||
? {
|
radial: component.radial,
|
||||||
width: layer.raster.width,
|
raster: component.raster
|
||||||
height: layer.raster.height,
|
? {
|
||||||
hash: rasterHash(layer.raster.data),
|
width: component.raster.width,
|
||||||
}
|
height: component.raster.height,
|
||||||
: null,
|
hash: rasterHash(component.raster.data),
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
})),
|
||||||
})),
|
})),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -49,8 +54,8 @@ function rasterHash(data: string) {
|
|||||||
return `${data.length}:${hash >>> 0}`;
|
return `${data.length}:${hash >>> 0}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function drawRaster(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number, h: number) {
|
function drawRaster(ctx: CanvasRenderingContext2D, component: LocalComponent, w: number, h: number) {
|
||||||
const mask = layer.raster;
|
const mask = component.raster;
|
||||||
if (!mask) return;
|
if (!mask) return;
|
||||||
try {
|
try {
|
||||||
const binary = atob(mask.data);
|
const binary = atob(mask.data);
|
||||||
@@ -82,13 +87,13 @@ function makeCanvas(w: number, h: number) {
|
|||||||
return canvas;
|
return canvas;
|
||||||
}
|
}
|
||||||
|
|
||||||
function drawRadial(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number, h: number) {
|
function drawRadial(ctx: CanvasRenderingContext2D, component: LocalComponent, w: number, h: number) {
|
||||||
const { cx, cy, rx, ry } = layer.radial;
|
const { cx, cy, rx, ry } = component.radial;
|
||||||
ctx.save();
|
ctx.save();
|
||||||
ctx.translate(cx * w, cy * h);
|
ctx.translate(cx * w, cy * h);
|
||||||
ctx.scale(Math.max(1, rx * w), Math.max(1, ry * h));
|
ctx.scale(Math.max(1, rx * w), Math.max(1, ry * h));
|
||||||
const gradient = ctx.createRadialGradient(0, 0, 0, 0, 0, 1);
|
const gradient = ctx.createRadialGradient(0, 0, 0, 0, 0, 1);
|
||||||
const inner = Math.max(0, Math.min(0.98, 1 - layer.feather / 100));
|
const inner = Math.max(0, Math.min(0.98, 1 - component.feather / 100));
|
||||||
gradient.addColorStop(0, 'rgba(255,255,255,1)');
|
gradient.addColorStop(0, 'rgba(255,255,255,1)');
|
||||||
if (inner > 0.001) gradient.addColorStop(inner, 'rgba(255,255,255,1)');
|
if (inner > 0.001) gradient.addColorStop(inner, 'rgba(255,255,255,1)');
|
||||||
gradient.addColorStop(1, 'rgba(255,255,255,0)');
|
gradient.addColorStop(1, 'rgba(255,255,255,0)');
|
||||||
@@ -99,8 +104,8 @@ function drawRadial(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number,
|
|||||||
ctx.restore();
|
ctx.restore();
|
||||||
}
|
}
|
||||||
|
|
||||||
function drawLinear(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number, h: number) {
|
function drawLinear(ctx: CanvasRenderingContext2D, component: LocalComponent, w: number, h: number) {
|
||||||
const { x1, y1, x2, y2 } = layer.linear;
|
const { x1, y1, x2, y2 } = component.linear;
|
||||||
const gradient = ctx.createLinearGradient(x1 * w, y1 * h, x2 * w, y2 * h);
|
const gradient = ctx.createLinearGradient(x1 * w, y1 * h, x2 * w, y2 * h);
|
||||||
gradient.addColorStop(0, 'rgba(255,255,255,1)');
|
gradient.addColorStop(0, 'rgba(255,255,255,1)');
|
||||||
gradient.addColorStop(1, 'rgba(255,255,255,0)');
|
gradient.addColorStop(1, 'rgba(255,255,255,0)');
|
||||||
@@ -108,32 +113,66 @@ function drawLinear(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number,
|
|||||||
ctx.fillRect(0, 0, w, h);
|
ctx.fillRect(0, 0, w, h);
|
||||||
}
|
}
|
||||||
|
|
||||||
function drawBrush(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number, h: number) {
|
/**
|
||||||
ctx.lineCap = 'round';
|
* One brush dab: white, solid out to `1 - feather` of the radius and fading to
|
||||||
ctx.lineJoin = 'round';
|
* nothing at the rim. Feather is the width of that band, so a stroke softens
|
||||||
for (const stroke of layer.brush.strokes) {
|
* inside the brush outline instead of spreading a halo past it.
|
||||||
|
*/
|
||||||
|
function brushDab(feather: number) {
|
||||||
|
const size = 64;
|
||||||
|
const canvas = makeCanvas(size, size);
|
||||||
|
const ctx = canvas.getContext('2d');
|
||||||
|
if (!ctx) return canvas;
|
||||||
|
const r = size / 2;
|
||||||
|
// A hair of softness even at 0 keeps the rim from aliasing on screen.
|
||||||
|
const soft = Math.max(0.02, Math.min(1, feather / 100));
|
||||||
|
const gradient = ctx.createRadialGradient(r, r, r * (1 - soft), r, r, r);
|
||||||
|
gradient.addColorStop(0, 'rgba(255,255,255,1)');
|
||||||
|
gradient.addColorStop(0.45, 'rgba(255,255,255,0.88)');
|
||||||
|
gradient.addColorStop(1, 'rgba(255,255,255,0)');
|
||||||
|
ctx.fillStyle = gradient;
|
||||||
|
ctx.fillRect(0, 0, size, size);
|
||||||
|
return canvas;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stamps the dab along the path. A stroked line can only have a hard edge, so
|
||||||
|
* the stroke is drawn as overlapping dabs: the rim is the dab's falloff, which
|
||||||
|
* keeps the mask inside the brush circle and smooth at every size.
|
||||||
|
*/
|
||||||
|
function drawBrush(ctx: CanvasRenderingContext2D, component: LocalComponent, w: number, h: number) {
|
||||||
|
const dab = brushDab(component.feather);
|
||||||
|
for (const stroke of component.brush.strokes) {
|
||||||
if (!stroke.points.length) continue;
|
if (!stroke.points.length) continue;
|
||||||
const width = Math.max(1, stroke.size * 2 * w);
|
const radius = Math.max(1, stroke.size * w);
|
||||||
|
const stamp = (x: number, y: number) =>
|
||||||
|
ctx.drawImage(dab, x - radius, y - radius, radius * 2, radius * 2);
|
||||||
ctx.globalCompositeOperation = stroke.erase ? 'destination-out' : 'source-over';
|
ctx.globalCompositeOperation = stroke.erase ? 'destination-out' : 'source-over';
|
||||||
ctx.strokeStyle = 'rgba(255,255,255,1)';
|
const first = stroke.points[0];
|
||||||
ctx.fillStyle = 'rgba(255,255,255,1)';
|
stamp(first.x * w, first.y * h);
|
||||||
ctx.lineWidth = width;
|
// Close enough that consecutive dabs overlap well inside the soft band.
|
||||||
if (stroke.points.length === 1) {
|
const spacing = Math.max(0.75, radius * 0.35);
|
||||||
ctx.beginPath();
|
|
||||||
ctx.arc(stroke.points[0].x * w, stroke.points[0].y * h, width / 2, 0, Math.PI * 2);
|
|
||||||
ctx.fill();
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
ctx.beginPath();
|
|
||||||
ctx.moveTo(stroke.points[0].x * w, stroke.points[0].y * h);
|
|
||||||
for (let i = 1; i < stroke.points.length; i++) {
|
for (let i = 1; i < stroke.points.length; i++) {
|
||||||
ctx.lineTo(stroke.points[i].x * w, stroke.points[i].y * h);
|
const a = stroke.points[i - 1];
|
||||||
|
const b = stroke.points[i];
|
||||||
|
const dx = (b.x - a.x) * w;
|
||||||
|
const dy = (b.y - a.y) * h;
|
||||||
|
const steps = Math.max(1, Math.ceil(Math.hypot(dx, dy) / spacing));
|
||||||
|
for (let step = 1; step <= steps; step++) {
|
||||||
|
stamp(a.x * w + (dx * step) / steps, a.y * h + (dy * step) / steps);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
ctx.stroke();
|
|
||||||
}
|
}
|
||||||
ctx.globalCompositeOperation = 'source-over';
|
ctx.globalCompositeOperation = 'source-over';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function drawComponent(ctx: CanvasRenderingContext2D, component: LocalComponent, w: number, h: number) {
|
||||||
|
if (component.kind === 'radial') drawRadial(ctx, component, w, h);
|
||||||
|
else if (component.kind === 'linear') drawLinear(ctx, component, w, h);
|
||||||
|
else if (component.kind === 'raster') drawRaster(ctx, component, w, h);
|
||||||
|
else drawBrush(ctx, component, w, h);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Softens a mask rim without thinning what was painted. A plain blur pulls the
|
* Softens a mask rim without thinning what was painted. A plain blur pulls the
|
||||||
* stroke edge inward and drops thin strokes below full coverage, which reads as
|
* stroke edge inward and drops thin strokes below full coverage, which reads as
|
||||||
@@ -155,9 +194,43 @@ function featherMask(canvas: HTMLCanvasElement, radius: number) {
|
|||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How one shape's coverage joins the accumulated mask inside its layer. The
|
||||||
|
* first shape starts the group, so its mode is ignored: there is nothing to
|
||||||
|
* subtract from or intersect with yet.
|
||||||
|
*/
|
||||||
|
export function blendCoverage(
|
||||||
|
acc: number,
|
||||||
|
value: number,
|
||||||
|
mode: LocalComponent['mode'],
|
||||||
|
first: boolean,
|
||||||
|
) {
|
||||||
|
if (first) return value;
|
||||||
|
if (mode === 'subtract') return acc * (1 - value);
|
||||||
|
if (mode === 'intersect') return acc * value;
|
||||||
|
return Math.max(acc, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mask texture size. Pixels are square, so both dimensions scale together with
|
||||||
|
* the source: clamping only the height would squeeze every round dab into an
|
||||||
|
* ellipse on tall or wide frames, so the width shrinks instead.
|
||||||
|
*/
|
||||||
|
export function maskSize(srcW: number, srcH: number) {
|
||||||
|
const safeW = Math.max(1, srcW);
|
||||||
|
const safeH = Math.max(1, srcH);
|
||||||
|
let w = 800;
|
||||||
|
let h = Math.round((w * safeH) / safeW);
|
||||||
|
const limit = h > 1400 ? 1400 : h < 120 ? 120 : 0;
|
||||||
|
if (limit) {
|
||||||
|
h = limit;
|
||||||
|
w = Math.max(160, Math.round((h * safeW) / safeH));
|
||||||
|
}
|
||||||
|
return { w, h: Math.max(1, h) };
|
||||||
|
}
|
||||||
|
|
||||||
export function buildLocalMasks(layers: LocalLayer[], srcW: number, srcH: number): PackedMasks {
|
export function buildLocalMasks(layers: LocalLayer[], srcW: number, srcH: number): PackedMasks {
|
||||||
const w = 800;
|
const { w, h } = maskSize(srcW, srcH);
|
||||||
const h = Math.max(120, Math.min(1400, Math.round((w * Math.max(1, srcH)) / Math.max(1, srcW))));
|
|
||||||
const out = new Uint8Array(w * h * 4);
|
const out = new Uint8Array(w * h * 4);
|
||||||
const out2 = new Uint8Array(w * h * 4);
|
const out2 = new Uint8Array(w * h * 4);
|
||||||
const count = Math.min(MAX_LOCAL_LAYERS, layers.length);
|
const count = Math.min(MAX_LOCAL_LAYERS, layers.length);
|
||||||
@@ -165,40 +238,37 @@ export function buildLocalMasks(layers: LocalLayer[], srcW: number, srcH: number
|
|||||||
|
|
||||||
for (let index = 0; index < count; index++) {
|
for (let index = 0; index < count; index++) {
|
||||||
const layer = layers[index];
|
const layer = layers[index];
|
||||||
const canvas = makeCanvas(w, h);
|
const components = layer.components ?? [];
|
||||||
const ctx = canvas.getContext('2d');
|
const acc = new Uint8Array(w * h);
|
||||||
if (!ctx) continue;
|
let first = true;
|
||||||
ctx.clearRect(0, 0, w, h);
|
|
||||||
|
|
||||||
if (layer.kind === 'radial') drawRadial(ctx, layer, w, h);
|
for (const component of components) {
|
||||||
else if (layer.kind === 'linear') drawLinear(ctx, layer, w, h);
|
const canvas = makeCanvas(w, h);
|
||||||
else if (layer.kind === 'raster') drawRaster(ctx, layer, w, h);
|
const ctx = canvas.getContext('2d');
|
||||||
else drawBrush(ctx, layer, w, h);
|
if (!ctx) continue;
|
||||||
|
ctx.clearRect(0, 0, w, h);
|
||||||
|
drawComponent(ctx, component, w, h);
|
||||||
|
|
||||||
let source = canvas;
|
let source = canvas;
|
||||||
if (layer.kind === 'brush') {
|
if (component.kind === 'raster') {
|
||||||
// Feather follows the brush, not the frame: 100% softens the edge by
|
// Generated masks are low-resolution coverage, so their feather is tied
|
||||||
// roughly three quarters of the stroke's half width, so a small dab and a
|
// to the frame width and only ever loosens the outside edge.
|
||||||
// wide sweep both feel the same under the slider.
|
source = featherMask(canvas, ((component.feather / 100) * w) / 16);
|
||||||
let widest = 0;
|
|
||||||
for (const stroke of layer.brush.strokes) {
|
|
||||||
widest = Math.max(widest, stroke.size * 2 * w);
|
|
||||||
}
|
}
|
||||||
source = featherMask(canvas, (layer.feather / 100) * widest * 0.75);
|
|
||||||
} else if (layer.kind === 'raster') {
|
const pixels = source.getContext('2d')?.getImageData(0, 0, w, h).data;
|
||||||
// Generated masks are low-resolution coverage, so their feather is tied
|
if (!pixels) continue;
|
||||||
// to the frame width and only ever loosens the outside edge.
|
for (let p = 0, o = 0; p < pixels.length; p += 4, o++) {
|
||||||
source = featherMask(canvas, ((layer.feather / 100) * w) / 16);
|
let value = pixels[p + 3] / 255;
|
||||||
|
if (component.inverted) value = 1 - value;
|
||||||
|
acc[o] = Math.round(blendCoverage(acc[o] / 255, value, component.mode, first) * 255);
|
||||||
|
}
|
||||||
|
first = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
const pixels = source.getContext('2d')?.getImageData(0, 0, w, h).data;
|
|
||||||
if (!pixels) continue;
|
|
||||||
const channel = index % 4;
|
const channel = index % 4;
|
||||||
const target = index < 4 ? out : out2;
|
const target = index < 4 ? out : out2;
|
||||||
for (let p = 0, o = 0; p < pixels.length; p += 4, o += 4) {
|
for (let o = 0; o < acc.length; o++) target[o * 4 + channel] = acc[o];
|
||||||
const alpha = pixels[p + 3];
|
|
||||||
target[o + channel] = layer.inverted ? 255 - alpha : alpha;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return { data: out, data2: out2, w, h };
|
return { data: out, data2: out2, w, h };
|
||||||
|
|||||||
+229
-41
@@ -1,6 +1,6 @@
|
|||||||
import type { LensCorrection } from '../lib/lensEngine';
|
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 { CurvePoint, Edits, GeometryEdits, LocalLayer } from '../types';
|
||||||
import { buildSampler, clamp01 } from '../lib/curves';
|
import { buildSampler, clamp01 } from '../lib/curves';
|
||||||
import { bwFilterRgb, MAX_HEAL_SPOTS, MAX_LOCAL_LAYERS } from '../lib/edits';
|
import { bwFilterRgb, MAX_HEAL_SPOTS, MAX_LOCAL_LAYERS } from '../lib/edits';
|
||||||
import { wbGainFor } from '../lib/whiteBalance';
|
import { wbGainFor } from '../lib/whiteBalance';
|
||||||
@@ -18,7 +18,11 @@ void main(){
|
|||||||
const GRADE_FRAG = `#version 300 es
|
const GRADE_FRAG = `#version 300 es
|
||||||
precision highp float;
|
precision highp float;
|
||||||
in vec2 v_uv;
|
in vec2 v_uv;
|
||||||
out vec4 outColor;
|
layout(location = 0) out vec4 outColor;
|
||||||
|
// Source coordinate that produced this pixel, written alongside the picture so
|
||||||
|
// later passes can read the source-space masks at the right place. Alpha is 1
|
||||||
|
// when the pixel is inside the cropped image and 0 on the letterbox.
|
||||||
|
layout(location = 1) out vec4 outMap;
|
||||||
|
|
||||||
uniform sampler2D u_src;
|
uniform sampler2D u_src;
|
||||||
uniform sampler2D u_curve;
|
uniform sampler2D u_curve;
|
||||||
@@ -77,11 +81,18 @@ uniform vec2 u_healSize[24];
|
|||||||
uniform sampler2D u_masks; // layers 1-4
|
uniform sampler2D u_masks; // layers 1-4
|
||||||
uniform sampler2D u_masks2; // layers 5-8
|
uniform sampler2D u_masks2; // layers 5-8
|
||||||
uniform int u_localCount;
|
uniform int u_localCount;
|
||||||
|
// Local mask overlay: index of the layer tinted over the picture, -1 = off.
|
||||||
|
uniform float u_maskView;
|
||||||
|
// Opacity of that tint, 0-1.
|
||||||
|
uniform float u_maskStrength;
|
||||||
uniform vec4 u_localAdj[8]; // exposure, contrast, temp, tint
|
uniform vec4 u_localAdj[8]; // exposure, contrast, temp, tint
|
||||||
uniform vec4 u_localAdj2[8]; // saturation, highlights, shadows, unused
|
uniform vec4 u_localAdj2[8]; // saturation, highlights, shadows, unused
|
||||||
uniform vec4 u_localAdj3[8]; // whites, blacks, vibrance, hue degrees
|
uniform vec4 u_localAdj3[8]; // whites, blacks, vibrance, hue degrees
|
||||||
uniform vec4 u_localRange[8]; // lumaMin, lumaMax, hue, hueRange
|
uniform vec4 u_localRange[8]; // lumaMin, lumaMax, hue, hueRange
|
||||||
uniform vec4 u_localRange2[8]; // satMin, enabled, unused, unused
|
uniform vec4 u_localRange2[8]; // satMin, enabled, unused, unused
|
||||||
|
// 256×8 LUT, one row per layer: the per-mask tone curve, applied to the masked
|
||||||
|
// pixels only so a burnt sky can hold its own contrast independently.
|
||||||
|
uniform sampler2D u_localCurves;
|
||||||
|
|
||||||
// Lens/perspective correction: distortion, vertical, horizontal, rotation.
|
// Lens/perspective correction: distortion, vertical, horizontal, rotation.
|
||||||
uniform vec4 u_geom;
|
uniform vec4 u_geom;
|
||||||
@@ -275,6 +286,7 @@ vec2 warpGeometry(vec2 s){
|
|||||||
}
|
}
|
||||||
|
|
||||||
void main(){
|
void main(){
|
||||||
|
outMap = vec4(0.0);
|
||||||
// The eyedropper renders one pixel at an arbitrary point, so the mapping below
|
// The eyedropper renders one pixel at an arbitrary point, so the mapping below
|
||||||
// takes its coordinate from the uniform instead of the fragment position.
|
// takes its coordinate from the uniform instead of the fragment position.
|
||||||
vec2 outUv = u_pick > 0.5 ? u_pickUv : v_uv;
|
vec2 outUv = u_pick > 0.5 ? u_pickUv : v_uv;
|
||||||
@@ -317,6 +329,9 @@ void main(){
|
|||||||
: lensQ;
|
: lensQ;
|
||||||
}
|
}
|
||||||
vec2 uv = lensCoord;
|
vec2 uv = lensCoord;
|
||||||
|
// Hand the source coordinate to the passes that need source-space data (the
|
||||||
|
// local detail masks) instead of making them repeat this warp.
|
||||||
|
outMap = vec4(uv, 0.0, 1.0);
|
||||||
vec3 src;
|
vec3 src;
|
||||||
if (showLens && (u_lensFlags & 2) != 0) {
|
if (showLens && (u_lensFlags & 2) != 0) {
|
||||||
vec4 t = lensSample(u_lensTca, u_lensTcaSize, lensCoord);
|
vec4 t = lensSample(u_lensTca, u_lensTcaSize, lensCoord);
|
||||||
@@ -330,10 +345,6 @@ void main(){
|
|||||||
? sampleBicubic(u_src, uv, u_srcSize)
|
? sampleBicubic(u_src, uv, u_srcSize)
|
||||||
: textureLod(u_src, uv, u_srcLod).rgb;
|
: textureLod(u_src, uv, u_srcLod).rgb;
|
||||||
}
|
}
|
||||||
if (showLens && (u_lensFlags & 4) != 0) {
|
|
||||||
src *= lensSample(u_lensVig, u_lensVigSize, lensQ).rgb;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Camera-native proxies are converted once, before the source is read any
|
// Camera-native proxies are converted once, before the source is read any
|
||||||
// further: the frame, the healed patches and the eyedropper all work on the
|
// further: the frame, the healed patches and the eyedropper all work on the
|
||||||
// same sRGB values whatever the camera matrix was.
|
// same sRGB values whatever the camera matrix was.
|
||||||
@@ -366,9 +377,15 @@ void main(){
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Eyedropper: hand back the untouched source colour at the sampled point.
|
// Eyedropper: hand back the source colour at the sampled point, with the lens
|
||||||
|
// gain applied the same way the frame is, so a corner sample reads the
|
||||||
|
// brightness on screen.
|
||||||
if (u_pick > 0.5) {
|
if (u_pick > 0.5) {
|
||||||
outColor = vec4(src, 1.0);
|
vec3 picked = toLinear(clamp(src, 0.0, 1.0));
|
||||||
|
if (showLens && (u_lensFlags & 4) != 0) {
|
||||||
|
picked *= lensSample(u_lensVig, u_lensVigSize, lensQ).rgb;
|
||||||
|
}
|
||||||
|
outColor = vec4(clamp(toSRGB(picked), 0.0, 1.0), 1.0);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -382,6 +399,13 @@ void main(){
|
|||||||
|
|
||||||
vec3 col = toLinear(clamp(src, 0.0, 1.0));
|
vec3 col = toLinear(clamp(src, 0.0, 1.0));
|
||||||
|
|
||||||
|
// Lens vignetting is a flat-field gain from Lensfun's linear-light
|
||||||
|
// transmission model, so it belongs after the sRGB decode. Multiplying it into
|
||||||
|
// the encoded values brightened the corners far more than the lens lost.
|
||||||
|
if (showLens && (u_lensFlags & 4) != 0) {
|
||||||
|
col *= lensSample(u_lensVig, u_lensVigSize, lensQ).rgb;
|
||||||
|
}
|
||||||
|
|
||||||
// White balance gains, solved on the CPU: either the relative Temp offset or
|
// White balance gains, solved on the CPU: either the relative Temp offset or
|
||||||
// the absolute Kelvin control, both normalised so exposure is unchanged.
|
// the absolute Kelvin control, both normalised so exposure is unchanged.
|
||||||
col *= u_wbGain;
|
col *= u_wbGain;
|
||||||
@@ -543,16 +567,34 @@ void main(){
|
|||||||
1.0,
|
1.0,
|
||||||
adj3.z
|
adj3.z
|
||||||
);
|
);
|
||||||
|
// Per-mask curve, looked up in this layer's LUT row before the mask blend.
|
||||||
|
float curveRow = (float(i) + 0.5) / 8.0;
|
||||||
|
local = vec3(
|
||||||
|
texture(u_localCurves, vec2(clamp(local.r, 0.0, 1.0), curveRow)).r,
|
||||||
|
texture(u_localCurves, vec2(clamp(local.g, 0.0, 1.0), curveRow)).g,
|
||||||
|
texture(u_localCurves, vec2(clamp(local.b, 0.0, 1.0), curveRow)).b
|
||||||
|
);
|
||||||
srgb = mix(srgb, clamp(local, 0.0, 1.0), m);
|
srgb = mix(srgb, clamp(local, 0.0, 1.0), m);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Alpha carries the *source* clipping state to the finish pass, so the
|
// Mask overlay: tint the baked shape, not a redrawn brush band. Reading the
|
||||||
// warning reflects the pixels the sensor/proxy had, not the graded result.
|
// same source uv the adjustments use keeps the preview on the picture through
|
||||||
float clipFlag = 0.0;
|
// crops, straightening, zoom and lens correction, and it shows the feather
|
||||||
if (max(src.r, max(src.g, src.b)) >= 0.996) clipFlag += 0.5;
|
// exactly as the mask stores it.
|
||||||
if (min(src.r, min(src.g, src.b)) <= 0.004) clipFlag += 0.25;
|
if (u_maskView >= 0.0 && u_localCount > 0) {
|
||||||
outColor = vec4(clamp(srgb, 0.0, 1.0), clipFlag);
|
int mv = int(u_maskView + 0.5);
|
||||||
|
int mk = mv < 4 ? mv : mv - 4;
|
||||||
|
vec4 mtex = mv < 4 ? texture(u_masks, uv) : texture(u_masks2, uv);
|
||||||
|
float cov = mk == 0 ? mtex.r : mk == 1 ? mtex.g : mk == 2 ? mtex.b : mtex.a;
|
||||||
|
srgb = mix(
|
||||||
|
srgb,
|
||||||
|
vec3(0.98, 0.72, 0.35),
|
||||||
|
clamp(cov, 0.0, 1.0) * clamp(u_maskStrength, 0.0, 1.0)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
outColor = vec4(clamp(srgb, 0.0, 1.0), 1.0);
|
||||||
}`;
|
}`;
|
||||||
|
|
||||||
const BLUR_FRAG = `#version 300 es
|
const BLUR_FRAG = `#version 300 es
|
||||||
@@ -581,6 +623,8 @@ uniform sampler2D u_blurBig;
|
|||||||
// grade pass. Amounts are added to the global sliders per pixel.
|
// grade pass. Amounts are added to the global sliders per pixel.
|
||||||
uniform sampler2D u_masks;
|
uniform sampler2D u_masks;
|
||||||
uniform sampler2D u_masks2;
|
uniform sampler2D u_masks2;
|
||||||
|
// Source coordinate of this output pixel, from the grade pass.
|
||||||
|
uniform sampler2D u_maskUv;
|
||||||
uniform int u_localCount;
|
uniform int u_localCount;
|
||||||
uniform vec4 u_localDetail[8]; // texture, clarity, dehaze, sharpen
|
uniform vec4 u_localDetail[8]; // texture, clarity, dehaze, sharpen
|
||||||
uniform vec4 u_localModes[8]; // x = add / subtract / intersect
|
uniform vec4 u_localModes[8]; // x = add / subtract / intersect
|
||||||
@@ -665,9 +709,14 @@ void main(){
|
|||||||
float localClarity = 0.0;
|
float localClarity = 0.0;
|
||||||
float localDehaze = 0.0;
|
float localDehaze = 0.0;
|
||||||
float localSharpen = 0.0;
|
float localSharpen = 0.0;
|
||||||
if (u_localCount > 0) {
|
// The masks are baked in source space, so read them through the source
|
||||||
vec4 maskA = texture(u_masks, v_uv);
|
// coordinate the grade pass wrote for this pixel: crop, straightening, zoom
|
||||||
vec4 maskB = texture(u_masks2, v_uv);
|
// and lens correction all move the mask along with the picture.
|
||||||
|
vec4 maskMap = texture(u_maskUv, v_uv);
|
||||||
|
if (u_localCount > 0 && maskMap.a > 0.5) {
|
||||||
|
vec2 maskUv = maskMap.rg;
|
||||||
|
vec4 maskA = texture(u_masks, maskUv);
|
||||||
|
vec4 maskB = texture(u_masks2, maskUv);
|
||||||
float prevMask = 1.0;
|
float prevMask = 1.0;
|
||||||
for (int i = 0; i < 8; i++) {
|
for (int i = 0; i < 8; i++) {
|
||||||
if (i >= u_localCount) break;
|
if (i >= u_localCount) break;
|
||||||
@@ -856,16 +905,42 @@ void main(){
|
|||||||
vec3 finalCol = clamp(col, 0.0, 1.0);
|
vec3 finalCol = clamp(col, 0.0, 1.0);
|
||||||
// Clipping overlay: which channels have run out of headroom. Red/green/blue
|
// Clipping overlay: which channels have run out of headroom. Red/green/blue
|
||||||
// mean one channel clipped, yellow means two, white means all three — the
|
// mean one channel clipped, yellow means two, white means all three — the
|
||||||
// same reading Aperture's exposure warnings gave while you dragged.
|
// same reading Aperture's exposure warnings gave while you dragged. It reads
|
||||||
// The grade pass wrote the untouched source's clipping state into alpha:
|
// the finished frame rather than the source, so holding Ctrl while moving
|
||||||
// 0.25 shadow, 0.50 highlight, 0.75 both. Warning about the source means it
|
// Exposure or Recovery shows the warnings appear and clear as you go.
|
||||||
// still tells the truth after a curve or a shadow lift.
|
|
||||||
float srcClip = texture(u_graded, v_uv).a;
|
|
||||||
if (u_clip > 1.5) {
|
if (u_clip > 1.5) {
|
||||||
if (srcClip >= 0.2 && srcClip < 0.5) finalCol = vec3(0.15, 0.4, 1.0);
|
// Shadow clipping: which channels have fallen to the bottom of the range.
|
||||||
else if (srcClip >= 0.7) finalCol = vec3(0.15, 0.4, 1.0);
|
// The palette mirrors the highlight one, so red/green/blue mean one channel
|
||||||
|
// and the secondary colours name the pair that ran out of shadow detail:
|
||||||
|
// yellow red+green, magenta red+blue, cyan green+blue.
|
||||||
|
vec3 k = 1.0 - step(vec3(0.021), finalCol);
|
||||||
|
float n = k.r + k.g + k.b;
|
||||||
|
if (n > 0.5) {
|
||||||
|
vec3 mark = vec3(1.0);
|
||||||
|
if (n < 2.5) {
|
||||||
|
if (n > 1.5) {
|
||||||
|
if (k.r > 0.5 && k.g > 0.5) mark = vec3(1.0, 0.9, 0.1);
|
||||||
|
else if (k.r > 0.5) mark = vec3(1.0, 0.15, 0.85);
|
||||||
|
else mark = vec3(0.1, 0.85, 1.0);
|
||||||
|
} else if (k.r > 0.5) mark = vec3(1.0, 0.12, 0.12);
|
||||||
|
else if (k.g > 0.5) mark = vec3(0.1, 1.0, 0.2);
|
||||||
|
else mark = vec3(0.15, 0.4, 1.0);
|
||||||
|
}
|
||||||
|
finalCol = mark;
|
||||||
|
}
|
||||||
} else if (u_clip > 0.5) {
|
} else if (u_clip > 0.5) {
|
||||||
if (srcClip >= 0.5) finalCol = vec3(1.0);
|
vec3 k = step(0.985, finalCol);
|
||||||
|
float n = k.r + k.g + k.b;
|
||||||
|
if (n > 0.5) {
|
||||||
|
vec3 mark = vec3(1.0);
|
||||||
|
if (n < 2.5) {
|
||||||
|
if (n > 1.5) mark = vec3(1.0, 0.9, 0.1);
|
||||||
|
else if (k.r > 0.5) mark = vec3(1.0, 0.12, 0.12);
|
||||||
|
else if (k.g > 0.5) mark = vec3(0.1, 1.0, 0.2);
|
||||||
|
else mark = vec3(0.15, 0.4, 1.0);
|
||||||
|
}
|
||||||
|
finalCol = mark;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
outColor = vec4(finalCol, 1.0);
|
outColor = vec4(finalCol, 1.0);
|
||||||
}`;
|
}`;
|
||||||
@@ -884,6 +959,8 @@ interface Target {
|
|||||||
h: number;
|
h: number;
|
||||||
/** Half-float pixels keep subtle gradients from banding between passes. */
|
/** Half-float pixels keep subtle gradients from banding between passes. */
|
||||||
float: boolean;
|
float: boolean;
|
||||||
|
/** Second colour attachment, e.g. the source-coordinate map of the grade. */
|
||||||
|
aux?: WebGLTexture;
|
||||||
}
|
}
|
||||||
|
|
||||||
function makeHistogram(): Histogram {
|
function makeHistogram(): Histogram {
|
||||||
@@ -1116,6 +1193,28 @@ export function buildCurveLUT(edits: Edits): Uint8Array {
|
|||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Per-mask curve LUT: 256 samples per row, eight rows (one per layer), RGB in
|
||||||
|
* the colour channels. The running maximum keeps the curve monotonic for the
|
||||||
|
* same reason the global one does — a folded mask curve posterises the area.
|
||||||
|
*/
|
||||||
|
export function buildLocalCurveLUT(layers: { curve?: CurvePoint[] }[]): Uint8Array {
|
||||||
|
const data = new Uint8Array(256 * 8 * 4);
|
||||||
|
for (let row = 0; row < 8; row++) {
|
||||||
|
const points = layers[row]?.curve;
|
||||||
|
const sampler = points && points.length >= 2 ? buildSampler(points) : (x: number) => x;
|
||||||
|
let previous = 0;
|
||||||
|
for (let i = 0; i < 256; i++) {
|
||||||
|
const value = Math.max(previous, Math.min(1, sampler(i / 255)));
|
||||||
|
previous = value;
|
||||||
|
const o = (row * 256 + i) * 4;
|
||||||
|
data[o] = data[o + 1] = data[o + 2] = Math.round(value * 255);
|
||||||
|
data[o + 3] = 255;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
class Prog {
|
class Prog {
|
||||||
private cache = new Map<string, WebGLUniformLocation | null>();
|
private cache = new Map<string, WebGLUniformLocation | null>();
|
||||||
constructor(private gl: WebGL2RenderingContext, public program: WebGLProgram) {}
|
constructor(private gl: WebGL2RenderingContext, public program: WebGLProgram) {}
|
||||||
@@ -1256,6 +1355,8 @@ export class Renderer {
|
|||||||
private denMix = 0;
|
private denMix = 0;
|
||||||
private denBitmap: ImageBitmap | null = null;
|
private denBitmap: ImageBitmap | null = null;
|
||||||
private curveTex: WebGLTexture;
|
private curveTex: WebGLTexture;
|
||||||
|
/** 256×8 LUT of per-mask curves; created on first use. */
|
||||||
|
private localCurveTex: WebGLTexture | null = null;
|
||||||
private targets: { graded?: Target; smallA?: Target; smallB?: Target; bigA?: Target; bigB?: Target } = {};
|
private targets: { graded?: Target; smallA?: Target; smallB?: Target; bigA?: Target; bigB?: Target } = {};
|
||||||
private histTarget: Target | null = null;
|
private histTarget: Target | null = null;
|
||||||
private pickTarget: Target | null = null;
|
private pickTarget: Target | null = null;
|
||||||
@@ -1437,6 +1538,9 @@ export class Renderer {
|
|||||||
this.srcW = bitmap.width;
|
this.srcW = bitmap.width;
|
||||||
this.srcH = bitmap.height;
|
this.srcH = bitmap.height;
|
||||||
gl.bindTexture(gl.TEXTURE_2D, this.srcTex);
|
gl.bindTexture(gl.TEXTURE_2D, this.srcTex);
|
||||||
|
// The flag is honoured for the ArrayBufferView sidecar but ignored for the
|
||||||
|
// ImageBitmap proxy, so the sidecar arrives already in the proxy's row order
|
||||||
|
// and must be uploaded unflipped.
|
||||||
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
|
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
|
||||||
const usable = hdr && hdr.width === bitmap.width && hdr.height === bitmap.height ? hdr : null;
|
const usable = hdr && hdr.width === bitmap.width && hdr.height === bitmap.height ? hdr : null;
|
||||||
let half = false;
|
let half = false;
|
||||||
@@ -1575,36 +1679,48 @@ export class Renderer {
|
|||||||
this.proofLutOn = 1;
|
this.proofLutOn = 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
private makeTarget(w: number, h: number, float = this.floatTargets): Target {
|
private makeTarget(w: number, h: number, float = this.floatTargets, aux = false): Target {
|
||||||
const gl = this.gl;
|
const gl = this.gl;
|
||||||
const tex = gl.createTexture();
|
const tex = gl.createTexture();
|
||||||
const fbo = gl.createFramebuffer();
|
const fbo = gl.createFramebuffer();
|
||||||
if (!tex || !fbo) throw new Error('Unable to allocate render target');
|
if (!tex || !fbo) throw new Error('Unable to allocate render target');
|
||||||
gl.bindTexture(gl.TEXTURE_2D, tex);
|
const alloc = (texture: WebGLTexture) => {
|
||||||
if (float) {
|
gl.bindTexture(gl.TEXTURE_2D, texture);
|
||||||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA16F, w, h, 0, gl.RGBA, gl.HALF_FLOAT, null);
|
if (float) {
|
||||||
} else {
|
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA16F, w, h, 0, gl.RGBA, gl.HALF_FLOAT, null);
|
||||||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, w, h, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
|
} else {
|
||||||
}
|
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, w, h, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
|
||||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
|
}
|
||||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
|
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
|
||||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
|
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
|
||||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
|
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
|
||||||
|
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
|
||||||
|
};
|
||||||
|
alloc(tex);
|
||||||
|
const auxTex = aux ? gl.createTexture() : null;
|
||||||
|
if (aux && !auxTex) throw new Error('Unable to allocate render target');
|
||||||
gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);
|
gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);
|
||||||
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
|
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
|
||||||
|
if (auxTex) {
|
||||||
|
alloc(auxTex);
|
||||||
|
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT1, gl.TEXTURE_2D, auxTex, 0);
|
||||||
|
gl.drawBuffers([gl.COLOR_ATTACHMENT0, gl.COLOR_ATTACHMENT1]);
|
||||||
|
}
|
||||||
if (float && gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) {
|
if (float && gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) {
|
||||||
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
|
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
|
||||||
gl.deleteTexture(tex);
|
gl.deleteTexture(tex);
|
||||||
|
if (auxTex) gl.deleteTexture(auxTex);
|
||||||
gl.deleteFramebuffer(fbo);
|
gl.deleteFramebuffer(fbo);
|
||||||
throw new Error('Half-float render targets are unavailable');
|
throw new Error('Half-float render targets are unavailable');
|
||||||
}
|
}
|
||||||
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
|
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
|
||||||
return { tex, fbo, w, h, float };
|
return { tex, fbo, w, h, float, aux: auxTex ?? undefined };
|
||||||
}
|
}
|
||||||
|
|
||||||
private freeTarget(target?: Target) {
|
private freeTarget(target?: Target) {
|
||||||
if (!target) return;
|
if (!target) return;
|
||||||
this.gl.deleteTexture(target.tex);
|
this.gl.deleteTexture(target.tex);
|
||||||
|
if (target.aux) this.gl.deleteTexture(target.aux);
|
||||||
this.gl.deleteFramebuffer(target.fbo);
|
this.gl.deleteFramebuffer(target.fbo);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1627,13 +1743,14 @@ export class Renderer {
|
|||||||
for (const useFloat of modes) {
|
for (const useFloat of modes) {
|
||||||
const made: Target[] = [];
|
const made: Target[] = [];
|
||||||
try {
|
try {
|
||||||
const mk = (mw: number, mh: number) => {
|
const mk = (mw: number, mh: number, extra = false) => {
|
||||||
const target = this.makeTarget(mw, mh, useFloat);
|
const target = this.makeTarget(mw, mh, useFloat, extra);
|
||||||
made.push(target);
|
made.push(target);
|
||||||
return target;
|
return target;
|
||||||
};
|
};
|
||||||
this.targets = {
|
this.targets = {
|
||||||
graded: mk(w, h),
|
// The grade also writes the source-coordinate map for the finish pass.
|
||||||
|
graded: mk(w, h, true),
|
||||||
smallA: mk(sw, sh),
|
smallA: mk(sw, sh),
|
||||||
smallB: mk(sw, sh),
|
smallB: mk(sw, sh),
|
||||||
bigA: mk(bw, bh),
|
bigA: mk(bw, bh),
|
||||||
@@ -1682,6 +1799,26 @@ export class Renderer {
|
|||||||
return layers.length;
|
return layers.length;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** One 256×8 texture carries every layer's mask curve, so no extra units. */
|
||||||
|
private uploadLocalCurves(layers: LocalLayer[]): WebGLTexture {
|
||||||
|
const gl = this.gl;
|
||||||
|
let tex = this.localCurveTex;
|
||||||
|
if (!tex) {
|
||||||
|
tex = gl.createTexture();
|
||||||
|
this.localCurveTex = tex;
|
||||||
|
gl.bindTexture(gl.TEXTURE_2D, tex);
|
||||||
|
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
|
||||||
|
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
|
||||||
|
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
|
||||||
|
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
|
||||||
|
}
|
||||||
|
const data = buildLocalCurveLUT(layers);
|
||||||
|
gl.bindTexture(gl.TEXTURE_2D, tex);
|
||||||
|
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
|
||||||
|
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, 256, 8, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
|
||||||
|
return tex;
|
||||||
|
}
|
||||||
|
|
||||||
private uploadLensMaps() {
|
private uploadLensMaps() {
|
||||||
const gl = this.gl;
|
const gl = this.gl;
|
||||||
const correction = this.lensCorrection;
|
const correction = this.lensCorrection;
|
||||||
@@ -1705,6 +1842,8 @@ export class Renderer {
|
|||||||
bounds: { w: number; h: number },
|
bounds: { w: number; h: number },
|
||||||
upscale: boolean,
|
upscale: boolean,
|
||||||
srcLod = 0,
|
srcLod = 0,
|
||||||
|
maskView = -1,
|
||||||
|
maskStrength = 0.5,
|
||||||
) {
|
) {
|
||||||
const g = this.grade;
|
const g = this.grade;
|
||||||
this.gl.useProgram(g.program);
|
this.gl.useProgram(g.program);
|
||||||
@@ -1786,9 +1925,14 @@ export class Renderer {
|
|||||||
g.f('u_lensScale', lens?.scale ?? 1);
|
g.f('u_lensScale', lens?.scale ?? 1);
|
||||||
g.f('u_lensSplit', this.lensSplit);
|
g.f('u_lensSplit', this.lensSplit);
|
||||||
|
|
||||||
|
const curveTex = this.uploadLocalCurves(edits.local ?? []);
|
||||||
g.tex('u_masks', this.maskTex, 2);
|
g.tex('u_masks', this.maskTex, 2);
|
||||||
g.tex('u_masks2', this.maskTex2, 7);
|
g.tex('u_masks2', this.maskTex2, 7);
|
||||||
|
g.tex('u_localCurves', curveTex, 8);
|
||||||
g.i('u_localCount', localCount);
|
g.i('u_localCount', localCount);
|
||||||
|
// Only tint a layer that this edit actually has; -1 leaves the picture alone.
|
||||||
|
g.f('u_maskView', maskView >= 0 && maskView < localCount ? maskView : -1);
|
||||||
|
g.f('u_maskStrength', clamp01(maskStrength));
|
||||||
for (let i = 0; i < localCount; i++) {
|
for (let i = 0; i < localCount; i++) {
|
||||||
const layer = edits.local[i];
|
const layer = edits.local[i];
|
||||||
g.v4i('u_localAdj', i, layer.adjust.exposure, layer.adjust.contrast, layer.adjust.temp, layer.adjust.tint);
|
g.v4i('u_localAdj', i, layer.adjust.exposure, layer.adjust.contrast, layer.adjust.temp, layer.adjust.tint);
|
||||||
@@ -1831,6 +1975,7 @@ export class Renderer {
|
|||||||
// shows the Optics split.
|
// shows the Optics split.
|
||||||
const split = this.lensSplit;
|
const split = this.lensSplit;
|
||||||
this.lensSplit = -1;
|
this.lensSplit = -1;
|
||||||
|
// No mask overlay here: the eyedropper must read the photo, not the tint.
|
||||||
this.bindGrade(edits, crop, valid, bounds, !!opts.upscale);
|
this.bindGrade(edits, crop, valid, bounds, !!opts.upscale);
|
||||||
this.lensSplit = split;
|
this.lensSplit = split;
|
||||||
this.grade.f('u_pick', 1);
|
this.grade.f('u_pick', 1);
|
||||||
@@ -1872,6 +2017,10 @@ export class Renderer {
|
|||||||
clipPreview?: boolean;
|
clipPreview?: boolean;
|
||||||
/** paint blown highlights or crushed shadows outside the range */
|
/** paint blown highlights or crushed shadows outside the range */
|
||||||
clipping?: 'highlights' | 'shadows';
|
clipping?: 'highlights' | 'shadows';
|
||||||
|
/** tint this local layer's baked mask over the picture; -1 or omitted = off */
|
||||||
|
maskView?: number;
|
||||||
|
/** opacity of the mask tint, 0-1 (default 0.5) */
|
||||||
|
maskStrength?: number;
|
||||||
/** return the finished image as linear-space floats instead of drawing the canvas */
|
/** return the finished image as linear-space floats instead of drawing the canvas */
|
||||||
floatOut?: boolean;
|
floatOut?: boolean;
|
||||||
},
|
},
|
||||||
@@ -1916,7 +2065,16 @@ export class Renderer {
|
|||||||
const cropPxW = Math.max(1, bounds.w * crop.w);
|
const cropPxW = Math.max(1, bounds.w * crop.w);
|
||||||
const cropPxH = Math.max(1, bounds.h * crop.h);
|
const cropPxH = Math.max(1, bounds.h * crop.h);
|
||||||
const srcLod = Math.max(0, Math.log2(Math.max(cropPxW / w, cropPxH / h)));
|
const srcLod = Math.max(0, Math.log2(Math.max(cropPxW / w, cropPxH / h)));
|
||||||
this.bindGrade(edits, crop, valid, bounds, !!opts.upscale, srcLod);
|
this.bindGrade(
|
||||||
|
edits,
|
||||||
|
crop,
|
||||||
|
valid,
|
||||||
|
bounds,
|
||||||
|
!!opts.upscale,
|
||||||
|
srcLod,
|
||||||
|
opts.maskView ?? -1,
|
||||||
|
opts.maskStrength ?? 0.5,
|
||||||
|
);
|
||||||
this.drawQuad();
|
this.drawQuad();
|
||||||
|
|
||||||
// Passes 2-3: small blur (detail) and large blur (clarity) from the graded image
|
// Passes 2-3: small blur (detail) and large blur (clarity) from the graded image
|
||||||
@@ -2000,6 +2158,9 @@ export class Renderer {
|
|||||||
this.finish.f('u_detailScale', detailScale);
|
this.finish.f('u_detailScale', detailScale);
|
||||||
this.finish.tex('u_masks', this.maskTex, 3);
|
this.finish.tex('u_masks', this.maskTex, 3);
|
||||||
this.finish.tex('u_masks2', this.maskTex2, 4);
|
this.finish.tex('u_masks2', this.maskTex2, 4);
|
||||||
|
// Source coordinate per pixel, written by the grade pass. The masks are
|
||||||
|
// source-space, so local detail reads them through this instead of v_uv.
|
||||||
|
if (t.graded!.aux) this.finish.tex('u_maskUv', t.graded!.aux, 5);
|
||||||
const innerLayers = (edits.local ?? []).slice(0, MAX_LOCAL_LAYERS);
|
const innerLayers = (edits.local ?? []).slice(0, MAX_LOCAL_LAYERS);
|
||||||
this.finish.i('u_localCount', innerLayers.length);
|
this.finish.i('u_localCount', innerLayers.length);
|
||||||
for (let i = 0; i < innerLayers.length; i++) {
|
for (let i = 0; i < innerLayers.length; i++) {
|
||||||
@@ -2076,6 +2237,7 @@ export class Renderer {
|
|||||||
const data = new Float32Array(w * h * 4);
|
const data = new Float32Array(w * h * 4);
|
||||||
gl.readPixels(0, 0, w, h, gl.RGBA, gl.FLOAT, data);
|
gl.readPixels(0, 0, w, h, gl.RGBA, gl.FLOAT, data);
|
||||||
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
|
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
|
||||||
|
this.checkDrawError();
|
||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2103,9 +2265,35 @@ export class Renderer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
this.checkDrawError();
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A rejected draw leaves the canvas untouched, which the editor shows as a
|
||||||
|
* black photo with nothing to explain it. Poll the error queue once per
|
||||||
|
* frame, after the draws are queued, and let the caller report a real
|
||||||
|
* failure instead of painting black.
|
||||||
|
*/
|
||||||
|
private checkDrawError() {
|
||||||
|
const gl = this.gl;
|
||||||
|
const err = gl.getError();
|
||||||
|
if (err === gl.NO_ERROR) return;
|
||||||
|
const name =
|
||||||
|
err === gl.INVALID_OPERATION
|
||||||
|
? 'INVALID_OPERATION'
|
||||||
|
: err === gl.INVALID_VALUE
|
||||||
|
? 'INVALID_VALUE'
|
||||||
|
: err === gl.INVALID_FRAMEBUFFER_OPERATION
|
||||||
|
? 'INVALID_FRAMEBUFFER_OPERATION'
|
||||||
|
: err === gl.OUT_OF_MEMORY
|
||||||
|
? 'OUT_OF_MEMORY'
|
||||||
|
: `0x${err.toString(16)}`;
|
||||||
|
throw new Error(
|
||||||
|
`The photo could not be drawn on this GPU (WebGL ${name}). Reload the page, and if it keeps happening update your graphics driver.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/** Wait for queued GPU work, e.g. before the canvas is encoded to a file. */
|
/** Wait for queued GPU work, e.g. before the canvas is encoded to a file. */
|
||||||
finishGpu() {
|
finishGpu() {
|
||||||
this.gl.finish();
|
this.gl.finish();
|
||||||
|
|||||||
@@ -68,6 +68,60 @@ describe('segmentation', () => {
|
|||||||
expect(background[32 * width + 32]).toBe(0);
|
expect(background[32 * width + 32]).toBe(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('leaves a saturated object that runs off the frame out of the subject', () => {
|
||||||
|
// Grass around a red mat that spans the whole bottom edge, with the person
|
||||||
|
// sitting in the middle: the mat touches three borders, the person none.
|
||||||
|
const width = 96;
|
||||||
|
const height = 64;
|
||||||
|
const data = new Uint8Array(width * height * 4);
|
||||||
|
for (let y = 0; y < height; y++) {
|
||||||
|
for (let x = 0; x < width; x++) {
|
||||||
|
const o = (y * width + x) * 4;
|
||||||
|
const mat = y > height * 0.6;
|
||||||
|
const person = x > width * 0.42 && x < width * 0.58 && y > height * 0.35 && y < height * 0.68;
|
||||||
|
if (person) {
|
||||||
|
data[o] = 40;
|
||||||
|
data[o + 1] = 70;
|
||||||
|
data[o + 2] = 180;
|
||||||
|
} else if (mat) {
|
||||||
|
data[o] = 200;
|
||||||
|
data[o + 1] = 30;
|
||||||
|
data[o + 2] = 40;
|
||||||
|
} else {
|
||||||
|
data[o] = 90;
|
||||||
|
data[o + 1] = 130;
|
||||||
|
data[o + 2] = 70;
|
||||||
|
}
|
||||||
|
data[o + 3] = 255;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const mask = segmentMask(data, width, height, 'subject');
|
||||||
|
const at = (x: number, y: number) => mask[Math.round(y) * width + Math.round(x)];
|
||||||
|
expect(at(width * 0.5, height * 0.5)).toBe(255);
|
||||||
|
expect(at(4, height * 0.9)).toBe(0);
|
||||||
|
expect(at(width * 0.5, height * 0.95)).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not swallow a dark scene with no clear subject', () => {
|
||||||
|
const width = 64;
|
||||||
|
const height = 64;
|
||||||
|
const data = new Uint8Array(width * height * 4);
|
||||||
|
for (let y = 0; y < height; y++) {
|
||||||
|
for (let x = 0; x < width; x++) {
|
||||||
|
const o = (y * width + x) * 4;
|
||||||
|
const streak = y > 30 && y < 33 && x > 8 && x < 52;
|
||||||
|
data[o] = streak ? 220 : 18;
|
||||||
|
data[o + 1] = streak ? 90 : 22;
|
||||||
|
data[o + 2] = streak ? 40 : 34;
|
||||||
|
data[o + 3] = 255;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const mask = segmentMask(data, width, height, 'subject');
|
||||||
|
let inside = 0;
|
||||||
|
for (const value of mask) if (value) inside++;
|
||||||
|
expect(inside / mask.length).toBeLessThan(0.6);
|
||||||
|
});
|
||||||
|
|
||||||
it('splits a bimodal score map', () => {
|
it('splits a bimodal score map', () => {
|
||||||
const values = new Float32Array(1000);
|
const values = new Float32Array(1000);
|
||||||
for (let i = 0; i < 500; i++) values[i] = 0.1;
|
for (let i = 0; i < 500; i++) values[i] = 0.1;
|
||||||
|
|||||||
+24
-2
@@ -1,7 +1,8 @@
|
|||||||
import type { EventRecord, PhotoRecord } from '../types';
|
import type { EventRecord, PhotoRecord } from '../types';
|
||||||
|
import { withoutLensVignetting } from './edits';
|
||||||
|
|
||||||
const DB_NAME = 'lumenroom';
|
const DB_NAME = 'lumenroom';
|
||||||
const DB_VERSION = 1;
|
const DB_VERSION = 2;
|
||||||
|
|
||||||
let dbPromise: Promise<IDBDatabase> | null = null;
|
let dbPromise: Promise<IDBDatabase> | null = null;
|
||||||
|
|
||||||
@@ -9,7 +10,7 @@ export function openDB(): Promise<IDBDatabase> {
|
|||||||
if (dbPromise) return dbPromise;
|
if (dbPromise) return dbPromise;
|
||||||
dbPromise = new Promise((resolve, reject) => {
|
dbPromise = new Promise((resolve, reject) => {
|
||||||
const req = indexedDB.open(DB_NAME, DB_VERSION);
|
const req = indexedDB.open(DB_NAME, DB_VERSION);
|
||||||
req.onupgradeneeded = () => {
|
req.onupgradeneeded = (event) => {
|
||||||
const db = req.result;
|
const db = req.result;
|
||||||
if (!db.objectStoreNames.contains('photos')) {
|
if (!db.objectStoreNames.contains('photos')) {
|
||||||
const store = db.createObjectStore('photos', { keyPath: 'id' });
|
const store = db.createObjectStore('photos', { keyPath: 'id' });
|
||||||
@@ -18,6 +19,11 @@ export function openDB(): Promise<IDBDatabase> {
|
|||||||
if (!db.objectStoreNames.contains('assets')) db.createObjectStore('assets');
|
if (!db.objectStoreNames.contains('assets')) db.createObjectStore('assets');
|
||||||
if (!db.objectStoreNames.contains('events')) db.createObjectStore('events', { keyPath: 'id' });
|
if (!db.objectStoreNames.contains('events')) db.createObjectStore('events', { keyPath: 'id' });
|
||||||
if (!db.objectStoreNames.contains('kv')) db.createObjectStore('kv');
|
if (!db.objectStoreNames.contains('kv')) db.createObjectStore('kv');
|
||||||
|
// v2: applying a lens profile used to enable its vignetting correction,
|
||||||
|
// and the corner gain over-exposed the edges. Clear that flag once, here,
|
||||||
|
// instead of on every load, so a profile the user enables afterwards stays
|
||||||
|
// enabled.
|
||||||
|
if (event.oldVersion < 2) clearStoredLensVignetting(req.transaction);
|
||||||
};
|
};
|
||||||
req.onsuccess = () => resolve(req.result);
|
req.onsuccess = () => resolve(req.result);
|
||||||
req.onerror = () => reject(req.error ?? new Error('Unable to open database'));
|
req.onerror = () => reject(req.error ?? new Error('Unable to open database'));
|
||||||
@@ -25,6 +31,22 @@ export function openDB(): Promise<IDBDatabase> {
|
|||||||
return dbPromise;
|
return dbPromise;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Walks the photo store inside the version-change transaction and clears any
|
||||||
|
* stored lens vignetting flag. Runs once, on the database upgrade.
|
||||||
|
*/
|
||||||
|
function clearStoredLensVignetting(tx: IDBTransaction | null) {
|
||||||
|
if (!tx) return;
|
||||||
|
const cursorRequest = tx.objectStore('photos').openCursor();
|
||||||
|
cursorRequest.onsuccess = () => {
|
||||||
|
const cursor = cursorRequest.result;
|
||||||
|
if (!cursor) return;
|
||||||
|
const cleared = withoutLensVignetting(cursor.value as PhotoRecord);
|
||||||
|
if (cleared) cursor.update(cleared);
|
||||||
|
cursor.continue();
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
function wrap<T>(request: IDBRequest<T>): Promise<T> {
|
function wrap<T>(request: IDBRequest<T>): Promise<T> {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
request.onsuccess = () => resolve(request.result);
|
request.onsuccess = () => resolve(request.result);
|
||||||
|
|||||||
+119
-27
@@ -6,6 +6,7 @@ import type {
|
|||||||
Edits,
|
Edits,
|
||||||
Flag,
|
Flag,
|
||||||
HealSpot,
|
HealSpot,
|
||||||
|
LocalComponent,
|
||||||
LocalLayer,
|
LocalLayer,
|
||||||
LocalMaskKind,
|
LocalMaskKind,
|
||||||
LocalPoint,
|
LocalPoint,
|
||||||
@@ -99,6 +100,9 @@ export const MAX_HEAL_SPOTS = 24;
|
|||||||
/** Eight masks are packed into two RGBA textures. */
|
/** Eight masks are packed into two RGBA textures. */
|
||||||
export const MAX_LOCAL_LAYERS = 8;
|
export const MAX_LOCAL_LAYERS = 8;
|
||||||
|
|
||||||
|
/** More shapes than this in one group stops being quicker than a second layer. */
|
||||||
|
export const MAX_LOCAL_COMPONENTS = 8;
|
||||||
|
|
||||||
export function defaultLocalAdjust(): LocalLayer['adjust'] {
|
export function defaultLocalAdjust(): LocalLayer['adjust'] {
|
||||||
return {
|
return {
|
||||||
exposure: 0,
|
exposure: 0,
|
||||||
@@ -119,10 +123,9 @@ export function defaultLocalAdjust(): LocalLayer['adjust'] {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function defaultLocalLayer(kind: LocalMaskKind, index: number): LocalLayer {
|
export function defaultLocalComponent(kind: LocalMaskKind): LocalComponent {
|
||||||
return {
|
return {
|
||||||
id: `local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`,
|
id: `shape-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`,
|
||||||
name: `Local ${index + 1}`,
|
|
||||||
kind,
|
kind,
|
||||||
mode: 'add',
|
mode: 'add',
|
||||||
inverted: false,
|
inverted: false,
|
||||||
@@ -130,7 +133,17 @@ export function defaultLocalLayer(kind: LocalMaskKind, index: number): LocalLaye
|
|||||||
brush: { strokes: [] },
|
brush: { strokes: [] },
|
||||||
linear: { x1: 0.5, y1: 0.2, x2: 0.5, y2: 0.8 },
|
linear: { x1: 0.5, y1: 0.2, x2: 0.5, y2: 0.8 },
|
||||||
radial: { cx: 0.5, cy: 0.5, rx: 0.25, ry: 0.3 },
|
radial: { cx: 0.5, cy: 0.5, rx: 0.25, ry: 0.3 },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function defaultLocalLayer(kind: LocalMaskKind, index: number): LocalLayer {
|
||||||
|
return {
|
||||||
|
id: `local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`,
|
||||||
|
name: `Local ${index + 1}`,
|
||||||
|
mode: 'add',
|
||||||
|
components: [defaultLocalComponent(kind)],
|
||||||
range: { enabled: false, lumaMin: 0, lumaMax: 100, hue: 30, hueRange: 180, satMin: 0 },
|
range: { enabled: false, lumaMin: 0, lumaMax: 100, hue: 30, hueRange: 180, satMin: 0 },
|
||||||
|
curve: identityCurve(),
|
||||||
adjust: defaultLocalAdjust(),
|
adjust: defaultLocalAdjust(),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -269,40 +282,84 @@ function rasterMask(input: unknown): RasterMask | undefined {
|
|||||||
return { data: raw.data, width, height };
|
return { data: raw.data, width, height };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Per-mask curve points. Masks saved before the field existed have none, and
|
||||||
|
* they must come back as the identity rather than leaving the shader LUT row
|
||||||
|
* undefined.
|
||||||
|
*/
|
||||||
|
function localCurve(input: unknown): CurvePoint[] {
|
||||||
|
if (!Array.isArray(input)) return identityCurve();
|
||||||
|
const points: CurvePoint[] = [];
|
||||||
|
for (const raw of input.slice(0, 16)) {
|
||||||
|
if (!raw || typeof raw !== 'object') continue;
|
||||||
|
const point = raw as Partial<CurvePoint>;
|
||||||
|
points.push({ x: clamp01(num(point.x, 0, 0, 1)), y: clamp01(num(point.y, 0, 0, 1)) });
|
||||||
|
}
|
||||||
|
points.sort((a, b) => a.x - b.x);
|
||||||
|
return points.length >= 2 ? points : identityCurve();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One shape from stored edits. It also reads the pre-group flat layout, where
|
||||||
|
* the layer itself carried kind/feather/brush/...: that is how every mask saved
|
||||||
|
* before mask groups existed migrates into `components[0]`.
|
||||||
|
*/
|
||||||
|
function localComponent(input: unknown, index: number): LocalComponent | null {
|
||||||
|
if (!input || typeof input !== 'object') return null;
|
||||||
|
const shape = input as Partial<LocalComponent> & { kind?: unknown };
|
||||||
|
const kind: LocalMaskKind =
|
||||||
|
shape.kind === 'linear' || shape.kind === 'radial' || shape.kind === 'raster' ? shape.kind : 'brush';
|
||||||
|
const linear = (shape.linear ?? {}) as Partial<LocalComponent['linear']>;
|
||||||
|
const radial = (shape.radial ?? {}) as Partial<LocalComponent['radial']>;
|
||||||
|
const raster = kind === 'raster' ? rasterMask(shape.raster) : undefined;
|
||||||
|
// A raster shape without its coverage would composite an empty hole, so it
|
||||||
|
// falls back to a brush shape that can at least be painted over.
|
||||||
|
const resolved: LocalMaskKind = kind === 'raster' && !raster ? 'brush' : kind;
|
||||||
|
return {
|
||||||
|
id: typeof shape.id === 'string' && shape.id ? shape.id.slice(0, 60) : `shape-${index}`,
|
||||||
|
kind: resolved,
|
||||||
|
mode: shape.mode === 'subtract' || shape.mode === 'intersect' ? shape.mode : 'add',
|
||||||
|
inverted: !!shape.inverted,
|
||||||
|
feather: num(shape.feather, 50, 0, 100),
|
||||||
|
brush: { strokes: localStrokes(shape.brush?.strokes) },
|
||||||
|
raster: resolved === 'raster' ? raster : undefined,
|
||||||
|
linear: {
|
||||||
|
x1: clamp01(num(linear.x1, 0.5, 0, 1)),
|
||||||
|
y1: clamp01(num(linear.y1, 0.2, 0, 1)),
|
||||||
|
x2: clamp01(num(linear.x2, 0.5, 0, 1)),
|
||||||
|
y2: clamp01(num(linear.y2, 0.8, 0, 1)),
|
||||||
|
},
|
||||||
|
radial: {
|
||||||
|
cx: clamp01(num(radial.cx, 0.5, 0, 1)),
|
||||||
|
cy: clamp01(num(radial.cy, 0.5, 0, 1)),
|
||||||
|
rx: num(radial.rx, 0.25, 0.01, 1.5),
|
||||||
|
ry: num(radial.ry, 0.3, 0.01, 1.5),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
function localLayers(input: unknown): LocalLayer[] {
|
function localLayers(input: unknown): LocalLayer[] {
|
||||||
if (!Array.isArray(input)) return [];
|
if (!Array.isArray(input)) return [];
|
||||||
const out: LocalLayer[] = [];
|
const out: LocalLayer[] = [];
|
||||||
for (const raw of input.slice(0, MAX_LOCAL_LAYERS)) {
|
for (const raw of input.slice(0, MAX_LOCAL_LAYERS)) {
|
||||||
if (!raw || typeof raw !== 'object') continue;
|
if (!raw || typeof raw !== 'object') continue;
|
||||||
const layer = raw as Partial<LocalLayer>;
|
const layer = raw as Partial<LocalLayer>;
|
||||||
const kind: LocalMaskKind =
|
|
||||||
layer.kind === 'linear' || layer.kind === 'radial' || layer.kind === 'raster' ? layer.kind : 'brush';
|
|
||||||
const adjust = (layer.adjust ?? {}) as Partial<LocalLayer['adjust']>;
|
const adjust = (layer.adjust ?? {}) as Partial<LocalLayer['adjust']>;
|
||||||
const range = (layer.range ?? {}) as Partial<LocalLayer['range']>;
|
const range = (layer.range ?? {}) as Partial<LocalLayer['range']>;
|
||||||
const linear = (layer.linear ?? {}) as Partial<LocalLayer['linear']>;
|
const stored = Array.isArray(layer.components) && layer.components.length ? layer.components : [layer];
|
||||||
const radial = (layer.radial ?? {}) as Partial<LocalLayer['radial']>;
|
const components: LocalComponent[] = [];
|
||||||
|
for (const entry of stored.slice(0, MAX_LOCAL_COMPONENTS)) {
|
||||||
|
const component = localComponent(entry, components.length);
|
||||||
|
if (component) components.push(component);
|
||||||
|
}
|
||||||
|
// A layer must keep at least one shape, or it would adjust nothing with no
|
||||||
|
// way to tell why from the panel.
|
||||||
|
if (!components.length) components.push(defaultLocalComponent('brush'));
|
||||||
out.push({
|
out.push({
|
||||||
id: typeof layer.id === 'string' && layer.id ? layer.id : `local-${out.length}`,
|
id: typeof layer.id === 'string' && layer.id ? layer.id : `local-${out.length}`,
|
||||||
name: typeof layer.name === 'string' && layer.name.trim() ? layer.name.slice(0, 40) : `Local ${out.length + 1}`,
|
name: typeof layer.name === 'string' && layer.name.trim() ? layer.name.slice(0, 40) : `Local ${out.length + 1}`,
|
||||||
kind,
|
mode: layer.mode === 'subtract' || layer.mode === 'intersect' ? layer.mode : 'add',
|
||||||
mode:
|
components,
|
||||||
layer.mode === 'subtract' || layer.mode === 'intersect' ? layer.mode : 'add',
|
|
||||||
inverted: !!layer.inverted,
|
|
||||||
feather: num(layer.feather, 50, 0, 100),
|
|
||||||
brush: { strokes: localStrokes(layer.brush?.strokes) },
|
|
||||||
raster: kind === 'raster' ? rasterMask(layer.raster) : undefined,
|
|
||||||
linear: {
|
|
||||||
x1: clamp01(num(linear.x1, 0.5, 0, 1)),
|
|
||||||
y1: clamp01(num(linear.y1, 0.2, 0, 1)),
|
|
||||||
x2: clamp01(num(linear.x2, 0.5, 0, 1)),
|
|
||||||
y2: clamp01(num(linear.y2, 0.8, 0, 1)),
|
|
||||||
},
|
|
||||||
radial: {
|
|
||||||
cx: clamp01(num(radial.cx, 0.5, 0, 1)),
|
|
||||||
cy: clamp01(num(radial.cy, 0.5, 0, 1)),
|
|
||||||
rx: num(radial.rx, 0.25, 0.01, 1.5),
|
|
||||||
ry: num(radial.ry, 0.3, 0.01, 1.5),
|
|
||||||
},
|
|
||||||
range: {
|
range: {
|
||||||
enabled: !!range.enabled,
|
enabled: !!range.enabled,
|
||||||
lumaMin: num(range.lumaMin, 0, 0, 100),
|
lumaMin: num(range.lumaMin, 0, 0, 100),
|
||||||
@@ -311,6 +368,7 @@ function localLayers(input: unknown): LocalLayer[] {
|
|||||||
hueRange: num(range.hueRange, 180, 0, 180),
|
hueRange: num(range.hueRange, 180, 0, 180),
|
||||||
satMin: num(range.satMin, 0, 0, 100),
|
satMin: num(range.satMin, 0, 0, 100),
|
||||||
},
|
},
|
||||||
|
curve: localCurve(layer.curve),
|
||||||
adjust: {
|
adjust: {
|
||||||
exposure: num(adjust.exposure, 0, -4, 4),
|
exposure: num(adjust.exposure, 0, -4, 4),
|
||||||
contrast: num(adjust.contrast, 0, -100, 100),
|
contrast: num(adjust.contrast, 0, -100, 100),
|
||||||
@@ -363,12 +421,46 @@ function lensProfile(input: unknown): LensProfile | undefined {
|
|||||||
corrections: {
|
corrections: {
|
||||||
distortion: corrections?.distortion !== false,
|
distortion: corrections?.distortion !== false,
|
||||||
tca: corrections?.tca !== false,
|
tca: corrections?.tca !== false,
|
||||||
vignetting: corrections?.vignetting !== false,
|
// The vignetting map is a flat-field gain applied to the already
|
||||||
|
// tone-mapped proxy, which pushes the corners brighter than the frame
|
||||||
|
// centre and over-exposes the edges. It stays opt-in, so a profile saved
|
||||||
|
// without an explicit flag never brightens the corners.
|
||||||
|
vignetting: corrections?.vignetting === true,
|
||||||
},
|
},
|
||||||
distance: num(raw.distance, 1000, 0.1, 100000),
|
distance: num(raw.distance, 1000, 0.1, 100000),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One-off cleanup for records saved while applying a lens profile enabled all
|
||||||
|
* three corrections. The vignetting gain over-exposed the edges on the tone
|
||||||
|
* mapped proxy, so it is opt-in now; this clears the flag old edits stored,
|
||||||
|
* including snapshots and history, and returns null when nothing needed doing.
|
||||||
|
*/
|
||||||
|
export function withoutLensVignetting(photo: PhotoRecord): PhotoRecord | null {
|
||||||
|
let changed = false;
|
||||||
|
const strip = (edits: Edits): Edits => {
|
||||||
|
const lens = edits.lens;
|
||||||
|
if (!lens || lens.corrections.vignetting !== true) return edits;
|
||||||
|
changed = true;
|
||||||
|
return {
|
||||||
|
...edits,
|
||||||
|
lens: { ...lens, corrections: { ...lens.corrections, vignetting: false } },
|
||||||
|
};
|
||||||
|
};
|
||||||
|
const edits = strip(photo.edits);
|
||||||
|
const snapshots = photo.snapshots?.map((snapshot) => ({
|
||||||
|
...snapshot,
|
||||||
|
edits: strip(snapshot.edits),
|
||||||
|
}));
|
||||||
|
const history = photo.history?.map((entry) => ({ ...entry, edits: strip(entry.edits) }));
|
||||||
|
if (!changed) return null;
|
||||||
|
const next: PhotoRecord = { ...photo, edits };
|
||||||
|
if (snapshots) next.snapshots = snapshots;
|
||||||
|
if (history) next.history = history;
|
||||||
|
return next;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Keeps a stored camera profile usable: a profile with a missing or non-finite
|
* Keeps a stored camera profile usable: a profile with a missing or non-finite
|
||||||
* matrix would black out the photo, so it is dropped instead.
|
* matrix would black out the photo, so it is dropped instead.
|
||||||
|
|||||||
+4
-1
@@ -85,7 +85,10 @@ function editsForImport(meta: PhotoMeta, defaults: CameraLensDefault[]) {
|
|||||||
if (match) {
|
if (match) {
|
||||||
edits.lens = {
|
edits.lens = {
|
||||||
...match.profile,
|
...match.profile,
|
||||||
corrections: { ...match.profile.corrections },
|
// A saved default still carries whatever the profile had when it was
|
||||||
|
// stored. Applying it on import must not switch the vignetting gain back
|
||||||
|
// on and over-expose the corners, so that correction stays opt-in.
|
||||||
|
corrections: { ...match.profile.corrections, vignetting: false },
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
return edits;
|
return edits;
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { describe, expect, it } from 'vitest';
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { normalizeEdits, withoutLensVignetting } from './edits';
|
||||||
import { defaultForMeta, type CameraLensDefault } from './lensDefaults';
|
import { defaultForMeta, type CameraLensDefault } from './lensDefaults';
|
||||||
import type { LensProfile } from '../types';
|
import type { LensProfile, PhotoRecord } from '../types';
|
||||||
|
|
||||||
const profile = (model: string): LensProfile => ({
|
const profile = (model: string): LensProfile => ({
|
||||||
maker: 'Nikon',
|
maker: 'Nikon',
|
||||||
@@ -64,4 +65,47 @@ describe('camera-lens default selection', () => {
|
|||||||
).toBe(newer);
|
).toBe(newer);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('leaves the vignetting correction off unless the profile asked for it', () => {
|
||||||
|
// Older saved profiles carry no corrections block at all; the flat-field
|
||||||
|
// gain would brighten the corners past the frame centre if it defaulted on.
|
||||||
|
const legacy = normalizeEdits({ lens: { maker: 'Nikon', model: 'Nikkor 50mm', crop: 1 } } as never);
|
||||||
|
expect(legacy.lens?.corrections).toEqual({ distortion: true, tca: true, vignetting: false });
|
||||||
|
|
||||||
|
const optedIn = normalizeEdits({
|
||||||
|
lens: {
|
||||||
|
maker: 'Nikon',
|
||||||
|
model: 'Nikkor 50mm',
|
||||||
|
crop: 1,
|
||||||
|
corrections: { distortion: true, tca: true, vignetting: true },
|
||||||
|
},
|
||||||
|
} as never);
|
||||||
|
expect(optedIn.lens?.corrections.vignetting).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clears a stored vignetting flag once, in edits, snapshots and history', () => {
|
||||||
|
const profile: LensProfile = {
|
||||||
|
maker: 'Canon',
|
||||||
|
model: 'EF 50mm',
|
||||||
|
crop: 1,
|
||||||
|
corrections: { distortion: true, tca: true, vignetting: true },
|
||||||
|
};
|
||||||
|
const photo = {
|
||||||
|
id: 'p1',
|
||||||
|
edits: { lens: profile },
|
||||||
|
snapshots: [{ id: 's1', name: 'Before', ts: 1, edits: { lens: profile } }],
|
||||||
|
history: [
|
||||||
|
{ label: 'Import', ts: 1, edits: { lens: profile } },
|
||||||
|
{ label: 'Exposure', ts: 2, edits: {} },
|
||||||
|
],
|
||||||
|
} as unknown as PhotoRecord;
|
||||||
|
|
||||||
|
const cleared = withoutLensVignetting(photo);
|
||||||
|
expect(cleared?.edits.lens?.corrections.vignetting).toBe(false);
|
||||||
|
expect(cleared?.snapshots?.[0].edits.lens?.corrections.vignetting).toBe(false);
|
||||||
|
expect(cleared?.history?.[0].edits.lens?.corrections.vignetting).toBe(false);
|
||||||
|
// Geometry and CA stay on: only the corner gain was the problem.
|
||||||
|
expect(cleared?.edits.lens?.corrections.distortion).toBe(true);
|
||||||
|
// Nothing left to do the second time, so the upgrade is idempotent.
|
||||||
|
expect(withoutLensVignetting(cleared as PhotoRecord)).toBeNull();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -140,7 +140,11 @@ export interface MapSet {
|
|||||||
geometry: Float32Array;
|
geometry: Float32Array;
|
||||||
/** 6 floats per point: red x/y, input x/y, blue x/y. */
|
/** 6 floats per point: red x/y, input x/y, blue x/y. */
|
||||||
tca?: Float32Array;
|
tca?: Float32Array;
|
||||||
/** 3 floats per point: the same gain for R, G and B. */
|
/**
|
||||||
|
* 3 floats per point: the same gain for R, G and B. Lensfun's vignetting
|
||||||
|
* model describes linear light, so the renderer must apply this after the
|
||||||
|
* sRGB decode rather than to encoded code values.
|
||||||
|
*/
|
||||||
vignetting?: Float32Array;
|
vignetting?: Float32Array;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,106 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { defaultLocalLayer, MAX_LOCAL_COMPONENTS, normalizeEdits } from './edits';
|
||||||
|
|
||||||
|
/** Stored edits as they look before mask groups: geometry on the layer itself. */
|
||||||
|
function legacyLayer() {
|
||||||
|
return {
|
||||||
|
id: 'local-1',
|
||||||
|
name: 'Sky',
|
||||||
|
kind: 'gradientish' as unknown as string,
|
||||||
|
mode: 'subtract',
|
||||||
|
inverted: true,
|
||||||
|
feather: 20,
|
||||||
|
brush: { strokes: [] },
|
||||||
|
linear: { x1: 0.1, y1: 0.2, x2: 0.3, y2: 0.9 },
|
||||||
|
radial: { cx: 0.4, cy: 0.6, rx: 0.2, ry: 0.3 },
|
||||||
|
range: { enabled: false, lumaMin: 0, lumaMax: 100, hue: 30, hueRange: 180, satMin: 0 },
|
||||||
|
curve: [
|
||||||
|
{ x: 0, y: 0 },
|
||||||
|
{ x: 1, y: 1 },
|
||||||
|
],
|
||||||
|
adjust: {},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('mask groups', () => {
|
||||||
|
it('migrates a flat layer into a single component without changing the mask', () => {
|
||||||
|
const edits = normalizeEdits({ local: [legacyLayer()] as never });
|
||||||
|
const layer = edits.local[0];
|
||||||
|
expect(layer.components).toHaveLength(1);
|
||||||
|
const shape = layer.components[0];
|
||||||
|
// An unknown kind is a brush, as it always was; geometry and the layer's
|
||||||
|
// combine mode move onto the shape, layer mode stays for blending layers.
|
||||||
|
expect(shape.kind).toBe('brush');
|
||||||
|
expect(shape.mode).toBe('subtract');
|
||||||
|
expect(shape.inverted).toBe(true);
|
||||||
|
expect(shape.feather).toBe(20);
|
||||||
|
expect(shape.linear.x2).toBe(0.3);
|
||||||
|
expect(shape.radial.ry).toBe(0.3);
|
||||||
|
expect(layer.mode).toBe('subtract');
|
||||||
|
expect(layer.name).toBe('Sky');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps a stored component list in order with its own modes', () => {
|
||||||
|
const edit = normalizeEdits({
|
||||||
|
local: [
|
||||||
|
{
|
||||||
|
id: 'local-a',
|
||||||
|
name: 'Group',
|
||||||
|
mode: 'add',
|
||||||
|
components: [
|
||||||
|
{ id: 's1', kind: 'radial', mode: 'add', radial: { cx: 0.5, cy: 0.5, rx: 0.4, ry: 0.4 } },
|
||||||
|
{ id: 's2', kind: 'linear', mode: 'subtract', feather: 0, linear: { x1: 0, y1: 0, x2: 1, y2: 1 } },
|
||||||
|
{ id: 's3', kind: 'brush', mode: 'intersect', brush: { strokes: [] } },
|
||||||
|
],
|
||||||
|
curve: [],
|
||||||
|
adjust: {},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
} as never);
|
||||||
|
const shapes = edit.local[0].components;
|
||||||
|
expect(shapes.map((shape) => shape.id)).toEqual(['s1', 's2', 's3']);
|
||||||
|
expect(shapes.map((shape) => shape.mode)).toEqual(['add', 'subtract', 'intersect']);
|
||||||
|
expect(shapes[1].kind).toBe('linear');
|
||||||
|
expect(shapes[2].kind).toBe('brush');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('drops a raster component that lost its coverage instead of baking an empty mask', () => {
|
||||||
|
const edit = normalizeEdits({
|
||||||
|
local: [
|
||||||
|
{
|
||||||
|
id: 'local-r',
|
||||||
|
name: 'Raster',
|
||||||
|
mode: 'add',
|
||||||
|
components: [{ id: 's1', kind: 'raster', mode: 'add' }],
|
||||||
|
curve: [],
|
||||||
|
adjust: {},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
} as never);
|
||||||
|
expect(edit.local[0].components[0].kind).toBe('brush');
|
||||||
|
expect(edit.local[0].components[0].raster).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('always leaves a layer with at least one shape and caps the group', () => {
|
||||||
|
const many = Array.from({ length: MAX_LOCAL_COMPONENTS + 4 }, (_, i) => ({
|
||||||
|
id: `s${i}`,
|
||||||
|
kind: 'radial',
|
||||||
|
mode: 'add',
|
||||||
|
}));
|
||||||
|
const edit = normalizeEdits({
|
||||||
|
local: [
|
||||||
|
{ id: 'local-m', name: 'Many', mode: 'add', components: many, curve: [], adjust: {} },
|
||||||
|
{ id: 'local-e', name: 'Empty', mode: 'add', components: [], curve: [], adjust: {} },
|
||||||
|
],
|
||||||
|
} as never);
|
||||||
|
expect(edit.local[0].components).toHaveLength(MAX_LOCAL_COMPONENTS);
|
||||||
|
expect(edit.local[1].components).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('creates new layers with one shape so the panel always has something to edit', () => {
|
||||||
|
const layer = defaultLocalLayer('linear', 0);
|
||||||
|
expect(layer.components).toHaveLength(1);
|
||||||
|
expect(layer.components[0].kind).toBe('linear');
|
||||||
|
expect(layer.components[0].mode).toBe('add');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { buildLocalCurveLUT } from '../gl/renderer';
|
||||||
|
|
||||||
|
/** Bytes of one LUT row (red channel; R/G/B are written identically). */
|
||||||
|
function row(data: Uint8Array, index: number) {
|
||||||
|
return Array.from(data.slice(index * 256 * 4, (index + 1) * 256 * 4)).filter((_, i) => i % 4 === 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('mask curve LUT', () => {
|
||||||
|
it('is the identity for a mask without a curve', () => {
|
||||||
|
const values = row(buildLocalCurveLUT([{}]), 0);
|
||||||
|
expect(values[0]).toBe(0);
|
||||||
|
expect(values[64]).toBeGreaterThan(60);
|
||||||
|
expect(values[64]).toBeLessThan(69);
|
||||||
|
expect(values[255]).toBe(255);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('lifts only the row belonging to that mask', () => {
|
||||||
|
const data = buildLocalCurveLUT([{}, { curve: [{ x: 0, y: 0.25 }, { x: 1, y: 1 }] }]);
|
||||||
|
expect(row(data, 0)[64]).toBeLessThan(80);
|
||||||
|
expect(row(data, 1)[64]).toBeGreaterThan(100);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps an inverted curve monotonic instead of folding', () => {
|
||||||
|
// A curve that dips and rises again would posterise the masked area.
|
||||||
|
const values = row(
|
||||||
|
buildLocalCurveLUT([
|
||||||
|
{ curve: [{ x: 0, y: 0 }, { x: 0.3, y: 0.8 }, { x: 0.7, y: 0.2 }, { x: 1, y: 1 }] },
|
||||||
|
]),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
for (let i = 1; i < values.length; i++) expect(values[i]).toBeGreaterThanOrEqual(values[i - 1]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fills all eight rows so a ninth mask cannot read stale data', () => {
|
||||||
|
const data = buildLocalCurveLUT([{ curve: [{ x: 0, y: 0 }, { x: 1, y: 0.5 }] }]);
|
||||||
|
expect(data.length).toBe(256 * 8 * 4);
|
||||||
|
expect(row(data, 7)[255]).toBe(255);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -149,7 +149,7 @@ describe('parsePreview16', () => {
|
|||||||
expect(Array.from(parsed!.rgba.slice(4, 8))).toEqual([0x3c00, 0, 0x3800, 0x3c00]);
|
expect(Array.from(parsed!.rgba.slice(4, 8))).toEqual([0x3c00, 0, 0x3800, 0x3c00]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('flips the rows so upload needs no UNPACK_FLIP_Y', async () => {
|
it('keeps the PNG row order so the sidecar matches the JPEG texture', async () => {
|
||||||
const parsed = await parsePreview16(
|
const parsed = await parsePreview16(
|
||||||
encodePng16(
|
encodePng16(
|
||||||
[
|
[
|
||||||
@@ -161,9 +161,11 @@ describe('parsePreview16', () => {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
expect(parsed).not.toBeNull();
|
expect(parsed).not.toBeNull();
|
||||||
// Row 0 of the returned buffer is the last image row.
|
// Chrome ignores UNPACK_FLIP_Y_WEBGL for ImageBitmap uploads, so the JPEG
|
||||||
expect(parsed!.rgba[0]).toBe(0);
|
// proxy is top-down in the texture. Flipping here put the 16-bit sidecar
|
||||||
expect(parsed!.rgba[4]).toBe(0x3c00);
|
// upside down once it replaced the proxy a few seconds after load.
|
||||||
|
expect(parsed!.rgba[0]).toBe(0x3c00);
|
||||||
|
expect(parsed!.rgba[4]).toBe(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('reads the camera matrix out of the sidecar text chunk', async () => {
|
it('reads the camera matrix out of the sidecar text chunk', async () => {
|
||||||
|
|||||||
@@ -8,14 +8,16 @@
|
|||||||
* always optional.
|
* always optional.
|
||||||
*
|
*
|
||||||
* The parser only accepts what the encoder writes (16-bit, non-interlaced,
|
* The parser only accepts what the encoder writes (16-bit, non-interlaced,
|
||||||
* RGB or RGBA) and returns the samples as half-float RGBA with the rows already
|
* RGB or RGBA) and returns the samples as half-float RGBA in the PNG's own
|
||||||
* flipped, because `UNPACK_FLIP_Y_WEBGL` is ignored for ArrayBufferView uploads.
|
* top-down row order. That is the order the JPEG proxy already lands in: an
|
||||||
|
* ImageBitmap upload ignores `UNPACK_FLIP_Y_WEBGL`, so the sidecar has to match
|
||||||
|
* it row for row or the picture jumps upside down when it swaps in.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
export interface Preview16 {
|
export interface Preview16 {
|
||||||
width: number;
|
width: number;
|
||||||
height: number;
|
height: number;
|
||||||
/** RGBA half-float, rows bottom-up, ready for `texImage2D` without a flip. */
|
/** RGBA half-float, top-down like the proxy, ready for `texImage2D` unflipped. */
|
||||||
rgba: Uint16Array;
|
rgba: Uint16Array;
|
||||||
/**
|
/**
|
||||||
* Camera-to-sRGB matrix, row major, when the samples are camera native.
|
* Camera-to-sRGB matrix, row major, when the samples are camera native.
|
||||||
@@ -195,8 +197,9 @@ export async function parsePreview16(buffer: ArrayBuffer): Promise<Preview16 | n
|
|||||||
const rgba = new Uint16Array(width * height * 4);
|
const rgba = new Uint16Array(width * height * 4);
|
||||||
const opaque = table[65535];
|
const opaque = table[65535];
|
||||||
let out = 0;
|
let out = 0;
|
||||||
for (let y = height - 1; y >= 0; y--) {
|
for (let y = 0; y < height; y++) {
|
||||||
// Bottom-up: the texture upload cannot flip an ArrayBufferView.
|
// Top-down: the JPEG texture is uploaded from an ImageBitmap, which ignores
|
||||||
|
// UNPACK_FLIP_Y_WEBGL, so both sources must hand the GPU the same row order.
|
||||||
let src = y * (stride + 1) + 1;
|
let src = y * (stride + 1) + 1;
|
||||||
for (let x = 0; x < width; x++) {
|
for (let x = 0; x < width; x++) {
|
||||||
rgba[out++] = table[(raw[src] << 8) | raw[src + 1]];
|
rgba[out++] = table[(raw[src] << 8) | raw[src + 1]];
|
||||||
|
|||||||
+4
-8
@@ -1,5 +1,5 @@
|
|||||||
import { describe, expect, it } from 'vitest';
|
import { describe, expect, it } from 'vitest';
|
||||||
import { defaultEdits, normalizeEdits } from './edits';
|
import { defaultEdits, defaultLocalLayer, normalizeEdits } from './edits';
|
||||||
import { editsToXmp, xmpFileName, xmpToEdits } from './xmp';
|
import { editsToXmp, xmpFileName, xmpToEdits } from './xmp';
|
||||||
|
|
||||||
describe('xmp sidecars', () => {
|
describe('xmp sidecars', () => {
|
||||||
@@ -12,13 +12,9 @@ describe('xmp sidecars', () => {
|
|||||||
edits.parametric.darks = -17;
|
edits.parametric.darks = -17;
|
||||||
edits.hsl.hue[3] = 12;
|
edits.hsl.hue[3] = 12;
|
||||||
edits.grain.roughness = 71;
|
edits.grain.roughness = 71;
|
||||||
edits.local = [
|
const mask = defaultLocalLayer('linear', 0);
|
||||||
{
|
if (mask.components[0]) mask.components[0].linear = { x1: 0.1, y1: 0.2, x2: 0.8, y2: 0.9 };
|
||||||
...defaultEdits().local[0],
|
edits.local = [mask];
|
||||||
kind: 'linear',
|
|
||||||
linear: { x1: 0.1, y1: 0.2, x2: 0.8, y2: 0.9 },
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
const xml = editsToXmp(edits);
|
const xml = editsToXmp(edits);
|
||||||
const back = xmpToEdits(xml, defaultEdits());
|
const back = xmpToEdits(xml, defaultEdits());
|
||||||
|
|||||||
@@ -3435,10 +3435,21 @@ figcaption {
|
|||||||
.clip-dot.y {
|
.clip-dot.y {
|
||||||
background: #ffe61a;
|
background: #ffe61a;
|
||||||
}
|
}
|
||||||
|
.clip-dot.m {
|
||||||
|
background: #ff26d9;
|
||||||
|
}
|
||||||
|
.clip-dot.c {
|
||||||
|
background: #1ad9ff;
|
||||||
|
}
|
||||||
.clip-dot.w {
|
.clip-dot.w {
|
||||||
background: #ffffff;
|
background: #ffffff;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Groups the shadow palette dots so "one channel" reads with its own colours. */
|
||||||
|
.clip-legend .clip-label {
|
||||||
|
margin-right: 5px;
|
||||||
|
}
|
||||||
|
|
||||||
@media (max-width: 760px) {
|
@media (max-width: 760px) {
|
||||||
.admin-create-grid {
|
.admin-create-grid {
|
||||||
grid-template-columns: 1fr 1fr;
|
grid-template-columns: 1fr 1fr;
|
||||||
@@ -4650,6 +4661,15 @@ figcaption {
|
|||||||
stroke: rgba(255, 92, 92, 0.4);
|
stroke: rgba(255, 92, 92, 0.4);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* The soft band of the feather, drawn under the solid core. */
|
||||||
|
.local-brush.band {
|
||||||
|
stroke: rgba(240, 170, 80, 0.14);
|
||||||
|
}
|
||||||
|
|
||||||
|
.local-brush.band.erase {
|
||||||
|
stroke: rgba(255, 92, 92, 0.13);
|
||||||
|
}
|
||||||
|
|
||||||
.local-outline,
|
.local-outline,
|
||||||
.local-line {
|
.local-line {
|
||||||
fill: none;
|
fill: none;
|
||||||
@@ -4675,6 +4695,12 @@ figcaption {
|
|||||||
stroke-dasharray: 3 3;
|
stroke-dasharray: 3 3;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Marks where the feather band starts, mirroring the baked mask. */
|
||||||
|
.local-cursor.inner {
|
||||||
|
stroke: rgba(240, 174, 85, 0.5);
|
||||||
|
stroke-dasharray: 2 4;
|
||||||
|
}
|
||||||
|
|
||||||
.local-list {
|
.local-list {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
@@ -4682,6 +4708,16 @@ figcaption {
|
|||||||
margin-bottom: 7px;
|
margin-bottom: 7px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Shapes sit under their layer, indented so the group reads as a child list. */
|
||||||
|
.local-list.shapes {
|
||||||
|
margin-bottom: 4px;
|
||||||
|
padding-left: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.local-list.shapes .local-item {
|
||||||
|
font-size: 11px;
|
||||||
|
}
|
||||||
|
|
||||||
.local-item {
|
.local-item {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
|
|||||||
+19
-5
@@ -63,12 +63,11 @@ export interface LocalStroke {
|
|||||||
erase?: boolean;
|
erase?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** One non-destructive local adjustment layer. Mask geometry is in source uv. */
|
/** One shape inside a local adjustment layer's mask group. */
|
||||||
export interface LocalLayer {
|
export interface LocalComponent {
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
|
||||||
kind: LocalMaskKind;
|
kind: LocalMaskKind;
|
||||||
/** How this mask combines with the layer above it in the list. */
|
/** How this shape combines with the shapes before it inside the layer. */
|
||||||
mode: 'add' | 'subtract' | 'intersect';
|
mode: 'add' | 'subtract' | 'intersect';
|
||||||
inverted: boolean;
|
inverted: boolean;
|
||||||
/** softness of the mask edge, 0–100 */
|
/** softness of the mask edge, 0–100 */
|
||||||
@@ -77,7 +76,17 @@ export interface LocalLayer {
|
|||||||
linear: { x1: number; y1: number; x2: number; y2: number };
|
linear: { x1: number; y1: number; x2: number; y2: number };
|
||||||
radial: { cx: number; cy: number; rx: number; ry: number };
|
radial: { cx: number; cy: number; rx: number; ry: number };
|
||||||
raster?: RasterMask;
|
raster?: RasterMask;
|
||||||
/** luminance and colour limits applied on top of the shape */
|
}
|
||||||
|
|
||||||
|
/** One non-destructive local adjustment layer. Mask geometry is in source uv. */
|
||||||
|
export interface LocalLayer {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
/** How the whole layer combines with the layer above it in the list. */
|
||||||
|
mode: 'add' | 'subtract' | 'intersect';
|
||||||
|
/** Shapes composited in order into this layer's mask. */
|
||||||
|
components: LocalComponent[];
|
||||||
|
/** luminance and colour limits applied on top of the shape group */
|
||||||
range: {
|
range: {
|
||||||
enabled: boolean;
|
enabled: boolean;
|
||||||
lumaMin: number;
|
lumaMin: number;
|
||||||
@@ -86,6 +95,11 @@ export interface LocalLayer {
|
|||||||
hueRange: number;
|
hueRange: number;
|
||||||
satMin: number;
|
satMin: number;
|
||||||
};
|
};
|
||||||
|
/**
|
||||||
|
* Per-mask RGB tone curve, applied to the masked pixels only. Identity for
|
||||||
|
* masks created before this existed, so old edits keep their look.
|
||||||
|
*/
|
||||||
|
curve: CurvePoint[];
|
||||||
adjust: {
|
adjust: {
|
||||||
exposure: number;
|
exposure: number;
|
||||||
contrast: number;
|
contrast: number;
|
||||||
|
|||||||
Reference in New Issue
Block a user