@abgin/abgin 0.0.0-stage → 0.1.2

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.
Files changed (131) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +61 -2
  3. package/dist/THIRD-PARTY-NOTICES.txt +27 -0
  4. package/dist/abgin.js +3 -0
  5. package/dist/abgin.js.map +1 -0
  6. package/dist/chunks/appbar-qrxjDiTR.js +3 -0
  7. package/dist/chunks/appbar-qrxjDiTR.js.map +1 -0
  8. package/dist/chunks/behavior-DcTSsbjM.js +3 -0
  9. package/dist/chunks/behavior-DcTSsbjM.js.map +1 -0
  10. package/dist/chunks/dialog-YuGr7AZw.js +3 -0
  11. package/dist/chunks/dialog-YuGr7AZw.js.map +1 -0
  12. package/dist/chunks/direction-JCXVGRGq.js +3 -0
  13. package/dist/chunks/direction-JCXVGRGq.js.map +1 -0
  14. package/dist/chunks/drawer-V2-RJZaj.js +3 -0
  15. package/dist/chunks/drawer-V2-RJZaj.js.map +1 -0
  16. package/dist/chunks/dropdown-BsSoDo4Z.js +3 -0
  17. package/dist/chunks/dropdown-BsSoDo4Z.js.map +1 -0
  18. package/dist/chunks/engine-DOFQfCtE.js +3 -0
  19. package/dist/chunks/engine-DOFQfCtE.js.map +1 -0
  20. package/dist/chunks/focus-BNE6ytl8.js +3 -0
  21. package/dist/chunks/focus-BNE6ytl8.js.map +1 -0
  22. package/dist/chunks/glass-9XMne6tP.js +3 -0
  23. package/dist/chunks/glass-9XMne6tP.js.map +1 -0
  24. package/dist/chunks/modal-GUayszcw.js +3 -0
  25. package/dist/chunks/modal-GUayszcw.js.map +1 -0
  26. package/dist/chunks/motion-scene-BNPBmw5W.js +3 -0
  27. package/dist/chunks/motion-scene-BNPBmw5W.js.map +1 -0
  28. package/dist/chunks/optics-BSQ3SSNg.js +3 -0
  29. package/dist/chunks/optics-BSQ3SSNg.js.map +1 -0
  30. package/dist/chunks/overlay-CKgXnT5J.js +3 -0
  31. package/dist/chunks/overlay-CKgXnT5J.js.map +1 -0
  32. package/dist/chunks/popover-CMbdxv9C.js +3 -0
  33. package/dist/chunks/popover-CMbdxv9C.js.map +1 -0
  34. package/dist/chunks/position-Bx0n9Xgs.js +3 -0
  35. package/dist/chunks/position-Bx0n9Xgs.js.map +1 -0
  36. package/dist/chunks/sheet-Dje0MQib.js +3 -0
  37. package/dist/chunks/sheet-Dje0MQib.js.map +1 -0
  38. package/dist/chunks/sidebar-DA1aYsdf.js +3 -0
  39. package/dist/chunks/sidebar-DA1aYsdf.js.map +1 -0
  40. package/dist/chunks/tabbar-B2BkNJJw.js +3 -0
  41. package/dist/chunks/tabbar-B2BkNJJw.js.map +1 -0
  42. package/dist/chunks/tabs-CUFBy_Bw.js +3 -0
  43. package/dist/chunks/tabs-CUFBy_Bw.js.map +1 -0
  44. package/dist/chunks/toast-YwwbcxDG.js +3 -0
  45. package/dist/chunks/toast-YwwbcxDG.js.map +1 -0
  46. package/dist/chunks/toolbar-BxJFkGlB.js +3 -0
  47. package/dist/chunks/toolbar-BxJFkGlB.js.map +1 -0
  48. package/dist/chunks/tooltip-COC1Ta6M.js +3 -0
  49. package/dist/chunks/tooltip-COC1Ta6M.js.map +1 -0
  50. package/dist/chunks/webgl-backend-BE1U7Yp0.js +294 -0
  51. package/dist/chunks/webgl-backend-BE1U7Yp0.js.map +1 -0
  52. package/dist/css/abgin.css +2 -0
  53. package/dist/css/background.css +2 -0
  54. package/dist/css/base.css +2 -0
  55. package/dist/css/components/accordion.css +2 -0
  56. package/dist/css/components/alert.css +2 -0
  57. package/dist/css/components/appbar.css +2 -0
  58. package/dist/css/components/badge.css +2 -0
  59. package/dist/css/components/breadcrumbs.css +2 -0
  60. package/dist/css/components/button.css +2 -0
  61. package/dist/css/components/card.css +2 -0
  62. package/dist/css/components/checkbox.css +2 -0
  63. package/dist/css/components/code.css +2 -0
  64. package/dist/css/components/divider.css +2 -0
  65. package/dist/css/components/drawer.css +2 -0
  66. package/dist/css/components/dropdown.css +2 -0
  67. package/dist/css/components/field.css +2 -0
  68. package/dist/css/components/icon.css +2 -0
  69. package/dist/css/components/input.css +2 -0
  70. package/dist/css/components/join.css +2 -0
  71. package/dist/css/components/kbd.css +2 -0
  72. package/dist/css/components/link.css +2 -0
  73. package/dist/css/components/list.css +2 -0
  74. package/dist/css/components/menu.css +2 -0
  75. package/dist/css/components/modal.css +2 -0
  76. package/dist/css/components/navbar.css +2 -0
  77. package/dist/css/components/pagination.css +2 -0
  78. package/dist/css/components/popover.css +2 -0
  79. package/dist/css/components/progress.css +2 -0
  80. package/dist/css/components/radio.css +2 -0
  81. package/dist/css/components/range.css +2 -0
  82. package/dist/css/components/search.css +2 -0
  83. package/dist/css/components/segmented.css +2 -0
  84. package/dist/css/components/select.css +2 -0
  85. package/dist/css/components/sheet.css +2 -0
  86. package/dist/css/components/shell.css +2 -0
  87. package/dist/css/components/sidebar.css +2 -0
  88. package/dist/css/components/spinner.css +2 -0
  89. package/dist/css/components/tabbar.css +2 -0
  90. package/dist/css/components/table.css +2 -0
  91. package/dist/css/components/tabs.css +2 -0
  92. package/dist/css/components/textarea.css +2 -0
  93. package/dist/css/components/toast.css +2 -0
  94. package/dist/css/components/toggle.css +2 -0
  95. package/dist/css/components/toolbar.css +2 -0
  96. package/dist/css/components/tooltip.css +2 -0
  97. package/dist/css/glass/appbar.css +2 -0
  98. package/dist/css/glass/base.css +2 -0
  99. package/dist/css/glass/button.css +2 -0
  100. package/dist/css/glass/card.css +2 -0
  101. package/dist/css/glass/checkbox.css +2 -0
  102. package/dist/css/glass/drawer.css +2 -0
  103. package/dist/css/glass/dropdown.css +2 -0
  104. package/dist/css/glass/join.css +2 -0
  105. package/dist/css/glass/modal.css +2 -0
  106. package/dist/css/glass/navbar.css +2 -0
  107. package/dist/css/glass/popover.css +2 -0
  108. package/dist/css/glass/radio.css +2 -0
  109. package/dist/css/glass/range.css +2 -0
  110. package/dist/css/glass/search.css +2 -0
  111. package/dist/css/glass/segmented.css +2 -0
  112. package/dist/css/glass/sheet.css +2 -0
  113. package/dist/css/glass/sidebar.css +2 -0
  114. package/dist/css/glass/tabbar.css +2 -0
  115. package/dist/css/glass/tabs.css +2 -0
  116. package/dist/css/glass/toast.css +2 -0
  117. package/dist/css/glass/toggle.css +2 -0
  118. package/dist/css/glass/toolbar.css +2 -0
  119. package/dist/css/glass/tooltip.css +2 -0
  120. package/dist/css/glass/vivid.css +2 -0
  121. package/dist/css/glass.css +2 -0
  122. package/dist/css/layers.css +2 -0
  123. package/dist/css/prose.css +2 -0
  124. package/dist/css/standard.css +2 -0
  125. package/dist/css/themes/dark.css +2 -0
  126. package/dist/css/themes/light.css +2 -0
  127. package/dist/css/tokens.css +2 -0
  128. package/dist/css/utilities.css +2 -0
  129. package/dist/index.d.ts +67 -0
  130. package/dist/manifest.json +1196 -0
  131. package/package.json +69 -3
