@sessile/core 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,547 @@
1
+ /**
2
+ * Adaptive backdrop legibility kernel.
3
+ *
4
+ * The host fixes the foreground (text color, polarity, target contrast); the glass yields.
5
+ * Every quantity here is expressed in sRGB-encoded relative luminance ("encoded luminance"),
6
+ * the domain browsers composite in, so veil-over-backdrop blending stays affine and WCAG
7
+ * bounds convert exactly for neutrals.
8
+ *
9
+ * The per-pixel stage is a luminance-keyed multiplicative film evaluated by the Route B3 SVG
10
+ * filter: `out = c * M(x)` for light text and `1 - out = (1 - c) * M(x)` for dark text. Scaling
11
+ * all channels by one factor keeps hue and saturation (no signed chroma intermediates, no gamut
12
+ * clipping) while absolute chroma converges exactly where luminance is compressed.
13
+ *
14
+ * SPDX-License-Identifier: MPL-2.0
15
+ */
16
+ import { clamp, lerp, smoothstep } from "./physics.js";
17
+ export const LEGIBILITY_POLICIES = {
18
+ clear: {
19
+ contrast: 3,
20
+ knee: 0.72,
21
+ filmMax: 0.06,
22
+ saturationFloor: 0.88,
23
+ blurBoostPx: 1.5,
24
+ refractionFloor: 0.85,
25
+ edgeGain: 0.35,
26
+ shadowGain: 0.4,
27
+ assumedRisk: 0.3,
28
+ },
29
+ regular: {
30
+ contrast: 4.5,
31
+ knee: 0.7,
32
+ filmMax: 0.14,
33
+ saturationFloor: 0.72,
34
+ blurBoostPx: 3,
35
+ refractionFloor: 0.65,
36
+ edgeGain: 0.6,
37
+ shadowGain: 0.8,
38
+ assumedRisk: 0.5,
39
+ },
40
+ legible: {
41
+ contrast: 7,
42
+ knee: 0.65,
43
+ filmMax: 0.26,
44
+ saturationFloor: 0.55,
45
+ blurBoostPx: 6,
46
+ refractionFloor: 0.4,
47
+ edgeGain: 0.9,
48
+ shadowGain: 1.2,
49
+ assumedRisk: 0.8,
50
+ },
51
+ };
52
+ /**
53
+ * Attack is fast so text never sits on an unsafe backdrop for more than a few frames; hold and
54
+ * release bridge the calm gutters between cards so scrolling across a grid does not strobe.
55
+ */
56
+ export const LEGIBILITY_SMOOTHING = {
57
+ attackMs: 90,
58
+ holdMs: 240,
59
+ releaseMs: 700,
60
+ // The final snap moves film alpha by at most `filmMax * epsilon` (~0.001), invisible, while
61
+ // letting the frame loop sleep a couple of seconds earlier than a 1e-3 tail would.
62
+ epsilon: 0.004,
63
+ };
64
+ /** Knee fraction used at zero luminance risk. */
65
+ export const LEGIBILITY_CALM_KNEE = 0.9;
66
+ /** Samples in each per-pixel multiplier table (`feFunc* type="table"`). */
67
+ export const LEGIBILITY_TABLE_SIZE = 33;
68
+ /**
69
+ * Filter-graph contract for the per-pixel stage, keyed by polarity.
70
+ * `k` are `feComposite operator="arithmetic"` coefficients with `in` = color, `in2` = multiplier.
71
+ * Light text keys on true luminance (`linearRGB` matrix): sRGB luma underestimates saturated
72
+ * colors (pure red has luma 0.21 but encoded luminance ~0.50) and would leave them unclamped.
73
+ * Dark text keys on sRGB luma, which only ever underestimates, so the lift errs on the safe side
74
+ * and avoids quantizing shadows in an 8-bit linear buffer.
75
+ */
76
+ export const LEGIBILITY_STAGES = {
77
+ light: { luminanceSpace: 'linearRGB', k: [1, 0, 0, 0] },
78
+ dark: { luminanceSpace: 'sRGB', k: [1, 0, -1, 1] },
79
+ };
80
+ /**
81
+ * Encoded-luminance headroom kept below the exact limit. Covers the residual error of
82
+ * scaling in sRGB space (the transfer curve is not a pure power law), veil blending of colored
83
+ * pixels, and 8-bit filter intermediates; sized by the reference-model sweep in the unit tests.
84
+ */
85
+ export const LEGIBILITY_LIMIT_MARGIN = 0.008;
86
+ /** Telemetry floats per grid cell: `lumaHigh, lumaLow, channelHigh, channelLow, chroma, detail`. */
87
+ export const TELEMETRY_STRIDE = 6;
88
+ export function srgbToLinear(c) {
89
+ return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
90
+ }
91
+ export function linearToSrgb(l) {
92
+ return l <= 0.0031308 ? l * 12.92 : 1.055 * Math.pow(l, 1 / 2.4) - 0.055;
93
+ }
94
+ /** WCAG 2 relative luminance of a normalized sRGB color. */
95
+ /** Rec. 709 weights applied to the encoded sRGB channels; a lower bound on encoded luminance. */
96
+ export function srgbLuma(r, g, b) {
97
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
98
+ }
99
+ export function relativeLuminance(r, g, b) {
100
+ return 0.2126 * srgbToLinear(r) + 0.7152 * srgbToLinear(g) + 0.0722 * srgbToLinear(b);
101
+ }
102
+ /** WCAG 2 contrast ratio between two relative luminances. */
103
+ export function contrastRatio(a, b) {
104
+ const hi = Math.max(a, b);
105
+ const lo = Math.min(a, b);
106
+ return (hi + 0.05) / (lo + 0.05);
107
+ }
108
+ /** Resolves the host declaration into a polarity and an encoded-luminance limit. */
109
+ export function resolveLegibilityGoal(target) {
110
+ const policy = LEGIBILITY_POLICIES[target.tier ?? 'regular'];
111
+ const contrast = target.contrast !== undefined && Number.isFinite(target.contrast)
112
+ ? Math.max(1, target.contrast)
113
+ : policy.contrast;
114
+ const fg = target.foreground;
115
+ const lf = relativeLuminance(fg[0] ?? 0, fg[1] ?? 0, fg[2] ?? 0);
116
+ const ceiling = (lf + 0.05) / contrast - 0.05;
117
+ const floor = contrast * (lf + 0.05) - 0.05;
118
+ const polarity = target.polarity ?? (ceiling >= 1 - floor ? 'light' : 'dark');
119
+ const limit = polarity === 'light' ? ceiling : floor;
120
+ return {
121
+ polarity,
122
+ contrast,
123
+ policy,
124
+ perceivedLimit: linearToSrgb(clamp(limit, 0, 1)),
125
+ };
126
+ }
127
+ /**
128
+ * Converts the perceived limit into a limit on the backdrop under a veil of `veilRgba`,
129
+ * expressed in "risk space" `u` (`u = x` for light text, `u = 1 - x` for dark) so both
130
+ * polarities share one ceiling curve. Returns `>= 1` when no compression is needed and `<= 0`
131
+ * when the veil alone violates the goal.
132
+ */
133
+ function backdropCeiling(goal, veilRgba) {
134
+ const a = clamp(veilRgba[3] ?? 0, 0, 1);
135
+ const r = clamp(veilRgba[0] ?? 0, 0, 1);
136
+ const g = clamp(veilRgba[1] ?? 0, 0, 1);
137
+ const b = clamp(veilRgba[2] ?? 0, 0, 1);
138
+ // Bound the veil by its extreme channel: blending happens per channel, so a saturated tint
139
+ // over a complementary backdrop composites far darker (or brighter) than its luminance implies.
140
+ const light = goal.polarity === 'light';
141
+ const veil = light ? Math.max(r, g, b) : Math.min(r, g, b);
142
+ const p = light
143
+ ? goal.perceivedLimit - LEGIBILITY_LIMIT_MARGIN
144
+ : goal.perceivedLimit + LEGIBILITY_LIMIT_MARGIN;
145
+ if (a >= 0.999) {
146
+ const ok = light ? veil <= p : veil >= p;
147
+ return ok ? 1 : -1;
148
+ }
149
+ const limit = (p - a * veil) / (1 - a);
150
+ return light ? limit : 1 - limit;
151
+ }
152
+ const IDENTITY_VEIL_OPTICS = { brightness: 1, contrast: 1, contrastFirst: false };
153
+ function veilAffineScale(optics) {
154
+ return Math.max(0, optics.brightness * optics.contrast);
155
+ }
156
+ /**
157
+ * Host optics as the CSS `backdrop-filter` path renders them: two filter functions in order, each
158
+ * clamped to `[0, 1]`. Folding them into one affine would miss the clip between them (contrast
159
+ * can saturate white before a dimming brightness), and only this path relies on the estimate;
160
+ * the per-pixel stage clamps absolute pixel values after the filter's own color matrix.
161
+ */
162
+ function applyVeilOptics(optics, x) {
163
+ const b = Math.max(0, optics.brightness);
164
+ const c = Math.max(0, optics.contrast);
165
+ return optics.contrastFirst
166
+ ? clamp(b * clamp(c * x + 0.5 * (1 - c), 0, 1), 0, 1)
167
+ : clamp(c * clamp(b * x, 0, 1) + 0.5 * (1 - c), 0, 1);
168
+ }
169
+ /**
170
+ * Extreme of `applyVeilOptics(x) - x` over `[lo, hi]`. The map is piecewise linear, so the
171
+ * extreme sits at an endpoint or at one of its (at most three) clip kinks.
172
+ */
173
+ function opticsDeviation(optics, lo, hi, upper) {
174
+ const b = Math.max(0, optics.brightness);
175
+ const c = Math.max(0, optics.contrast);
176
+ const k = 0.5 * (1 - c);
177
+ let k1 = Number.NaN;
178
+ let k2 = Number.NaN;
179
+ let k3 = Number.NaN;
180
+ if (optics.contrastFirst) {
181
+ if (c > 0) {
182
+ k1 = -k / c;
183
+ k2 = (1 - k) / c;
184
+ if (b > 0)
185
+ k3 = (1 / b - k) / c;
186
+ }
187
+ }
188
+ else if (b > 0) {
189
+ k1 = 1 / b;
190
+ if (c > 0) {
191
+ k2 = -k / c / b;
192
+ k3 = (1 - k) / c / b;
193
+ }
194
+ }
195
+ let best = applyVeilOptics(optics, lo) - lo;
196
+ best = deviationAt(optics, hi, lo, hi, best, upper);
197
+ best = deviationAt(optics, k1, lo, hi, best, upper);
198
+ best = deviationAt(optics, k2, lo, hi, best, upper);
199
+ return deviationAt(optics, k3, lo, hi, best, upper);
200
+ }
201
+ function deviationAt(optics, x, lo, hi, best, upper) {
202
+ if (!(x >= lo && x <= hi))
203
+ return best;
204
+ const d = applyVeilOptics(optics, x) - x;
205
+ return upper ? Math.max(best, d) : Math.min(best, d);
206
+ }
207
+ /**
208
+ * Maps backdrop telemetry to `[0, 1]` risk per channel for the given goal and base veil.
209
+ * Telemetry describes the raw page, but the glass shows it after the host's `optics`, and the
210
+ * fallback correction runs after those optics too. The optics clip each channel, so a colored
211
+ * pixel's output luminance is not a function of its input luminance. It is bounded instead:
212
+ * - by the optics applied to its extreme channel, since luminance lies between min and max
213
+ * channel and the optics are monotonic;
214
+ * - by `L + D`, where `D` is the extreme of `f(x) - x` over its channel range. The dark tail is
215
+ * sRGB luma, a weighted mean of the channels, so this holds exactly; the bright tail is
216
+ * encoded luminance, a translated power mean, which by Minkowski's inequality moves no
217
+ * further than a shift applied to every channel.
218
+ * Both bounds are exact for neutral pixels and collapse to `L` under identity optics, so the
219
+ * estimate stays continuous as the host's optics change. Chroma and gradients scale by the
220
+ * affine slope.
221
+ *
222
+ * `saturation` is the host's `saturate()`, which runs first: `x' = luma + s * (x - luma)` per
223
+ * channel, then clipped. Desaturating never clips, keeps sRGB luma and (by Jensen) never raises
224
+ * encoded luminance, so only `s > 1` matters; there each clipped channel moves by at most
225
+ * `(s - 1)` times the channel spread, a bounded shift that widens the channel range and the
226
+ * luminance tails by the same amount. The legibility response only ever lowers saturation, so
227
+ * the host's value bounds the effective one.
228
+ */
229
+ export function computeBackdropRisk(telemetry, goal, veilRgba, out, optics = IDENTITY_VEIL_OPTICS, saturation = 1) {
230
+ const s = veilAffineScale(optics);
231
+ const ceiling = backdropCeiling(goal, veilRgba);
232
+ const rawHigh = clamp(telemetry.lumaHigh, 0, 1);
233
+ const rawLow = clamp(telemetry.lumaLow, 0, 1);
234
+ const rawChannelHigh = clamp(Math.max(telemetry.channelHigh ?? rawHigh, rawHigh), 0, 1);
235
+ const rawChannelLow = clamp(Math.min(telemetry.channelLow ?? rawLow, rawLow), 0, 1);
236
+ const shift = Math.max(0, saturation - 1) * (rawChannelHigh - rawChannelLow);
237
+ const high = rawHigh + shift;
238
+ const low = rawLow - shift;
239
+ const channelHigh = Math.min(1, rawChannelHigh + shift);
240
+ const channelLow = Math.max(0, rawChannelLow - shift);
241
+ const tail = goal.polarity === 'light'
242
+ ? Math.min(high + Math.max(0, opticsDeviation(optics, channelLow, channelHigh, true)), applyVeilOptics(optics, channelHigh))
243
+ : 1 -
244
+ Math.max(low + Math.min(0, opticsDeviation(optics, channelLow, channelHigh, false)), applyVeilOptics(optics, channelLow));
245
+ if (ceiling >= 1) {
246
+ out.luma = 0;
247
+ }
248
+ else {
249
+ const knee = Math.max(0, ceiling) * goal.policy.knee;
250
+ out.luma = clamp((tail - knee) / Math.max(1e-6, 1 - knee), 0, 1);
251
+ }
252
+ out.chroma = smoothstep(0.12, 0.45, s * telemetry.chroma);
253
+ out.detail = smoothstep(0.04, 0.22, s * telemetry.detail);
254
+ return out;
255
+ }
256
+ export function createLegibilityParams() {
257
+ const table = new Float32Array(LEGIBILITY_TABLE_SIZE);
258
+ table.fill(1);
259
+ return {
260
+ polarity: 'light',
261
+ table,
262
+ tableRevision: 0,
263
+ veilRgba: new Float32Array(4),
264
+ blurBoostPx: 0,
265
+ refractionScale: 1,
266
+ saturationScale: 1,
267
+ hairlineScale: 1,
268
+ shadowScale: 1,
269
+ fallbackVeil: { brightness: 1, contrast: 1, contrastFirst: false },
270
+ backdropLimit: 1,
271
+ feasible: true,
272
+ };
273
+ }
274
+ /**
275
+ * Soft-knee ceiling in risk space: identity below `knee`, then a rational shoulder whose slope is
276
+ * continuous at the knee and which lands exactly on `ceiling` at `u = 1`, so the guarantee holds
277
+ * for the brightest possible pixel without flattening mid-tones.
278
+ */
279
+ function softCeiling(u, knee, ceiling) {
280
+ if (u <= knee)
281
+ return u;
282
+ const s = (1 - knee) / (ceiling - knee);
283
+ const t = (u - knee) / (1 - knee);
284
+ return knee + (ceiling - knee) * ((s * t) / (1 + (s - 1) * t));
285
+ }
286
+ function multiplierAt(u, knee, ceiling) {
287
+ if (ceiling >= 1 || u <= knee)
288
+ return 1;
289
+ return ceiling > 0 ? softCeiling(u, knee, ceiling) / u : 0;
290
+ }
291
+ /**
292
+ * Solves the material response for the smoothed `risk` and writes it into `out`.
293
+ * Allocation-free; returns `true` when any output changed.
294
+ */
295
+ export function resolveLegibilityParams(goal, risk, baseVeilRgba, out) {
296
+ const policy = goal.policy;
297
+ const light = goal.polarity === 'light';
298
+ let changed = out.polarity !== goal.polarity;
299
+ out.polarity = goal.polarity;
300
+ // The film reuses the host tint's hue pushed toward the safe extreme; mixing toward a neutral
301
+ // mid-gray is what makes compressed glass read as dirty.
302
+ const filmAlpha = policy.filmMax * Math.max(risk.luma, 0.6 * risk.detail);
303
+ const baseA = clamp(baseVeilRgba[3] ?? 0, 0, 1);
304
+ const alpha = filmAlpha + baseA * (1 - filmAlpha);
305
+ const veil = out.veilRgba;
306
+ for (let i = 0; i < 3; i++) {
307
+ const tint = clamp(baseVeilRgba[i] ?? 0, 0, 1);
308
+ const film = light ? tint * 0.15 : 1 - (1 - tint) * 0.15;
309
+ const v = alpha > 0 ? (filmAlpha * film + baseA * (1 - filmAlpha) * tint) / alpha : tint;
310
+ changed ||= Math.abs(veil[i] - v) > 1e-4;
311
+ veil[i] = v;
312
+ }
313
+ changed ||= Math.abs(veil[3] - alpha) > 1e-4;
314
+ veil[3] = alpha;
315
+ const rawCeiling = backdropCeiling(goal, veil);
316
+ out.feasible = rawCeiling > 0;
317
+ const ceiling = clamp(rawCeiling, 0, 1);
318
+ out.backdropLimit = light ? ceiling : 1 - ceiling;
319
+ const knee = ceiling * lerp(LEGIBILITY_CALM_KNEE, policy.knee, risk.luma);
320
+ // The table is only republished when some entry moves by half an 8-bit step, so a slowly
321
+ // releasing smoother does not rewrite filter attributes every frame.
322
+ const table = out.table;
323
+ const last = table.length - 1;
324
+ let tableChanged = false;
325
+ for (let i = 0; i <= last && !tableChanged; i++) {
326
+ const u = light ? i / last : 1 - i / last;
327
+ tableChanged = Math.abs(table[i] - multiplierAt(u, knee, ceiling)) > 0.5 / 255;
328
+ }
329
+ if (tableChanged) {
330
+ for (let i = 0; i <= last; i++) {
331
+ table[i] = multiplierAt(light ? i / last : 1 - i / last, knee, ceiling);
332
+ }
333
+ out.tableRevision += 1;
334
+ changed = true;
335
+ }
336
+ // Paths without a per-pixel filter can only scale the whole backdrop. The tail estimate
337
+ // inverts `computeBackdropRisk`, so the affine follows the same smoothed signal.
338
+ const baseCeiling = backdropCeiling(goal, baseVeilRgba);
339
+ const baseKnee = clamp(baseCeiling, 0, 1) * policy.knee;
340
+ const tail = baseKnee + risk.luma * (1 - baseKnee);
341
+ const scale = ceiling >= 1 || tail <= ceiling ? 1 : ceiling / tail;
342
+ // Light text: x -> scale * x. Dark text: x -> scale * x + 1 - scale, written contrast-first as
343
+ // b * (c * x + 0.5 * (1 - c)) with b = 2 - scale; the contrast step stays inside [0, 1] and
344
+ // b times its maximum is exactly 1, so neither stage clamps.
345
+ const fallback = out.fallbackVeil;
346
+ const brightness = light ? scale : 2 - scale;
347
+ const contrast = light ? 1 : scale / brightness;
348
+ if (fallback.contrastFirst === light ||
349
+ Math.abs(fallback.brightness - brightness) > 1e-4 ||
350
+ Math.abs(fallback.contrast - contrast) > 1e-4) {
351
+ fallback.brightness = brightness;
352
+ fallback.contrast = contrast;
353
+ fallback.contrastFirst = !light;
354
+ changed = true;
355
+ }
356
+ changed = assign(out, 'blurBoostPx', policy.blurBoostPx * risk.detail) || changed;
357
+ changed = assign(out, 'refractionScale', lerp(1, policy.refractionFloor, risk.detail)) || changed;
358
+ changed = assign(out, 'saturationScale', lerp(1, policy.saturationFloor, risk.chroma)) || changed;
359
+ changed =
360
+ assign(out, 'hairlineScale', 1 + policy.edgeGain * Math.max(risk.luma, risk.detail)) || changed;
361
+ changed = assign(out, 'shadowScale', 1 + policy.shadowGain * risk.luma) || changed;
362
+ return changed;
363
+ }
364
+ function assign(out, key, value) {
365
+ if (Math.abs(out[key] - value) <= 1e-4)
366
+ return false;
367
+ out[key] = value;
368
+ return true;
369
+ }
370
+ export function createTelemetryAccumulator() {
371
+ let weight = 0;
372
+ let high = 0;
373
+ let low = 0;
374
+ let channelHigh = 0;
375
+ let channelLow = 0;
376
+ let chroma = 0;
377
+ let detail = 0;
378
+ const push = (h, l, ch, cl, c, d, w) => {
379
+ if (!(w > 0))
380
+ return;
381
+ const hh = clamp(h, 0, 1);
382
+ const ll = 1 - clamp(l, 0, 1);
383
+ // Luminance lies between a pixel's extreme channels; inconsistent input falls back to neutral.
384
+ const chh = Math.max(hh, clamp(ch, 0, 1));
385
+ const cll = Math.max(ll, 1 - clamp(cl, 0, 1));
386
+ weight += w;
387
+ high += w * hh * hh;
388
+ low += w * ll * ll;
389
+ channelHigh += w * chh * chh;
390
+ channelLow += w * cll * cll;
391
+ chroma += w * clamp(c, 0, 1);
392
+ detail += w * clamp(d, 0, 1);
393
+ };
394
+ return {
395
+ get weight() {
396
+ return weight;
397
+ },
398
+ reset() {
399
+ weight = high = low = channelHigh = channelLow = chroma = detail = 0;
400
+ },
401
+ add(t, w) {
402
+ push(t.lumaHigh, t.lumaLow, t.channelHigh ?? t.lumaHigh, t.channelLow ?? t.lumaLow, t.chroma, t.detail, w);
403
+ },
404
+ addRecord(data, offset, w) {
405
+ push(data[offset], data[offset + 1], data[offset + 2], data[offset + 3], data[offset + 4], data[offset + 5], w);
406
+ },
407
+ resolve(out) {
408
+ if (!(weight > 0))
409
+ return false;
410
+ out.lumaHigh = Math.sqrt(high / weight);
411
+ out.lumaLow = 1 - Math.sqrt(low / weight);
412
+ out.channelHigh = Math.sqrt(channelHigh / weight);
413
+ out.channelLow = 1 - Math.sqrt(channelLow / weight);
414
+ out.chroma = chroma / weight;
415
+ out.detail = detail / weight;
416
+ return true;
417
+ },
418
+ };
419
+ }
420
+ const HISTOGRAM_BINS = 64;
421
+ /**
422
+ * Measures a `cols x rows` telemetry grid from straight (non-premultiplied) RGBA bytes.
423
+ * Runs once per source image, never per frame; callers obtain pixels through normal
424
+ * same-origin or CORS-approved channels only.
425
+ */
426
+ export function measureTelemetryGrid(rgba, width, height, cols, rows) {
427
+ const w = Math.max(1, Math.floor(width));
428
+ const h = Math.max(1, Math.floor(height));
429
+ const gc = Math.max(1, Math.floor(cols));
430
+ const gr = Math.max(1, Math.floor(rows));
431
+ const data = new Float32Array(gc * gr * TELEMETRY_STRIDE);
432
+ const lum = new Float32Array(w * h);
433
+ const luma = new Float32Array(w * h);
434
+ const maxPx = new Float32Array(w * h);
435
+ const minPx = new Float32Array(w * h);
436
+ for (let i = 0; i < w * h; i++) {
437
+ const r = (rgba[i * 4] ?? 0) / 255;
438
+ const g = (rgba[i * 4 + 1] ?? 0) / 255;
439
+ const b = (rgba[i * 4 + 2] ?? 0) / 255;
440
+ lum[i] = linearToSrgb(relativeLuminance(r, g, b));
441
+ luma[i] = srgbLuma(r, g, b);
442
+ maxPx[i] = Math.max(r, g, b);
443
+ minPx[i] = Math.min(r, g, b);
444
+ }
445
+ const hist = new Uint32Array(HISTOGRAM_BINS);
446
+ const lumaHist = new Uint32Array(HISTOGRAM_BINS);
447
+ const maxHist = new Uint32Array(HISTOGRAM_BINS);
448
+ const minHist = new Uint32Array(HISTOGRAM_BINS);
449
+ for (let cy = 0; cy < gr; cy++) {
450
+ const y0 = Math.floor((cy * h) / gr);
451
+ const y1 = Math.max(y0 + 1, Math.floor(((cy + 1) * h) / gr));
452
+ for (let cx = 0; cx < gc; cx++) {
453
+ const x0 = Math.floor((cx * w) / gc);
454
+ const x1 = Math.max(x0 + 1, Math.floor(((cx + 1) * w) / gc));
455
+ hist.fill(0);
456
+ lumaHist.fill(0);
457
+ maxHist.fill(0);
458
+ minHist.fill(0);
459
+ let count = 0;
460
+ let chroma = 0;
461
+ let gradient = 0;
462
+ for (let y = y0; y < y1; y++) {
463
+ for (let x = x0; x < x1; x++) {
464
+ const i = y * w + x;
465
+ const l = lum[i];
466
+ hist[histogramBin(l)] += 1;
467
+ lumaHist[histogramBin(luma[i])] += 1;
468
+ maxHist[histogramBin(maxPx[i])] += 1;
469
+ minHist[histogramBin(minPx[i])] += 1;
470
+ chroma += maxPx[i] - minPx[i];
471
+ // Gradients stay inside the cell so a card edge on a cell border is not counted as detail.
472
+ const right = x + 1 < x1 ? lum[i + 1] : l;
473
+ const down = y + 1 < y1 ? lum[i + w] : l;
474
+ gradient += Math.abs(right - l) + Math.abs(down - l);
475
+ count += 1;
476
+ }
477
+ }
478
+ const o = (cy * gc + cx) * TELEMETRY_STRIDE;
479
+ data[o] = percentileFromHistogram(hist, count, 0.95);
480
+ data[o + 1] = percentileFromHistogram(lumaHist, count, 0.05);
481
+ // Bin bounds rather than centers keep the channel extremes conservative after quantization.
482
+ data[o + 2] = Math.max(data[o], percentileFromHistogram(maxHist, count, 0.95, 1));
483
+ data[o + 3] = Math.min(data[o + 1], percentileFromHistogram(minHist, count, 0.05, 0));
484
+ data[o + 4] = chroma / count;
485
+ data[o + 5] = Math.min(1, (gradient / count) * 4);
486
+ }
487
+ }
488
+ return { cols: gc, rows: gr, data };
489
+ }
490
+ function histogramBin(v) {
491
+ return Math.min(HISTOGRAM_BINS - 1, Math.max(0, Math.floor(v * HISTOGRAM_BINS)));
492
+ }
493
+ /** `edge` places the result inside the matching bin: `0.5` its center, `0` / `1` its bounds. */
494
+ function percentileFromHistogram(hist, count, q, edge = 0.5) {
495
+ const target = q * count;
496
+ let acc = 0;
497
+ for (let i = 0; i < hist.length; i++) {
498
+ acc += hist[i];
499
+ if (acc >= target)
500
+ return (i + edge) / hist.length;
501
+ }
502
+ return 1;
503
+ }
504
+ export function createAsymmetricSmoother(channels, options) {
505
+ const values = new Float32Array(channels);
506
+ const holdLeft = new Float32Array(channels);
507
+ const holdMs = Math.max(0, options.holdMs ?? 0);
508
+ const attackMs = Math.max(1e-3, options.attackMs);
509
+ const releaseMs = Math.max(1e-3, options.releaseMs);
510
+ const epsilon = Math.max(0, options.epsilon ?? 1e-3);
511
+ holdLeft.fill(holdMs);
512
+ return {
513
+ values,
514
+ step(target, dtMs) {
515
+ const dt = Number.isFinite(dtMs) && dtMs > 0 ? dtMs : 0;
516
+ let settled = true;
517
+ for (let i = 0; i < channels; i++) {
518
+ const goal = target[i] ?? 0;
519
+ let v = values[i];
520
+ if (goal >= v - epsilon) {
521
+ holdLeft[i] = holdMs;
522
+ if (goal > v)
523
+ v += (goal - v) * (1 - Math.exp(-dt / attackMs));
524
+ }
525
+ else {
526
+ const releaseDt = Math.max(0, dt - holdLeft[i]);
527
+ holdLeft[i] = Math.max(0, holdLeft[i] - dt);
528
+ v += (goal - v) * (1 - Math.exp(-releaseDt / releaseMs));
529
+ }
530
+ if (Math.abs(goal - v) <= epsilon) {
531
+ v = goal;
532
+ }
533
+ else {
534
+ settled = false;
535
+ }
536
+ values[i] = v;
537
+ }
538
+ return settled;
539
+ },
540
+ reset(next) {
541
+ for (let i = 0; i < channels; i++) {
542
+ values[i] = typeof next === 'number' ? next : (next[i] ?? 0);
543
+ }
544
+ holdLeft.fill(holdMs);
545
+ },
546
+ };
547
+ }
package/dist/optics.d.ts CHANGED
@@ -70,6 +70,12 @@ export declare function buildColorOpticsMatrix(saturate: number, brightness: num
70
70
  export declare function buildContourAlphaDataUrl(contourPath: string, width: number, height: number): string;
71
71
  /** Parses a browser-computed `rgb(...)`, `rgba(...)`, or `color(srgb ...)` string into normalized `[0..1]` RGBA. */
72
72
  export declare function parseCssRgba(color: string): [number, number, number, number];
73
+ /**
74
+ * Like `parseCssRgba`, but returns `null` instead of transparent black for anything it cannot
75
+ * resolve (`var()`, percentage `color(srgb ...)` channels, other color spaces), so callers can
76
+ * tell a real transparent color from an unsupported one.
77
+ */
78
+ export declare function tryParseCssRgba(color: string): [number, number, number, number] | null;
73
79
  /** Extracts `brightness(...)` and `contrast(...)` affine composition from a CSS filter string. */
74
80
  export declare function parseCssFilterOptics(filterStr: string): BackdropVeilOptics;
75
81
  /** Linearly interpolates two backdrop veil optics states in 1D affine `(scale, offset)` space. */
package/dist/optics.js CHANGED
@@ -106,6 +106,14 @@ export function buildContourAlphaDataUrl(contourPath, width, height) {
106
106
  }
107
107
  /** Parses a browser-computed `rgb(...)`, `rgba(...)`, or `color(srgb ...)` string into normalized `[0..1]` RGBA. */
108
108
  export function parseCssRgba(color) {
109
+ return tryParseCssRgba(color) ?? [0, 0, 0, 0];
110
+ }
111
+ /**
112
+ * Like `parseCssRgba`, but returns `null` instead of transparent black for anything it cannot
113
+ * resolve (`var()`, percentage `color(srgb ...)` channels, other color spaces), so callers can
114
+ * tell a real transparent color from an unsupported one.
115
+ */
116
+ export function tryParseCssRgba(color) {
109
117
  const trimmed = color.trim().toLowerCase();
110
118
  if (!trimmed || trimmed === 'none' || trimmed === 'transparent') {
111
119
  return [0, 0, 0, 0];
@@ -140,7 +148,7 @@ export function parseCssRgba(color) {
140
148
  }
141
149
  }
142
150
  }
143
- return [0, 0, 0, 0];
151
+ return null;
144
152
  }
