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>
72 lines
2.3 KiB
TypeScript
72 lines
2.3 KiB
TypeScript
import type { CurvePoint } from '../types';
|
|
|
|
export const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));
|
|
export const clamp01 = (v: number) => clamp(v, 0, 1);
|
|
export const round2 = (v: number) => Math.round(v * 100) / 100;
|
|
|
|
export type CurveSampler = (x: number) => number;
|
|
|
|
/** Monotone cubic (Fritsch-Carlson) interpolation through normalized curve points. */
|
|
export function buildSampler(input: CurvePoint[]): CurveSampler {
|
|
const pts = [...input].sort((a, b) => a.x - b.x);
|
|
if (pts.length < 2) return (x: number) => clamp01(x);
|
|
const xs = pts.map((p) => clamp01(p.x));
|
|
const ys = pts.map((p) => clamp01(p.y));
|
|
const n = xs.length;
|
|
|
|
const d: number[] = [];
|
|
for (let i = 0; i < n - 1; i++) d.push((ys[i + 1] - ys[i]) / Math.max(1e-6, xs[i + 1] - xs[i]));
|
|
|
|
const m: number[] = new Array(n);
|
|
m[0] = d[0];
|
|
m[n - 1] = d[n - 2];
|
|
for (let i = 1; i < n - 1; i++) {
|
|
if (d[i - 1] * d[i] <= 0) m[i] = 0;
|
|
else m[i] = (d[i - 1] + d[i]) / 2;
|
|
}
|
|
for (let i = 0; i < n - 1; i++) {
|
|
if (d[i] === 0) {
|
|
m[i] = 0;
|
|
m[i + 1] = 0;
|
|
continue;
|
|
}
|
|
const a = m[i] / d[i];
|
|
const b = m[i + 1] / d[i];
|
|
const s = a * a + b * b;
|
|
if (s > 9) {
|
|
const t = 3 / Math.sqrt(s);
|
|
m[i] = t * a * d[i];
|
|
m[i + 1] = t * b * d[i];
|
|
}
|
|
}
|
|
|
|
return (x: number) => {
|
|
if (x <= xs[0]) return clamp01(ys[0] + (x - xs[0]) * m[0]);
|
|
if (x >= xs[n - 1]) return clamp01(ys[n - 1] + (x - xs[n - 1]) * m[n - 1]);
|
|
let i = 0;
|
|
while (i < n - 2 && x > xs[i + 1]) i++;
|
|
const h = xs[i + 1] - xs[i];
|
|
const t = (x - xs[i]) / h;
|
|
const t2 = t * t;
|
|
const t3 = t2 * t;
|
|
const h00 = 2 * t3 - 3 * t2 + 1;
|
|
const h10 = t3 - 2 * t2 + t;
|
|
const h01 = -2 * t3 + 3 * t2;
|
|
const h11 = t3 - t2;
|
|
return clamp01(h00 * ys[i] + h10 * h * m[i] + h01 * ys[i + 1] + h11 * h * m[i + 1]);
|
|
};
|
|
}
|
|
|
|
export function sanitizeCurve(input: unknown): CurvePoint[] {
|
|
const fallback: CurvePoint[] = [
|
|
{ x: 0, y: 0 },
|
|
{ x: 1, y: 1 },
|
|
];
|
|
if (!Array.isArray(input)) return fallback;
|
|
const pts = input
|
|
.filter((p): p is CurvePoint => !!p && typeof p.x === 'number' && typeof p.y === 'number')
|
|
.map((p) => ({ x: clamp01(p.x), y: clamp01(p.y) }))
|
|
.sort((a, b) => a.x - b.x);
|
|
return pts.length >= 2 ? pts : fallback;
|
|
}
|