@@ -0,0 +1,294 @@
1
+ /*! @abgin/abgin 0.1.2 | MIT License */
2
+ import{i as e,r as t,t as n}from"./optics-BSQ3SSNg.js";const r=e=>Math.min(1,Math.max(0,e));function i(e){return e.length<=256?e:Array.from({length:256},(t,n)=>e[Math.floor(n*.6180339887498949%1*e.length)]??0)}function a(e,t,n){let i=r((n-e)/(t-e));return i*i*(3-2*i)}function o(e,t,n,i,a,o){let s=.2126*e+.7152*t+.0722*n,c=e=>r((s+(e-s)*i)*a)*(1-o);return[c(e),c(t),c(n)]}function s(n,r,i,a,o){let s=o=>t(e(n[0]+(r[0]-n[0])*o,n[1]+(r[1]-n[1])*o,n[2]+(r[2]-n[2])*o),i)>=a;if(s(o))return o;if(!s(1))return 1;let c=o,l=1;for(let e=0;e<16;e++){let e=(c+l)/2;s(e)?l=e:c=e}return l}function c(e,t,n,r,i,a,o){let s=e.width/t,c=e.height/n,l=Math.min(e.width-1,Math.max(0,Math.floor(r*s))),u=Math.min(e.height-1,Math.max(0,Math.floor(i*c)));return[l,u,Math.min(e.width-1,Math.max(l,Math.ceil(a*s)-1)),Math.min(e.height-1,Math.max(u,Math.ceil(o*c)-1))]}function l(e,[t,n,r,i]){let a=[];for(let o=n;o<=i;o++)for(let n=t;n<=r;n++)a.push(o*e.width+n);return a}function u(e,t){return e.tint===t.tint&&e.labelLuminance===t.labelLuminance&&e.target===t.target&&e.saturation===t.saturation&&e.brightness===t.brightness&&e.dim===t.dim&&e.adaptivity===t.adaptivity&&e.fill.every((e,n)=>e===t.fill[n])}function d(e){let t=r(e.fill[3]*e.tint);return{baseAlpha:t,designAlpha:t,dim:e.dim,lightScale:1,blurScale:1,mean:NaN,deviation:NaN,cells:0}}function f(t,n,c){if(!n.length)return d(c);let l=i(n),u=r(c.adaptivity),f=l.map(n=>e(t.rgb[n*3]??0,t.rgb[n*3+1]??0,t.rgb[n*3+2]??0)),p=f.reduce((e,t)=>e+t,0)/f.length,m=Math.sqrt(f.reduce((e,t)=>e+(t-p)**2,0)/f.length),h=r(c.fill[3]*c.tint),g=c.dim*(1-u+u*a(.08,.3,p)),_=[c.fill[0],c.fill[1],c.fill[2]],v=l.map(e=>s(o(t.rgb[e*3]??0,t.rgb[e*3+1]??0,t.rgb[e*3+2]??0,c.saturation,c.brightness,g),_,c.labelLuminance,c.target,h)).sort((e,t)=>e-t);return{baseAlpha:h+u*((v[Math.floor(.9*(v.length-1))]??h)-h),designAlpha:h,dim:g,lightScale:1+u*(.25-.5*p),blurScale:1+u*.5*a(.08,.25,m),mean:p,deviation:m,cells:l.length}}function p(e,t,n,r=400){let i=1-Math.exp(-Math.max(0,n)/r),a=(e,t)=>e+(t-e)*i;return{...t,baseAlpha:a(e.baseAlpha,t.baseAlpha),dim:a(e.dim,t.dim),lightScale:a(e.lightScale,t.lightScale),blurScale:a(e.blurScale,t.blurScale)}}const m=2048;function h(e,t=m){let n=e.map((e,t)=>t).sort((t,n)=>(e[n]?.height??0)-(e[t]?.height??0)||t-n),r=0,i=0;for(let{width:n,height:a}of e)n>t||a>t||(r+=n*a,i=Math.max(i,n));let a=Math.min(t,Math.max(i,Math.ceil(Math.sqrt(r)*1.1/256)*256)),o=[],s=[],c=0,l=0,u=0,d=0,f=()=>{s.length&&o.push({width:c,height:u+d,places:s}),s=[],c=l=u=d=0};for(let r of n){let n=e[r];n.width>t||n.height>t?o.push({width:n.width,height:n.height,places:[{index:r,x:0,y:0}]}):(l+n.width>a&&(u+=d,l=d=0),u+n.height>t&&f(),s.push({index:r,x:l,y:u}),l+=n.width,c=Math.max(c,l),d=Math.max(d,n.height))}return f(),o}function g(e){return e>0&&Number.isFinite(e)?Math.max(0,Math.floor(Math.log2(e/1.25))):0}const _=e=>`#version 300 es
3
+ precision highp float;
4
+ precision highp int;
5
+ in vec2 vPos;
6
+ out vec4 outColor;
7
+
8
+ #define MAX_SHAPES ${e}
9
+
10
+ uniform sampler2D uSource;
11
+ uniform vec2 uSize; // layer size, device px
12
+ uniform vec4 uRegion; // the layer's rectangle in source px: x, y, width, height
13
+ uniform vec4 uVisible; // visible image bounds in source px: x0, y0, x1, y1
14
+ uniform vec2 uNatural; // source size in source px
15
+ uniform float uTexelScale; // texels per source px (below 1 when a large source was downscaled)
16
+ uniform float uBevel, uThickness, uIor, uMaxShift, uLens, uBlur, uDispersion; // lengths in device px
17
+ uniform int uTaps; // 1, 5 (balanced), or 13 (ultra)
18
+ uniform float uSaturation, uBrightness, uSpecular, uRim, uEdge;
19
+ uniform vec2 uLight; // unit vector toward the light, y down
20
+ uniform float uMinContrast; // 0 disables the legibility floor; the target is per shape (uShapeB.z)
21
+ uniform int uMode;
22
+ uniform vec4 uVisibleUv; // visible image bounds in texture coordinates: x0, y0, x1, y1
23
+
24
+ // Shapes (D-76), in layer device px. Material values are per shape and blended by the field's weights.
25
+ uniform int uShapeCount; // 1 to MAX_SHAPES
26
+ uniform vec4 uShapeBox[MAX_SHAPES]; // center x, y; half width, half height
27
+ uniform vec4 uShapeRadii[MAX_SHAPES]; // top-left, top-right, bottom-right, bottom-left
28
+ uniform vec4 uShapeFill[MAX_SHAPES]; // design fill: straight sRGB color and alpha
29
+ uniform vec4 uShapeA[MAX_SHAPES]; // corner exponent, label luminance, base alpha (D-75), dim
30
+ uniform vec4 uShapeB[MAX_SHAPES]; // edge light scale, scattering scale (D-75), contrast target, glow (D-79)
31
+ uniform float uMergeK; // smooth-union radius, device px; 0: plain union
32
+ uniform float uMergeP; // smooth-union exponent (2 to 6)
33
+ uniform vec3 uPointer; // pointer x, y and light radius in layer device px; radius 0: none (D-79)
34
+
35
+ float weights[MAX_SHAPES];
36
+
37
+ float srgbLum(vec3 c) {
38
+ vec3 l = mix(c / 12.92, pow((c + 0.055) / 1.055, vec3(2.4)), step(vec3(0.04045), c));
39
+ return dot(l, vec3(0.2126, 0.7152, 0.0722));
40
+ }
41
+ bool legible(vec3 c, float label, float target) {
42
+ float a = srgbLum(c);
43
+ return (max(a, label) + 0.05) / (min(a, label) + 0.05) >= target;
44
+ }
45
+
46
+ // One corner's curve: signed distance (x) and normal (yz, toward the corner) at the offset q from the curve's center
47
+ // toward the corner, both components positive. Circular corners give the exact distance; superellipse corners the
48
+ // first-order estimate (L - r) / |grad L| of the p-norm L.
49
+ vec3 cornerField(vec2 q, float r, float e) {
50
+ if (e == 2.0) {
51
+ float l = length(q);
52
+ return vec3(l - r, q / l);
53
+ }
54
+ float l = pow(pow(q.x, e) + pow(q.y, e), 1.0 / e);
55
+ if (l <= 0.0) return vec3(-r, 1.0, 0.0);
56
+ vec2 grad = pow(q / l, vec2(e - 1.0));
57
+ float len = length(grad);
58
+ return vec3((l - r) / len, grad / len);
59
+ }
60
+
61
+ // Signed distance (x) and outward normal (yz) of shape i for every radius CSS allows (D-77): the box cut by each
62
+ // corner's curve inside that corner's square. Adjacent squares never overlap; opposite ones can, when a radius passes
63
+ // the center line. Inside a square its curve replaces the corner's two edges; the nearest bound counts.
64
+ vec3 shapeField(int i, vec2 p) {
65
+ vec4 box = uShapeBox[i];
66
+ vec4 rr = uShapeRadii[i];
67
+ float e = uShapeA[i].x;
68
+ vec2 d = p - box.xy;
69
+ vec4 edges = vec4(-d.x, d.x, -d.y, d.y) - box.zzww; // left, right, top, bottom
70
+ vec2 qtl = edges.xz + rr.x;
71
+ vec2 qtr = edges.yz + rr.y;
72
+ vec2 qbr = edges.yw + rr.z;
73
+ vec2 qbl = edges.xw + rr.w;
74
+ bool tl = min(qtl.x, qtl.y) > 0.0;
75
+ bool tr = min(qtr.x, qtr.y) > 0.0;
76
+ bool br = min(qbr.x, qbr.y) > 0.0;
77
+ bool bl = min(qbl.x, qbl.y) > 0.0;
78
+ vec3 f = vec3(-1e9, 0.0, 0.0);
79
+ if (!tl && !bl) f = vec3(edges.x, -1.0, 0.0);
80
+ if (!tr && !br && edges.y >= f.x) f = vec3(edges.y, 1.0, 0.0);
81
+ if (!tl && !tr && edges.z >= f.x) f = vec3(edges.z, 0.0, -1.0);
82
+ if (!bl && !br && edges.w >= f.x) f = vec3(edges.w, 0.0, 1.0);
83
+ if (tl || tr) {
84
+ vec3 c = cornerField(tl ? qtl : qtr, tl ? rr.x : rr.y, e);
85
+ if (c.x >= f.x) f = vec3(c.x, tl ? -c.y : c.y, -c.z);
86
+ }
87
+ if (bl || br) {
88
+ vec3 c = cornerField(bl ? qbl : qbr, bl ? rr.w : rr.z, e);
89
+ if (c.x >= f.x) f = vec3(c.x, bl ? -c.y : c.y, c.z);
90
+ }
91
+ return f;
92
+ }
93
+
94
+ // The field of all shapes: a left fold of the polynomial smooth minimum f(h) = h^p / (2p) (shape.ts, sceneField).
95
+ // Fills weights[] with each shape's share. The gradient is the weighted sum of the normals (shorter than 1 where a
96
+ // junction blends two of them), which fades refraction and highlights smoothly across a junction.
97
+ vec3 scene(vec2 p) {
98
+ vec3 acc = shapeField(0, p);
99
+ weights[0] = 1.0;
100
+ for (int i = 1; i < MAX_SHAPES; i++) {
101
+ if (i >= uShapeCount) break;
102
+ vec3 f = shapeField(i, p);
103
+ float share;
104
+ float dist;
105
+ if (uMergeK > 0.0) {
106
+ float h = max(uMergeK - abs(acc.x - f.x), 0.0) / uMergeK;
107
+ float fp = 0.5 * pow(h, uMergeP - 1.0);
108
+ dist = min(acc.x, f.x) - uMergeK * pow(h, uMergeP) / (2.0 * uMergeP);
109
+ share = acc.x <= f.x ? 1.0 - fp : fp;
110
+ } else {
111
+ dist = min(acc.x, f.x);
112
+ share = acc.x <= f.x ? 1.0 : 0.0;
113
+ }
114
+ for (int j = 0; j < MAX_SHAPES; j++) {
115
+ if (j >= i) break;
116
+ weights[j] *= share;
117
+ }
118
+ weights[i] = 1.0 - share;
119
+ acc = vec3(dist, acc.yz * share + f.yz * (1.0 - share));
120
+ }
121
+ return acc;
122
+ }
123
+
124
+ vec2 rimOffset(float d, vec2 g, float ior) {
125
+ float depth = -d;
126
+ if (depth <= 0.0 || depth >= uBevel || uBevel <= 0.0 || uThickness <= 0.0 || ior <= 1.0) return vec2(0.0);
127
+ float t = depth / uBevel;
128
+ float slope = uThickness * 2.0 * (1.0 - t) / uBevel;
129
+ vec3 n = normalize(vec3(slope * g, 1.0));
130
+ vec3 r = refract(vec3(0.0, 0.0, -1.0), n, 1.0 / ior);
131
+ float height = uThickness * (1.0 - (1.0 - t) * (1.0 - t));
132
+ return r.xy / max(-r.z, 1e-3) * height;
133
+ }
134
+
135
+ vec2 displacement(float d, vec2 g, vec2 p, vec2 center, float ior) {
136
+ vec2 v = rimOffset(d, g, ior) + (p - center) * (1.0 / (1.0 + 0.5 * uLens) - 1.0);
137
+ float m = length(v);
138
+ if (m > uMaxShift && m > 0.0) v *= uMaxShift / m;
139
+ return v;
140
+ }
141
+
142
+ vec2 sourceUv(vec2 p, vec2 disp) {
143
+ vec2 src = uRegion.xy + (p + disp) * (uRegion.zw / uSize);
144
+ src = clamp(src, uVisible.xy + 0.5, max(uVisible.zw - 0.5, uVisible.xy + 0.5));
145
+ return src / uNatural;
146
+ }
147
+
148
+ // Keeps a scattering tap, and the texels its mipmap level averages, inside the visible image: an object-fit crop
149
+ // must not leak pixels the page does not show (D-75). The inset is 1.5 texels of the coarser level in use.
150
+ vec2 inside(vec2 uv, float lod, vec2 texel) {
151
+ vec2 inset = texel * 1.5 * exp2(ceil(lod));
152
+ vec2 lo = uVisibleUv.xy + inset;
153
+ return clamp(uv, lo, max(uVisibleUv.zw - inset, lo));
154
+ }
155
+
156
+ vec4 scatter(vec2 uv, float blur) {
157
+ float radius = blur * (uRegion.z / uSize.x) * uTexelScale; // blur radius in texels
158
+ if (radius < 0.5) return textureLod(uSource, uv, 0.0);
159
+ // The mip level averages about the blur radius; the taps smooth the box edges of that level. Ultra uses a
160
+ // finer level and two rings, so thin high-contrast lines do not leave a tap pattern.
161
+ bool ultra = uTaps >= 13;
162
+ float lod = log2(max(radius * (ultra ? 0.6 : 1.0), 1.0));
163
+ vec2 texel = 1.0 / vec2(textureSize(uSource, 0));
164
+ vec4 sum = textureLod(uSource, inside(uv, lod, texel), lod) * 2.0;
165
+ float weight = 2.0;
166
+ if (uTaps >= 5) {
167
+ float r = ultra ? 0.4 : 0.5;
168
+ for (int i = 0; i < 4; i++) {
169
+ float a = 0.7853982 + float(i) * 1.5707963;
170
+ sum += textureLod(uSource, inside(uv + vec2(cos(a), sin(a)) * radius * r * texel, lod, texel), lod);
171
+ }
172
+ weight += 4.0;
173
+ }
174
+ if (ultra) {
175
+ for (int i = 0; i < 8; i++) {
176
+ float a = float(i) * 0.7853982;
177
+ sum += textureLod(uSource, inside(uv + vec2(cos(a), sin(a)) * radius * 0.85 * texel, lod, texel), lod) * 0.75;
178
+ }
179
+ weight += 6.0;
180
+ }
181
+ return sum / weight;
182
+ }
183
+
184
+ void main() {
185
+ // Exact pixel centers keep nearest-edge ties consistent across atlas viewports.
186
+ vec2 pixel = floor(vPos) + vec2(0.5);
187
+ vec3 f = scene(pixel);
188
+ float d = f.x;
189
+ vec2 g = f.yz;
190
+ // The distance over the gradient length gives a correct edge width at junctions; one shape keeps the exact
191
+ // Phase 04 coverage (its gradient is a unit vector).
192
+ float coverage = clamp(0.5 - (uShapeCount > 1 ? d / max(length(g), 0.25) : d), 0.0, 1.0);
193
+ // Every pixel is written (no discard), so the shared canvas needs no clear between surfaces.
194
+ if (coverage <= 0.0) { outColor = vec4(0.0); return; }
195
+ // Per-pixel material: the shapes' values blended by their weights.
196
+ vec4 fill = vec4(0.0);
197
+ vec2 center = vec2(0.0);
198
+ float baseAlpha = 0.0, dim = 0.0, lightScale = 0.0, blurScale = 0.0, glow = 0.0;
199
+ for (int i = 0; i < MAX_SHAPES; i++) {
200
+ if (i >= uShapeCount) break;
201
+ float w = weights[i];
202
+ fill += uShapeFill[i] * w;
203
+ center += uShapeBox[i].xy * w;
204
+ baseAlpha += uShapeA[i].z * w;
205
+ dim += uShapeA[i].w * w;
206
+ lightScale += uShapeB[i].x * w;
207
+ blurScale += uShapeB[i].y * w;
208
+ glow += uShapeB[i].w * w;
209
+ }
210
+ float blur = uBlur * blurScale;
211
+ vec2 disp = displacement(d, g, pixel, center, uIor);
212
+ if (uMode == 2) {
213
+ outColor = vec4(uMaxShift > 0.0 ? disp / (2.0 * uMaxShift) + 0.5 : vec2(0.5), 0.5, 1.0);
214
+ return;
215
+ }
216
+ vec4 src;
217
+ if (uDispersion > 0.0) {
218
+ vec4 green = scatter(sourceUv(pixel, disp), blur);
219
+ float red = scatter(sourceUv(pixel, displacement(d, g, pixel, center, uIor * (1.0 - 0.03 * uDispersion))), blur).r;
220
+ float blue = scatter(sourceUv(pixel, displacement(d, g, pixel, center, uIor * (1.0 + 0.03 * uDispersion))), blur).b;
221
+ src = vec4(red, green.g, blue, green.a);
222
+ } else {
223
+ src = scatter(sourceUv(pixel, disp), blur);
224
+ }
225
+ // Textures are premultiplied; colors below are straight.
226
+ vec3 col = src.a > 0.0 ? clamp(src.rgb / src.a, 0.0, 1.0) : vec3(0.0);
227
+ if (uMode == 1) { outColor = vec4(col, 1.0) * src.a * coverage; return; }
228
+
229
+ float luma = dot(col, vec3(0.2126, 0.7152, 0.0722));
230
+ vec3 base = clamp(mix(vec3(luma), col, uSaturation) * uBrightness, 0.0, 1.0) * (1.0 - dim);
231
+ float depth = -d;
232
+ float rimZone = clamp(1.0 - depth / max(uBevel, 1.0), 0.0, 1.0);
233
+ float facing = max(dot(g, uLight), 0.0);
234
+ float spec = uSpecular * pow(facing, 6.0) * rimZone * rimZone;
235
+ float rim = uRim * (1.0 - smoothstep(0.0, uEdge + 1.0, depth));
236
+ // Interaction light (D-79): the rim and the highlight brighten and the surface lifts a little, most around the pointer.
237
+ // It is part of the light the legibility floor attenuates.
238
+ float spot = 0.0;
239
+ if (uPointer.z > 0.0) {
240
+ vec2 to = (pixel - uPointer.xy) / uPointer.z;
241
+ spot = exp(-dot(to, to));
242
+ }
243
+ vec3 light = vec3(spec + rim * 0.6) * lightScale * (1.0 + 0.8 * glow) + vec3(glow * (0.06 + 0.18 * spot));
244
+ float a = clamp(baseAlpha, 0.0, 1.0);
245
+ vec3 c = clamp(mix(base, fill.rgb, a) + light, 0.0, 1.0);
246
+ // Legibility floor (D-58): a pixel that would fall below the label contrast target gets only the extra tint
247
+ // it needs; if the lighting alone breaks the target at full tint, the lighting is attenuated first. The rim
248
+ // line (uEdge + 1 px) is exempt: labels never sit there.
249
+ // In a group each contributing shape's floor is computed against its own label and target, and the results are
250
+ // blended by the shapes' weights, so the tint stays continuous across a junction between different colors.
251
+ if (uMinContrast > 0.0 && depth > uEdge + 1.0) {
252
+ float aSum = 0.0, kSum = 0.0;
253
+ for (int s = 0; s < MAX_SHAPES; s++) {
254
+ if (s >= uShapeCount) break;
255
+ float w = weights[s];
256
+ if (w <= 0.0) continue;
257
+ float label = uShapeA[s].y;
258
+ float goal = uShapeB[s].z;
259
+ float ks = 1.0;
260
+ float as = a;
261
+ if (!legible(c, label, goal)) {
262
+ if (!legible(clamp(fill.rgb + light, 0.0, 1.0), label, goal)) {
263
+ float lo = 0.0, hi = 1.0;
264
+ for (int i = 0; i < 10; i++) {
265
+ float m = 0.5 * (lo + hi);
266
+ if (legible(clamp(fill.rgb + light * m, 0.0, 1.0), label, goal)) lo = m; else hi = m;
267
+ }
268
+ ks = lo;
269
+ }
270
+ float lo = a, hi = 1.0;
271
+ for (int i = 0; i < 10; i++) {
272
+ float m = 0.5 * (lo + hi);
273
+ if (legible(clamp(mix(base, fill.rgb, m) + light * ks, 0.0, 1.0), label, goal)) hi = m; else lo = m;
274
+ }
275
+ as = hi;
276
+ }
277
+ aSum += w * as;
278
+ kSum += w * ks;
279
+ }
280
+ a = aSum;
281
+ c = clamp(mix(base, fill.rgb, a) + light * kSum, 0.0, 1.0);
282
+ }
283
+ float alpha = coverage * (src.a + (1.0 - src.a) * a);
284
+ outColor = vec4(c * alpha, alpha);
285
+ }`,v=/swiftshader|llvmpipe|softpipe|microsoft basic render|\bwarp\b/i,y=/* @__PURE__ */ `uSource.uSize.uRegion.uVisible.uNatural.uTexelScale.uBevel.uThickness.uIor.uMaxShift.uLens.uBlur.uDispersion.uTaps.uSaturation.uBrightness.uSpecular.uRim.uEdge.uLight.uMinContrast.uMode.uVisibleUv.uShapeCount.uShapeBox.uShapeRadii.uShapeFill.uShapeA.uShapeB.uMergeK.uMergeP.uPointer`.split(`.`),b={material:0,backdrop:1,displacement:2},ee=[0,0,0,0],x=2e3;function te(n,r,i){let a=n=>n!==null&&n[3]>0&&t(e(n[0],n[1],n[2]),i)>=4.5;if(a(n))return n;if(a(r))return[r[0],r[1],r[2],n[3]];let o=+(t(1,i)>=t(0,i));return[o,o,o,n[3]]}function S(t={}){let r=t.output??`material`,i=null,a=null,o=null,s=null,S=0,C=null,w=null,T=null,E={},D=4096,O=4096,k=``,A=!1,j=!1,M=/* @__PURE__ */ new Map,N=/* @__PURE__ */ new Map,P=/* @__PURE__ */ new Map,F={uShapeBox:/* @__PURE__ */ new Float32Array(64),uShapeRadii:/* @__PURE__ */ new Float32Array(64),uShapeFill:/* @__PURE__ */ new Float32Array(64),uShapeA:/* @__PURE__ */ new Float32Array(64),uShapeB:/* @__PURE__ */ new Float32Array(64)},I=/* @__PURE__ */ new Map,L=null,R=/* @__PURE__ */ new Map,z=null,B=null,V=null,H=null,U=0,W=[],G=[],K={initMs:0,uploads:0,uploadMs:0,lastUploadMs:0,renders:0,surfaces:0,lastRenderMs:0,maxRenderMs:0,backdropReads:0,asyncReads:0,backdropReadMs:0,lastBackdropReadMs:0},q=[],J=()=>{A=!0,i?.lost(`WebGL 2 context lost`)};function ne(e,t){let n=o,r=n.createShader(e);if(!r)throw Error(`WebGL 2 could not create a shader.`);return n.shaderSource(r,t),n.compileShader(r),r}async function re(e){let t=o,n=t.createProgram(),r=[ne(t.VERTEX_SHADER,`#version 300 es
286
+ in vec2 aCorner;
287
+ uniform vec2 uSize;
288
+ out vec2 vPos;
289
+ void main() {
290
+ // Surface-local device pixels, y down; the viewport covers exactly the surface.
291
+ vPos = aCorner * uSize;
292
+ gl_Position = vec4(aCorner.x * 2.0 - 1.0, 1.0 - aCorner.y * 2.0, 0.0, 1.0);
293
+ }`),ne(t.FRAGMENT_SHADER,_(e))];for(let e of r)t.attachShader(n,e);t.bindAttribLocation(n,0,`aCorner`),t.linkProgram(n);let i=t.getExtension(`KHR_parallel_shader_compile`);if(i)for(;;){if(j||t.isContextLost())throw Error(`The WebGL 2 backend was disposed during compilation.`);if(t.getProgramParameter(n,i.COMPLETION_STATUS_KHR))break;await new Promise(e=>setTimeout(e,4))}if(!t.getProgramParameter(n,t.LINK_STATUS)&&!t.isContextLost()){let e=r.map(e=>t.getShaderInfoLog(e)).filter(Boolean);throw Error(`WebGL 2 program failed: ${[t.getProgramInfoLog(n),...e].filter(Boolean).join(`; `)}`)}for(let e of r)t.deleteShader(e);return n}function ie(e,t){let n=o;s&&n.deleteProgram(s),s=e,S=t,E=Object.fromEntries(y.map(t=>[t,n.getUniformLocation(e,t)])),ae()}function ae(){let e=o,t=e.createTexture();e.bindTexture(e.TEXTURE_2D,t),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,/* @__PURE__ */ new Uint8Array(4)),e.useProgram(s),e.bindVertexArray(w),e.viewport(0,0,1,1),X(`uSize`,1,1),X(`uRegion`,0,0,1,1),X(`uVisible`,0,0,1,1),X(`uNatural`,1,1),X(`uTexelScale`,1),X(`uMode`,b[r]),e.drawArrays(e.TRIANGLE_STRIP,0,4),e.bindVertexArray(null),e.deleteTexture(t)}function Y(e){let t=R.get(e);if(t!==void 0)return t;let n=null;if(e&&typeof CSS<`u`&&CSS.supports(`color`,e)){z??=Object.assign(document.createElement(`canvas`),{width:1,height:1});let t=z.getContext(`2d`,{willReadFrequently:!0});if(t){t.clearRect(0,0,1,1),t.fillStyle=e,t.fillRect(0,0,1,1);let[r=0,i=0,a=0,o=0]=t.getImageData(0,0,1,1).data;n=[r/255,i/255,a/255,o/255]}}return R.size>256&&R.clear(),R.set(e,n),n}function oe(e,t){let n=o;se(e.id);let r=M.get(e.id);if(r?.version===e.version&&r.element===e.element&&r.level<=t)return r;let i=performance.now(),a=Math.max(e.width,e.height),s=Math.min(1/2**t,a>D?D/a:1),c=Math.max(1,Math.round(e.width*s)),l=Math.max(1,Math.round(e.height*s)),u=e.element;if(s<1){B??=document.createElement(`canvas`),B.width=c,B.height=l;let t=B.getContext(`2d`);t&&(t.imageSmoothingQuality=`high`,t.drawImage(e.element,0,0,c,l)),u=B}let d=r??{texture:n.createTexture(),element:e.element,version:-1,width:0,height:0,texWidth:0,texHeight:0,level:0,changedAt:-1/0,continuous:!1,grid:null,gridVersion:-1,gridAt:-1/0,pending:null,packBuffer:null,poll:null,settling:!1,quiet:!1,fires:0};n.bindTexture(n.TEXTURE_2D,d.texture),n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,!1),n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!0),d.texWidth===c&&d.texHeight===l?n.texSubImage2D(n.TEXTURE_2D,0,0,0,n.RGBA,n.UNSIGNED_BYTE,u):(n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,u),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR_MIPMAP_LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE)),n.generateMipmap(n.TEXTURE_2D),d.fires=0;let f=performance.now();return(d.version!==e.version||d.element!==e.element)&&(d.continuous=f-d.changedAt<300,d.changedAt=f),Object.assign(d,{element:e.element,version:e.version,width:e.width,height:e.height,texWidth:c,texHeight:l,level:t}),M.set(e.id,d),K.uploads++,K.lastUploadMs=performance.now()-i,K.uploadMs+=K.lastUploadMs,d}function se(e){let t=I.get(e);t!==void 0&&(clearTimeout(t),I.delete(e))}function ce(e){se(e);let t=M.get(e);t&&(M.delete(e),o&&!o.isContextLost()&&le(o,t))}function le(e,t){t.poll!==null&&clearTimeout(t.poll),t.poll=null,t.pending&&e.deleteSync(t.pending.sync),t.packBuffer&&e.deleteBuffer(t.packBuffer),t.pending=null,t.packBuffer=null,e.deleteTexture(t.texture)}function ue(e){for(let t of N.values())if(t.sourceId===e)return;M.has(e)&&!I.has(e)&&I.set(e,setTimeout(()=>{I.delete(e);for(let t of N.values())if(t.sourceId===e)return;ce(e)},1e3))}function de(e,t,n){t>e.width&&(e.width=Math.min(O,Math.ceil(t/256)*256)),n>e.height&&(e.height=Math.min(O,Math.ceil(n/256)*256))}function fe(){H??=setTimeout(()=>{if(H=null,!j&&a){if(performance.now()-U<x)fe();else{for(let e of W.splice(0))o?.deleteSync(e);for(let e of[V?.canvas,B])e&&(e.width=e.height=0);a.width*a.height>1048576&&(a.width=a.height=256)}}},x)}function pe(){let e=o;if(!e)return 0;let t=0;for(;t<W.length&&e.getSyncParameter(W[t],e.SYNC_STATUS)===e.SIGNALED;)t++;for(let n of W.splice(0,t))e.deleteSync(n);return W.length}function X(e,...t){let n=o,r=E[e]??null;e===`uTaps`||e===`uMode`||e===`uSource`||e===`uShapeCount`?n.uniform1i(r,t[0]??0):t.length===1?n.uniform1f(r,t[0]??0):t.length===2?n.uniform2f(r,t[0]??0,t[1]??0):t.length===3?n.uniform3f(r,t[0]??0,t[1]??0,t[2]??0):n.uniform4f(r,t[0]??0,t[1]??0,t[2]??0,t[3]??0)}function me(e,t,n){let r=new Float32Array(t*n*3);for(let i=0;i<t*n;i++){let t=(e[i*4+3]??0)/255;for(let n=0;n<3;n++)r[i*3+n]=t>0?Math.min(1,(e[i*4+n]??0)/255/t):0}return{width:t,height:n,rgb:r}}function Z(e,t){t.poll!==null&&clearTimeout(t.poll),t.poll=null,!t.pending&&!t.settling||t.fires>=60||(t.poll=setTimeout(()=>{if(t.poll=null,j||!o||o.isContextLost()||M.get(e)!==t)return;t.fires++;let n=he(t);performance.now()-t.changedAt<300?Z(e,t):(!n&&!t.pending&&t.gridVersion!==t.version&&(t.quiet=!0),n||t.settling||t.quiet?i?.redraw?.(e):Z(e,t))},50))}function he(e){let t=o,n=e.pending;if(!n||t.getSyncParameter(n.sync,t.SYNC_STATUS)!==t.SIGNALED)return!1;let r=performance.now(),i=new Uint8Array(n.width*n.height*4);t.bindBuffer(t.PIXEL_PACK_BUFFER,e.packBuffer),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,i),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteSync(n.sync),e.pending=null;let a=n.version>=e.gridVersion;return a&&(e.grid=me(i,n.width,n.height),e.gridVersion=n.version),K.backdropReadMs+=performance.now()-r,a}function ge(e){let t=o;he(e);let n=performance.now(),r=e.continuous&&!e.quiet&&n-e.gridAt<200;if(e.grid&&(e.gridVersion===e.version||r)||e.continuous&&e.grid&&e.pending)return e.grid;let i=n,a=0,s=e.texWidth,c=e.texHeight;for(;Math.max(s,c)>128;)a++,s=Math.max(1,s>>1),c=Math.max(1,c>>1);L??=t.createFramebuffer(),t.bindFramebuffer(t.FRAMEBUFFER,L),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e.texture,a);let l=t.checkFramebufferStatus(t.FRAMEBUFFER)===t.FRAMEBUFFER_COMPLETE,u=l&&e.continuous&&e.grid!==null;if(u){e.packBuffer??=t.createBuffer(),t.bindBuffer(t.PIXEL_PACK_BUFFER,e.packBuffer),t.bufferData(t.PIXEL_PACK_BUFFER,s*c*4,t.STREAM_READ),t.readPixels(0,0,s,c,t.RGBA,t.UNSIGNED_BYTE,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);let n=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);n&&(e.pending={sync:n,width:s,height:c,version:e.version}),t.flush()}else if(l){let n=new Uint8Array(s*c*4);t.readPixels(0,0,s,c,t.RGBA,t.UNSIGNED_BYTE,n),e.grid=me(n,s,c),e.gridVersion=e.version}else e.grid=null,e.gridVersion=e.version;return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,null,0),t.bindFramebuffer(t.FRAMEBUFFER,null),e.gridAt=n,e.quiet=!1,K.backdropReads++,u&&K.asyncReads++,K.lastBackdropReadMs=performance.now()-i,K.backdropReadMs+=K.lastBackdropReadMs,e.grid}function _e(e,t,n,r,i,a){let o=t.optics,s=e.optics,m={fill:r,tint:o.tint,labelLuminance:i,target:a,saturation:o.saturation,brightness:o.brightness,dim:o.dim,adaptivity:o.adaptivity},h=o.adaptivity>0?ge(n):null;h&&n.gridVersion!==n.version&&(n.settling=!0);let g=P.get(t.id),_,v=null;if(h){let{region:n}=t,{visible:r}=e,i=(s.maxShift+s.blur)*e.dpr*(e.region.width/e.pixelWidth),a=Math.max(r.x,n.x-i),o=Math.max(r.y,n.y-i),d=Math.min(r.x+r.width,n.x+n.width+i),p=Math.min(r.y+r.height,n.y+n.height+i),y=c(h,e.source.width,e.source.height,a,o,d,p);v=y,_=g?.grid===h&&g.cells?.every((e,t)=>e===y[t])&&u(g.inputs,m)?g.target:f(h,l(h,y),m)}else _=d(m);let y=_,b=performance.now();return g&&g.element===t.element&&n.continuous&&(y=p(g.material,_,b-g.at),Math.max(Math.abs(y.baseAlpha-_.baseAlpha),Math.abs(y.dim-_.dim),Math.abs(y.lightScale-_.lightScale),Math.abs(y.blurScale-_.blurScale))>.005&&(n.settling=!0)),P.set(t.id,{element:t.element,material:y,at:b,target:_,grid:h,cells:v,inputs:m}),y}function ve(e){let{dpr:t}=e;return{id:e.id,element:e.element,box:[e.pixelWidth/2,e.pixelHeight/2,e.pixelWidth/2,e.pixelHeight/2],radii:[e.radii[0]*t,e.radii[1]*t,e.radii[2]*t,e.radii[3]*t],exponent:2,region:e.region,fill:e.fill,designFill:e.designFill,labelColor:e.labelColor,optics:e.optics}}function Q(e,t){o.uniform4fv(E[e]??null,F[e],0,t*4)}function ye(t,i,c,l){let u=o,d=a,f=oe(t.source,i),p=t.pixelWidth,m=t.pixelHeight,{dpr:h,optics:g,region:_,visible:v}=t,y=t.quality===`ultra`,x=g.lightAngle*Math.PI/180,C=t.shapes?.length?t.shapes:[ve(t)],T=Math.min(C.length,S);for(let r=0;r<T;r++){let i=C[r],a=Y(i.labelColor)??[0,0,0,1],o=e(a[0],a[1],a[2]),s=Y(i.fill),c=te(Y(i.designFill)??s??ee,s,o),{minContrast:l}=i.optics,u=Math.max(l+n,l*1.02),d=_e(t,i,f,c,o,u);F.uShapeBox.set(i.box,r*4),F.uShapeRadii.set(i.radii,r*4),F.uShapeFill.set(c,r*4),F.uShapeA.set([i.exponent,o,d.baseAlpha,d.dim],r*4),F.uShapeB.set([d.lightScale,d.blurScale,u,i.glow??0],r*4)}u.useProgram(s),u.bindVertexArray(w),u.viewport(c,d.height-l-m,p,m),u.activeTexture(u.TEXTURE0),u.bindTexture(u.TEXTURE_2D,f.texture),X(`uSource`,0),X(`uSize`,p,m),X(`uRegion`,_.x,_.y,_.width,_.height),X(`uVisible`,v.x,v.y,v.x+v.width,v.y+v.height),X(`uVisibleUv`,v.x/t.source.width,v.y/t.source.height,(v.x+v.width)/t.source.width,(v.y+v.height)/t.source.height),X(`uNatural`,t.source.width,t.source.height),X(`uTexelScale`,f.texWidth/Math.max(1,t.source.width)),X(`uBevel`,g.bevel*h),X(`uThickness`,g.thickness*h),X(`uIor`,g.ior),X(`uMaxShift`,g.maxShift*h),X(`uLens`,g.lens),X(`uBlur`,g.blur*h),X(`uDispersion`,y?g.dispersion:0),X(`uTaps`,y?13:5),X(`uSaturation`,g.saturation),X(`uBrightness`,g.brightness),X(`uSpecular`,g.specular),X(`uRim`,g.rimLight),X(`uEdge`,g.edgeWidth*h),X(`uLight`,Math.sin(x),-Math.cos(x)),X(`uMinContrast`,+(r===`material`)),X(`uMode`,b[r]),X(`uShapeCount`,T),Q(`uShapeBox`,T),Q(`uShapeRadii`,T),Q(`uShapeFill`,T),Q(`uShapeA`,T),Q(`uShapeB`,T),X(`uMergeK`,t.merge?.k??0),X(`uMergeP`,t.merge?.p??2),X(`uPointer`,t.pointer?.x??0,t.pointer?.y??0,t.pointer?.radius??0),u.drawArrays(u.TRIANGLE_STRIP,0,4)}function be(e){let t=N.get(e.id);if(t?.canvas!==e.layer){let n=e.layer.getContext(`2d`);if(!n)throw Error(`Canvas 2D is unavailable for a layer.`);t={canvas:e.layer,context:n,sourceId:e.source.id},N.set(e.id,t)}if(t.sourceId!==e.source.id){let n=t.sourceId;t.sourceId=e.source.id,ue(n)}return t}function xe(e,t,n){let r=a;if(e.length>1){let e=V??=document.createElement(`canvas`).getContext(`2d`);if(!e)throw Error(`Canvas 2D is unavailable.`);de(e.canvas,t,n),e.globalCompositeOperation=`copy`,e.drawImage(r,0,0,t,n,0,0,t,n),r=e.canvas}for(let{surface:t,place:n}of e){let{pixelWidth:e,pixelHeight:i}=t,{context:a}=be(t);a.clearRect(0,0,e,i),a.drawImage(r,n.x,n.y,e,i,0,0,e,i)}}function $(e,t){G.length<32&&G.push(t instanceof Error?t.message:String(t)),N.get(e.id)?.context.clearRect(0,0,e.pixelWidth,e.pixelHeight)}function Se(){let e=o;if(e&&!e.isContextLost()){for(let t of M.values())le(e,t);for(let t of W)e.deleteSync(t);s&&e.deleteProgram(s),w&&e.deleteVertexArray(w),T&&e.deleteBuffer(T),L&&e.deleteFramebuffer(L),e.getExtension(`WEBGL_lose_context`)?.loseContext()}M.clear(),W.length=0,s=null,S=0,w=null,T=null,L=null,E={},o=null}return{name:`webgl2`,get shapes(){return S>1},get resources(){return+!!o+M.size+N.size+ +!!L},get renders(){return K.renders},get lastRendered(){return q},async init(e){if(j)throw Error(`The WebGL 2 backend was disposed.`);let n=performance.now();i=e,a=document.createElement(`canvas`),a.width=256,a.height=256,a.addEventListener(`webglcontextlost`,J);let r=a.getContext(`webgl2`,{alpha:!0,premultipliedAlpha:!0,antialias:!1,depth:!1,stencil:!1,preserveDrawingBuffer:!1,failIfMajorPerformanceCaveat:!t.allowSoftware});if(!r)throw Error(t.allowSoftware?`WebGL 2 is unavailable.`:`WebGL 2 is unavailable or software-only.`);o=r;let s=r.getExtension(`WEBGL_debug_renderer_info`);if(k=String(r.getParameter(s?s.UNMASKED_RENDERER_WEBGL:r.RENDERER)??``),!t.allowSoftware&&v.test(k))throw Error(`WebGL 2 uses a software renderer (${k}).`);{let n=e.groups?16:1,i=await re(n);w=r.createVertexArray(),T=r.createBuffer(),r.bindVertexArray(w),r.bindBuffer(r.ARRAY_BUFFER,T),r.bufferData(r.ARRAY_BUFFER,new Float32Array([0,0,1,0,0,1,1,1]),r.STATIC_DRAW),r.enableVertexAttribArray(0),r.vertexAttribPointer(0,2,r.FLOAT,!1,0,0),r.bindVertexArray(null),r.disable(r.BLEND),D=Math.min(t.maxTextureSize??4096,r.getParameter(r.MAX_TEXTURE_SIZE));let a=r.getParameter(r.MAX_VIEWPORT_DIMS);O=Math.min(8192,a[0]??4096,a[1]??4096),ie(i,n)}K.initMs=performance.now()-n},backlog:pe,prepareShapes(){return S===16?Promise.resolve():(C??=re(16).then(e=>{if(j||!o||o.isContextLost())throw Error(`The WebGL 2 backend was disposed.`);ie(e,16)}),C)},render(e){if(K.renders++,q=[],!o||A||o.isContextLost())return;let t=performance.now();for(let t of e){let e=M.get(t.source.id);e&&(e.settling=!1)}let n=/* @__PURE__ */ new Map,r=[];for(let t of e){let{region:e,source:i}=t,a=Math.min(e.width/t.pixelWidth,e.height/t.pixelHeight),o=i.kind===`image`?g(a):0;n.set(i.id,Math.min(o,n.get(i.id)??o)),t.pixelWidth<=O&&t.pixelHeight<=O?r.push(t):$(t,/* @__PURE__ */ Error(`Surface of ${t.pixelWidth} x ${t.pixelHeight} px exceeds ${O} px.`))}let i=r.map(e=>({width:e.pixelWidth,height:e.pixelHeight}));for(let e of h(i,Math.min(m,O))){de(a,e.width,e.height);let t=[];for(let i of e.places){let e=r[i.index];try{ye(e,n.get(e.source.id)??0,i.x,i.y),t.push({surface:e,place:i})}catch(t){$(e,t)}}try{xe(t,e.width,e.height);for(let{surface:e}of t)q.push(e.id);K.surfaces+=t.length}catch(e){for(let{surface:n}of t)$(n,e)}}U=performance.now();let s=W.length<8?o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0):null;s&&(W.push(s),o.flush()),fe(),K.lastRenderMs=performance.now()-t,K.maxRenderMs=Math.max(K.maxRenderMs,K.lastRenderMs);for(let t of new Set(e.map(e=>e.source.id))){let e=M.get(t);e&&Z(t,e)}},releaseSource(e){for(let t of N.values())t.sourceId===e&&t.context.clearRect(0,0,t.canvas.width,t.canvas.height);ce(e)},removeSurface(e){let t=N.get(e);t&&(t.context.clearRect(0,0,t.canvas.width,t.canvas.height),N.delete(e),P.delete(e),ue(t.sourceId))},dispose(){if(!j){j=!0,i=null;for(let e of N.values())e.context.clearRect(0,0,e.canvas.width,e.canvas.height);N.clear(),P.clear(),a?.removeEventListener(`webglcontextlost`,J),H!==null&&clearTimeout(H),H=null,Se(),a&&(a.width=0,a.height=0),a=null;for(let e of[z,B,V?.canvas])e&&(e.width=0,e.height=0);z=null,B=null,V=null,R.clear()}},stats(){let e=0;for(let t of M.values())e+=Math.round(t.texWidth*t.texHeight*4*4/3);return{initMs:K.initMs,capacity:S,contexts:o&&!A&&!o.isContextLost()?1:0,textures:M.size,textureBytes:e,uploads:K.uploads,uploadMs:K.uploadMs,lastUploadMs:K.lastUploadMs,renders:K.renders,surfacesRendered:K.surfaces,lastRenderMs:K.lastRenderMs,maxRenderMs:K.maxRenderMs,canvas:[a?.width??0,a?.height??0],stage:[V?.canvas.width??0,V?.canvas.height??0],renderer:k,lost:A,errors:[...G],backdropReads:K.backdropReads,asyncBackdropReads:K.asyncReads,backdropReadMs:K.backdropReadMs,lastBackdropReadMs:K.lastBackdropReadMs}},adaptation(e){for(let t of P.values())if(t.element===e)return t.material;return null},simulateContextLoss(){o?.getExtension(`WEBGL_lose_context`)?.loseContext()}}}export{S as createWebGLBackend};
294
+ //# sourceMappingURL=webgl-backend-BE1U7Yp0.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webgl-backend-BE1U7Yp0.js","names":["luminance","contrast","CONTRAST_MARGIN","clamp01","v","sampleCells","all","_","k","smoothstep","edge0","edge1","x","t","materialBackdrop","r","g","b","saturation","brightness","dim","luma","ch","c","requiredAlpha","base","fill","labelLuminance","target","from","ok","a","lo","hi","i","m","cellRange","grid","sourceWidth","sourceHeight","x0","y0","x1","y1","fx","fy","cx0","cy0","cellsIn","cells","y","sameInputs","presetMaterial","inputs","designAlpha","adaptMaterial","lums","mean","s","deviation","required","smoothMaterial","previous","elapsedMs","tau","step","p","ATLAS_SIDE","packAtlas","items","side","order","index","area","widest","width","height","limit","batches","places","shelf","close","item","textureLevel","density","fragmentShader","maxShapes","SOFTWARE","UNIFORMS","[\n\t\"uSource\",\n\t\"uSize\",\n\t\"uRegion\",\n\t\"uVisible\",\n\t\"uNatural\",\n\t\"uTexelScale\",\n\t\"uBevel\",\n\t\"uThickness\",\n\t\"uIor\",\n\t\"uMaxShift\",\n\t\"uLens\",\n\t\"uBlur\",\n\t\"uDispersion\",\n\t\"uTaps\",\n\t\"uSaturation\",\n\t\"uBrightness\",\n\t\"uSpecular\",\n\t\"uRim\",\n\t\"uEdge\",\n\t\"uLight\",\n\t\"uMinContrast\",\n\t\"uMode\",\n\t\"uVisibleUv\",\n\t\"uShapeCount\",\n\t\"uShapeBox\",\n\t\"uShapeRadii\",\n\t\"uShapeFill\",\n\t\"uShapeA\",\n\t\"uShapeB\",\n\t\"uMergeK\",\n\t\"uMergeP\",\n\t\"uPointer\"\n]","MODES","TRANSPARENT","IDLE_MS","floorFill","design","css","usable","createWebGLBackend","options","output","host","canvas","gl","program","capacity","upgrade","vao","buffer","locations","maxTexture","maxCanvas","renderer","lost","disposed","textures","layers","adaptations","arrays","retained","framebuffer","colors","colorCanvas","scratch","stage","idle","lastRender","fences","errors","counts","lastRendered","onLost","compile","type","source","shader","link","shaders","parallel","resolve","logs","adopt","linked","name","warmUp","texture","set","color","known","value","context","textureFor","level","keep","started","longest","f","texWidth","texHeight","pixels","entry","now","sourceId","timer","deleteTexture","releaseEntry","releaseUnused","fit","releaseWhenIdle","sync","backlog","done","values","location","toGrid","bytes","rgb","settleLater","collected","collect","read","newer","backdropGrid","interval","w","h","complete","async","adapt","shape","tex","minContrast","shared","region","visible","reach","range","material","ownShape","dpr","setArray","count","drawSurface","o","ultra","angle","shapes","label","layerOf","present","batch","surface","place","failed","error","releaseGl","engineHost","info","viewport","surfaces","levels","drawn","fence","id","surfaceId","element"],"sources":["../../../glass/dist/adaptive.js","../../../glass/dist/atlas.js","../../../glass/dist/webgl-shaders.js","../../../glass/dist/webgl-backend.js"],"sourcesContent":["// Backdrop adaptation of the GPU material (D-75). The backdrop of a B1 surface is known from its declared source:\n// the WebGL 2 backend reads a small mipmap level of the source texture back once per content version (at most\n// 128 texels per side; throttled for continuously changing sources) and passes the cells under each surface here.\n// The result is a bounded, region-level adjustment of the material, applied uniformly to the surface:\n//\n// - tint baseline: the alpha that keeps 90% of the region's cells at the label contrast target, between the\n// design alpha and 1 (the per-pixel floor in the shader still guarantees every pixel);\n// - dimming: the preset's dim is reduced over dark backdrops (DESIGN_TOKENS.md, \"Clear and dimming\");\n// - edge lighting: stronger over dark backdrops, subtler over bright ones (factor 0.75 to 1.25);\n// - scattering: up to 1.5 times the preset's blur over busy, high-contrast backdrops.\n//\n// At most 256 cells are evaluated per surface, so the cost is bounded. Larger areas are sampled with a fixed\n// golden-ratio sequence over the cells under the surface: deterministic (the same cells every time, so no flicker)\n// and free of the aliasing an even stride has with periodic backdrops such as stripes.\n//\n// `adaptivity` (0 to 1) scales every adjustment; 0 keeps the preset values. B0 and B2 surfaces have no source\n// pixels and keep the deterministic CSS material. Pure functions only; nothing runs at import time.\nimport { contrast, luminance } from \"./optics.js\";\nconst clamp01 = (v) => Math.min(1, Math.max(0, v));\n/** Upper bound on the cells evaluated per surface. */\nexport const MAX_CELLS = 256;\nconst GOLDEN = 0.6180339887498949;\n/** The cells evaluated: all of them, or MAX_CELLS chosen by the golden-ratio sequence. */\nexport function sampleCells(all) {\n if (all.length <= MAX_CELLS)\n return all;\n return Array.from({ length: MAX_CELLS }, (_, k) => all[Math.floor(((k * GOLDEN) % 1) * all.length)] ?? 0);\n}\nexport function smoothstep(edge0, edge1, x) {\n const t = clamp01((x - edge0) / (edge1 - edge0));\n return t * t * (3 - 2 * t);\n}\n/** The material's backdrop color before the tint, as the shader computes it: saturation, brightness, dimming. */\nexport function materialBackdrop(r, g, b, saturation, brightness, dim) {\n const luma = 0.2126 * r + 0.7152 * g + 0.0722 * b;\n const ch = (c) => clamp01((luma + (c - luma) * saturation) * brightness) * (1 - dim);\n return [ch(r), ch(g), ch(b)];\n}\n/** The lowest tint alpha, at least `from`, at which `base` tinted with `fill` keeps `target` against the label. */\nexport function requiredAlpha(base, fill, labelLuminance, target, from) {\n const ok = (a) => contrast(luminance(base[0] + (fill[0] - base[0]) * a, base[1] + (fill[1] - base[1]) * a, base[2] + (fill[2] - base[2]) * a), labelLuminance) >= target;\n if (ok(from))\n return from;\n if (!ok(1))\n return 1;\n let lo = from;\n let hi = 1;\n for (let i = 0; i < 16; i++) {\n const m = (lo + hi) / 2;\n if (ok(m))\n hi = m;\n else\n lo = m;\n }\n return hi;\n}\n/** The grid cells that overlap a rectangle in source pixels (at least one cell). */\nexport function cellRange(grid, sourceWidth, sourceHeight, x0, y0, x1, y1) {\n const fx = grid.width / sourceWidth;\n const fy = grid.height / sourceHeight;\n const cx0 = Math.min(grid.width - 1, Math.max(0, Math.floor(x0 * fx)));\n const cy0 = Math.min(grid.height - 1, Math.max(0, Math.floor(y0 * fy)));\n const cx1 = Math.min(grid.width - 1, Math.max(cx0, Math.ceil(x1 * fx) - 1));\n const cy1 = Math.min(grid.height - 1, Math.max(cy0, Math.ceil(y1 * fy) - 1));\n return [cx0, cy0, cx1, cy1];\n}\n/** Indices of the cells in a range. */\nexport function cellsIn(grid, [x0, y0, x1, y1]) {\n const cells = [];\n for (let y = y0; y <= y1; y++)\n for (let x = x0; x <= x1; x++)\n cells.push(y * grid.width + x);\n return cells;\n}\n/** Indices of the grid cells that overlap a rectangle in source pixels (at least one cell). */\nexport function cellsUnder(grid, sourceWidth, sourceHeight, x0, y0, x1, y1) {\n return cellsIn(grid, cellRange(grid, sourceWidth, sourceHeight, x0, y0, x1, y1));\n}\n/** Whether two sets of inputs give the same material over the same cells. */\nexport function sameInputs(a, b) {\n return (a.tint === b.tint &&\n a.labelLuminance === b.labelLuminance &&\n a.target === b.target &&\n a.saturation === b.saturation &&\n a.brightness === b.brightness &&\n a.dim === b.dim &&\n a.adaptivity === b.adaptivity &&\n a.fill.every((v, i) => v === b.fill[i]));\n}\n/** The neutral result: the preset values, used without backdrop knowledge. */\nexport function presetMaterial(inputs) {\n const designAlpha = clamp01(inputs.fill[3] * inputs.tint);\n return {\n baseAlpha: designAlpha,\n designAlpha,\n dim: inputs.dim,\n lightScale: 1,\n blurScale: 1,\n mean: Number.NaN,\n deviation: Number.NaN,\n cells: 0,\n };\n}\nexport function adaptMaterial(grid, all, inputs) {\n if (!all.length)\n return presetMaterial(inputs);\n const cells = sampleCells(all);\n const a = clamp01(inputs.adaptivity);\n const lums = cells.map((i) => luminance(grid.rgb[i * 3] ?? 0, grid.rgb[i * 3 + 1] ?? 0, grid.rgb[i * 3 + 2] ?? 0));\n const mean = lums.reduce((s, v) => s + v, 0) / lums.length;\n const deviation = Math.sqrt(lums.reduce((s, v) => s + (v - mean) ** 2, 0) / lums.length);\n const designAlpha = clamp01(inputs.fill[3] * inputs.tint);\n // Dimming helps over bright media only; over dark media it would only lower the backdrop further.\n const dim = inputs.dim * (1 - a + a * smoothstep(0.08, 0.3, mean));\n const fill = [inputs.fill[0], inputs.fill[1], inputs.fill[2]];\n const required = cells\n .map((i) => requiredAlpha(materialBackdrop(grid.rgb[i * 3] ?? 0, grid.rgb[i * 3 + 1] ?? 0, grid.rgb[i * 3 + 2] ?? 0, inputs.saturation, inputs.brightness, dim), fill, inputs.labelLuminance, inputs.target, designAlpha))\n .sort((x, y) => x - y);\n const needed = required[Math.floor(0.9 * (required.length - 1))] ?? designAlpha;\n return {\n baseAlpha: designAlpha + a * (needed - designAlpha),\n designAlpha,\n dim,\n lightScale: 1 + a * (0.25 - 0.5 * mean),\n blurScale: 1 + a * 0.5 * smoothstep(0.08, 0.25, deviation),\n mean,\n deviation,\n cells: cells.length,\n };\n}\n/**\n * Moves a previous result toward a new target with a time constant of `tau` milliseconds, for sources that change\n * continuously (video, animated canvas), so the material follows the content without visible steps.\n */\nexport function smoothMaterial(previous, target, elapsedMs, tau = 400) {\n const k = 1 - Math.exp(-Math.max(0, elapsedMs) / tau);\n const step = (p, t) => p + (t - p) * k;\n return {\n ...target,\n baseAlpha: step(previous.baseAlpha, target.baseAlpha),\n dim: step(previous.dim, target.dim),\n lightScale: step(previous.lightScale, target.lightScale),\n blurScale: step(previous.blurScale, target.blurScale),\n };\n}\n//# sourceMappingURL=adaptive.js.map","// Placement of the layers of one render in the shared drawing buffer (D-83). Pure. Layers are drawn side by side and\n// copied out once per batch, because reading the drawing buffer back for every single layer is what costs most in\n// browsers that use CPU-backed Canvas 2D.\n/** Side of a batch in device pixels; an item that is larger gets a batch of its own. */\nexport const ATLAS_SIDE = 2048;\n/** Places items on shelves, the tallest first, in as few batches as fit. */\nexport function packAtlas(items, side = ATLAS_SIDE) {\n const order = items\n .map((_, index) => index)\n .sort((a, b) => (items[b]?.height ?? 0) - (items[a]?.height ?? 0) || a - b);\n let area = 0;\n let widest = 0;\n for (const { width, height } of items) {\n if (width > side || height > side)\n continue;\n area += width * height;\n widest = Math.max(widest, width);\n }\n // About square, so that the buffer grows in both directions, and as wide as the widest item.\n const limit = Math.min(side, Math.max(widest, Math.ceil((Math.sqrt(area) * 1.1) / 256) * 256));\n const batches = [];\n let places = [];\n let width = 0;\n let x = 0;\n let y = 0;\n let shelf = 0;\n const close = () => {\n if (places.length)\n batches.push({ width, height: y + shelf, places });\n places = [];\n width = x = y = shelf = 0;\n };\n for (const index of order) {\n const item = items[index];\n if (item.width > side || item.height > side) {\n batches.push({ width: item.width, height: item.height, places: [{ index, x: 0, y: 0 }] });\n continue;\n }\n if (x + item.width > limit) {\n y += shelf;\n x = shelf = 0;\n }\n if (y + item.height > side)\n close();\n places.push({ index, x, y });\n x += item.width;\n width = Math.max(width, x);\n shelf = Math.max(shelf, item.height);\n }\n close();\n return batches;\n}\n/**\n * The mipmap level a still image is uploaded at: every surface that shows it keeps at least 1.25 texels per device pixel,\n * so nothing visible is lost. `density` is the number of source pixels per device pixel of the closest surface.\n */\nexport function textureLevel(density) {\n return density > 0 && Number.isFinite(density) ? Math.max(0, Math.floor(Math.log2(density / 1.25))) : 0;\n}\n//# sourceMappingURL=atlas.js.map","// GLSL ES 3.00 sources of the WebGL 2 optical backend (D-74). The math matches the CPU references in shape.ts and\n// optics.ts: the signed distance of up to MAX_SHAPES rounded boxes with per-corner radii and circular or superellipse\n// corners, combined by a polynomial smooth union (D-76) that leaves an individual shape's field unchanged, bevel\n// profile h(t) = 1 - (1 - t)^2, Snell refraction toward the backdrop plane (D-52), lens magnification about the\n// shapes' centers, and a bound on the displacement. Per-shape material values (tint, label, adaptation) are blended\n// with the shapes' weights in the field, so a merged group has one continuous tint and one rim.\n// Scattering is approximate: a mipmap level for the blur radius plus a ring of taps (5 in `balanced`, 13 in\n// `ultra`), not an exact Gaussian. Colors are composited in sRGB-encoded space, as browsers composite the CSS\n// tint. Output modes: 0 = material, 1 = backdrop (refraction and scattering only), 2 = encoded displacement.\nexport const VERTEX_SHADER = `#version 300 es\nin vec2 aCorner;\nuniform vec2 uSize;\nout vec2 vPos;\nvoid main() {\n // Surface-local device pixels, y down; the viewport covers exactly the surface.\n vPos = aCorner * uSize;\n gl_Position = vec4(aCorner.x * 2.0 - 1.0, 1.0 - aCorner.y * 2.0, 0.0, 1.0);\n}`;\n/**\n * The fragment shader for up to `maxShapes` shapes. The single-shape program avoids shape loops. In benchmarks\n * the group program took about twice as long to compile, so the backend compiles it only when a group needs it\n * (D-76).\n */\nexport const fragmentShader = (maxShapes) => `#version 300 es\nprecision highp float;\nprecision highp int;\nin vec2 vPos;\nout vec4 outColor;\n\n#define MAX_SHAPES ${maxShapes}\n\nuniform sampler2D uSource;\nuniform vec2 uSize; // layer size, device px\nuniform vec4 uRegion; // the layer's rectangle in source px: x, y, width, height\nuniform vec4 uVisible; // visible image bounds in source px: x0, y0, x1, y1\nuniform vec2 uNatural; // source size in source px\nuniform float uTexelScale; // texels per source px (below 1 when a large source was downscaled)\nuniform float uBevel, uThickness, uIor, uMaxShift, uLens, uBlur, uDispersion; // lengths in device px\nuniform int uTaps; // 1, 5 (balanced), or 13 (ultra)\nuniform float uSaturation, uBrightness, uSpecular, uRim, uEdge;\nuniform vec2 uLight; // unit vector toward the light, y down\nuniform float uMinContrast; // 0 disables the legibility floor; the target is per shape (uShapeB.z)\nuniform int uMode;\nuniform vec4 uVisibleUv; // visible image bounds in texture coordinates: x0, y0, x1, y1\n\n// Shapes (D-76), in layer device px. Material values are per shape and blended by the field's weights.\nuniform int uShapeCount; // 1 to MAX_SHAPES\nuniform vec4 uShapeBox[MAX_SHAPES]; // center x, y; half width, half height\nuniform vec4 uShapeRadii[MAX_SHAPES]; // top-left, top-right, bottom-right, bottom-left\nuniform vec4 uShapeFill[MAX_SHAPES]; // design fill: straight sRGB color and alpha\nuniform vec4 uShapeA[MAX_SHAPES]; // corner exponent, label luminance, base alpha (D-75), dim\nuniform vec4 uShapeB[MAX_SHAPES]; // edge light scale, scattering scale (D-75), contrast target, glow (D-79)\nuniform float uMergeK; // smooth-union radius, device px; 0: plain union\nuniform float uMergeP; // smooth-union exponent (2 to 6)\nuniform vec3 uPointer; // pointer x, y and light radius in layer device px; radius 0: none (D-79)\n\nfloat weights[MAX_SHAPES];\n\nfloat srgbLum(vec3 c) {\n vec3 l = mix(c / 12.92, pow((c + 0.055) / 1.055, vec3(2.4)), step(vec3(0.04045), c));\n return dot(l, vec3(0.2126, 0.7152, 0.0722));\n}\nbool legible(vec3 c, float label, float target) {\n float a = srgbLum(c);\n return (max(a, label) + 0.05) / (min(a, label) + 0.05) >= target;\n}\n\n// One corner's curve: signed distance (x) and normal (yz, toward the corner) at the offset q from the curve's center\n// toward the corner, both components positive. Circular corners give the exact distance; superellipse corners the\n// first-order estimate (L - r) / |grad L| of the p-norm L.\nvec3 cornerField(vec2 q, float r, float e) {\n if (e == 2.0) {\n float l = length(q);\n return vec3(l - r, q / l);\n }\n float l = pow(pow(q.x, e) + pow(q.y, e), 1.0 / e);\n if (l <= 0.0) return vec3(-r, 1.0, 0.0);\n vec2 grad = pow(q / l, vec2(e - 1.0));\n float len = length(grad);\n return vec3((l - r) / len, grad / len);\n}\n\n// Signed distance (x) and outward normal (yz) of shape i for every radius CSS allows (D-77): the box cut by each\n// corner's curve inside that corner's square. Adjacent squares never overlap; opposite ones can, when a radius passes\n// the center line. Inside a square its curve replaces the corner's two edges; the nearest bound counts.\nvec3 shapeField(int i, vec2 p) {\n vec4 box = uShapeBox[i];\n vec4 rr = uShapeRadii[i];\n float e = uShapeA[i].x;\n vec2 d = p - box.xy;\n vec4 edges = vec4(-d.x, d.x, -d.y, d.y) - box.zzww; // left, right, top, bottom\n vec2 qtl = edges.xz + rr.x;\n vec2 qtr = edges.yz + rr.y;\n vec2 qbr = edges.yw + rr.z;\n vec2 qbl = edges.xw + rr.w;\n bool tl = min(qtl.x, qtl.y) > 0.0;\n bool tr = min(qtr.x, qtr.y) > 0.0;\n bool br = min(qbr.x, qbr.y) > 0.0;\n bool bl = min(qbl.x, qbl.y) > 0.0;\n vec3 f = vec3(-1e9, 0.0, 0.0);\n if (!tl && !bl) f = vec3(edges.x, -1.0, 0.0);\n if (!tr && !br && edges.y >= f.x) f = vec3(edges.y, 1.0, 0.0);\n if (!tl && !tr && edges.z >= f.x) f = vec3(edges.z, 0.0, -1.0);\n if (!bl && !br && edges.w >= f.x) f = vec3(edges.w, 0.0, 1.0);\n if (tl || tr) {\n vec3 c = cornerField(tl ? qtl : qtr, tl ? rr.x : rr.y, e);\n if (c.x >= f.x) f = vec3(c.x, tl ? -c.y : c.y, -c.z);\n }\n if (bl || br) {\n vec3 c = cornerField(bl ? qbl : qbr, bl ? rr.w : rr.z, e);\n if (c.x >= f.x) f = vec3(c.x, bl ? -c.y : c.y, c.z);\n }\n return f;\n}\n\n// The field of all shapes: a left fold of the polynomial smooth minimum f(h) = h^p / (2p) (shape.ts, sceneField).\n// Fills weights[] with each shape's share. The gradient is the weighted sum of the normals (shorter than 1 where a\n// junction blends two of them), which fades refraction and highlights smoothly across a junction.\nvec3 scene(vec2 p) {\n vec3 acc = shapeField(0, p);\n weights[0] = 1.0;\n for (int i = 1; i < MAX_SHAPES; i++) {\n if (i >= uShapeCount) break;\n vec3 f = shapeField(i, p);\n float share;\n float dist;\n if (uMergeK > 0.0) {\n float h = max(uMergeK - abs(acc.x - f.x), 0.0) / uMergeK;\n float fp = 0.5 * pow(h, uMergeP - 1.0);\n dist = min(acc.x, f.x) - uMergeK * pow(h, uMergeP) / (2.0 * uMergeP);\n share = acc.x <= f.x ? 1.0 - fp : fp;\n } else {\n dist = min(acc.x, f.x);\n share = acc.x <= f.x ? 1.0 : 0.0;\n }\n for (int j = 0; j < MAX_SHAPES; j++) {\n if (j >= i) break;\n weights[j] *= share;\n }\n weights[i] = 1.0 - share;\n acc = vec3(dist, acc.yz * share + f.yz * (1.0 - share));\n }\n return acc;\n}\n\nvec2 rimOffset(float d, vec2 g, float ior) {\n float depth = -d;\n if (depth <= 0.0 || depth >= uBevel || uBevel <= 0.0 || uThickness <= 0.0 || ior <= 1.0) return vec2(0.0);\n float t = depth / uBevel;\n float slope = uThickness * 2.0 * (1.0 - t) / uBevel;\n vec3 n = normalize(vec3(slope * g, 1.0));\n vec3 r = refract(vec3(0.0, 0.0, -1.0), n, 1.0 / ior);\n float height = uThickness * (1.0 - (1.0 - t) * (1.0 - t));\n return r.xy / max(-r.z, 1e-3) * height;\n}\n\nvec2 displacement(float d, vec2 g, vec2 p, vec2 center, float ior) {\n vec2 v = rimOffset(d, g, ior) + (p - center) * (1.0 / (1.0 + 0.5 * uLens) - 1.0);\n float m = length(v);\n if (m > uMaxShift && m > 0.0) v *= uMaxShift / m;\n return v;\n}\n\nvec2 sourceUv(vec2 p, vec2 disp) {\n vec2 src = uRegion.xy + (p + disp) * (uRegion.zw / uSize);\n src = clamp(src, uVisible.xy + 0.5, max(uVisible.zw - 0.5, uVisible.xy + 0.5));\n return src / uNatural;\n}\n\n// Keeps a scattering tap, and the texels its mipmap level averages, inside the visible image: an object-fit crop\n// must not leak pixels the page does not show (D-75). The inset is 1.5 texels of the coarser level in use.\nvec2 inside(vec2 uv, float lod, vec2 texel) {\n vec2 inset = texel * 1.5 * exp2(ceil(lod));\n vec2 lo = uVisibleUv.xy + inset;\n return clamp(uv, lo, max(uVisibleUv.zw - inset, lo));\n}\n\nvec4 scatter(vec2 uv, float blur) {\n float radius = blur * (uRegion.z / uSize.x) * uTexelScale; // blur radius in texels\n if (radius < 0.5) return textureLod(uSource, uv, 0.0);\n // The mip level averages about the blur radius; the taps smooth the box edges of that level. Ultra uses a\n // finer level and two rings, so thin high-contrast lines do not leave a tap pattern.\n bool ultra = uTaps >= 13;\n float lod = log2(max(radius * (ultra ? 0.6 : 1.0), 1.0));\n vec2 texel = 1.0 / vec2(textureSize(uSource, 0));\n vec4 sum = textureLod(uSource, inside(uv, lod, texel), lod) * 2.0;\n float weight = 2.0;\n if (uTaps >= 5) {\n float r = ultra ? 0.4 : 0.5;\n for (int i = 0; i < 4; i++) {\n float a = 0.7853982 + float(i) * 1.5707963;\n sum += textureLod(uSource, inside(uv + vec2(cos(a), sin(a)) * radius * r * texel, lod, texel), lod);\n }\n weight += 4.0;\n }\n if (ultra) {\n for (int i = 0; i < 8; i++) {\n float a = float(i) * 0.7853982;\n sum += textureLod(uSource, inside(uv + vec2(cos(a), sin(a)) * radius * 0.85 * texel, lod, texel), lod) * 0.75;\n }\n weight += 6.0;\n }\n return sum / weight;\n}\n\nvoid main() {\n // Exact pixel centers keep nearest-edge ties consistent across atlas viewports.\n vec2 pixel = floor(vPos) + vec2(0.5);\n vec3 f = scene(pixel);\n float d = f.x;\n vec2 g = f.yz;\n // The distance over the gradient length gives a correct edge width at junctions; one shape keeps the exact\n // Phase 04 coverage (its gradient is a unit vector).\n float coverage = clamp(0.5 - (uShapeCount > 1 ? d / max(length(g), 0.25) : d), 0.0, 1.0);\n // Every pixel is written (no discard), so the shared canvas needs no clear between surfaces.\n if (coverage <= 0.0) { outColor = vec4(0.0); return; }\n // Per-pixel material: the shapes' values blended by their weights.\n vec4 fill = vec4(0.0);\n vec2 center = vec2(0.0);\n float baseAlpha = 0.0, dim = 0.0, lightScale = 0.0, blurScale = 0.0, glow = 0.0;\n for (int i = 0; i < MAX_SHAPES; i++) {\n if (i >= uShapeCount) break;\n float w = weights[i];\n fill += uShapeFill[i] * w;\n center += uShapeBox[i].xy * w;\n baseAlpha += uShapeA[i].z * w;\n dim += uShapeA[i].w * w;\n lightScale += uShapeB[i].x * w;\n blurScale += uShapeB[i].y * w;\n glow += uShapeB[i].w * w;\n }\n float blur = uBlur * blurScale;\n vec2 disp = displacement(d, g, pixel, center, uIor);\n if (uMode == 2) {\n outColor = vec4(uMaxShift > 0.0 ? disp / (2.0 * uMaxShift) + 0.5 : vec2(0.5), 0.5, 1.0);\n return;\n }\n vec4 src;\n if (uDispersion > 0.0) {\n vec4 green = scatter(sourceUv(pixel, disp), blur);\n float red = scatter(sourceUv(pixel, displacement(d, g, pixel, center, uIor * (1.0 - 0.03 * uDispersion))), blur).r;\n float blue = scatter(sourceUv(pixel, displacement(d, g, pixel, center, uIor * (1.0 + 0.03 * uDispersion))), blur).b;\n src = vec4(red, green.g, blue, green.a);\n } else {\n src = scatter(sourceUv(pixel, disp), blur);\n }\n // Textures are premultiplied; colors below are straight.\n vec3 col = src.a > 0.0 ? clamp(src.rgb / src.a, 0.0, 1.0) : vec3(0.0);\n if (uMode == 1) { outColor = vec4(col, 1.0) * src.a * coverage; return; }\n\n float luma = dot(col, vec3(0.2126, 0.7152, 0.0722));\n vec3 base = clamp(mix(vec3(luma), col, uSaturation) * uBrightness, 0.0, 1.0) * (1.0 - dim);\n float depth = -d;\n float rimZone = clamp(1.0 - depth / max(uBevel, 1.0), 0.0, 1.0);\n float facing = max(dot(g, uLight), 0.0);\n float spec = uSpecular * pow(facing, 6.0) * rimZone * rimZone;\n float rim = uRim * (1.0 - smoothstep(0.0, uEdge + 1.0, depth));\n // Interaction light (D-79): the rim and the highlight brighten and the surface lifts a little, most around the pointer.\n // It is part of the light the legibility floor attenuates.\n float spot = 0.0;\n if (uPointer.z > 0.0) {\n vec2 to = (pixel - uPointer.xy) / uPointer.z;\n spot = exp(-dot(to, to));\n }\n vec3 light = vec3(spec + rim * 0.6) * lightScale * (1.0 + 0.8 * glow) + vec3(glow * (0.06 + 0.18 * spot));\n float a = clamp(baseAlpha, 0.0, 1.0);\n vec3 c = clamp(mix(base, fill.rgb, a) + light, 0.0, 1.0);\n // Legibility floor (D-58): a pixel that would fall below the label contrast target gets only the extra tint\n // it needs; if the lighting alone breaks the target at full tint, the lighting is attenuated first. The rim\n // line (uEdge + 1 px) is exempt: labels never sit there.\n // In a group each contributing shape's floor is computed against its own label and target, and the results are\n // blended by the shapes' weights, so the tint stays continuous across a junction between different colors.\n if (uMinContrast > 0.0 && depth > uEdge + 1.0) {\n float aSum = 0.0, kSum = 0.0;\n for (int s = 0; s < MAX_SHAPES; s++) {\n if (s >= uShapeCount) break;\n float w = weights[s];\n if (w <= 0.0) continue;\n float label = uShapeA[s].y;\n float goal = uShapeB[s].z;\n float ks = 1.0;\n float as = a;\n if (!legible(c, label, goal)) {\n if (!legible(clamp(fill.rgb + light, 0.0, 1.0), label, goal)) {\n float lo = 0.0, hi = 1.0;\n for (int i = 0; i < 10; i++) {\n float m = 0.5 * (lo + hi);\n if (legible(clamp(fill.rgb + light * m, 0.0, 1.0), label, goal)) lo = m; else hi = m;\n }\n ks = lo;\n }\n float lo = a, hi = 1.0;\n for (int i = 0; i < 10; i++) {\n float m = 0.5 * (lo + hi);\n if (legible(clamp(mix(base, fill.rgb, m) + light * ks, 0.0, 1.0), label, goal)) hi = m; else lo = m;\n }\n as = hi;\n }\n aSum += w * as;\n kSum += w * ks;\n }\n a = aSum;\n c = clamp(mix(base, fill.rgb, a) + light * kSum, 0.0, 1.0);\n }\n float alpha = coverage * (src.a + (1.0 - src.a) * a);\n outColor = vec4(c * alpha, alpha);\n}`;\n//# sourceMappingURL=webgl-shaders.js.map","// WebGL 2 optical backend (D-51, D-52, D-74). Loaded lazily through `@abgin/glass/webgl`; this module creates no\n// context when imported. Topology: one WebGL 2 context on a detached canvas renders the dirty surfaces side by side into\n// its drawing buffer (atlas.ts), and the results are copied into the surfaces' engine-owned layer canvases (2D\n// `drawImage`) in the same task; several surfaces go through one copy of the whole batch, so the drawing buffer is read\n// once (D-83). The layers keep their pixels, so static scenes need no rendering, and every surface keeps its own canvas\n// for correct stacking (D-51). Resource ownership:\n//\n// - context, program, vertex array, and buffer: the backend, released in `dispose()` (the context is lost on\n// purpose so the driver frees it at once);\n// - one texture per declared source in use, uploaded only when the source's content version changes, deleted in\n// `releaseSource()`, 1 s after the last surface using it is removed (so a layer that leaves for a transition and\n// returns, D-61, does not upload again; D-75), and in `dispose()`. Still images much larger than they are shown are\n// uploaded at a lower resolution (D-83);\n// - a 2D context per layer canvas (owned by the layer; the backend keeps only a reference until `removeSurface()`);\n// - the copy of the last batch, the canvas that downscales sources, and a drawing buffer larger than 1 MP: released 2 s\n// after the last render;\n// - a 1 x 1 canvas that resolves colors, released in `dispose()`.\nimport { adaptMaterial, cellRange, cellsIn, presetMaterial, sameInputs, smoothMaterial, } from \"./adaptive.js\";\nimport { ATLAS_SIDE, packAtlas, textureLevel } from \"./atlas.js\";\nimport { CONTRAST_MARGIN, contrast, luminance } from \"./optics.js\";\nimport { MAX_SHAPES } from \"./shape.js\";\nimport { VERTEX_SHADER, fragmentShader } from \"./webgl-shaders.js\";\nconst SOFTWARE = /swiftshader|llvmpipe|softpipe|microsoft basic render|\\bwarp\\b/i;\nconst UNIFORMS = [\n \"uSource\",\n \"uSize\",\n \"uRegion\",\n \"uVisible\",\n \"uNatural\",\n \"uTexelScale\",\n \"uBevel\",\n \"uThickness\",\n \"uIor\",\n \"uMaxShift\",\n \"uLens\",\n \"uBlur\",\n \"uDispersion\",\n \"uTaps\",\n \"uSaturation\",\n \"uBrightness\",\n \"uSpecular\",\n \"uRim\",\n \"uEdge\",\n \"uLight\",\n \"uMinContrast\",\n \"uMode\",\n \"uVisibleUv\",\n \"uShapeCount\",\n \"uShapeBox\",\n \"uShapeRadii\",\n \"uShapeFill\",\n \"uShapeA\",\n \"uShapeB\",\n \"uMergeK\",\n \"uMergeP\",\n \"uPointer\",\n];\nconst MODES = { material: 0, backdrop: 1, displacement: 2 };\nconst TRANSPARENT = [0, 0, 0, 0];\n/** How long a texture no layer uses is kept before it is deleted (D-75). */\nconst RETAIN_MS = 1000;\n/** Buffers for rendering larger than this are released when nothing was rendered for IDLE_MS (D-83). */\nconst IDLE_MS = 2000;\nconst IDLE_PIXELS = 1024 * 1024;\n/**\n * The color the legibility floor tints toward (D-75). The design fill is used when its color itself keeps 4.5:1\n * against the label. A fill without color (alpha 0: a material with opacity or tint 0) or with a color that cannot\n * reach 4.5:1 would leave the floor unable to reach its target, so the CSS material's fill color is used instead,\n * and failing that black or white, whichever contrasts more with the label. The design alpha is kept.\n */\nexport function floorFill(design, css, labelLuminance) {\n const usable = (c) => c !== null && c[3] > 0 && contrast(luminance(c[0], c[1], c[2]), labelLuminance) >= 4.5;\n if (usable(design))\n return design;\n if (usable(css))\n return [css[0], css[1], css[2], design[3]];\n const v = contrast(1, labelLuminance) >= contrast(0, labelLuminance) ? 1 : 0;\n return [v, v, v, design[3]];\n}\nexport function createWebGLBackend(options = {}) {\n const output = options.output ?? \"material\";\n let host = null;\n let canvas = null;\n let gl = null;\n let program = null;\n /** Shapes the current program draws: 1 until a group needs more (D-76), then MAX_SHAPES. */\n let capacity = 0;\n /** The running or finished upgrade to MAX_SHAPES. */\n let upgrade = null;\n let vao = null;\n let buffer = null;\n let locations = {};\n let maxTexture = 4096;\n let maxCanvas = 4096;\n let renderer = \"\";\n let lost = false;\n let disposed = false;\n const textures = new Map();\n const layers = new Map();\n const adaptations = new Map();\n /** Shape uniforms, filled per draw without allocation (MAX_SHAPES vec4 each). */\n const arrays = {\n uShapeBox: new Float32Array(MAX_SHAPES * 4),\n uShapeRadii: new Float32Array(MAX_SHAPES * 4),\n uShapeFill: new Float32Array(MAX_SHAPES * 4),\n uShapeA: new Float32Array(MAX_SHAPES * 4),\n uShapeB: new Float32Array(MAX_SHAPES * 4),\n };\n /** Textures no layer uses, with the timer that deletes them. */\n const retained = new Map();\n let framebuffer = null;\n const colors = new Map();\n let colorCanvas = null;\n let scratch = null;\n /** A copy of the drawing buffer, from which the layers of one batch are filled. */\n let stage = null;\n let idle = null;\n let lastRender = 0;\n /** Fences of renders the GPU has not finished, oldest first. */\n const fences = [];\n const errors = [];\n const counts = {\n initMs: 0,\n uploads: 0,\n uploadMs: 0,\n lastUploadMs: 0,\n renders: 0,\n surfaces: 0,\n lastRenderMs: 0,\n maxRenderMs: 0,\n backdropReads: 0,\n asyncReads: 0,\n backdropReadMs: 0,\n lastBackdropReadMs: 0,\n };\n let lastRendered = [];\n const onLost = () => {\n lost = true;\n host?.lost(\"WebGL 2 context lost\");\n };\n function compile(type, source) {\n const g = gl;\n const shader = g.createShader(type);\n if (!shader)\n throw new Error(\"WebGL 2 could not create a shader.\");\n g.shaderSource(shader, source);\n g.compileShader(shader);\n return shader;\n }\n /**\n * Compiles and links the program for up to `maxShapes` shapes. With `KHR_parallel_shader_compile` the wait does not\n * block the main thread; statuses are read only after completion, and the shader logs are reported on failure. The\n * program keeps its shaders alive, so they are released with it.\n */\n async function link(maxShapes) {\n const g = gl;\n const p = g.createProgram();\n const shaders = [compile(g.VERTEX_SHADER, VERTEX_SHADER), compile(g.FRAGMENT_SHADER, fragmentShader(maxShapes))];\n for (const shader of shaders)\n g.attachShader(p, shader);\n g.bindAttribLocation(p, 0, \"aCorner\");\n g.linkProgram(p);\n const parallel = g.getExtension(\"KHR_parallel_shader_compile\");\n if (parallel) {\n for (;;) {\n if (disposed || g.isContextLost())\n throw new Error(\"The WebGL 2 backend was disposed during compilation.\");\n if (g.getProgramParameter(p, parallel.COMPLETION_STATUS_KHR))\n break;\n await new Promise((resolve) => setTimeout(resolve, 4));\n }\n }\n if (!g.getProgramParameter(p, g.LINK_STATUS) && !g.isContextLost()) {\n const logs = shaders.map((shader) => g.getShaderInfoLog(shader)).filter(Boolean);\n throw new Error(`WebGL 2 program failed: ${[g.getProgramInfoLog(p), ...logs].filter(Boolean).join(\"; \")}`);\n }\n for (const shader of shaders)\n g.deleteShader(shader);\n return p;\n }\n /** Makes `linked` the current program (the previous one, if any, is deleted) and draws once with it. */\n function adopt(linked, maxShapes) {\n const g = gl;\n if (program)\n g.deleteProgram(program);\n program = linked;\n capacity = maxShapes;\n locations = Object.fromEntries(UNIFORMS.map((name) => [name, g.getUniformLocation(linked, name)]));\n warmUp();\n }\n /** One 1 x 1 draw, so drivers that compile at first use do it now, before any surface is shown. */\n function warmUp() {\n const g = gl;\n const texture = g.createTexture();\n g.bindTexture(g.TEXTURE_2D, texture);\n g.texImage2D(g.TEXTURE_2D, 0, g.RGBA, 1, 1, 0, g.RGBA, g.UNSIGNED_BYTE, new Uint8Array(4));\n g.useProgram(program);\n g.bindVertexArray(vao);\n g.viewport(0, 0, 1, 1);\n set(\"uSize\", 1, 1);\n set(\"uRegion\", 0, 0, 1, 1);\n set(\"uVisible\", 0, 0, 1, 1);\n set(\"uNatural\", 1, 1);\n set(\"uTexelScale\", 1);\n set(\"uMode\", MODES[output]);\n g.drawArrays(g.TRIANGLE_STRIP, 0, 4);\n g.bindVertexArray(null);\n g.deleteTexture(texture);\n }\n /** Resolves a computed CSS color to sRGB channels 0 to 1 (straight alpha), through a private 1 x 1 canvas. */\n function color(css) {\n const known = colors.get(css);\n if (known !== undefined)\n return known;\n let value = null;\n if (css && typeof CSS !== \"undefined\" && CSS.supports(\"color\", css)) {\n colorCanvas ??= Object.assign(document.createElement(\"canvas\"), { width: 1, height: 1 });\n const context = colorCanvas.getContext(\"2d\", { willReadFrequently: true });\n if (context) {\n context.clearRect(0, 0, 1, 1);\n context.fillStyle = css;\n context.fillRect(0, 0, 1, 1);\n const [r = 0, g = 0, b = 0, a = 0] = context.getImageData(0, 0, 1, 1).data;\n value = [r / 255, g / 255, b / 255, a / 255];\n }\n }\n if (colors.size > 256)\n colors.clear();\n colors.set(css, value);\n return value;\n }\n function textureFor(source, level) {\n const g = gl;\n keep(source.id);\n const known = textures.get(source.id);\n if (known?.version === source.version && known.element === source.element && known.level <= level)\n return known;\n const started = performance.now();\n const longest = Math.max(source.width, source.height);\n const f = Math.min(1 / 2 ** level, longest > maxTexture ? maxTexture / longest : 1);\n const texWidth = Math.max(1, Math.round(source.width * f));\n const texHeight = Math.max(1, Math.round(source.height * f));\n let pixels = source.element;\n if (f < 1) {\n // Bounded allocation: larger sources are downscaled once per upload; coordinates stay in source pixels.\n scratch ??= document.createElement(\"canvas\");\n scratch.width = texWidth;\n scratch.height = texHeight;\n const context = scratch.getContext(\"2d\");\n if (context) {\n context.imageSmoothingQuality = \"high\";\n context.drawImage(source.element, 0, 0, texWidth, texHeight);\n }\n pixels = scratch;\n }\n const entry = known ?? {\n texture: g.createTexture(),\n element: source.element,\n version: -1,\n width: 0,\n height: 0,\n texWidth: 0,\n texHeight: 0,\n level: 0,\n changedAt: -Infinity,\n continuous: false,\n grid: null,\n gridVersion: -1,\n gridAt: -Infinity,\n pending: null,\n packBuffer: null,\n poll: null,\n settling: false,\n quiet: false,\n fires: 0,\n };\n g.bindTexture(g.TEXTURE_2D, entry.texture);\n g.pixelStorei(g.UNPACK_FLIP_Y_WEBGL, false);\n g.pixelStorei(g.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);\n if (entry.texWidth === texWidth && entry.texHeight === texHeight) {\n g.texSubImage2D(g.TEXTURE_2D, 0, 0, 0, g.RGBA, g.UNSIGNED_BYTE, pixels);\n }\n else {\n g.texImage2D(g.TEXTURE_2D, 0, g.RGBA, g.RGBA, g.UNSIGNED_BYTE, pixels);\n g.texParameteri(g.TEXTURE_2D, g.TEXTURE_MIN_FILTER, g.LINEAR_MIPMAP_LINEAR);\n g.texParameteri(g.TEXTURE_2D, g.TEXTURE_MAG_FILTER, g.LINEAR);\n g.texParameteri(g.TEXTURE_2D, g.TEXTURE_WRAP_S, g.CLAMP_TO_EDGE);\n g.texParameteri(g.TEXTURE_2D, g.TEXTURE_WRAP_T, g.CLAMP_TO_EDGE);\n }\n g.generateMipmap(g.TEXTURE_2D);\n entry.fires = 0;\n const now = performance.now();\n // The same content at another resolution is not a change of the content.\n if (entry.version !== source.version || entry.element !== source.element) {\n entry.continuous = now - entry.changedAt < 300;\n entry.changedAt = now;\n }\n Object.assign(entry, {\n element: source.element,\n version: source.version,\n width: source.width,\n height: source.height,\n texWidth,\n texHeight,\n level,\n });\n textures.set(source.id, entry);\n counts.uploads++;\n counts.lastUploadMs = performance.now() - started;\n counts.uploadMs += counts.lastUploadMs;\n return entry;\n }\n function keep(sourceId) {\n const timer = retained.get(sourceId);\n if (timer === undefined)\n return;\n clearTimeout(timer);\n retained.delete(sourceId);\n }\n function deleteTexture(sourceId) {\n keep(sourceId);\n const entry = textures.get(sourceId);\n if (!entry)\n return;\n textures.delete(sourceId);\n if (gl && !gl.isContextLost())\n releaseEntry(gl, entry);\n }\n function releaseEntry(g, entry) {\n if (entry.poll !== null)\n clearTimeout(entry.poll);\n entry.poll = null;\n if (entry.pending)\n g.deleteSync(entry.pending.sync);\n if (entry.packBuffer)\n g.deleteBuffer(entry.packBuffer);\n entry.pending = null;\n entry.packBuffer = null;\n g.deleteTexture(entry.texture);\n }\n /**\n * Deletes a texture no layer uses any more after RETAIN_MS, so texture memory follows the sources actually shown\n * and a layer that returns within that time (for example after a transition) needs no upload.\n */\n function releaseUnused(sourceId) {\n for (const entry of layers.values())\n if (entry.sourceId === sourceId)\n return;\n if (!textures.has(sourceId) || retained.has(sourceId))\n return;\n retained.set(sourceId, setTimeout(() => {\n retained.delete(sourceId);\n for (const entry of layers.values())\n if (entry.sourceId === sourceId)\n return;\n deleteTexture(sourceId);\n }, RETAIN_MS));\n }\n /** A buffer grows to the batches drawn into it (in 256 px steps, bounded) and shrinks only when idle. */\n function fit(c, width, height) {\n if (width > c.width)\n c.width = Math.min(maxCanvas, Math.ceil(width / 256) * 256);\n if (height > c.height)\n c.height = Math.min(maxCanvas, Math.ceil(height / 256) * 256);\n }\n /** One timer at a time, rearmed at most once per IDLE_MS while rendering goes on. */\n function releaseWhenIdle() {\n idle ??= setTimeout(() => {\n idle = null;\n if (disposed || !canvas)\n return;\n if (performance.now() - lastRender < IDLE_MS) {\n releaseWhenIdle();\n return;\n }\n for (const sync of fences.splice(0))\n gl?.deleteSync(sync);\n for (const c of [stage?.canvas, scratch])\n if (c)\n c.width = c.height = 0;\n if (canvas.width * canvas.height > IDLE_PIXELS)\n canvas.width = canvas.height = 256;\n }, IDLE_MS);\n }\n /** Renders submitted to the GPU that it has not finished (D-84). Never waits for it. */\n function backlog() {\n const g = gl;\n if (!g)\n return 0;\n let done = 0;\n while (done < fences.length && g.getSyncParameter(fences[done], g.SYNC_STATUS) === g.SIGNALED)\n done++;\n for (const sync of fences.splice(0, done))\n g.deleteSync(sync);\n return fences.length;\n }\n function set(name, ...values) {\n const g = gl;\n const location = locations[name] ?? null;\n if (name === \"uTaps\" || name === \"uMode\" || name === \"uSource\" || name === \"uShapeCount\")\n g.uniform1i(location, values[0] ?? 0);\n else if (values.length === 1)\n g.uniform1f(location, values[0] ?? 0);\n else if (values.length === 2)\n g.uniform2f(location, values[0] ?? 0, values[1] ?? 0);\n else if (values.length === 3)\n g.uniform3f(location, values[0] ?? 0, values[1] ?? 0, values[2] ?? 0);\n else\n g.uniform4f(location, values[0] ?? 0, values[1] ?? 0, values[2] ?? 0, values[3] ?? 0);\n }\n /** Straight colors from premultiplied RGBA bytes. */\n function toGrid(bytes, width, height) {\n const rgb = new Float32Array(width * height * 3);\n for (let i = 0; i < width * height; i++) {\n const a = (bytes[i * 4 + 3] ?? 0) / 255;\n for (let k = 0; k < 3; k++)\n rgb[i * 3 + k] = a > 0 ? Math.min(1, (bytes[i * 4 + k] ?? 0) / 255 / a) : 0;\n }\n return { width, height, rgb };\n }\n /**\n * Continuously changing content can stop between two renders, leaving a pending read or a material still moving\n * toward its target (smoothing). Once the content has not changed for 300 ms, the read is collected (or the final\n * content read) and the engine is asked to draw the source's layers again (`host.redraw`), until the material has\n * settled: checked every 50 ms after the last render, at most 60 times per content version. While the content\n * keeps changing, its own renders collect and smooth, and nothing extra is drawn.\n */\n function settleLater(sourceId, entry) {\n if (entry.poll !== null)\n clearTimeout(entry.poll);\n entry.poll = null;\n if ((!entry.pending && !entry.settling) || entry.fires >= 60)\n return;\n entry.poll = setTimeout(() => {\n entry.poll = null;\n if (disposed || !gl || gl.isContextLost() || textures.get(sourceId) !== entry)\n return;\n entry.fires++;\n const collected = collect(entry);\n // Content still changing (a new frame within 300 ms): its next render collects and smooths; keep waiting.\n if (performance.now() - entry.changedAt < 300) {\n settleLater(sourceId, entry);\n return;\n }\n // Colors older than the content and no read on the way: read the current content at the next redraw.\n if (!collected && !entry.pending && entry.gridVersion !== entry.version)\n entry.quiet = true;\n if (collected || entry.settling || entry.quiet)\n host?.redraw?.(sourceId);\n else\n settleLater(sourceId, entry);\n }, 50);\n }\n /** Collects a finished asynchronous read; never waits for the GPU. True when new colors were collected. */\n function collect(entry) {\n const g = gl;\n const read = entry.pending;\n if (!read || g.getSyncParameter(read.sync, g.SYNC_STATUS) !== g.SIGNALED)\n return false;\n const started = performance.now();\n const bytes = new Uint8Array(read.width * read.height * 4);\n g.bindBuffer(g.PIXEL_PACK_BUFFER, entry.packBuffer);\n g.getBufferSubData(g.PIXEL_PACK_BUFFER, 0, bytes);\n g.bindBuffer(g.PIXEL_PACK_BUFFER, null);\n g.deleteSync(read.sync);\n entry.pending = null;\n // A synchronous read of newer content may have happened meanwhile; never replace it with older colors.\n const newer = read.version >= entry.gridVersion;\n if (newer) {\n entry.grid = toGrid(bytes, read.width, read.height);\n entry.gridVersion = read.version;\n }\n counts.backdropReadMs += performance.now() - started;\n return newer;\n }\n /**\n * Backdrop colors for adaptation (D-75): the mipmap level of at most 128 texels per side (at most 64 KiB) is read\n * back through a framebuffer once per content version. Static content is read at once, so its first frame is\n * already adapted. Continuously changing sources are read at most every 200 ms and asynchronously (a pixel pack\n * buffer and a fence, collected at a later render), so they never wait for the GPU; their smoothing covers the\n * latency of a frame or two.\n */\n function backdropGrid(entry) {\n const g = gl;\n collect(entry);\n const now = performance.now();\n const interval = entry.continuous && !entry.quiet && now - entry.gridAt < 200;\n if (entry.grid && (entry.gridVersion === entry.version || interval))\n return entry.grid;\n if (entry.continuous && entry.grid && entry.pending)\n return entry.grid;\n const started = now;\n let level = 0;\n let w = entry.texWidth;\n let h = entry.texHeight;\n while (Math.max(w, h) > 128) {\n level++;\n w = Math.max(1, w >> 1);\n h = Math.max(1, h >> 1);\n }\n framebuffer ??= g.createFramebuffer();\n g.bindFramebuffer(g.FRAMEBUFFER, framebuffer);\n g.framebufferTexture2D(g.FRAMEBUFFER, g.COLOR_ATTACHMENT0, g.TEXTURE_2D, entry.texture, level);\n const complete = g.checkFramebufferStatus(g.FRAMEBUFFER) === g.FRAMEBUFFER_COMPLETE;\n const async = complete && entry.continuous && entry.grid !== null;\n if (async) {\n entry.packBuffer ??= g.createBuffer();\n g.bindBuffer(g.PIXEL_PACK_BUFFER, entry.packBuffer);\n g.bufferData(g.PIXEL_PACK_BUFFER, w * h * 4, g.STREAM_READ);\n g.readPixels(0, 0, w, h, g.RGBA, g.UNSIGNED_BYTE, 0);\n g.bindBuffer(g.PIXEL_PACK_BUFFER, null);\n const sync = g.fenceSync(g.SYNC_GPU_COMMANDS_COMPLETE, 0);\n if (sync)\n entry.pending = { sync, width: w, height: h, version: entry.version };\n g.flush();\n }\n else if (complete) {\n const bytes = new Uint8Array(w * h * 4);\n g.readPixels(0, 0, w, h, g.RGBA, g.UNSIGNED_BYTE, bytes);\n entry.grid = toGrid(bytes, w, h);\n entry.gridVersion = entry.version;\n }\n else {\n entry.grid = null;\n entry.gridVersion = entry.version;\n }\n g.framebufferTexture2D(g.FRAMEBUFFER, g.COLOR_ATTACHMENT0, g.TEXTURE_2D, null, 0);\n g.bindFramebuffer(g.FRAMEBUFFER, null);\n entry.gridAt = now;\n entry.quiet = false;\n counts.backdropReads++;\n if (async)\n counts.asyncReads++;\n counts.lastBackdropReadMs = performance.now() - started;\n counts.backdropReadMs += counts.lastBackdropReadMs;\n return entry.grid;\n }\n /** The adaptive material of a surface: from the cells under it (plus the reach of refraction and blur). */\n function adapt(s, shape, tex, fill, labelLuminance, minContrast) {\n // The shape's own tokens decide tint, dimming, and adaptivity; the reach of refraction and blur is the layer's.\n const o = shape.optics;\n const shared = s.optics;\n const inputs = {\n fill,\n tint: o.tint,\n labelLuminance,\n target: minContrast,\n saturation: o.saturation,\n brightness: o.brightness,\n dim: o.dim,\n adaptivity: o.adaptivity,\n };\n const grid = o.adaptivity > 0 ? backdropGrid(tex) : null;\n // Colors of earlier content (an asynchronous read on the way, or the 200 ms interval): settle later.\n if (grid && tex.gridVersion !== tex.version)\n tex.settling = true;\n const previous = adaptations.get(shape.id);\n let target;\n let cells = null;\n if (grid) {\n const { region } = shape;\n const { visible } = s;\n const reach = (shared.maxShift + shared.blur) * s.dpr * (s.region.width / s.pixelWidth);\n const x0 = Math.max(visible.x, region.x - reach);\n const y0 = Math.max(visible.y, region.y - reach);\n const x1 = Math.min(visible.x + visible.width, region.x + region.width + reach);\n const y1 = Math.min(visible.y + visible.height, region.y + region.height + reach);\n const range = cellRange(grid, s.source.width, s.source.height, x0, y0, x1, y1);\n cells = range;\n target =\n previous?.grid === grid &&\n previous.cells?.every((v, i) => v === range[i]) &&\n sameInputs(previous.inputs, inputs)\n ? previous.target\n : adaptMaterial(grid, cellsIn(grid, range), inputs);\n }\n else\n target = presetMaterial(inputs);\n let material = target;\n const now = performance.now();\n // Continuously changing sources move toward the new values over about 0.4 s instead of jumping (no flicker);\n // static content applies them at once.\n if (previous && previous.element === shape.element && tex.continuous) {\n material = smoothMaterial(previous.material, target, now - previous.at);\n const residual = Math.max(Math.abs(material.baseAlpha - target.baseAlpha), Math.abs(material.dim - target.dim), Math.abs(material.lightScale - target.lightScale), Math.abs(material.blurScale - target.blurScale));\n if (residual > 0.005)\n tex.settling = true;\n }\n adaptations.set(shape.id, { element: shape.element, material, at: now, target, grid, cells, inputs });\n return material;\n }\n /** Use the surface's border box and radii when the caller omits `shapes`. */\n function ownShape(s) {\n const { dpr } = s;\n return {\n id: s.id,\n element: s.element,\n box: [s.pixelWidth / 2, s.pixelHeight / 2, s.pixelWidth / 2, s.pixelHeight / 2],\n radii: [s.radii[0] * dpr, s.radii[1] * dpr, s.radii[2] * dpr, s.radii[3] * dpr],\n exponent: 2,\n region: s.region,\n fill: s.fill,\n designFill: s.designFill,\n labelColor: s.labelColor,\n optics: s.optics,\n };\n }\n function setArray(name, count) {\n gl.uniform4fv(locations[name] ?? null, arrays[name], 0, count * 4);\n }\n /** Draws a surface into the drawing buffer, with its top-left corner at (x, y) from the top left. */\n function drawSurface(s, level, x, y) {\n const g = gl;\n const c = canvas;\n const tex = textureFor(s.source, level);\n const w = s.pixelWidth;\n const h = s.pixelHeight;\n const { dpr, optics: o, region, visible } = s;\n const ultra = s.quality === \"ultra\";\n const angle = (o.lightAngle * Math.PI) / 180;\n const shapes = s.shapes?.length ? s.shapes : [ownShape(s)];\n const count = Math.min(shapes.length, capacity);\n for (let i = 0; i < count; i++) {\n const shape = shapes[i];\n const label = color(shape.labelColor) ?? [0, 0, 0, 1];\n const labelLuminance = luminance(label[0], label[1], label[2]);\n const css = color(shape.fill);\n const fill = floorFill(color(shape.designFill) ?? css ?? TRANSPARENT, css, labelLuminance);\n // A material may raise the contrast target but never lower it below 4.5:1 (clamped in readOptics).\n // Match the CSS derivation's 2% headroom for higher targets that also protect secondary text (D-89).\n const { minContrast } = shape.optics;\n const target = Math.max(minContrast + CONTRAST_MARGIN, minContrast * 1.02);\n const material = adapt(s, shape, tex, fill, labelLuminance, target);\n arrays.uShapeBox.set(shape.box, i * 4);\n arrays.uShapeRadii.set(shape.radii, i * 4);\n arrays.uShapeFill.set(fill, i * 4);\n arrays.uShapeA.set([shape.exponent, labelLuminance, material.baseAlpha, material.dim], i * 4);\n arrays.uShapeB.set([material.lightScale, material.blurScale, target, shape.glow ?? 0], i * 4);\n }\n g.useProgram(program);\n g.bindVertexArray(vao);\n g.viewport(x, c.height - y - h, w, h);\n g.activeTexture(g.TEXTURE0);\n g.bindTexture(g.TEXTURE_2D, tex.texture);\n set(\"uSource\", 0);\n set(\"uSize\", w, h);\n set(\"uRegion\", region.x, region.y, region.width, region.height);\n set(\"uVisible\", visible.x, visible.y, visible.x + visible.width, visible.y + visible.height);\n set(\"uVisibleUv\", visible.x / s.source.width, visible.y / s.source.height, (visible.x + visible.width) / s.source.width, (visible.y + visible.height) / s.source.height);\n set(\"uNatural\", s.source.width, s.source.height);\n set(\"uTexelScale\", tex.texWidth / Math.max(1, s.source.width));\n set(\"uBevel\", o.bevel * dpr);\n set(\"uThickness\", o.thickness * dpr);\n set(\"uIor\", o.ior);\n set(\"uMaxShift\", o.maxShift * dpr);\n set(\"uLens\", o.lens);\n set(\"uBlur\", o.blur * dpr);\n set(\"uDispersion\", ultra ? o.dispersion : 0);\n set(\"uTaps\", ultra ? 13 : 5);\n set(\"uSaturation\", o.saturation);\n set(\"uBrightness\", o.brightness);\n set(\"uSpecular\", o.specular);\n set(\"uRim\", o.rimLight);\n set(\"uEdge\", o.edgeWidth * dpr);\n set(\"uLight\", Math.sin(angle), -Math.cos(angle));\n set(\"uMinContrast\", output === \"material\" ? 1 : 0);\n set(\"uMode\", MODES[output]);\n set(\"uShapeCount\", count);\n setArray(\"uShapeBox\", count);\n setArray(\"uShapeRadii\", count);\n setArray(\"uShapeFill\", count);\n setArray(\"uShapeA\", count);\n setArray(\"uShapeB\", count);\n set(\"uMergeK\", s.merge?.k ?? 0);\n set(\"uMergeP\", s.merge?.p ?? 2);\n set(\"uPointer\", s.pointer?.x ?? 0, s.pointer?.y ?? 0, s.pointer?.radius ?? 0);\n g.drawArrays(g.TRIANGLE_STRIP, 0, 4);\n }\n /** The 2D context of a surface's layer; the layer may be new, or the surface may have changed its source. */\n function layerOf(s) {\n let entry = layers.get(s.id);\n if (entry?.canvas !== s.layer) {\n const context = s.layer.getContext(\"2d\");\n if (!context)\n throw new Error(\"Canvas 2D is unavailable for a layer.\");\n entry = { canvas: s.layer, context, sourceId: s.source.id };\n layers.set(s.id, entry);\n }\n if (entry.sourceId !== s.source.id) {\n const previous = entry.sourceId;\n entry.sourceId = s.source.id;\n releaseUnused(previous);\n }\n return entry;\n }\n /** Copies the surfaces of a batch from the drawing buffer into their layers, through one copy if there are several. */\n function present(batch, width, height) {\n let from = canvas;\n if (batch.length > 1) {\n const context = (stage ??= document.createElement(\"canvas\").getContext(\"2d\"));\n if (!context)\n throw new Error(\"Canvas 2D is unavailable.\");\n fit(context.canvas, width, height);\n context.globalCompositeOperation = \"copy\";\n context.drawImage(from, 0, 0, width, height, 0, 0, width, height);\n from = context.canvas;\n }\n for (const { surface, place } of batch) {\n const { pixelWidth: w, pixelHeight: h } = surface;\n const { context } = layerOf(surface);\n context.clearRect(0, 0, w, h);\n context.drawImage(from, place.x, place.y, w, h, 0, 0, w, h);\n }\n }\n function failed(s, error) {\n // One unusable source (for example a texture upload the browser refused) must not end the backend: that layer is\n // left empty, so the CSS material shows through it.\n if (errors.length < 32)\n errors.push(error instanceof Error ? error.message : String(error));\n layers.get(s.id)?.context.clearRect(0, 0, s.pixelWidth, s.pixelHeight);\n }\n function releaseGl() {\n const g = gl;\n if (g && !g.isContextLost()) {\n for (const entry of textures.values())\n releaseEntry(g, entry);\n for (const sync of fences)\n g.deleteSync(sync);\n if (program)\n g.deleteProgram(program);\n if (vao)\n g.deleteVertexArray(vao);\n if (buffer)\n g.deleteBuffer(buffer);\n if (framebuffer)\n g.deleteFramebuffer(framebuffer);\n // Lose the context on purpose: the driver frees it now instead of at garbage collection.\n g.getExtension(\"WEBGL_lose_context\")?.loseContext();\n }\n textures.clear();\n fences.length = 0;\n program = null;\n capacity = 0;\n vao = null;\n buffer = null;\n framebuffer = null;\n locations = {};\n gl = null;\n }\n return {\n name: \"webgl2\",\n get shapes() {\n return capacity > 1;\n },\n get resources() {\n return (gl ? 1 : 0) + textures.size + layers.size + (framebuffer ? 1 : 0);\n },\n get renders() {\n return counts.renders;\n },\n get lastRendered() {\n return lastRendered;\n },\n async init(engineHost) {\n if (disposed)\n throw new Error(\"The WebGL 2 backend was disposed.\");\n const started = performance.now();\n host = engineHost;\n canvas = document.createElement(\"canvas\");\n canvas.width = 256;\n canvas.height = 256;\n canvas.addEventListener(\"webglcontextlost\", onLost);\n const context = canvas.getContext(\"webgl2\", {\n alpha: true,\n premultipliedAlpha: true,\n antialias: false,\n depth: false,\n stencil: false,\n preserveDrawingBuffer: false,\n failIfMajorPerformanceCaveat: !options.allowSoftware,\n });\n if (!context) {\n throw new Error(options.allowSoftware ? \"WebGL 2 is unavailable.\" : \"WebGL 2 is unavailable or software-only.\");\n }\n gl = context;\n const info = context.getExtension(\"WEBGL_debug_renderer_info\");\n renderer = String(context.getParameter(info ? info.UNMASKED_RENDERER_WEBGL : context.RENDERER) ?? \"\");\n if (!options.allowSoftware && SOFTWARE.test(renderer))\n throw new Error(`WebGL 2 uses a software renderer (${renderer}).`);\n {\n // A page that already has a group pays for the larger program once, here; others never do.\n const maxShapes = engineHost.groups ? MAX_SHAPES : 1;\n const linked = await link(maxShapes);\n vao = context.createVertexArray();\n buffer = context.createBuffer();\n context.bindVertexArray(vao);\n context.bindBuffer(context.ARRAY_BUFFER, buffer);\n context.bufferData(context.ARRAY_BUFFER, new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]), context.STATIC_DRAW);\n context.enableVertexAttribArray(0);\n context.vertexAttribPointer(0, 2, context.FLOAT, false, 0, 0);\n context.bindVertexArray(null);\n context.disable(context.BLEND);\n maxTexture = Math.min(options.maxTextureSize ?? 4096, context.getParameter(context.MAX_TEXTURE_SIZE));\n const viewport = context.getParameter(context.MAX_VIEWPORT_DIMS);\n maxCanvas = Math.min(8192, viewport[0] ?? 4096, viewport[1] ?? 4096);\n adopt(linked, maxShapes);\n }\n counts.initMs = performance.now() - started;\n },\n backlog,\n prepareShapes() {\n if (capacity === MAX_SHAPES)\n return Promise.resolve();\n upgrade ??= link(MAX_SHAPES).then((linked) => {\n if (disposed || !gl || gl.isContextLost())\n throw new Error(\"The WebGL 2 backend was disposed.\");\n adopt(linked, MAX_SHAPES);\n });\n return upgrade;\n },\n render(surfaces) {\n counts.renders++;\n lastRendered = [];\n if (!gl || lost || gl.isContextLost())\n return;\n const started = performance.now();\n for (const s of surfaces) {\n const entry = textures.get(s.source.id);\n if (entry)\n entry.settling = false;\n }\n // A still image is uploaded at the resolution its closest surface needs; video and canvas sources at their own.\n const levels = new Map();\n const usable = [];\n for (const s of surfaces) {\n const { region, source } = s;\n const density = Math.min(region.width / s.pixelWidth, region.height / s.pixelHeight);\n const level = source.kind === \"image\" ? textureLevel(density) : 0;\n levels.set(source.id, Math.min(level, levels.get(source.id) ?? level));\n if (s.pixelWidth <= maxCanvas && s.pixelHeight <= maxCanvas)\n usable.push(s);\n else\n failed(s, new Error(`Surface of ${s.pixelWidth} x ${s.pixelHeight} px exceeds ${maxCanvas} px.`));\n }\n const items = usable.map((s) => ({ width: s.pixelWidth, height: s.pixelHeight }));\n for (const batch of packAtlas(items, Math.min(ATLAS_SIDE, maxCanvas))) {\n fit(canvas, batch.width, batch.height);\n const drawn = [];\n for (const place of batch.places) {\n const surface = usable[place.index];\n try {\n drawSurface(surface, levels.get(surface.source.id) ?? 0, place.x, place.y);\n drawn.push({ surface, place });\n }\n catch (error) {\n failed(surface, error);\n }\n }\n try {\n present(drawn, batch.width, batch.height);\n for (const { surface } of drawn)\n lastRendered.push(surface.id);\n counts.surfaces += drawn.length;\n }\n catch (error) {\n for (const { surface } of drawn)\n failed(surface, error);\n }\n }\n lastRender = performance.now();\n const fence = fences.length < 8 ? gl.fenceSync(gl.SYNC_GPU_COMMANDS_COMPLETE, 0) : null;\n if (fence) {\n fences.push(fence);\n gl.flush();\n }\n releaseWhenIdle();\n counts.lastRenderMs = performance.now() - started;\n counts.maxRenderMs = Math.max(counts.maxRenderMs, counts.lastRenderMs);\n for (const id of new Set(surfaces.map((s) => s.source.id))) {\n const entry = textures.get(id);\n if (entry)\n settleLater(id, entry);\n }\n },\n releaseSource(sourceId) {\n for (const entry of layers.values()) {\n if (entry.sourceId === sourceId)\n entry.context.clearRect(0, 0, entry.canvas.width, entry.canvas.height);\n }\n deleteTexture(sourceId);\n },\n removeSurface(surfaceId) {\n const entry = layers.get(surfaceId);\n if (!entry)\n return;\n entry.context.clearRect(0, 0, entry.canvas.width, entry.canvas.height);\n layers.delete(surfaceId);\n adaptations.delete(surfaceId);\n releaseUnused(entry.sourceId);\n },\n dispose() {\n if (disposed)\n return;\n disposed = true;\n host = null;\n for (const entry of layers.values())\n entry.context.clearRect(0, 0, entry.canvas.width, entry.canvas.height);\n layers.clear();\n adaptations.clear();\n canvas?.removeEventListener(\"webglcontextlost\", onLost);\n if (idle !== null)\n clearTimeout(idle);\n idle = null;\n releaseGl();\n if (canvas) {\n canvas.width = 0;\n canvas.height = 0;\n }\n canvas = null;\n for (const c of [colorCanvas, scratch, stage?.canvas]) {\n if (c) {\n c.width = 0;\n c.height = 0;\n }\n }\n colorCanvas = null;\n scratch = null;\n stage = null;\n colors.clear();\n },\n stats() {\n let bytes = 0;\n for (const t of textures.values())\n bytes += Math.round((t.texWidth * t.texHeight * 4 * 4) / 3);\n return {\n initMs: counts.initMs,\n capacity,\n contexts: gl && !lost && !gl.isContextLost() ? 1 : 0,\n textures: textures.size,\n textureBytes: bytes,\n uploads: counts.uploads,\n uploadMs: counts.uploadMs,\n lastUploadMs: counts.lastUploadMs,\n renders: counts.renders,\n surfacesRendered: counts.surfaces,\n lastRenderMs: counts.lastRenderMs,\n maxRenderMs: counts.maxRenderMs,\n canvas: [canvas?.width ?? 0, canvas?.height ?? 0],\n stage: [stage?.canvas.width ?? 0, stage?.canvas.height ?? 0],\n renderer,\n lost,\n errors: [...errors],\n backdropReads: counts.backdropReads,\n asyncBackdropReads: counts.asyncReads,\n backdropReadMs: counts.backdropReadMs,\n lastBackdropReadMs: counts.lastBackdropReadMs,\n };\n },\n adaptation(element) {\n for (const a of adaptations.values())\n if (a.element === element)\n return a.material;\n return null;\n },\n simulateContextLoss() {\n gl?.getExtension(\"WEBGL_lose_context\")?.loseContext();\n },\n };\n}\n//# sourceMappingURL=webgl-backend.js.map"],"mappings":";A,uDAkBA,MAAMG,EAAWC,GAAM,KAAK,IAAI,EAAG,KAAK,IAAI,EAAGA,CAAC,CAA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