145
153
  const VEIL_SINGULAR_EPS = 1e-6;
146
154
  function veilOpticsToAffine(veil) {
@@ -478,6 +486,19 @@ export function interpolateOpticalMaterial(from, to, t) {
478
486
  if (from.rimBottomRatio !== undefined || to.rimBottomRatio !== undefined) {
479
487
  result.rimBottomRatio = lerp(from.rimBottomRatio ?? 0.72, to.rimBottomRatio ?? 0.72, u);
480
488
  }
489
+ if (from.bevelProfile !== undefined || to.bevelProfile !== undefined) {
490
+ result.bevelProfile =
491
+ u < 0.5 ? (from.bevelProfile ?? to.bevelProfile) : (to.bevelProfile ?? from.bevelProfile);
492
+ }
493
+ if (from.lightAngle !== undefined || to.lightAngle !== undefined) {
494
+ result.lightAngle = lerp(from.lightAngle ?? -45, to.lightAngle ?? -45, u);
495
+ }
496
+ if (from.lightElevation !== undefined || to.lightElevation !== undefined) {
497
+ result.lightElevation = lerp(from.lightElevation ?? 22, to.lightElevation ?? 22, u);
498
+ }
499
+ if (from.rimShade !== undefined || to.rimShade !== undefined) {
500
+ result.rimShade = lerp(from.rimShade ?? 0.32, to.rimShade ?? 0.32, u);
501
+ }
481
502
  return result;
482
503
  }
483
504
  /** Convenience resolver interpolating between `DEFAULT_OPTICAL_MATERIALS[theme].crisp` and `.frosted` by `styleMix`. */
@@ -15,7 +15,7 @@
15
15
  */
16
16
  import type { IGlassOverlayRenderer } from './contracts.ts';
17
17
  export declare const OVERLAY_VERTEX_SHADER = "#version 300 es\nprecision highp float;\n\nout vec2 vUv;\n\nvoid main() {\n vec2 pos = vec2(\n (gl_VertexID == 1) ? 3.0 : -1.0,\n (gl_VertexID == 2) ? 3.0 : -1.0\n );\n vUv = pos * 0.5 + 0.5;\n gl_Position = vec4(pos, 0.0, 1.0);\n}\n";
18
- export declare const OVERLAY_FRAGMENT_SHADER = "#version 300 es\nprecision highp float;\n\n#define MAX_PRIMITIVES 16\n\nin vec2 vUv;\nout vec4 fragColor;\n\nuniform vec2 uViewport;\nuniform float uDpr;\nuniform int uPrimitiveCount;\nuniform vec4 uPrimitives[MAX_PRIMITIVES]; // (cx, cy, halfW, halfH) in local CSS px\nuniform float uRadii[MAX_PRIMITIVES];\nuniform float uBlendK;\nuniform float uRimOpacity;\nuniform float uStyleMix;\nuniform float uOpacity;\n\nuniform vec4 uRimParams; // (material.rimOpacity, material.rimWidth, material.rimTail, material.rimFocus)\nuniform vec4 uHairline; // (width, sideAlpha, cornerAlpha, flatAlpha)\nuniform vec3 uShadow; // (blur, offsetY, alpha)\nuniform vec4 uBorderColor; // normalized RGBA of optional uniform inner border\nuniform vec2 uBorderParams; // (borderWidthPx, rimBottomRatio)\n\nstruct SdfSample {\n float dist;\n vec2 normal;\n};\n\nfloat safePow(float x, float y) {\n return (x <= 1e-6) ? 0.0 : pow(x, y);\n}\n\nfloat computeDirectionalRimWeight(vec2 normal, float focus, float bottomRatio) {\n if (focus < 0.05) {\n return 1.0;\n }\n float topBias = clamp(-normal.y, 0.0, 1.0);\n float botBias = clamp(normal.y, 0.0, 1.0);\n return safePow(max(topBias, botBias * clamp(bottomRatio, 0.0, 1.0)), max(focus, 0.25));\n}\n\nSdfSample sdRoundedBoxRefined(vec2 p, vec2 center, vec2 halfSize, float r) {\n vec2 safeHalf = max(halfSize, vec2(0.001));\n float rad = clamp(r, 0.0, min(safeHalf.x, safeHalf.y));\n vec2 rel = p - center;\n vec2 s = vec2(rel.x >= 0.0 ? 1.0 : -1.0, rel.y >= 0.0 ? 1.0 : -1.0);\n vec2 q = abs(rel) - safeHalf + rad;\n vec2 qPos = max(q, 0.0);\n\n float outside = length(qPos);\n float inside = min(max(q.x, q.y), 0.0);\n float baseDist = outside + inside - rad;\n\n vec2 baseNormal;\n if (q.x > 0.0 && q.y > 0.0) {\n baseNormal = (outside > 1e-5) ? (qPos / outside) * s : normalize(s);\n } else if (q.x > q.y) {\n baseNormal = vec2(s.x, 0.0);\n } else {\n baseNormal = vec2(0.0, s.y);\n }\n\n // Superellipse octant normal refinement within 5 CSS px of the boundary for smooth corner speculars;\n // dist stays exact baseDist for 0px alignment with the Marching Squares contour.\n float rimProximity = smoothstep(5.0, 0.0, abs(baseDist));\n vec2 normal = baseNormal;\n\n if (rimProximity > 0.001 && rad > 1.0 && q.x > 0.0 && q.y > 0.0) {\n const float pExp = 2.55;\n vec2 qn = qPos / rad;\n vec2 grad = vec2(\n safePow(qn.x, pExp - 1.0),\n safePow(qn.y, pExp - 1.0)\n );\n float gl = length(grad);\n if (gl > 1e-5) {\n vec2 superNormal = (grad / gl) * s;\n vec2 mixedN = mix(baseNormal, superNormal, rimProximity);\n float mnl = length(mixedN);\n normal = (mnl > 1e-5) ? (mixedN / mnl) : baseNormal;\n }\n }\n\n return SdfSample(baseDist, normal);\n}\n\nSdfSample evaluateGlassSdf(vec2 p) {\n if (uPrimitiveCount <= 0) {\n return SdfSample(1e6, vec2(0.0, -1.0));\n }\n\n SdfSample acc = sdRoundedBoxRefined(p, uPrimitives[0].xy, uPrimitives[0].zw, uRadii[0]);\n for (int i = 1; i < MAX_PRIMITIVES; i++) {\n if (i >= uPrimitiveCount) break;\n SdfSample b = sdRoundedBoxRefined(p, uPrimitives[i].xy, uPrimitives[i].zw, uRadii[i]);\n if (uBlendK <= 0.001) {\n if (b.dist < acc.dist) {\n acc = b;\n }\n } else {\n float h = clamp(0.5 + 0.5 * (b.dist - acc.dist) / uBlendK, 0.0, 1.0);\n float d = mix(b.dist, acc.dist, h) - uBlendK * h * (1.0 - h);\n vec2 n = mix(b.normal, acc.normal, h);\n float nl = length(n);\n n = (nl > 1e-5) ? (n / nl) : acc.normal;\n acc = SdfSample(d, n);\n }\n }\n\n return acc;\n}\n\nvoid main() {\n if (uOpacity <= 0.001 || uPrimitiveCount <= 0) {\n fragColor = vec4(0.0);\n return;\n }\n\n // Convert GL UV (bottom-left origin) to local CSS px (top-left origin).\n vec2 pCss = vec2(vUv.x * uViewport.x, (1.0 - vUv.y) * uViewport.y);\n SdfSample sdf = evaluateGlassSdf(pCss);\n float d = sdf.dist;\n vec2 normal = sdf.normal;\n\n float aa = 1.0 / max(uDpr, 1.0);\n float glassMask = smoothstep(0.5 * aa, -0.5 * aa, d);\n float outsideMask = 1.0 - glassMask;\n\n // 1. Outside-only drop shadow (d > 0)\n float shadowA = 0.0;\n if (outsideMask > 0.001 && uShadow.z > 0.001) {\n SdfSample shadowSdf = evaluateGlassSdf(pCss - vec2(0.0, uShadow.y));\n float sigma = max(uShadow.x * 0.5, 1.0);\n float shadowFalloff = 1.0 / (1.0 + exp(clamp(1.65 * shadowSdf.dist / sigma, -12.0, 12.0)));\n shadowA = outsideMask * shadowFalloff * uShadow.z * uOpacity;\n }\n\n // 2. Dark outer hairline: strictly outside when a uniform CSS inner border is present (d >= 0), otherwise straddling the outer edge (d >= -0.25)\n float hw = max(uHairline.x, 0.5 / max(uDpr, 1.0));\n float hairlineHalfW = hw * 0.5;\n float hasUniformBorder = step(0.001, uBorderParams.x);\n float hairlineCenter = mix(-0.25 + hairlineHalfW, hairlineHalfW, hasUniformBorder);\n float hairlineMinD = mix(-0.25 - 0.5 * aa, -0.15 * aa, hasUniformBorder);\n float hairlineBand =\n smoothstep(hairlineHalfW + 0.5 * aa, hairlineHalfW * 0.25, abs(d - hairlineCenter)) *\n smoothstep(hairlineMinD, hairlineMinD + 0.75 * aa, d);\n float hairA = 0.0;\n if (hairlineBand > 0.001) {\n float ax = abs(normal.x);\n float ay = abs(normal.y);\n float cornerW = safePow(clamp(2.0 * ax * ay, 0.0, 1.0), 1.5);\n float sideVsFlat = mix(uHairline.y, uHairline.w, ay * ay);\n float hairlineProfileAlpha = mix(sideVsFlat, uHairline.z, cornerW);\n hairA = hairlineBand * hairlineProfileAlpha * uOpacity;\n }\n\n // 3. Optional 1px uniform inner border + directional/soft inner rim highlight (inset < 5.0 CSS px)\n float inset = max(-d, 0.0);\n float borderMask = 0.0;\n float borderA = 0.0;\n vec3 borderRgb = vec3(0.0);\n if (glassMask > 0.001 && hasUniformBorder > 0.5 && inset < uBorderParams.x + aa) {\n borderMask = smoothstep(uBorderParams.x + 0.5 * aa, max(0.0, uBorderParams.x - 0.5 * aa), inset) * glassMask;\n borderA = clamp(borderMask * uBorderColor.a * uOpacity, 0.0, 1.0);\n borderRgb = uBorderColor.rgb * borderA;\n }\n\n float rimA = 0.0;\n if (glassMask > 0.001 && inset < 5.0 && uRimParams.x > 0.001) {\n float ny = abs(normal.y);\n float wDirectional = 1.0 - clamp(uStyleMix, 0.0, 1.0);\n float wSoft = clamp(uStyleMix, 0.0, 1.0) * clamp(uRimOpacity, 0.0, 1.0);\n\n if (hasUniformBorder > 0.5) {\n // Match CSS inset box-shadow: keep inner rim inside the padding edge so the 1px border is not double-brightened\n float padInset = max(inset - uBorderParams.x, 0.0);\n float padMask = 1.0 - borderMask;\n float dirWeight = computeDirectionalRimWeight(normal, uRimParams.w, uBorderParams.y);\n float core = smoothstep(max(uRimParams.y, 0.4) + 0.6, 0.0, padInset);\n float tail = exp(-padInset / 1.8) * uRimParams.z * smoothstep(5.0, 3.2, inset);\n rimA = clamp((core + tail) * dirWeight * uRimParams.x * padMask * glassMask * uOpacity, 0.0, 1.0);\n } else {\n if (wDirectional > 0.001) {\n float dirWeight = computeDirectionalRimWeight(normal, uRimParams.w, uBorderParams.y);\n float core = smoothstep(max(uRimParams.y, 0.4) + 0.6, 0.0, inset);\n float tail = exp(-inset / 1.8) * uRimParams.z * smoothstep(5.0, 3.2, inset);\n rimA += (core + tail) * dirWeight * uRimParams.x * wDirectional;\n }\n\n if (wSoft > 0.001) {\n float bandT = clamp(inset / 5.0, 0.0, 1.0);\n float steppedT = min(floor(bandT * 9.0) / 9.0, 1.0);\n float bandCurve = mix(safePow(1.0 - bandT, 2.1), safePow(1.0 - steppedT, 2.1), 0.35);\n float rimCoreBoost = 0.65 + 0.35 * smoothstep(1.2, 0.0, inset);\n float angWeight = mix(0.015, 1.0, safePow(ny, 2.1)) * (normal.y < 0.0 ? 1.0 : 0.85);\n rimA += bandCurve * rimCoreBoost * angWeight * uRimParams.x * wSoft;\n }\n\n // Boost specular luminance to match source-over alpha blending expectations\n rimA = clamp(rimA * 1.35 * glassMask * uOpacity, 0.0, 1.0);\n }\n }\n\n // Keep interior strictly transparent when shadow, hairline, border, and rim are all zero\n if (shadowA <= 0.0001 && hairA <= 0.0001 && borderA <= 0.0001 && rimA <= 0.0001) {\n fragColor = vec4(0.0);\n return;\n }\n\n // Premultiplied alpha composite: uniform border over inner rim over hairline and shadow\n float darkA = clamp(shadowA + hairA * (1.0 - shadowA), 0.0, 1.0);\n vec3 afterRimRgb = vec3(rimA);\n float afterRimA = rimA + darkA * (1.0 - rimA);\n vec3 outRgb = borderRgb + afterRimRgb * (1.0 - borderA);\n float outA = clamp(borderA + afterRimA * (1.0 - borderA), 0.0, 1.0);\n fragColor = vec4(outRgb, outA);\n}\n";
18
+ export declare const OVERLAY_FRAGMENT_SHADER = "#version 300 es\nprecision highp float;\n\n#define MAX_PRIMITIVES 16\n\nin vec2 vUv;\nout vec4 fragColor;\n\nuniform vec2 uViewport;\nuniform float uDpr;\nuniform int uPrimitiveCount;\nuniform vec4 uPrimitives[MAX_PRIMITIVES]; // (cx, cy, halfW, halfH) in local CSS px\nuniform float uRadii[MAX_PRIMITIVES];\nuniform float uBlendK;\nuniform float uRimOpacity;\nuniform float uStyleMix;\nuniform float uOpacity;\n\nuniform vec4 uRimParams; // (material.rimOpacity, material.rimWidth, material.rimTail, material.rimFocus)\nuniform vec4 uHairline; // (width, sideAlpha, cornerAlpha, flatAlpha)\nuniform vec3 uShadow; // (blur, offsetY, alpha)\nuniform vec4 uBorderColor; // normalized RGBA of optional uniform inner border\nuniform vec2 uBorderParams; // (borderWidthPx, rimBottomRatio)\nuniform vec4 uPhysicalLight; // (lx, ly, lz, enabled)\nuniform vec4 uPhysicalParams; // (bevelPx, specularStrength, shadeStrength, profileCode)\n\nstruct SdfSample {\n float dist;\n vec2 normal;\n};\n\nfloat safePow(float x, float y) {\n return (x <= 1e-6) ? 0.0 : pow(x, y);\n}\n\nfloat computeDirectionalRimWeight(vec2 normal, float focus, float bottomRatio) {\n if (focus < 0.05) {\n return 1.0;\n }\n float topBias = clamp(-normal.y, 0.0, 1.0);\n float botBias = clamp(normal.y, 0.0, 1.0);\n return safePow(max(topBias, botBias * clamp(bottomRatio, 0.0, 1.0)), max(focus, 0.25));\n}\n\nSdfSample sdRoundedBoxRefined(vec2 p, vec2 center, vec2 halfSize, float r) {\n vec2 safeHalf = max(halfSize, vec2(0.001));\n float rad = clamp(r, 0.0, min(safeHalf.x, safeHalf.y));\n vec2 rel = p - center;\n vec2 s = vec2(rel.x >= 0.0 ? 1.0 : -1.0, rel.y >= 0.0 ? 1.0 : -1.0);\n vec2 q = abs(rel) - safeHalf + rad;\n vec2 qPos = max(q, 0.0);\n\n float outside = length(qPos);\n float inside = min(max(q.x, q.y), 0.0);\n float baseDist = outside + inside - rad;\n\n vec2 baseNormal;\n if (q.x > 0.0 && q.y > 0.0) {\n baseNormal = (outside > 1e-5) ? (qPos / outside) * s : normalize(s);\n } else if (q.x > q.y) {\n baseNormal = vec2(s.x, 0.0);\n } else {\n baseNormal = vec2(0.0, s.y);\n }\n\n // Superellipse octant normal refinement within 5 CSS px of the boundary for smooth corner speculars;\n // dist stays exact baseDist for 0px alignment with the Marching Squares contour.\n float rimProximity = smoothstep(5.0, 0.0, abs(baseDist));\n vec2 normal = baseNormal;\n\n if (rimProximity > 0.001 && rad > 1.0 && q.x > 0.0 && q.y > 0.0) {\n const float pExp = 2.55;\n vec2 qn = qPos / rad;\n vec2 grad = vec2(\n safePow(qn.x, pExp - 1.0),\n safePow(qn.y, pExp - 1.0)\n );\n float gl = length(grad);\n if (gl > 1e-5) {\n vec2 superNormal = (grad / gl) * s;\n vec2 mixedN = mix(baseNormal, superNormal, rimProximity);\n float mnl = length(mixedN);\n normal = (mnl > 1e-5) ? (mixedN / mnl) : baseNormal;\n }\n }\n\n return SdfSample(baseDist, normal);\n}\n\nfloat evalBezelHeight(float t, float code) {\n float u = clamp(1.0 - t, 0.0, 1.0);\n if (code > 2.5) {\n float sq = safePow(max(0.0, 1.0 - safePow(u, 4.0)), 0.25);\n float s = sin(3.14159265 * clamp(t, 0.0, 1.0));\n return sq + 0.14 * s * s;\n }\n if (code > 1.5) {\n return 1.0 - u * u;\n }\n if (code > 0.5) {\n return sqrt(max(0.0, 1.0 - u * u));\n }\n return safePow(max(0.0, 1.0 - safePow(u, 4.0)), 0.25);\n}\n\nSdfSample evaluateGlassSdf(vec2 p) {\n if (uPrimitiveCount <= 0) {\n return SdfSample(1e6, vec2(0.0, -1.0));\n }\n\n SdfSample acc = sdRoundedBoxRefined(p, uPrimitives[0].xy, uPrimitives[0].zw, uRadii[0]);\n float d = acc.dist;\n vec2 g = acc.normal;\n for (int i = 1; i < MAX_PRIMITIVES; i++) {\n if (i >= uPrimitiveCount) break;\n SdfSample b = sdRoundedBoxRefined(p, uPrimitives[i].xy, uPrimitives[i].zw, uRadii[i]);\n if (uBlendK <= 0.001) {\n if (b.dist < d) {\n d = b.dist;\n g = b.normal;\n }\n } else {\n float h = clamp(0.5 + 0.5 * (b.dist - d) / uBlendK, 0.0, 1.0);\n d = mix(b.dist, d, h) - uBlendK * h * (1.0 - h);\n g = mix(b.normal, g, h);\n }\n }\n\n // Soften cancelling normals in smin saddle necks (NORMAL_FLOOR = 0.25) so speculars never flip 180 degrees.\n float gl = max(length(g), 0.25);\n return SdfSample(d, g / gl);\n}\n\nvoid main() {\n if (uOpacity <= 0.001 || uPrimitiveCount <= 0) {\n fragColor = vec4(0.0);\n return;\n }\n\n // Convert GL UV (bottom-left origin) to local CSS px (top-left origin).\n vec2 pCss = vec2(vUv.x * uViewport.x, (1.0 - vUv.y) * uViewport.y);\n SdfSample sdf = evaluateGlassSdf(pCss);\n float d = sdf.dist;\n vec2 normal = sdf.normal;\n\n float aa = 1.0 / max(uDpr, 1.0);\n float glassMask = smoothstep(0.5 * aa, -0.5 * aa, d);\n float outsideMask = 1.0 - glassMask;\n\n // 1. Outside-only drop shadow (d > 0)\n float shadowA = 0.0;\n if (outsideMask > 0.001 && uShadow.z > 0.001) {\n SdfSample shadowSdf = evaluateGlassSdf(pCss - vec2(0.0, uShadow.y));\n float sigma = max(uShadow.x * 0.5, 1.0);\n float shadowFalloff = 1.0 / (1.0 + exp(clamp(1.65 * shadowSdf.dist / sigma, -12.0, 12.0)));\n shadowA = outsideMask * shadowFalloff * uShadow.z * uOpacity;\n }\n\n // 2. Dark outer hairline: strictly outside when a uniform CSS inner border is present (d >= 0), otherwise straddling the outer edge (d >= -0.25)\n float hw = max(uHairline.x, 0.5 / max(uDpr, 1.0));\n float hairlineHalfW = hw * 0.5;\n float hasUniformBorder = step(0.001, uBorderParams.x);\n float hairlineCenter = mix(-0.25 + hairlineHalfW, hairlineHalfW, hasUniformBorder);\n float hairlineMinD = mix(-0.25 - 0.5 * aa, -0.15 * aa, hasUniformBorder);\n float hairlineBand =\n smoothstep(hairlineHalfW + 0.5 * aa, hairlineHalfW * 0.25, abs(d - hairlineCenter)) *\n smoothstep(hairlineMinD, hairlineMinD + 0.75 * aa, d);\n float hairA = 0.0;\n if (hairlineBand > 0.001) {\n float ax = abs(normal.x);\n float ay = abs(normal.y);\n float cornerW = safePow(clamp(2.0 * ax * ay, 0.0, 1.0), 1.5);\n float sideVsFlat = mix(uHairline.y, uHairline.w, ay * ay);\n float hairlineProfileAlpha = mix(sideVsFlat, uHairline.z, cornerW);\n hairA = hairlineBand * hairlineProfileAlpha * uOpacity;\n }\n\n // 3. Optional 1px uniform inner border + directional/soft inner rim highlight (inset < 5.0 CSS px)\n float inset = max(-d, 0.0);\n float borderMask = 0.0;\n float borderA = 0.0;\n vec3 borderRgb = vec3(0.0);\n if (glassMask > 0.001 && hasUniformBorder > 0.5 && inset < uBorderParams.x + aa) {\n borderMask = smoothstep(uBorderParams.x + 0.5 * aa, max(0.0, uBorderParams.x - 0.5 * aa), inset) * glassMask;\n borderA = clamp(borderMask * uBorderColor.a * uOpacity, 0.0, 1.0);\n borderRgb = uBorderColor.rgb * borderA;\n }\n\n float rimA = 0.0;\n float physLitA = 0.0;\n float physShadeA = 0.0;\n float isPhysicalRim = step(0.5, uPhysicalLight.w) * (1.0 - hasUniformBorder);\n\n if (glassMask > 0.001 && inset < 5.0 && uRimParams.x > 0.001 && isPhysicalRim < 0.5) {\n float ny = abs(normal.y);\n float wDirectional = 1.0 - clamp(uStyleMix, 0.0, 1.0);\n float wSoft = clamp(uStyleMix, 0.0, 1.0) * clamp(uRimOpacity, 0.0, 1.0);\n\n if (hasUniformBorder > 0.5) {\n // Match CSS inset box-shadow: keep inner rim inside the padding edge so the 1px border is not double-brightened\n float padInset = max(inset - uBorderParams.x, 0.0);\n float padMask = 1.0 - borderMask;\n float dirWeight = computeDirectionalRimWeight(normal, uRimParams.w, uBorderParams.y);\n float core = smoothstep(max(uRimParams.y, 0.4) + 0.6, 0.0, padInset);\n float tail = exp(-padInset / 1.8) * uRimParams.z * smoothstep(5.0, 3.2, inset);\n rimA = clamp((core + tail) * dirWeight * uRimParams.x * padMask * glassMask * uOpacity, 0.0, 1.0);\n } else {\n if (wDirectional > 0.001) {\n float dirWeight = computeDirectionalRimWeight(normal, uRimParams.w, uBorderParams.y);\n float core = smoothstep(max(uRimParams.y, 0.4) + 0.6, 0.0, inset);\n float tail = exp(-inset / 1.8) * uRimParams.z * smoothstep(5.0, 3.2, inset);\n rimA += (core + tail) * dirWeight * uRimParams.x * wDirectional;\n }\n\n if (wSoft > 0.001) {\n float bandT = clamp(inset / 5.0, 0.0, 1.0);\n float steppedT = min(floor(bandT * 9.0) / 9.0, 1.0);\n float bandCurve = mix(safePow(1.0 - bandT, 2.1), safePow(1.0 - steppedT, 2.1), 0.35);\n float rimCoreBoost = 0.65 + 0.35 * smoothstep(1.2, 0.0, inset);\n float angWeight = mix(0.015, 1.0, safePow(ny, 2.1)) * (normal.y < 0.0 ? 1.0 : 0.85);\n rimA += bandCurve * rimCoreBoost * angWeight * uRimParams.x * wSoft;\n }\n\n // Boost specular luminance to match source-over alpha blending expectations\n rimA = clamp(rimA * 1.35 * glassMask * uOpacity, 0.0, 1.0);\n }\n } else if (glassMask > 0.001 && isPhysicalRim > 0.5 && inset < uPhysicalParams.x) {\n float bezelPx = max(uPhysicalParams.x, 1.0);\n float t = clamp(inset / bezelPx, 0.0, 1.0);\n float eps = 0.015;\n float t0 = max(0.0, t - eps);\n float t1 = min(1.0, t + eps);\n float slope = (evalBezelHeight(t1, uPhysicalParams.w) - evalBezelHeight(t0, uPhysicalParams.w)) / max(t1 - t0, 1e-4);\n vec3 N = normalize(vec3(normal * slope, 1.0));\n vec3 L = uPhysicalLight.xyz;\n vec3 H = vec3(L.xy, L.z + 1.0);\n float hLen = max(length(H), 1e-4);\n const float shininess = 36.0;\n float flatBase = safePow(clamp((L.z + 1.0) / hLen, 0.0, 1.0), shininess);\n float denomBase = max(1.0 - flatBase, 1e-4);\n float hDot = clamp(dot(N, H) / hLen, 0.0, 1.0);\n float highlight = max(safePow(hDot, shininess) - flatBase, 0.0) / denomBase;\n vec3 H_bounce = vec3(-L.xy, L.z + 1.0);\n float bDot = clamp(dot(N, H_bounce) / hLen, 0.0, 1.0);\n float bounce = max(safePow(bDot, shininess) - flatBase, 0.0) / denomBase;\n vec2 planar = L.xy / max(length(L.xy), 1e-4);\n float facing = dot(normal, planar);\n float fresnel = safePow(clamp(1.0 - N.z, 0.0, 1.0), 4.0);\n float rimTerm = fresnel * (0.25 + 0.75 * max(facing, 0.0) + 0.45 * max(-facing, 0.0));\n float shadeTerm = safePow(clamp(1.0 - N.z, 0.0, 1.0), 2.5) * (0.45 + 0.55 * max(-facing, 0.0));\n float lit = clamp((uPhysicalParams.y * (highlight + 0.45 * bounce) + uRimParams.x * rimTerm) * glassMask * uOpacity, 0.0, 1.0);\n float dark = clamp(uPhysicalParams.z * shadeTerm * glassMask * uOpacity, 0.0, 1.0) * (1.0 - lit);\n physLitA = lit;\n physShadeA = dark;\n }\n\n // Keep interior strictly transparent when shadow, hairline, border, and rim are all zero\n if (shadowA <= 0.0001 && hairA <= 0.0001 && borderA <= 0.0001 && rimA <= 0.0001 && physLitA <= 0.0001 && physShadeA <= 0.0001) {\n fragColor = vec4(0.0);\n return;\n }\n\n // Premultiplied alpha composite: uniform border over inner/physical rim over hairline and shadow\n float darkA = clamp(shadowA + hairA * (1.0 - shadowA), 0.0, 1.0);\n vec3 shadeColor = vec3(0.03921569, 0.07058824, 0.10980392);\n vec3 afterRimRgb = vec3(rimA + physLitA) + shadeColor * physShadeA;\n float totalRimA = clamp(rimA + physLitA + physShadeA * (1.0 - rimA), 0.0, 1.0);\n float afterRimA = totalRimA + darkA * (1.0 - totalRimA);\n vec3 outRgb = borderRgb + afterRimRgb * (1.0 - borderA);\n float outA = clamp(borderA + afterRimA * (1.0 - borderA), 0.0, 1.0);\n fragColor = vec4(outRgb, outA);\n}\n";
19
19
  /**
20
20
  * Traces an SVG path string emitted by `extractFieldContourPath` (`M`, `L`, `A`, `Z`)
21
21
  * directly onto a 2D Canvas context without relying on `Path2D`.