cd52a2f82f
Browser-based photo catalog with an optional team server (SQLite + LibRaw). Local database, uploaded photos, build output and dependencies are gitignored. 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com>
59 lines
2.0 KiB
TypeScript
59 lines
2.0 KiB
TypeScript
/**
|
||
* White balance eyedropper maths.
|
||
*
|
||
* The grade shader applies these gains in linear light:
|
||
* r × (1 + 0.30t + 0.06i)
|
||
* g × (1 − 0.16i)
|
||
* b × (1 − 0.26t + 0.06i)
|
||
* where t = temp / 100 and i = tint / 100 (a shared luma normalisation cancels
|
||
* out of the neutrality condition, so it is ignored here).
|
||
*
|
||
* Solving r·wr = g·wg and b·wb = g·wg for t and i is linear in i, which gives a
|
||
* closed-form answer: no iteration and no drift as the sliders move.
|
||
*/
|
||
|
||
const T_R = 0.3;
|
||
const T_B = 0.26;
|
||
const T_TINT = 0.16;
|
||
const TINT_CROSS = 0.06;
|
||
|
||
function toLinear(v: number): number {
|
||
const c = Math.min(1, Math.max(0, v));
|
||
return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
|
||
}
|
||
|
||
const clampRange = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));
|
||
|
||
/**
|
||
* Temperature and tint that make a sampled source colour neutral.
|
||
* `sample` is the untouched (sRGB-encoded) source pixel, 0–1 per channel.
|
||
* Returns null for samples too dark to carry a reliable colour cast.
|
||
*/
|
||
export function solveWhiteBalance(
|
||
sample: readonly [number, number, number],
|
||
): { temp: number; tint: number } | null {
|
||
const r = toLinear(sample[0]);
|
||
const g = toLinear(sample[1]);
|
||
const b = toLinear(sample[2]);
|
||
if (![r, g, b].every(Number.isFinite)) return null;
|
||
if (Math.max(r, g, b) < 0.004) return null;
|
||
|
||
// Ratios stay finite for very saturated or very dark picks; clamping them only
|
||
// caps how extreme the result can get, it does not affect ordinary neutrals.
|
||
const gr = clampRange(g / Math.max(1e-4, r), 0.02, 40);
|
||
const gb = clampRange(g / Math.max(1e-4, b), 0.02, 40);
|
||
|
||
const denom =
|
||
T_R * (TINT_CROSS + T_TINT * gb) + T_B * (T_TINT * gr + TINT_CROSS);
|
||
if (Math.abs(denom) < 1e-6) return null;
|
||
|
||
const ti = (T_B * (gr - 1) - T_R * (1 - gb)) / denom;
|
||
const t = ((1 - T_TINT * ti) * gr - 1 - TINT_CROSS * ti) / T_R;
|
||
if (!Number.isFinite(t) || !Number.isFinite(ti)) return null;
|
||
|
||
return {
|
||
temp: Math.round(clampRange(t * 100, -100, 100)),
|
||
tint: Math.round(clampRange(ti * 100, -100, 100)),
|
||
};
|
||
}
|