@sessile/core 0.2.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.
- package/dist/contour.js +57 -12
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -1
- package/dist/legibility.d.ts +281 -0
- package/dist/legibility.js +547 -0
- package/dist/optics.d.ts +6 -0
- package/dist/optics.js +9 -1
- package/package.json +1 -1
package/dist/contour.js
CHANGED
|
@@ -99,8 +99,34 @@ function fmt(value) {
|
|
|
99
99
|
const rounded = Math.round(value * 100) / 100;
|
|
100
100
|
return rounded === 0 ? 0 : rounded;
|
|
101
101
|
}
|
|
102
|
-
|
|
103
|
-
|
|
102
|
+
/**
|
|
103
|
+
* Selects the smallest grid step from the half-octave lattice `{1, 1.5} * 2^k`
|
|
104
|
+
* that is at least `minStep` so multi-primitive Marching Squares sample nodes stay
|
|
105
|
+
* locked to fixed world-space coordinates when only one primitive moves.
|
|
106
|
+
*/
|
|
107
|
+
function pickDiscreteGridStep(minStep) {
|
|
108
|
+
if (!(minStep > 0) || !Number.isFinite(minStep)) {
|
|
109
|
+
return 1;
|
|
110
|
+
}
|
|
111
|
+
const exp = Math.floor(Math.log2(minStep));
|
|
112
|
+
const pow2 = Math.pow(2, exp);
|
|
113
|
+
if (pow2 >= minStep) {
|
|
114
|
+
return pow2;
|
|
115
|
+
}
|
|
116
|
+
const mid = pow2 * 1.5;
|
|
117
|
+
if (mid >= minStep) {
|
|
118
|
+
return mid;
|
|
119
|
+
}
|
|
120
|
+
return pow2 * 2;
|
|
121
|
+
}
|
|
122
|
+
/** Advances to the next rung on the `{1, 1.5} * 2^k` world-lattice step ladder. */
|
|
123
|
+
function nextDiscreteGridStep(step) {
|
|
124
|
+
if (!(step > 0) || !Number.isFinite(step)) {
|
|
125
|
+
return 1;
|
|
126
|
+
}
|
|
127
|
+
const exp = Math.floor(Math.log2(step));
|
|
128
|
+
const pow2 = Math.pow(2, exp);
|
|
129
|
+
return step < pow2 * 1.25 ? pow2 * 1.5 : pow2 * 2;
|
|
104
130
|
}
|
|
105
131
|
function isActivePrimitive(shape) {
|
|
106
132
|
return shape.size.width > MIN_ACTIVE_SIZE && shape.size.height > MIN_ACTIVE_SIZE;
|
|
@@ -284,19 +310,38 @@ export function extractFieldContourPath(field, offset = ZERO_POINT) {
|
|
|
284
310
|
function appendClusterMarchingSquaresLoops(minX, maxX, minY, maxY, clusterSize, blendK, prepared, offset, outLoops) {
|
|
285
311
|
// Margin compensating for multi-primitive cumulative smin dilation so outer boundary nodes stay strictly positive and form closed loops.
|
|
286
312
|
const msPadding = computeMaxSminDilationFactor(clusterSize) * blendK + 4;
|
|
287
|
-
const
|
|
288
|
-
const
|
|
289
|
-
const
|
|
290
|
-
const
|
|
291
|
-
const
|
|
313
|
+
const rawMinX = minX - msPadding;
|
|
314
|
+
const rawMaxX = maxX + msPadding;
|
|
315
|
+
const rawMinY = minY - msPadding;
|
|
316
|
+
const rawMaxY = maxY + msPadding;
|
|
317
|
+
const rawW = rawMaxX - rawMinX;
|
|
318
|
+
const rawH = rawMaxY - rawMinY;
|
|
319
|
+
const longest = rawW > rawH ? rawW : rawH;
|
|
292
320
|
if (longest <= MIN_ACTIVE_SIZE) {
|
|
293
321
|
return;
|
|
294
322
|
}
|
|
295
|
-
|
|
296
|
-
const
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
323
|
+
// Reserve 2 cells for outward world-lattice snapping (`floor` min / `ceil` max) within `MAX_GRID_STEPS`.
|
|
324
|
+
const baseStep = pickDiscreteGridStep(longest / (MAX_GRID_STEPS - 2));
|
|
325
|
+
let dx = rawW / baseStep < MIN_GRID_STEPS
|
|
326
|
+
? Math.min(baseStep, pickDiscreteGridStep(rawW / (MIN_GRID_STEPS + 12)))
|
|
327
|
+
: baseStep;
|
|
328
|
+
let dy = rawH / baseStep < MIN_GRID_STEPS
|
|
329
|
+
? Math.min(baseStep, pickDiscreteGridStep(rawH / (MIN_GRID_STEPS + 12)))
|
|
330
|
+
: baseStep;
|
|
331
|
+
let boundsX = Math.floor(rawMinX / dx) * dx;
|
|
332
|
+
let cols = Math.max(1, Math.round((Math.ceil(rawMaxX / dx) * dx - boundsX) / dx));
|
|
333
|
+
while (cols > MAX_GRID_STEPS) {
|
|
334
|
+
dx = nextDiscreteGridStep(dx);
|
|
335
|
+
boundsX = Math.floor(rawMinX / dx) * dx;
|
|
336
|
+
cols = Math.max(1, Math.round((Math.ceil(rawMaxX / dx) * dx - boundsX) / dx));
|
|
337
|
+
}
|
|
338
|
+
let boundsY = Math.floor(rawMinY / dy) * dy;
|
|
339
|
+
let rows = Math.max(1, Math.round((Math.ceil(rawMaxY / dy) * dy - boundsY) / dy));
|
|
340
|
+
while (rows > MAX_GRID_STEPS) {
|
|
341
|
+
dy = nextDiscreteGridStep(dy);
|
|
342
|
+
boundsY = Math.floor(rawMinY / dy) * dy;
|
|
343
|
+
rows = Math.max(1, Math.round((Math.ceil(rawMaxY / dy) * dy - boundsY) / dy));
|
|
344
|
+
}
|
|
300
345
|
const stride = cols + 1;
|
|
301
346
|
const ox = offset.x;
|
|
302
347
|
const oy = offset.y;
|
package/dist/index.d.ts
CHANGED
|
@@ -12,4 +12,5 @@ export { MAX_REFRACT_TILE_PX, clearRefractTilesCache, resolveRefractTiles, type
|
|
|
12
12
|
export { BEZEL_HEIGHT_PROFILES, CAUSTIC_FOLD_LIMIT, DEFAULT_REFRACTION_IOR, DEFAULT_REFRACTION_SAMPLES, NORMAL_FLOOR, computeRefractionProfileLut, getRefractionProfileKey, resolveRefractionProfileLut, sampleRefractionLut, traceBezelRay, type BezelHeightFn, type BezelHeightProfileName, type BezelRayTrace, type BezelRayTraceInput, type RefractionProfileLut, type RefractionProfileName, type RefractionProfileOptions, type RefractionProfileSpec, } from './refractProfile.ts';
|
|
13
13
|
export { OVERLAY_FRAGMENT_SHADER, OVERLAY_VERTEX_SHADER, createGlassOverlayRenderer, } from './overlayRenderer.ts';
|
|
14
14
|
export { clamp, computeAreaPreservingScale, createElasticPressController, createMorphTimeline, createSpringChannel, cubicBezier, deformSizePreservingArea, easeInOutCubic, easeInQuad, easeOutCubic, evaluateSpring, evaluateSpringState, lerp, riseAndFall, smoothstep, type AreaPreservingScale, type ElasticPressController, type ElasticPressOptions, type ElasticPressState, type MorphTimeline, type MorphTimelineOptions, type MorphTimelinePhase, type MorphTimelineState, type SpringChannel, type SpringChannelOptions, type SpringChannelState, type SpringSample, } from './physics.ts';
|
|
15
|
-
export { buildCircularBevelTable, buildColorOpticsMatrix, buildContourAlphaDataUrl, interpolateCssGlassSurfaceToMaterial, interpolateOpticalMaterial, interpolateVeilOptics, parseCssBoxShadow, parseCssFilterOptics, parseCssGlassSurface, parseCssRgba, resolveOpticalMaterial, type BackdropVeilOptics, type CircularBevelTable, type ExtractedCssGlassSurface, type ParseCssGlassSurfaceInput, type ParsedBoxShadowLayer, } from './optics.ts';
|
|
15
|
+
export { buildCircularBevelTable, buildColorOpticsMatrix, buildContourAlphaDataUrl, interpolateCssGlassSurfaceToMaterial, interpolateOpticalMaterial, interpolateVeilOptics, parseCssBoxShadow, parseCssFilterOptics, parseCssGlassSurface, parseCssRgba, tryParseCssRgba, resolveOpticalMaterial, type BackdropVeilOptics, type CircularBevelTable, type ExtractedCssGlassSurface, type ParseCssGlassSurfaceInput, type ParsedBoxShadowLayer, } from './optics.ts';
|
|
16
|
+
export { LEGIBILITY_CALM_KNEE, LEGIBILITY_LIMIT_MARGIN, LEGIBILITY_POLICIES, LEGIBILITY_SMOOTHING, LEGIBILITY_STAGES, LEGIBILITY_TABLE_SIZE, TELEMETRY_STRIDE, computeBackdropRisk, contrastRatio, createAsymmetricSmoother, createLegibilityParams, createTelemetryAccumulator, linearToSrgb, measureTelemetryGrid, relativeLuminance, srgbLuma, resolveLegibilityGoal, resolveLegibilityParams, srgbToLinear, type AsymmetricSmoother, type AsymmetricSmootherOptions, type BackdropTelemetry, type BackdropTelemetryAccumulator, type BackdropTelemetryGrid, type ForegroundPolarity, type LegibilityGoal, type LegibilityParams, type LegibilityPolicy, type LegibilityRisk, type LegibilityTarget, type LegibilityTier, } from './legibility.ts';
|
package/dist/index.js
CHANGED
|
@@ -12,4 +12,5 @@ export { MAX_REFRACT_TILE_PX, clearRefractTilesCache, resolveRefractTiles, } fro
|
|
|
12
12
|
export { BEZEL_HEIGHT_PROFILES, CAUSTIC_FOLD_LIMIT, DEFAULT_REFRACTION_IOR, DEFAULT_REFRACTION_SAMPLES, NORMAL_FLOOR, computeRefractionProfileLut, getRefractionProfileKey, resolveRefractionProfileLut, sampleRefractionLut, traceBezelRay, } from "./refractProfile.js";
|
|
13
13
|
export { OVERLAY_FRAGMENT_SHADER, OVERLAY_VERTEX_SHADER, createGlassOverlayRenderer, } from "./overlayRenderer.js";
|
|
14
14
|
export { clamp, computeAreaPreservingScale, createElasticPressController, createMorphTimeline, createSpringChannel, cubicBezier, deformSizePreservingArea, easeInOutCubic, easeInQuad, easeOutCubic, evaluateSpring, evaluateSpringState, lerp, riseAndFall, smoothstep, } from "./physics.js";
|
|
15
|
-
export { buildCircularBevelTable, buildColorOpticsMatrix, buildContourAlphaDataUrl, interpolateCssGlassSurfaceToMaterial, interpolateOpticalMaterial, interpolateVeilOptics, parseCssBoxShadow, parseCssFilterOptics, parseCssGlassSurface, parseCssRgba, resolveOpticalMaterial, } from "./optics.js";
|
|
15
|
+
export { buildCircularBevelTable, buildColorOpticsMatrix, buildContourAlphaDataUrl, interpolateCssGlassSurfaceToMaterial, interpolateOpticalMaterial, interpolateVeilOptics, parseCssBoxShadow, parseCssFilterOptics, parseCssGlassSurface, parseCssRgba, tryParseCssRgba, resolveOpticalMaterial, } from "./optics.js";
|
|
16
|
+
export { LEGIBILITY_CALM_KNEE, LEGIBILITY_LIMIT_MARGIN, LEGIBILITY_POLICIES, LEGIBILITY_SMOOTHING, LEGIBILITY_STAGES, LEGIBILITY_TABLE_SIZE, TELEMETRY_STRIDE, computeBackdropRisk, contrastRatio, createAsymmetricSmoother, createLegibilityParams, createTelemetryAccumulator, linearToSrgb, measureTelemetryGrid, relativeLuminance, srgbLuma, resolveLegibilityGoal, resolveLegibilityParams, srgbToLinear, } from "./legibility.js";
|
|
@@ -0,0 +1,281 @@
|
|
|
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 type { BackdropVeilOptics } from './optics.ts';
|
|
17
|
+
export type LegibilityTier = 'clear' | 'regular' | 'legible';
|
|
18
|
+
export type ForegroundPolarity = 'light' | 'dark';
|
|
19
|
+
/** Material response of one legibility tier. Gains and floors are reached at full risk. */
|
|
20
|
+
export interface LegibilityPolicy {
|
|
21
|
+
/** WCAG 2 contrast ratio the foreground keeps against the composited glass. */
|
|
22
|
+
contrast: number;
|
|
23
|
+
/**
|
|
24
|
+
* Fraction of the safe limit where the soft knee starts bending at full luminance risk, in
|
|
25
|
+
* `(0, LEGIBILITY_CALM_KNEE)`. A calm backdrop keeps a harder shoulder that spares mid-tones;
|
|
26
|
+
* the ceiling itself always holds, because aggregate telemetry cannot see a small bright
|
|
27
|
+
* patch (a speech balloon) that still sits under the text.
|
|
28
|
+
*/
|
|
29
|
+
knee: number;
|
|
30
|
+
/** Uniform film alpha added on the veil at full risk. */
|
|
31
|
+
filmMax: number;
|
|
32
|
+
/** Backdrop saturation multiplier at full chroma risk. */
|
|
33
|
+
saturationFloor: number;
|
|
34
|
+
/** Extra backdrop blur in CSS px at full detail risk. */
|
|
35
|
+
blurBoostPx: number;
|
|
36
|
+
/** Displacement-scale multiplier at full detail risk (never re-encodes the map). */
|
|
37
|
+
refractionFloor: number;
|
|
38
|
+
/** Relative hairline and rim alpha gain at full risk. */
|
|
39
|
+
edgeGain: number;
|
|
40
|
+
/** Relative outer-shadow alpha gain at full luminance risk. */
|
|
41
|
+
shadowGain: number;
|
|
42
|
+
/** Risk assumed on every channel while no telemetry is available. */
|
|
43
|
+
assumedRisk: number;
|
|
44
|
+
}
|
|
45
|
+
export declare const LEGIBILITY_POLICIES: {
|
|
46
|
+
readonly clear: {
|
|
47
|
+
readonly contrast: 3;
|
|
48
|
+
readonly knee: 0.72;
|
|
49
|
+
readonly filmMax: 0.06;
|
|
50
|
+
readonly saturationFloor: 0.88;
|
|
51
|
+
readonly blurBoostPx: 1.5;
|
|
52
|
+
readonly refractionFloor: 0.85;
|
|
53
|
+
readonly edgeGain: 0.35;
|
|
54
|
+
readonly shadowGain: 0.4;
|
|
55
|
+
readonly assumedRisk: 0.3;
|
|
56
|
+
};
|
|
57
|
+
readonly regular: {
|
|
58
|
+
readonly contrast: 4.5;
|
|
59
|
+
readonly knee: 0.7;
|
|
60
|
+
readonly filmMax: 0.14;
|
|
61
|
+
readonly saturationFloor: 0.72;
|
|
62
|
+
readonly blurBoostPx: 3;
|
|
63
|
+
readonly refractionFloor: 0.65;
|
|
64
|
+
readonly edgeGain: 0.6;
|
|
65
|
+
readonly shadowGain: 0.8;
|
|
66
|
+
readonly assumedRisk: 0.5;
|
|
67
|
+
};
|
|
68
|
+
readonly legible: {
|
|
69
|
+
readonly contrast: 7;
|
|
70
|
+
readonly knee: 0.65;
|
|
71
|
+
readonly filmMax: 0.26;
|
|
72
|
+
readonly saturationFloor: 0.55;
|
|
73
|
+
readonly blurBoostPx: 6;
|
|
74
|
+
readonly refractionFloor: 0.4;
|
|
75
|
+
readonly edgeGain: 0.9;
|
|
76
|
+
readonly shadowGain: 1.2;
|
|
77
|
+
readonly assumedRisk: 0.8;
|
|
78
|
+
};
|
|
79
|
+
};
|
|
80
|
+
/**
|
|
81
|
+
* Attack is fast so text never sits on an unsafe backdrop for more than a few frames; hold and
|
|
82
|
+
* release bridge the calm gutters between cards so scrolling across a grid does not strobe.
|
|
83
|
+
*/
|
|
84
|
+
export declare const LEGIBILITY_SMOOTHING: {
|
|
85
|
+
readonly attackMs: 90;
|
|
86
|
+
readonly holdMs: 240;
|
|
87
|
+
readonly releaseMs: 700;
|
|
88
|
+
readonly epsilon: 0.004;
|
|
89
|
+
};
|
|
90
|
+
/** Knee fraction used at zero luminance risk. */
|
|
91
|
+
export declare const LEGIBILITY_CALM_KNEE = 0.9;
|
|
92
|
+
/** Samples in each per-pixel multiplier table (`feFunc* type="table"`). */
|
|
93
|
+
export declare const LEGIBILITY_TABLE_SIZE = 33;
|
|
94
|
+
/**
|
|
95
|
+
* Filter-graph contract for the per-pixel stage, keyed by polarity.
|
|
96
|
+
* `k` are `feComposite operator="arithmetic"` coefficients with `in` = color, `in2` = multiplier.
|
|
97
|
+
* Light text keys on true luminance (`linearRGB` matrix): sRGB luma underestimates saturated
|
|
98
|
+
* colors (pure red has luma 0.21 but encoded luminance ~0.50) and would leave them unclamped.
|
|
99
|
+
* Dark text keys on sRGB luma, which only ever underestimates, so the lift errs on the safe side
|
|
100
|
+
* and avoids quantizing shadows in an 8-bit linear buffer.
|
|
101
|
+
*/
|
|
102
|
+
export declare const LEGIBILITY_STAGES: {
|
|
103
|
+
readonly light: {
|
|
104
|
+
readonly luminanceSpace: "linearRGB";
|
|
105
|
+
readonly k: readonly [1, 0, 0, 0];
|
|
106
|
+
};
|
|
107
|
+
readonly dark: {
|
|
108
|
+
readonly luminanceSpace: "sRGB";
|
|
109
|
+
readonly k: readonly [1, 0, -1, 1];
|
|
110
|
+
};
|
|
111
|
+
};
|
|
112
|
+
/**
|
|
113
|
+
* Encoded-luminance headroom kept below the exact limit. Covers the residual error of
|
|
114
|
+
* scaling in sRGB space (the transfer curve is not a pure power law), veil blending of colored
|
|
115
|
+
* pixels, and 8-bit filter intermediates; sized by the reference-model sweep in the unit tests.
|
|
116
|
+
*/
|
|
117
|
+
export declare const LEGIBILITY_LIMIT_MARGIN = 0.008;
|
|
118
|
+
export interface LegibilityTarget {
|
|
119
|
+
/** Foreground text color as normalized sRGB `[r, g, b]` (a trailing alpha is ignored). */
|
|
120
|
+
foreground: readonly number[];
|
|
121
|
+
/** Tier preset (defaults to `'regular'`). */
|
|
122
|
+
tier?: LegibilityTier;
|
|
123
|
+
/** Overrides the tier's WCAG contrast ratio. */
|
|
124
|
+
contrast?: number;
|
|
125
|
+
/** Overrides the polarity inferred from the foreground luminance. */
|
|
126
|
+
polarity?: ForegroundPolarity;
|
|
127
|
+
}
|
|
128
|
+
export interface LegibilityGoal {
|
|
129
|
+
readonly polarity: ForegroundPolarity;
|
|
130
|
+
readonly contrast: number;
|
|
131
|
+
readonly policy: LegibilityPolicy;
|
|
132
|
+
/** Encoded-luminance bound the composited glass must stay beyond (ceiling for light text, floor for dark). */
|
|
133
|
+
readonly perceivedLimit: number;
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Backdrop statistics under a glass region, in encoded luminance and sRGB channel units.
|
|
137
|
+
* Hosts may inject these directly or let a probe aggregate them.
|
|
138
|
+
*/
|
|
139
|
+
export interface BackdropTelemetry {
|
|
140
|
+
/** Bright-tail encoded luminance (about the 95th percentile). */
|
|
141
|
+
lumaHigh: number;
|
|
142
|
+
/**
|
|
143
|
+
* Dark tail (about the 5th percentile) of sRGB luma (`srgbLuma`). Dark text needs a lower
|
|
144
|
+
* bound that survives per-channel lifts: by Jensen's inequality luma never exceeds encoded
|
|
145
|
+
* luminance, and unlike luminance it moves exactly affinely under per-channel
|
|
146
|
+
* `brightness`/`contrast` and the fallback lift, so a lift solved on it holds on saturated
|
|
147
|
+
* pixels too.
|
|
148
|
+
*/
|
|
149
|
+
lumaLow: number;
|
|
150
|
+
/**
|
|
151
|
+
* Bright tail (about the 95th percentile) of each pixel's largest sRGB channel. Host
|
|
152
|
+
* brightness/contrast clip per channel, so luminance alone cannot bound a colored backdrop
|
|
153
|
+
* under them. Omitted, the backdrop is assumed neutral (`lumaHigh`).
|
|
154
|
+
*/
|
|
155
|
+
channelHigh?: number;
|
|
156
|
+
/** Dark tail (about the 5th percentile) of each pixel's smallest sRGB channel; defaults to `lumaLow`. */
|
|
157
|
+
channelLow?: number;
|
|
158
|
+
/** Mean chroma (`max - min` of the sRGB channels). */
|
|
159
|
+
chroma: number;
|
|
160
|
+
/** Mean absolute luminance gradient per pixel, scaled to roughly `[0, 1]` (dense text reads high). */
|
|
161
|
+
detail: number;
|
|
162
|
+
}
|
|
163
|
+
export interface LegibilityRisk {
|
|
164
|
+
luma: number;
|
|
165
|
+
chroma: number;
|
|
166
|
+
detail: number;
|
|
167
|
+
}
|
|
168
|
+
/** Telemetry floats per grid cell: `lumaHigh, lumaLow, channelHigh, channelLow, chroma, detail`. */
|
|
169
|
+
export declare const TELEMETRY_STRIDE = 6;
|
|
170
|
+
export interface BackdropTelemetryGrid {
|
|
171
|
+
cols: number;
|
|
172
|
+
rows: number;
|
|
173
|
+
/** `cols * rows * TELEMETRY_STRIDE` floats, row-major. */
|
|
174
|
+
data: Float32Array;
|
|
175
|
+
}
|
|
176
|
+
/** Preallocated solver output; `resolveLegibilityParams` rewrites it in place. */
|
|
177
|
+
export interface LegibilityParams {
|
|
178
|
+
polarity: ForegroundPolarity;
|
|
179
|
+
/** Per-pixel multiplier `M` sampled uniformly over the luminance index `[0, 1]`. */
|
|
180
|
+
readonly table: Float32Array;
|
|
181
|
+
/** Increments whenever `table` changes beyond 8-bit precision, so consumers rewrite filter nodes only then. */
|
|
182
|
+
tableRevision: number;
|
|
183
|
+
/** Veil tint with the uniform film composited over it, normalized RGBA. */
|
|
184
|
+
readonly veilRgba: Float32Array;
|
|
185
|
+
blurBoostPx: number;
|
|
186
|
+
refractionScale: number;
|
|
187
|
+
saturationScale: number;
|
|
188
|
+
hairlineScale: number;
|
|
189
|
+
shadowScale: number;
|
|
190
|
+
/**
|
|
191
|
+
* Whole-backdrop correction for paths without the per-pixel filter. Apply it as its own
|
|
192
|
+
* `brightness`/`contrast` stage after the host's veil optics: CSS clamps between filter
|
|
193
|
+
* functions and the risk is solved on that clamped output, so folding it into the host pair
|
|
194
|
+
* would let an over-brightened backdrop escape the ceiling.
|
|
195
|
+
*/
|
|
196
|
+
readonly fallbackVeil: BackdropVeilOptics;
|
|
197
|
+
/** Encoded-luminance limit the backdrop is compressed toward after the film. */
|
|
198
|
+
backdropLimit: number;
|
|
199
|
+
/** `false` when the veil tint alone already violates the goal. */
|
|
200
|
+
feasible: boolean;
|
|
201
|
+
}
|
|
202
|
+
export declare function srgbToLinear(c: number): number;
|
|
203
|
+
export declare function linearToSrgb(l: number): number;
|
|
204
|
+
/** WCAG 2 relative luminance of a normalized sRGB color. */
|
|
205
|
+
/** Rec. 709 weights applied to the encoded sRGB channels; a lower bound on encoded luminance. */
|
|
206
|
+
export declare function srgbLuma(r: number, g: number, b: number): number;
|
|
207
|
+
export declare function relativeLuminance(r: number, g: number, b: number): number;
|
|
208
|
+
/** WCAG 2 contrast ratio between two relative luminances. */
|
|
209
|
+
export declare function contrastRatio(a: number, b: number): number;
|
|
210
|
+
/** Resolves the host declaration into a polarity and an encoded-luminance limit. */
|
|
211
|
+
export declare function resolveLegibilityGoal(target: LegibilityTarget): LegibilityGoal;
|
|
212
|
+
/**
|
|
213
|
+
* Maps backdrop telemetry to `[0, 1]` risk per channel for the given goal and base veil.
|
|
214
|
+
* Telemetry describes the raw page, but the glass shows it after the host's `optics`, and the
|
|
215
|
+
* fallback correction runs after those optics too. The optics clip each channel, so a colored
|
|
216
|
+
* pixel's output luminance is not a function of its input luminance. It is bounded instead:
|
|
217
|
+
* - by the optics applied to its extreme channel, since luminance lies between min and max
|
|
218
|
+
* channel and the optics are monotonic;
|
|
219
|
+
* - by `L + D`, where `D` is the extreme of `f(x) - x` over its channel range. The dark tail is
|
|
220
|
+
* sRGB luma, a weighted mean of the channels, so this holds exactly; the bright tail is
|
|
221
|
+
* encoded luminance, a translated power mean, which by Minkowski's inequality moves no
|
|
222
|
+
* further than a shift applied to every channel.
|
|
223
|
+
* Both bounds are exact for neutral pixels and collapse to `L` under identity optics, so the
|
|
224
|
+
* estimate stays continuous as the host's optics change. Chroma and gradients scale by the
|
|
225
|
+
* affine slope.
|
|
226
|
+
*
|
|
227
|
+
* `saturation` is the host's `saturate()`, which runs first: `x' = luma + s * (x - luma)` per
|
|
228
|
+
* channel, then clipped. Desaturating never clips, keeps sRGB luma and (by Jensen) never raises
|
|
229
|
+
* encoded luminance, so only `s > 1` matters; there each clipped channel moves by at most
|
|
230
|
+
* `(s - 1)` times the channel spread, a bounded shift that widens the channel range and the
|
|
231
|
+
* luminance tails by the same amount. The legibility response only ever lowers saturation, so
|
|
232
|
+
* the host's value bounds the effective one.
|
|
233
|
+
*/
|
|
234
|
+
export declare function computeBackdropRisk(telemetry: BackdropTelemetry, goal: LegibilityGoal, veilRgba: ArrayLike<number>, out: LegibilityRisk, optics?: BackdropVeilOptics, saturation?: number): LegibilityRisk;
|
|
235
|
+
export declare function createLegibilityParams(): LegibilityParams;
|
|
236
|
+
/**
|
|
237
|
+
* Solves the material response for the smoothed `risk` and writes it into `out`.
|
|
238
|
+
* Allocation-free; returns `true` when any output changed.
|
|
239
|
+
*/
|
|
240
|
+
export declare function resolveLegibilityParams(goal: LegibilityGoal, risk: LegibilityRisk, baseVeilRgba: ArrayLike<number>, out: LegibilityParams): boolean;
|
|
241
|
+
/**
|
|
242
|
+
* Area-weighted telemetry accumulator. Tails use a quadratic mean so a small bright patch still
|
|
243
|
+
* outweighs its area share, while the slope at small coverage stays bounded: a plain max (or a
|
|
244
|
+
* high power mean) would jump the moment a sliver of a white card enters the glass rect, which
|
|
245
|
+
* shows up as a material seam when primitives merge or scroll across card edges.
|
|
246
|
+
*/
|
|
247
|
+
export interface BackdropTelemetryAccumulator {
|
|
248
|
+
readonly weight: number;
|
|
249
|
+
reset(): void;
|
|
250
|
+
add(telemetry: BackdropTelemetry, weight: number): void;
|
|
251
|
+
/** Adds one `TELEMETRY_STRIDE` record from a grid or flat buffer without allocating. */
|
|
252
|
+
addRecord(data: ArrayLike<number>, offset: number, weight: number): void;
|
|
253
|
+
/** Writes the aggregate into `out`; returns `false` (leaving `out` untouched) when nothing was added. */
|
|
254
|
+
resolve(out: BackdropTelemetry): boolean;
|
|
255
|
+
}
|
|
256
|
+
export declare function createTelemetryAccumulator(): BackdropTelemetryAccumulator;
|
|
257
|
+
/**
|
|
258
|
+
* Measures a `cols x rows` telemetry grid from straight (non-premultiplied) RGBA bytes.
|
|
259
|
+
* Runs once per source image, never per frame; callers obtain pixels through normal
|
|
260
|
+
* same-origin or CORS-approved channels only.
|
|
261
|
+
*/
|
|
262
|
+
export declare function measureTelemetryGrid(rgba: ArrayLike<number>, width: number, height: number, cols: number, rows: number): BackdropTelemetryGrid;
|
|
263
|
+
export interface AsymmetricSmootherOptions {
|
|
264
|
+
attackMs: number;
|
|
265
|
+
/** Time a falling target must persist before release starts (defaults to `0`). */
|
|
266
|
+
holdMs?: number;
|
|
267
|
+
releaseMs: number;
|
|
268
|
+
/** Distance under which a channel snaps to its target and counts as settled (defaults to `1e-3`). */
|
|
269
|
+
epsilon?: number;
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* Frame-rate independent attack/hold/release smoother over a fixed channel count.
|
|
273
|
+
* Rising targets follow `attackMs`; falling targets wait `holdMs`, then follow `releaseMs`.
|
|
274
|
+
*/
|
|
275
|
+
export interface AsymmetricSmoother {
|
|
276
|
+
readonly values: Float32Array;
|
|
277
|
+
/** Advances by `dtMs` toward `target`; returns `true` once every channel has settled. */
|
|
278
|
+
step(target: ArrayLike<number>, dtMs: number): boolean;
|
|
279
|
+
reset(values: ArrayLike<number> | number): void;
|
|
280
|
+
}
|
|
281
|
+
export declare function createAsymmetricSmoother(channels: number, options: AsymmetricSmootherOptions): AsymmetricSmoother;
|
|
@@ -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
|
|
151
|
+
return null;
|
|
144
152
|
}
|
|
145
153
|
const VEIL_SINGULAR_EPS = 1e-6;
|
|
146
154
|
function veilOpticsToAffine(veil) {
|