@zaisma/cli 0.24.0 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,953 @@
1
+ // The shader check's drawing, shared by Zaisma's check (apps/site/src/shader-check.ts, on Cloudflare Browser Rendering) and `zaisma check` on
2
+ // a shader's folder (zaisma.mjs, in a local Chrome), so both draw, time and judge a shader the same way; and the GLSL every runner compiles
3
+ // round a shader's mainImage, which packages/core re-exports for Zaisma's own pages, the game domain and the dashboard. No dependencies: it
4
+ // runs in Workers and in Node 18 or newer. Types: shader-check.d.mts. Backgrounds in docs/DEVELOPER-API.md says what it checks.
5
+
6
+ /*
7
+ * The glass pass every shader background runs inside (apps/site/src/components/foundations.ts, BACKDROP_SCRIPT, and the game
8
+ * domain's background runner): a shader is one mainImage function, and this is the main round it. Kept here so Zaisma's own pages,
9
+ * the game domain, the shader check and `zaisma check` all compile the same thing (wrapShader below). WebGL2's GLSL (GLSL ES 3.00):
10
+ * it writes zaismaFragColor, and reads where the glass sits from iGlassPanes and iGlassPaneCount, which SHADER_HEAD declares so a
11
+ * shader can read them too.
12
+ */
13
+
14
+ /** How many pieces of glass the runner tells a shader about: the largest ones in view. */
15
+ export const MOST_GLASS_PANE_COUNT = 16;
16
+
17
+ /**
18
+ * The runner's pass round any shader's mainImage (BACKDROP_SCRIPT): glass that bends the backdrop's light. Under each piece of glass
19
+ * it draws what's behind a little magnified and bent inward along the cut edge, as through thick glass; fainter under smoked glass.
20
+ * The light the glass gathers along its edge is the pane's own rim (GLASS_SCRIPT's caustics), so it moves with the pane as the page
21
+ * scrolls; the backdrop sits still under the page and could only follow a frame late. Everything is in the canvas's own pixels, from
22
+ * its bottom left. iGlassPanes (each pane's left, bottom, right and top) and iGlassPaneCount come from SHADER_HEAD.
23
+ */
24
+ export const GLASS_LIGHT_PASS = `
25
+ uniform vec4 zaismaPaneCuts[${MOST_GLASS_PANE_COUNT}]; // each pane's cut corners: top left, top right, bottom right, bottom left; 4096 added to the last on smoked glass
26
+ uniform float zaismaPixel; // canvas pixels per CSS pixel
27
+ uniform vec2 zaismaViewOffset; // where the canvas sits in the scene it shows a part of (the gallery's framed examples), in its pixels
28
+ out vec4 zaismaFragColor;
29
+ // Signed distance to a pane's cut shape (negative inside), and the outward normal of its nearest side.
30
+ float zaismaPaneShape(vec2 f, vec4 r, vec4 c, out vec2 n) {
31
+ vec2 h = (r.zw - r.xy) * 0.5, q = f - (r.xy + r.zw) * 0.5, a = abs(q) - h;
32
+ float d = length(max(a, 0.0)) + min(max(a.x, a.y), 0.0), k = 0.70710678, e;
33
+ n = a.x > a.y ? vec2(sign(q.x), 0.0) : vec2(0.0, sign(q.y));
34
+ if (c.x > 0.0) { e = (dot(q, vec2(-1.0, 1.0)) - (h.x + h.y - c.x)) * k; if (e > d) { d = e; n = vec2(-k, k); } }
35
+ if (c.y > 0.0) { e = (dot(q, vec2(1.0, 1.0)) - (h.x + h.y - c.y)) * k; if (e > d) { d = e; n = vec2(k, k); } }
36
+ if (c.z > 0.0) { e = (dot(q, vec2(1.0, -1.0)) - (h.x + h.y - c.z)) * k; if (e > d) { d = e; n = vec2(k, -k); } }
37
+ if (c.w > 0.0) { e = (dot(q, vec2(-1.0, -1.0)) - (h.x + h.y - c.w)) * k; if (e > d) { d = e; n = vec2(-k, -k); } }
38
+ return d;
39
+ }
40
+ void main() {
41
+ vec2 f = gl_FragCoord.xy, at = f;
42
+ // The panes come smallest first, so a pane on a tray bends the light under it, not the tray.
43
+ for (int i = 0; i < ${MOST_GLASS_PANE_COUNT}; i++) {
44
+ if (i >= iGlassPaneCount) break;
45
+ vec4 cuts = zaismaPaneCuts[i]; float smoke = step(4096.0, cuts.w); cuts.w = mod(cuts.w, 4096.0);
46
+ vec2 n; float d = zaismaPaneShape(f, iGlassPanes[i], cuts, n);
47
+ float strength = mix(1.0, 0.5, smoke), rim = 18.0 * zaismaPixel;
48
+ if (d < 0.0) {
49
+ float depth = -d, edge = 1.0 - smoothstep(0.0, rim, depth);
50
+ vec2 center = (iGlassPanes[i].xy + iGlassPanes[i].zw) * 0.5;
51
+ // Thick glass: what's behind is magnified a little and bent inward along the rim, most at the very edge.
52
+ at = center + (f - center) * (1.0 - 0.018 * strength) - n * rim * 0.45 * strength * edge * edge;
53
+ break;
54
+ }
55
+ }
56
+ vec4 color = vec4(0.0); mainImage(color, at + zaismaViewOffset);
57
+ zaismaFragColor = vec4(color.rgb, 1.0);
58
+ }`;
59
+
60
+ /** The main round a buffer pass's mainImage: no glass, and the buffer keeps all four channels it writes, alpha too. */
61
+ export const BUFFER_PASS = `
62
+ out vec4 zaismaFragColor;
63
+ void main() {
64
+ vec4 color = vec4(0.0); mainImage(color, gl_FragCoord.xy);
65
+ zaismaFragColor = color;
66
+ }`;
67
+
68
+ /**
69
+ * Shaders: Shadertoy's form, `void mainImage(out vec4 fragColor, in vec2 fragCoord)`, in WebGL2's GLSL (GLSL ES 3.00), so most
70
+ * Shadertoy shaders paste in and run: an image pass, up to four buffers that keep their picture between frames (Shadertoy's Buffers A
71
+ * to D) and up to four textures the developer sends, read through iChannel0 to iChannel3 (ShaderManifest). One shader serves every
72
+ * device: it reads iQuality (0 for phones and slow devices, 1, 2 for desktops), and the check holds each level to its own time.
73
+ * The check draws it before anyone sees it; players' browsers draw it at fewer pixels and at most 30 frames a second, stepping down a
74
+ * level, then to fewer pixels, then holding a still frame, on a device that can't keep up.
75
+ */
76
+ export const SHADER_LIMITS = {
77
+ /** Each pass's source, the image pass's and each buffer's: storage costs nothing, and the check's time is what protects devices. */
78
+ maximumPassSizeBytes: 65_536,
79
+ /** Buffers A to D. */
80
+ maximumBufferCount: 4,
81
+ /** iChannel0 to iChannel3, on each pass. */
82
+ maximumChannelCount: 4,
83
+ /** Textures one shader's channels name, all its passes together. */
84
+ maximumShaderTextureCount: 4,
85
+ /** Pictures of kind shader_texture a game keeps. */
86
+ maximumGameTextureCount: 16,
87
+ /** A texture's size: PNG, JPEG or WebP. */
88
+ maximumTextureSidePx: 4096,
89
+ maximumTextureSizeBytes: 8 * 1024 * 1024,
90
+ checkWidthPx: 640,
91
+ checkHeightPx: 360,
92
+ /** Frames the check draws and times at each quality level, in order from iTime 0 (buffers need their history), each frameStepSec on. */
93
+ checkFrameCount: 90,
94
+ checkFrameStepSec: 1 / 30,
95
+ /**
96
+ * Software rendering's speed varies up to twice over from one browser to the next, so the check first times Zaisma's own
97
+ * background as it was when the levels were set (CHECK_REFERENCE_SHADER in shader-check.ts) in the same browser, and scales the
98
+ * shader's median frame to it: check_frame_ms is what a frame takes on a renderer that draws that reference in referenceFrameMs.
99
+ */
100
+ referenceFrameMs: 25,
101
+ /**
102
+ * Each quality level's most check_frame_ms. A shader that never reads iQuality is timed once, against level 0's. Level 0 is phones'
103
+ * and keeps the limit set Oct 21, 2026 on Cloudflare Browser Rendering (SwiftShader) at 640 × 360, scaled: the looks drafts' shaders
104
+ * took 11–47 ms (frostline the slowest, 43–47) and a 256-step ray-march 90–109 ms; the slowest × 1.5, rounded up to 5 ms. Desktops are
105
+ * four times and more faster than phones, so level 1 gets twice that and level 2 four times (Oct 23, 2026).
106
+ */
107
+ qualityLevels: [
108
+ { qualityLevel: 0, maximumCheckFrameMs: 75 },
109
+ { qualityLevel: 1, maximumCheckFrameMs: 150 },
110
+ { qualityLevel: 2, maximumCheckFrameMs: 300 },
111
+ ],
112
+ /** The level each screen's still is drawn at: wide screens are desktops' and tablets', phone is phones'. */
113
+ stillQualityLevelByScreen: { wide: 2, phone: 0 },
114
+ /** WCAG 2.3.1: no more than three flashes in any one second. */
115
+ maximumFlashCountPerSec: 3,
116
+ /** When the still frame is drawn. */
117
+ stillTimeSec: 2,
118
+ /** The still's size, wide (phone turns it round): a single pass draws it at once at full size. */
119
+ stillWidthPx: 1920,
120
+ stillHeightPx: 1080,
121
+ /** A shader with buffers draws its whole history again for the still and the sampled frames, so at this size. */
122
+ bufferedStillWidthPx: 960,
123
+ bufferedStillHeightPx: 540,
124
+ /** After the still, a shader with buffers steps its history this far a frame to reach its sampled frames, so the check keeps to its time. */
125
+ sampledHistoryStepSec: 0.5,
126
+ /** Frames saved for the developer and the safety checks, spread over the first 30 seconds. */
127
+ sampledFrameCount: 6,
128
+ sampledFramesOverSec: 30,
129
+ /** How long one shader may take on the renderer altogether before it's called too slow. */
130
+ checkTimeoutSec: 240,
131
+ /** Checks before sending (POST /games/:slug/shader-checks) a developer can run in a day; the upload command's local check has no limit. */
132
+ maximumShaderChecksPerDay: 100,
133
+ /** How long a check before sending keeps its sheet picture. */
134
+ checkSheetKeptDurationSec: 24 * 3600,
135
+ /** Shaders kept per screen besides the chosen one: older pending and unchosen ones go. */
136
+ keptShaderCount: 4,
137
+ runtimeMaximumFps: 30,
138
+ runtimeResolutionScale: 0.5,
139
+ /**
140
+ * Upscaling (SHADER_UPSCALE_SOURCE in core): every pass draws at this share of runtimeResolutionScale (0.7 a side, half the pixels),
141
+ * and the sharpening upscale writes the canvas at runtimeUpscaleNumber times that, so it's as sharp as before for half the work.
142
+ */
143
+ runtimeDrawShareNumber: 0.7,
144
+ runtimeUpscaleNumber: 1.4,
145
+ /** After this long with no input on the page, a background draws at runtimeIdleFramesPerSec, and at runtimeMaximumFps again on the first input. */
146
+ runtimeIdleTimeoutSec: 60,
147
+ runtimeIdleFramesPerSec: 15,
148
+ };
149
+
150
+ /** Buffers A to D, as a shader names them. */
151
+ export const SHADER_BUFFER_NAMES = ["a", "b", "c", "d"];
152
+
153
+ /** The passes a runner draws each frame, in order: the buffers, a to d, then the image pass (bufferName null), drawn last onto the canvas. */
154
+ export function shaderPassesInDrawOrder(manifest) {
155
+ const buffers = [...manifest.buffers].sort((first, second) => SHADER_BUFFER_NAMES.indexOf(first.buffer_name) - SHADER_BUFFER_NAMES.indexOf(second.buffer_name));
156
+ return [...buffers.map((buffer) => ({ bufferName: buffer.buffer_name, source: buffer.source, channels: buffer.channels })), { bufferName: null, source: manifest.image.source, channels: manifest.image.channels }];
157
+ }
158
+
159
+ /** A shader's text without its comments, so what a comment says is never taken for code. */
160
+ export const shaderWithoutComments = (source) => source.replace(/\/\*[\s\S]*?\*\//g, " ").replace(/\/\/[^\n]*/g, "");
161
+
162
+ /** Whether a shader reads iQuality, so the check times each level and runners pick one; one that doesn't is timed once. */
163
+ export const shaderReadsQuality = (manifest) => shaderPassesInDrawOrder(manifest).some((pass) => /\biQuality\b/.test(shaderWithoutComments(pass.source)));
164
+
165
+ /**
166
+ * How a runner samples a channel, in WebGL2's names (gl[name]): a texture has mipmaps, so linear is trilinear; a buffer has none.
167
+ * The check and every runner sample the same way, so a shader looks the same wherever it runs.
168
+ */
169
+ export function shaderChannelSampling(channel) {
170
+ const hasMipmaps = channel.input_kind === "texture";
171
+ const minificationFilterName = channel.filter === "nearest" ? "NEAREST" : hasMipmaps ? "LINEAR_MIPMAP_LINEAR" : "LINEAR";
172
+ return { minificationFilterName, magnificationFilterName: channel.filter === "nearest" ? "NEAREST" : "LINEAR", wrapName: channel.wrap === "repeat" ? "REPEAT" : "CLAMP_TO_EDGE", hasMipmaps };
173
+ }
174
+
175
+ /**
176
+ * What runners pass to createImageBitmap for a texture: flipped, so it's upright with fragCoord's bottom left (Shadertoy's way), and
177
+ * its colors as they are, unpremultiplied, since shaders read textures as data too.
178
+ */
179
+ export const SHADER_TEXTURE_BITMAP_OPTIONS = { imageOrientation: "flipY", premultiplyAlpha: "none", colorSpaceConversion: "none" };
180
+
181
+ /**
182
+ * What comes before every pass's own source: WebGL2's GLSL, full precision (buffers often keep positions and speeds, not colors), and
183
+ * every input a pass reads. Shadertoy's names (docs/NAMING.md, shader): iResolution (pixels), iTime and iTimeDelta (seconds), iFrame
184
+ * (frames since the runner started), iChannel0 to iChannel3 with each one's iChannelResolution. Zaisma's own: iQuality (0 for phones and
185
+ * slow devices, 1, 2 for desktops), and where Zaisma's glass sits, iGlassPanes (left, bottom, right, top, in the shader's pixels from its
186
+ * bottom left, smallest first) and iGlassPaneCount (none in the check). `#line 1` makes a compiler's line numbers the developer's own.
187
+ */
188
+ export const SHADER_HEAD = `#version 300 es
189
+ precision highp float;
190
+ precision highp int;
191
+ precision highp sampler2D;
192
+ uniform vec3 iResolution;
193
+ uniform float iTime;
194
+ uniform float iTimeDelta;
195
+ uniform int iFrame;
196
+ uniform float iQuality;
197
+ uniform sampler2D iChannel0;
198
+ uniform sampler2D iChannel1;
199
+ uniform sampler2D iChannel2;
200
+ uniform sampler2D iChannel3;
201
+ uniform vec3 iChannelResolution[4];
202
+ uniform vec4 iGlassPanes[${MOST_GLASS_PANE_COUNT}];
203
+ uniform int iGlassPaneCount;
204
+ #line 1
205
+ `;
206
+
207
+
208
+ /**
209
+ * The whole fragment shader an image pass compiles: the head, the developer's mainImage, and the glass pass round it
210
+ * (GLASS_LIGHT_PASS). The check, the game domain's runner and the dashboard's preview all compile this, so a shader that passed the
211
+ * check runs the same everywhere.
212
+ */
213
+ export function wrapShader(source) {
214
+ return SHADER_HEAD + source + "\n" + GLASS_LIGHT_PASS;
215
+ }
216
+ /** The whole fragment shader a buffer pass compiles: the head and the developer's mainImage, drawn to the buffer with no glass. */
217
+ export function wrapShaderBuffer(source) {
218
+ return SHADER_HEAD + source + "\n" + BUFFER_PASS;
219
+ }
220
+ /** The whole fragment shader a pass compiles: the image pass with the glass round it, a buffer pass without. */
221
+ export const wrapShaderPass = (pass) => (pass.bufferName === null ? wrapShader(pass.source) : wrapShaderBuffer(pass.source));
222
+ /** The vertex shader every pass draws with: one triangle over the whole canvas, from the corners [-1, -1, 3, -1, -1, 3]. */
223
+ export const SHADER_VERTEX_SOURCE = "#version 300 es\nin vec2 corner;\nvoid main() { gl_Position = vec4(corner, 0.0, 1.0); }";
224
+
225
+ /*
226
+ * What the check times first, to measure the renderer's speed: Zaisma's own background, light, as it was when the quality levels' limits
227
+ * were set (Oct 21 and 23, 2026), copied here and never changed, so a new Zaisma's own never moves every game's limit.
228
+ */
229
+ const CHECK_REFERENCE_HELPERS = `
230
+ float h1(float n) { return fract(sin(n * 127.1) * 43758.5453); }
231
+ float h2(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }
232
+ vec2 h22(vec2 p) { p = vec2(dot(p, vec2(127.1, 311.7)), dot(p, vec2(269.5, 183.3))); return fract(sin(p) * 43758.5453); }
233
+ float noise(vec2 p) { vec2 i = floor(p), f = fract(p); vec2 u = f * f * (3.0 - 2.0 * f);
234
+ return mix(mix(h2(i), h2(i + vec2(1.0, 0.0)), u.x), mix(h2(i + vec2(0.0, 1.0)), h2(i + vec2(1.0, 1.0)), u.x), u.y); }
235
+ float fbm(vec2 p) { float v = 0.0, a = 0.5; for (int i = 0; i < 5; i++) { v += a * noise(p); p = p * 2.03 + 1.7; a *= 0.5; } return v; }
236
+ // Soft particles in a grid of cells: each cell holds at most one, at a random spot, drifting with the grid.
237
+ float motes(vec2 p, float size, float chance, float seed) {
238
+ vec2 id = floor(p), f = fract(p) - 0.5; vec2 r = h22(id + seed) - 0.5;
239
+ float on = step(1.0 - chance, h2(id + seed * 1.3));
240
+ float d = length(f - r * 0.7);
241
+ return on * smoothstep(size, 0.0, d);
242
+ }
243
+ `;
244
+ const CHECK_REFERENCE_ZAISMA = `
245
+ void mainImage(out vec4 o, in vec2 f) {
246
+ vec2 uv = f / iResolution.xy; float ar = iResolution.x / iResolution.y; float t = iTime;
247
+ vec2 p = vec2(uv.x * ar, uv.y) * 3.6;
248
+ vec2 g = floor(p), fr = fract(p); float d1 = 8.0, d2 = 8.0; vec2 cid = vec2(0.0);
249
+ for (int j = -1; j <= 1; j++) for (int i = -1; i <= 1; i++) {
250
+ vec2 o2 = vec2(float(i), float(j)); vec2 h = h22(g + o2);
251
+ vec2 pt = o2 + 0.5 + 0.36 * sin(t * 0.11 + 6.2831 * h);
252
+ vec2 r = pt - fr; float d = dot(r, r);
253
+ if (d < d1) { d2 = d1; d1 = d; cid = g + o2; } else if (d < d2) d2 = d;
254
+ }
255
+ vec2 tilt = h22(cid * 1.7) - 0.5;
256
+ vec2 sun = vec2(cos(t * 0.04), sin(t * 0.04));
257
+ float shade = 0.5 + 0.5 * dot(normalize(tilt + 0.001), sun) * length(tilt) * 1.6;
258
+ float sweep = exp(-pow(uv.x * 0.8 + uv.y * 0.5 - (fract(t * 0.025) * 2.4 - 0.4), 2.0) * 24.0);
259
+ float edge = sqrt(d2) - sqrt(d1);
260
+ vec3 orange = vec3(0.969, 0.576, 0.102);
261
+ vec2 P = vec2(uv.x * ar, uv.y); float core = 0.0, glow = 0.0, near = 0.0;
262
+ for (int k = 0; k < 7; k++) {
263
+ float fk = float(k); vec2 hk = h22(vec2(fk * 7.13 + 1.0, fk * 3.71 + 2.0)); float sp = 0.05 + 0.06 * hk.x;
264
+ vec2 c = vec2(ar * (0.5 + 0.38 * sin(t * sp + 6.2831 * hk.y) + 0.1 * sin(t * sp * 2.3 + fk * 1.7)),
265
+ 0.5 + 0.34 * cos(t * sp * 0.83 + 6.2831 * hk.x) + 0.1 * sin(t * sp * 1.9 + fk * 2.9));
266
+ vec2 q = P - c; float dia = abs(q.x) + abs(q.y); float br = 0.6 + 0.4 * sin(t * 0.9 + fk * 1.3);
267
+ core = max(core, smoothstep(0.015, 0.0105, dia));
268
+ glow += exp(-dia * 36.0) * br;
269
+ near += exp(-length(q) * 7.0) * br;
270
+ }
271
+ float seam = 1.0 - smoothstep(0.0, 0.024, edge);
272
+ // Light: pearl-white facets.
273
+ vec3 light = mix(vec3(0.885, 0.905, 0.94), vec3(1.0), shade);
274
+ light += vec3(1.0, 0.97, 0.92) * sweep * 0.05;
275
+ light = mix(light, vec3(1.0), (1.0 - smoothstep(0.0, 0.04, edge)) * 0.75);
276
+ light -= (1.0 - smoothstep(0.0, 0.012, edge)) * 0.045;
277
+ light = mix(light, orange, seam * min(near, 1.0) * 0.4);
278
+ light += orange * glow * 0.28;
279
+ light = mix(light, orange, core);
280
+ light *= 0.975 + 0.04 * uv.y;
281
+ // Dark: graphite facets under a cool sweep, the nodes glowing onto them.
282
+ vec3 dark = mix(vec3(0.062, 0.072, 0.092), vec3(0.135, 0.152, 0.188), shade);
283
+ dark += vec3(0.55, 0.66, 0.9) * sweep * 0.045;
284
+ dark = mix(dark, vec3(0.27, 0.3, 0.36), (1.0 - smoothstep(0.0, 0.03, edge)) * 0.55);
285
+ dark -= (1.0 - smoothstep(0.0, 0.01, edge)) * 0.03;
286
+ dark += orange * min(near, 1.5) * 0.07;
287
+ dark += orange * seam * min(near, 1.0) * 0.85;
288
+ dark += orange * glow * 0.7;
289
+ dark = mix(dark, vec3(1.0, 0.74, 0.34), core);
290
+ dark *= 0.88 + 0.16 * uv.y;
291
+ o = vec4(mix(light, dark, iDark), 1.0);
292
+ }`;
293
+ export const CHECK_REFERENCE_SHADER = wrapShader(`uniform float iDark;\n${CHECK_REFERENCE_HELPERS}${CHECK_REFERENCE_ZAISMA}`);
294
+
295
+ /** Frames the reference is timed over. */
296
+ const REFERENCE_FRAME_COUNT = 30;
297
+ /** The frame of level 0's timed run, and the next, whose change the shimmer note reads. */
298
+ const SHIMMER_FRAME_INDEX = 60;
299
+
300
+ /**
301
+ * The sheet a check before sending answers with, as Zaisma's pages would show the shader: wide (a 1440 × 900 window, drawn at about the
302
+ * pixels a desktop draws) and phone (320 × 667), each under a pane of glass picked as the pages pick it; small; what changes between
303
+ * two frames 1/30 s apart, magnified 6 times, where speckle is shimmer; and the small view's middle pixel for pixel.
304
+ */
305
+ const SHEET_VIEWS = {
306
+ wide: { widthPx: 720, heightPx: 450, cssWidthPx: 1440, cssHeightPx: 900, qualityLevel: 2, pane: [96, 300, 460, 300] },
307
+ phone: { widthPx: 168, heightPx: 350, cssWidthPx: 320, cssHeightPx: 667, qualityLevel: 0, pane: [16, 430, 288, 210] },
308
+ small: { widthPx: 400, heightPx: 225, cssWidthPx: 400, cssHeightPx: 225, qualityLevel: 0, pane: null },
309
+ };
310
+
311
+ /** The check's page: no network, nothing but a canvas and the script that draws on it. Textures come in as base64 parts first. */
312
+ export const SHADER_CHECK_PAGE = `<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline'; img-src data: blob:"><body style="margin:0"><script>
313
+ window.zaismaTextureParts = [];
314
+ window.zaismaTexturePart = function (index, part) { (window.zaismaTextureParts[index] = window.zaismaTextureParts[index] || []).push(part); };
315
+ window.zaismaCheck = async function (input) {
316
+ var canvas = document.createElement("canvas"); canvas.width = input.checkWidthPx; canvas.height = input.checkHeightPx; document.body.appendChild(canvas);
317
+ var gl = canvas.getContext("webgl2", { antialias: false, depth: false, stencil: false, alpha: false, preserveDrawingBuffer: true });
318
+ if (!gl) throw new Error("No WebGL2 on the renderer");
319
+ var canDrawFloat = !!gl.getExtension("EXT_color_buffer_float");
320
+ var step = input.checkFrameStepSec;
321
+ var drawn = { compileError: null, referenceFrameTimesMs: [], levels: [], stillDataUrl: null, smallStillDataUrl: null, frameDataUrls: [], shimmerDataUrls: [], sheetDataUrl: null };
322
+ function compile(kind, source) { var shader = gl.createShader(kind); gl.shaderSource(shader, source); gl.compileShader(shader); return shader; }
323
+ function firstLine(log, fallback) { return (log || "").split("\\n").map(function (line) { return line.trim(); }).filter(Boolean)[0] || fallback; }
324
+ var vertex = compile(gl.VERTEX_SHADER, input.vertexSource);
325
+ gl.bindVertexArray(gl.createVertexArray());
326
+ gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
327
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);
328
+ gl.enableVertexAttribArray(0); gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
329
+ var UNIFORMS = ["iResolution", "iTime", "iTimeDelta", "iFrame", "iQuality", "iChannel0", "iChannel1", "iChannel2", "iChannel3", "iChannelResolution", "iGlassPanes", "iGlassPaneCount", "zaismaPaneCuts", "zaismaPixel", "zaismaViewOffset"];
330
+ // A fragment shader built into a program, or its first compiler error.
331
+ function build(fragmentSource) {
332
+ var fragment = compile(gl.FRAGMENT_SHADER, fragmentSource);
333
+ if (!gl.getShaderParameter(fragment, gl.COMPILE_STATUS)) return { error: firstLine(gl.getShaderInfoLog(fragment), "It didn't compile.") };
334
+ var program = gl.createProgram(); gl.attachShader(program, vertex); gl.attachShader(program, fragment); gl.bindAttribLocation(program, 0, "corner"); gl.linkProgram(program);
335
+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) return { error: firstLine(gl.getProgramInfoLog(program), "It didn't link.") };
336
+ var at = {}; UNIFORMS.forEach(function (name) { at[name] = gl.getUniformLocation(program, name); });
337
+ return { program: program, at: at };
338
+ }
339
+ // Textures: decoded from their bytes, upright as on Shadertoy, with mipmaps.
340
+ var textures = [];
341
+ for (var t = 0; t < input.textureCount; t++) {
342
+ var binary = atob((window.zaismaTextureParts[t] || []).join("")), bytes = new Uint8Array(binary.length);
343
+ for (var b = 0; b < binary.length; b++) bytes[b] = binary.charCodeAt(b);
344
+ var bitmap = await createImageBitmap(new Blob([bytes]), input.bitmapOptions);
345
+ var texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture);
346
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, bitmap); gl.generateMipmap(gl.TEXTURE_2D);
347
+ textures.push({ texture: texture, widthPx: bitmap.width, heightPx: bitmap.height });
348
+ }
349
+ var black = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, black);
350
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([0, 0, 0, 255]));
351
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
352
+ var samplers = {};
353
+ function samplerFor(channel) {
354
+ var key = channel.minificationFilterName + " " + channel.magnificationFilterName + " " + channel.wrapName;
355
+ if (!samplers[key]) {
356
+ var sampler = gl.createSampler();
357
+ gl.samplerParameteri(sampler, gl.TEXTURE_MIN_FILTER, gl[channel.minificationFilterName]); gl.samplerParameteri(sampler, gl.TEXTURE_MAG_FILTER, gl[channel.magnificationFilterName]);
358
+ gl.samplerParameteri(sampler, gl.TEXTURE_WRAP_S, gl[channel.wrapName]); gl.samplerParameteri(sampler, gl.TEXTURE_WRAP_T, gl[channel.wrapName]);
359
+ samplers[key] = sampler;
360
+ }
361
+ return samplers[key];
362
+ }
363
+ var passes = [];
364
+ for (var p = 0; p < input.passes.length; p++) {
365
+ var built = build(input.passes[p].fragmentSource);
366
+ if (built.error) { drawn.compileError = (input.passes[p].bufferName ? "buffer " + input.passes[p].bufferName + ": " : "") + built.error; return drawn; }
367
+ passes.push({ spec: input.passes[p], program: built.program, at: built.at, targets: null, front: 0 });
368
+ }
369
+ var size = { widthPx: 0, heightPx: 0 };
370
+ // A buffer's two pictures, drawn in turn: half floats where the browser can draw to them, else 8 bits a channel; each starts empty.
371
+ function target(widthPx, heightPx) {
372
+ var texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture);
373
+ if (canDrawFloat) gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA16F, widthPx, heightPx, 0, gl.RGBA, gl.HALF_FLOAT, null);
374
+ else gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, widthPx, heightPx, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
375
+ var framebuffer = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
376
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
377
+ gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT);
378
+ return { texture: texture, framebuffer: framebuffer };
379
+ }
380
+ // A new size starts every buffer empty, as a runner's resize does.
381
+ function setSize(widthPx, heightPx) {
382
+ canvas.width = widthPx; canvas.height = heightPx; size.widthPx = widthPx; size.heightPx = heightPx;
383
+ passes.forEach(function (pass) {
384
+ if (!pass.spec.bufferName) return;
385
+ if (pass.targets) pass.targets.forEach(function (old) { gl.deleteTexture(old.texture); gl.deleteFramebuffer(old.framebuffer); });
386
+ pass.targets = [target(widthPx, heightPx), target(widthPx, heightPx)]; pass.front = 0;
387
+ });
388
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
389
+ }
390
+ // One frame: each buffer a to d onto its next picture, reading the newest picture of each buffer it names (its own last frame for
391
+ // itself), then the image pass onto the canvas. imageOnly draws the image pass again over the same buffers, under glass.
392
+ function drawFrame(list, frame) {
393
+ for (var index = 0; index < list.length; index++) {
394
+ var pass = list[index];
395
+ if (frame.imageOnly && pass.spec.bufferName) continue;
396
+ var into = pass.spec.bufferName ? pass.targets[1 - pass.front] : null, at = pass.at;
397
+ gl.bindFramebuffer(gl.FRAMEBUFFER, into ? into.framebuffer : null);
398
+ gl.viewport(0, 0, size.widthPx, size.heightPx);
399
+ gl.useProgram(pass.program);
400
+ gl.uniform3f(at.iResolution, size.widthPx, size.heightPx, 1); gl.uniform1f(at.iTime, frame.timeSec); gl.uniform1f(at.iTimeDelta, frame.deltaSec);
401
+ gl.uniform1i(at.iFrame, frame.frameIndex); gl.uniform1f(at.iQuality, frame.qualityLevel);
402
+ var resolutions = new Float32Array(12);
403
+ for (var unit = 0; unit < 4; unit++) {
404
+ var channel = null;
405
+ for (var c = 0; c < pass.spec.channels.length; c++) if (pass.spec.channels[c].channelIndex === unit) channel = pass.spec.channels[c];
406
+ gl.activeTexture(gl.TEXTURE0 + unit);
407
+ if (channel && channel.bufferPassIndex >= 0) {
408
+ var source = passes[channel.bufferPassIndex];
409
+ gl.bindTexture(gl.TEXTURE_2D, source.targets[source.front].texture); gl.bindSampler(unit, samplerFor(channel));
410
+ resolutions[unit * 3] = size.widthPx; resolutions[unit * 3 + 1] = size.heightPx; resolutions[unit * 3 + 2] = 1;
411
+ } else if (channel && channel.textureIndex >= 0) {
412
+ var read = textures[channel.textureIndex];
413
+ gl.bindTexture(gl.TEXTURE_2D, read.texture); gl.bindSampler(unit, samplerFor(channel));
414
+ resolutions[unit * 3] = read.widthPx; resolutions[unit * 3 + 1] = read.heightPx; resolutions[unit * 3 + 2] = 1;
415
+ } else { gl.bindTexture(gl.TEXTURE_2D, black); gl.bindSampler(unit, null); }
416
+ gl.uniform1i(at["iChannel" + unit], unit);
417
+ }
418
+ gl.uniform3fv(at.iChannelResolution, resolutions);
419
+ var panes = frame.panes || [], rects = new Float32Array(64), cuts = new Float32Array(64);
420
+ for (var i = 0; i < panes.length; i++) { rects.set(panes[i].rect, i * 4); cuts.set(panes[i].cuts, i * 4); }
421
+ gl.uniform4fv(at.iGlassPanes, rects); gl.uniform1i(at.iGlassPaneCount, panes.length);
422
+ gl.uniform4fv(at.zaismaPaneCuts, cuts); gl.uniform1f(at.zaismaPixel, frame.pixelScale || 1); gl.uniform2f(at.zaismaViewOffset, 0, 0);
423
+ gl.drawArrays(gl.TRIANGLES, 0, 3);
424
+ if (into) pass.front = 1 - pass.front;
425
+ }
426
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
427
+ }
428
+ var onePixel = new Uint8Array(4);
429
+ // Reading a pixel waits until the frame is really drawn.
430
+ function finish() { gl.finish(); gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, onePixel); }
431
+ function pixels() { var read = new Uint8Array(size.widthPx * size.heightPx * 4); gl.readPixels(0, 0, size.widthPx, size.heightPx, gl.RGBA, gl.UNSIGNED_BYTE, read); return read; }
432
+ function linear(value) { value /= 255; return value <= 0.04045 ? value / 12.92 : Math.pow((value + 0.055) / 1.055, 2.4); }
433
+ function luminance(read) { var sum = 0, count = 0; for (var q = 0; q < read.length; q += 4 * 7) { sum += 0.2126 * linear(read[q]) + 0.7152 * linear(read[q + 1]) + 0.0722 * linear(read[q + 2]); count++; } return sum / count; }
434
+
435
+ // The renderer's speed varies from browser to browser, so a known shader is timed first, in the same browser, to measure against.
436
+ var reference = build(input.referenceSource);
437
+ if (reference.error) throw new Error("The reference shader didn't compile: " + reference.error);
438
+ var referenceList = [{ spec: { bufferName: null, channels: [] }, program: reference.program, at: reference.at }];
439
+ setSize(input.checkWidthPx, input.checkHeightPx);
440
+ for (var r = 0; r < input.referenceFrameCount; r++) {
441
+ var referenceStartedMs = performance.now();
442
+ drawFrame(referenceList, { timeSec: r * step, deltaSec: step, frameIndex: r, qualityLevel: 0 }); finish();
443
+ drawn.referenceFrameTimesMs.push(performance.now() - referenceStartedMs);
444
+ }
445
+ var sortedReference = drawn.referenceFrameTimesMs.slice().sort(function (first, second) { return first - second; });
446
+ var speedNumber = sortedReference[Math.floor(sortedReference.length / 2)] / input.referenceFrameMs;
447
+ var shimmerPixels = [];
448
+ for (var l = 0; l < input.qualityLevels.length; l++) {
449
+ var qualityLevel = input.qualityLevels[l], slowFrameMs = input.maximumCheckFrameMsByLevel[qualityLevel] * speedNumber;
450
+ var level = { qualityLevel: qualityLevel, frameTimesMs: [], frameLuminances: [] };
451
+ drawn.levels.push(level);
452
+ setSize(input.checkWidthPx, input.checkHeightPx);
453
+ for (var n = 0; n < input.checkFrameCount; n++) {
454
+ var startedMs = performance.now();
455
+ drawFrame(passes, { timeSec: n * step, deltaSec: step, frameIndex: n, qualityLevel: qualityLevel }); finish();
456
+ level.frameTimesMs.push(performance.now() - startedMs);
457
+ var read = pixels();
458
+ level.frameLuminances.push(luminance(read));
459
+ if (input.isSheetWanted && l === 0 && (n === input.shimmerFrameIndex || n === input.shimmerFrameIndex + 1)) { drawn.shimmerDataUrls.push(canvas.toDataURL("image/png")); shimmerPixels.push(read); }
460
+ // Far over the limit: no need to draw the rest, or the other levels. The frames so far, past the first (which compiles),
461
+ // must be, not one frame: a browser can stall a frame now and then, and on a fast GPU that alone is many times the limit.
462
+ if (n >= 4) {
463
+ var sortedSoFar = level.frameTimesMs.slice(1).sort(function (first, second) { return first - second; });
464
+ if (sortedSoFar[Math.floor(sortedSoFar.length / 2)] > slowFrameMs * 4) return drawn;
465
+ }
466
+ }
467
+ }
468
+
469
+ // The still and the sampled frames, at the level the screen runs. A single pass draws each moment at once; a shader with buffers runs
470
+ // its history again from iTime 0 at the still's size, each frameStepSec to the still, then sampledHistoryStepSec on.
471
+ var stillLevel = input.stillQualityLevel, stillFrameIndex = Math.round(input.stillTimeSec / step);
472
+ function snapshot(widthPx, heightPx) { var copy = document.createElement("canvas"); copy.width = widthPx || canvas.width; copy.height = heightPx || canvas.height; copy.getContext("2d").drawImage(canvas, 0, 0, copy.width, copy.height); return copy; }
473
+ if (!input.isBuffered) {
474
+ setSize(input.checkWidthPx, input.checkHeightPx);
475
+ drawFrame(passes, { timeSec: input.stillTimeSec, deltaSec: step, frameIndex: stillFrameIndex, qualityLevel: stillLevel });
476
+ drawn.smallStillDataUrl = canvas.toDataURL("image/png");
477
+ drawn.frameDataUrls = input.sampledTimesSec.map(function (timeSec) { drawFrame(passes, { timeSec: timeSec, deltaSec: step, frameIndex: Math.round(timeSec / step), qualityLevel: stillLevel }); return canvas.toDataURL("image/png"); });
478
+ setSize(input.stillWidthPx, input.stillHeightPx);
479
+ drawFrame(passes, { timeSec: input.stillTimeSec, deltaSec: step, frameIndex: stillFrameIndex, qualityLevel: stillLevel });
480
+ drawn.stillDataUrl = canvas.toDataURL("image/png");
481
+ } else {
482
+ setSize(input.stillWidthPx, input.stillHeightPx);
483
+ var lastTimeSec = input.sampledTimesSec[input.sampledTimesSec.length - 1], sampleIndex = 0;
484
+ var frameCount = stillFrameIndex + Math.ceil((lastTimeSec - input.stillTimeSec) / input.sampledHistoryStepSec - 1e-6);
485
+ for (var k = 0; k <= frameCount; k++) {
486
+ var isBeforeStill = k <= stillFrameIndex, timeSec = isBeforeStill ? k * step : input.stillTimeSec + (k - stillFrameIndex) * input.sampledHistoryStepSec;
487
+ drawFrame(passes, { timeSec: timeSec, deltaSec: isBeforeStill ? step : input.sampledHistoryStepSec, frameIndex: k, qualityLevel: stillLevel });
488
+ if (k === stillFrameIndex) { drawn.stillDataUrl = canvas.toDataURL("image/png"); drawn.smallStillDataUrl = snapshot(input.checkWidthPx, input.checkHeightPx).toDataURL("image/png"); }
489
+ while (sampleIndex < input.sampledTimesSec.length && timeSec >= input.sampledTimesSec[sampleIndex] - 1e-6) { drawn.frameDataUrls.push(canvas.toDataURL("image/png")); sampleIndex++; }
490
+ }
491
+ }
492
+ if (!input.isSheetWanted) return drawn;
493
+
494
+ // The sheet. The glass over each view is picked as Zaisma's pages pick it (background-tone.ts): light or smoked, as thin as words allow.
495
+ function shade(color) { return 0.2126 * linear(color[0]) + 0.7152 * linear(color[1]) + 0.0722 * linear(color[2]); }
496
+ function contrast(first, second) { var a = shade(first), z = shade(second); return (Math.max(a, z) + 0.05) / (Math.min(a, z) + 0.05); }
497
+ function blend(from, to, share) { return [from[0] + (to[0] - from[0]) * share, from[1] + (to[1] - from[1]) * share, from[2] + (to[2] - from[2]) * share]; }
498
+ function thinnest(isSmoked, base, sorted) {
499
+ var harsh = isSmoked ? sorted[Math.floor(sorted.length * 0.75)] : sorted[Math.floor(sorted.length * 0.25)];
500
+ for (var share = 0.3; share <= 0.95; share += 0.02) {
501
+ var seen = blend(harsh, base, share), ink = isSmoked ? [247, 249, 252] : [20, 23, 28], quiet = isSmoked ? blend(seen, ink, 0.7) : [89, 96, 106];
502
+ if (contrast(seen, quiet) >= 4.5 && contrast(seen, ink) >= 6) return share;
503
+ }
504
+ return 0.95;
505
+ }
506
+ function pickGlass(read) {
507
+ var colors = [], skip = 4 * Math.max(1, Math.floor(read.length / 4 / 2400));
508
+ for (var q = 0; q < read.length; q += skip) colors.push([read[q], read[q + 1], read[q + 2]]);
509
+ var sum = colors.reduce(function (total, color) { return [total[0] + color[0], total[1] + color[1], total[2] + color[2]]; }, [0, 0, 0]), average = sum.map(function (value) { return value / colors.length; });
510
+ var sorted = colors.slice().sort(function (first, second) { return shade(first) - shade(second); });
511
+ var light = blend([255, 255, 255], average, 0.1), smoked = blend([12, 15, 20], average, 0.3), lightShare = thinnest(false, light, sorted), smokedShare = thinnest(true, smoked, sorted);
512
+ var isSmoked = lightShare > smokedShare;
513
+ return { isSmoked: isSmoked, base: (isSmoked ? smoked : light).map(Math.round), share: Math.min(lightShare, smokedShare) };
514
+ }
515
+ function drawView(view) {
516
+ setSize(view.widthPx, view.heightPx);
517
+ var scale = view.widthPx / view.cssWidthPx;
518
+ for (var k = input.isBuffered ? 0 : stillFrameIndex; k <= stillFrameIndex; k++) drawFrame(passes, { timeSec: k * step, deltaSec: step, frameIndex: k, qualityLevel: view.qualityLevel });
519
+ var pick = pickGlass(pixels()), plain = snapshot();
520
+ if (!view.pane) return { plain: plain, glassed: plain, pick: pick };
521
+ var r = view.pane, rect = [r[0] * scale, (view.cssHeightPx - r[1] - r[3]) * scale, (r[0] + r[2]) * scale, (view.cssHeightPx - r[1]) * scale];
522
+ drawFrame(passes, { timeSec: stillFrameIndex * step, deltaSec: step, frameIndex: stillFrameIndex, qualityLevel: view.qualityLevel, imageOnly: true, pixelScale: scale, panes: [{ rect: rect, cuts: [18 * scale, 0, 18 * scale, 14 * scale + (pick.isSmoked ? 4096 : 0)] }] });
523
+ return { plain: plain, glassed: snapshot(), pick: pick };
524
+ }
525
+ function cutPath(context, x, y, w, h, a, z) { context.beginPath(); context.moveTo(x + a, y); context.lineTo(x + w, y); context.lineTo(x + w, y + h - a); context.lineTo(x + w - a, y + h); context.lineTo(x + z, y + h); context.lineTo(x, y + h - z); context.lineTo(x, y + a); context.closePath(); }
526
+ function glassOver(context, image, dx, dy, dw, dh, view, pick) {
527
+ var sx = dw / view.cssWidthPx, sy = dh / view.cssHeightPx, x = dx + view.pane[0] * sx, y = dy + view.pane[1] * sy, w = view.pane[2] * sx, h = view.pane[3] * sy;
528
+ context.save(); cutPath(context, x, y, w, h, 18 * sx, 14 * sx); context.clip();
529
+ context.filter = "blur(" + Math.round(18 * sx) + "px) saturate(1.4)"; context.drawImage(image, dx, dy, dw, dh); context.filter = "none";
530
+ context.fillStyle = "rgba(" + pick.base.join(",") + "," + pick.share.toFixed(2) + ")"; context.fillRect(x, y, w, h);
531
+ context.restore();
532
+ context.save(); cutPath(context, x + 0.5, y + 0.5, w - 1, h - 1, 18 * sx, 14 * sx); context.strokeStyle = pick.isSmoked ? "rgba(255,255,255,0.28)" : "rgba(255,255,255,0.7)"; context.lineWidth = 1; context.stroke(); context.restore();
533
+ context.fillStyle = pick.isSmoked ? "#F7F9FC" : "#14171C"; context.font = "600 " + Math.round(20 * sx) + "px sans-serif"; context.fillText("Your game", x + 20 * sx, y + 38 * sy);
534
+ context.fillStyle = pick.isSmoked ? "rgba(247,249,252,0.72)" : "#59606A"; context.font = "500 " + Math.round(13 * sx) + "px sans-serif"; context.fillText("Words on Zaisma's glass", x + 20 * sx, y + 62 * sy);
535
+ }
536
+ function label(context, text, x, y) { context.font = "500 12px monospace"; context.fillStyle = "rgba(0,0,0,0.65)"; context.fillRect(x, y, context.measureText(text).width + 10, 18); context.fillStyle = "#fff"; context.fillText(text, x + 5, y + 13); }
537
+ var sheet = document.createElement("canvas"); sheet.width = 1280; sheet.height = 745;
538
+ var context = sheet.getContext("2d"); context.fillStyle = "#1a1d22"; context.fillRect(0, 0, sheet.width, sheet.height);
539
+ var views = input.sheetViews, wide = drawView(views.wide), phone = drawView(views.phone), small = drawView(views.small);
540
+ context.drawImage(wide.glassed, 0, 0, 800, 500); glassOver(context, wide.glassed, 0, 0, 800, 500, views.wide, wide.pick);
541
+ label(context, "wide, quality " + views.wide.qualityLevel + ", " + (wide.pick.isSmoked ? "smoked" : "light") + " glass " + wide.pick.share.toFixed(2), 6, 6);
542
+ context.drawImage(phone.glassed, 810, 0, 240, 500); glassOver(context, phone.glassed, 810, 0, 240, 500, views.phone, phone.pick);
543
+ label(context, "phone, quality " + views.phone.qualityLevel, 814, 6);
544
+ context.imageSmoothingEnabled = false; context.drawImage(small.plain, 163, 57, 73, 111, 1060, 0, 220, 334); context.imageSmoothingEnabled = true;
545
+ label(context, "small, pixels x3", 1064, 6);
546
+ context.drawImage(small.plain, 0, 510, 400, 225); label(context, "small, " + views.small.widthPx + " by " + views.small.heightPx, 4, 514);
547
+ if (shimmerPixels.length === 2) {
548
+ var widthPx = input.checkWidthPx, heightPx = input.checkHeightPx, change = context.createImageData(widthPx, heightPx), first = shimmerPixels[0], second = shimmerPixels[1];
549
+ for (var y = 0; y < heightPx; y++) for (var x = 0; x < widthPx; x++) {
550
+ var from = ((heightPx - 1 - y) * widthPx + x) * 4, to = (y * widthPx + x) * 4;
551
+ for (var channelIndex = 0; channelIndex < 3; channelIndex++) change.data[to + channelIndex] = Math.min(255, Math.abs(first[from + channelIndex] - second[from + channelIndex]) * 6);
552
+ change.data[to + 3] = 255;
553
+ }
554
+ var changeCanvas = document.createElement("canvas"); changeCanvas.width = widthPx; changeCanvas.height = heightPx; changeCanvas.getContext("2d").putImageData(change, 0, 0);
555
+ context.drawImage(changeCanvas, 410, 510, 400, 225); label(context, "change in 1/30 s, x6", 414, 514);
556
+ }
557
+ context.font = "500 13px monospace"; context.fillStyle = "#d8dce3";
558
+ drawn.levels.forEach(function (timed, index) {
559
+ var sorted = timed.frameTimesMs.slice().sort(function (first, second) { return first - second; }), frameMs = sorted[Math.floor(sorted.length / 2)] / speedNumber;
560
+ context.fillText("quality " + timed.qualityLevel + ": " + frameMs.toFixed(1) + " ms a frame, the most " + input.maximumCheckFrameMsByLevel[timed.qualityLevel], 830, 540 + index * 22);
561
+ });
562
+ drawn.sheetDataUrl = sheet.toDataURL("image/png");
563
+ return drawn;
564
+ };</script>`;
565
+
566
+ /** The sizes a screen is checked and stilled at: landscape for wide, portrait for phones; a shader with buffers stills smaller. */
567
+ export function checkSizes(screen, isBuffered = false) {
568
+ const { checkWidthPx, checkHeightPx } = SHADER_LIMITS;
569
+ const [stillWidthPx, stillHeightPx] = isBuffered ? [SHADER_LIMITS.bufferedStillWidthPx, SHADER_LIMITS.bufferedStillHeightPx] : [SHADER_LIMITS.stillWidthPx, SHADER_LIMITS.stillHeightPx];
570
+ return screen === "wide" ? { checkWidthPx, checkHeightPx, stillWidthPx, stillHeightPx } : { checkWidthPx: checkHeightPx, checkHeightPx: checkWidthPx, stillWidthPx: stillHeightPx, stillHeightPx: stillWidthPx };
571
+ }
572
+
573
+ /** When the sampled frames are drawn: spread evenly over the first sampledFramesOverSec seconds. */
574
+ export const SAMPLED_TIMES_SEC = Array.from({ length: SHADER_LIMITS.sampledFrameCount }, (_, frameIndex) => (frameIndex * SHADER_LIMITS.sampledFramesOverSec) / (SHADER_LIMITS.sampledFrameCount - 1));
575
+
576
+ /** Base64 parts a texture goes to the page in, so no one message to the browser is big. */
577
+ const TEXTURE_PART_SIZE_BYTES = 768 * 1024;
578
+
579
+ function toBase64(bytes) {
580
+ let binary = "";
581
+ for (let byteIndex = 0; byteIndex < bytes.length; byteIndex += 0x8000) binary += String.fromCharCode(...bytes.subarray(byteIndex, byteIndex + 0x8000));
582
+ return btoa(binary);
583
+ }
584
+ function fromDataUrl(dataUrl) {
585
+ if (!dataUrl) return null;
586
+ const binary = atob(dataUrl.slice(dataUrl.indexOf(",") + 1));
587
+ return Uint8Array.from(binary, (character) => character.charCodeAt(0));
588
+ }
589
+
590
+ /**
591
+ * What the renderer draws for a shader: its passes wrapped in draw order, the textures its channels read (each { imageId, bytes }, by the
592
+ * image_id its channels name; a missing one reads black), the screen, the reference timed first, and the quality levels to time: all three
593
+ * for a shader that reads iQuality, else level 0 alone.
594
+ */
595
+ export function shaderRenderInputOf(manifest, screen, textures, isSheetWanted) {
596
+ return {
597
+ passes: shaderPassesInDrawOrder(manifest).map((pass) => ({ bufferName: pass.bufferName, fragmentSource: wrapShaderPass(pass), channels: pass.channels })),
598
+ textures,
599
+ screen,
600
+ referenceSource: CHECK_REFERENCE_SHADER,
601
+ qualityLevels: shaderReadsQuality(manifest) ? SHADER_LIMITS.qualityLevels.map((level) => level.qualityLevel) : [SHADER_LIMITS.qualityLevels[0].qualityLevel],
602
+ isSheetWanted,
603
+ };
604
+ }
605
+
606
+ /** What the page is given: the passes with each channel resolved to the pass or texture it reads and how it samples it. */
607
+ export function shaderCheckPageInput(input) {
608
+ const isBuffered = input.passes.some((pass) => pass.bufferName !== null);
609
+ return {
610
+ vertexSource: SHADER_VERTEX_SOURCE,
611
+ bitmapOptions: SHADER_TEXTURE_BITMAP_OPTIONS,
612
+ passes: input.passes.map((pass) => ({
613
+ bufferName: pass.bufferName,
614
+ fragmentSource: pass.fragmentSource,
615
+ channels: pass.channels.map((channel) => ({
616
+ channelIndex: channel.channel_index,
617
+ bufferPassIndex: channel.input_kind === "buffer" ? input.passes.findIndex((other) => other.bufferName === channel.buffer_name) : -1,
618
+ textureIndex: channel.input_kind === "texture" ? input.textures.findIndex((texture) => texture.imageId === channel.image_id) : -1,
619
+ ...shaderChannelSampling(channel),
620
+ })),
621
+ })),
622
+ textureCount: input.textures.length,
623
+ referenceSource: input.referenceSource,
624
+ referenceFrameCount: REFERENCE_FRAME_COUNT,
625
+ referenceFrameMs: SHADER_LIMITS.referenceFrameMs,
626
+ ...checkSizes(input.screen, isBuffered),
627
+ isBuffered,
628
+ qualityLevels: input.qualityLevels,
629
+ maximumCheckFrameMsByLevel: Object.fromEntries(SHADER_LIMITS.qualityLevels.map((level) => [level.qualityLevel, level.maximumCheckFrameMs])),
630
+ stillQualityLevel: input.qualityLevels.length > 1 ? SHADER_LIMITS.stillQualityLevelByScreen[input.screen] : input.qualityLevels[0],
631
+ checkFrameCount: SHADER_LIMITS.checkFrameCount,
632
+ checkFrameStepSec: SHADER_LIMITS.checkFrameStepSec,
633
+ stillTimeSec: SHADER_LIMITS.stillTimeSec,
634
+ sampledTimesSec: SAMPLED_TIMES_SEC,
635
+ sampledHistoryStepSec: SHADER_LIMITS.sampledHistoryStepSec,
636
+ isSheetWanted: input.isSheetWanted,
637
+ shimmerFrameIndex: SHIMMER_FRAME_INDEX,
638
+ sheetViews: SHEET_VIEWS,
639
+ };
640
+ }
641
+
642
+ /**
643
+ * What a browser evaluates on SHADER_CHECK_PAGE, in order: each texture's base64 parts, then the check, which answers the page's drawing.
644
+ * Expressions, not functions: a bundled function's text can carry helpers the page doesn't have.
645
+ */
646
+ export function shaderCheckPageExpressions(input) {
647
+ const textureExpressions = [];
648
+ for (const [textureIndex, texture] of input.textures.entries()) {
649
+ const encoded = toBase64(texture.bytes);
650
+ for (let partStartIndex = 0; partStartIndex < encoded.length; partStartIndex += TEXTURE_PART_SIZE_BYTES) textureExpressions.push(`window.zaismaTexturePart(${textureIndex}, ${JSON.stringify(encoded.slice(partStartIndex, partStartIndex + TEXTURE_PART_SIZE_BYTES))})`);
651
+ }
652
+ return { textureExpressions, checkExpression: `window.zaismaCheck(${JSON.stringify(shaderCheckPageInput(input))})` };
653
+ }
654
+
655
+ /** The page's drawing as the check reads it, its pictures as PNG bytes; null (out of time) counts as too slow at the first level, with the time it had. */
656
+ export function shaderRenderFromPage(drawn, input) {
657
+ if (!drawn) {
658
+ return { compileError: null, referenceFrameTimesMs: [], levels: [{ qualityLevel: input.qualityLevels[0], frameTimesMs: [SHADER_LIMITS.checkTimeoutSec * 1000], frameLuminances: [] }], stillPng: null, smallStillPng: null, framePngs: [], shimmerPngs: [], sheetPng: null };
659
+ }
660
+ return {
661
+ compileError: drawn.compileError,
662
+ referenceFrameTimesMs: drawn.referenceFrameTimesMs,
663
+ levels: drawn.levels,
664
+ stillPng: fromDataUrl(drawn.stillDataUrl),
665
+ smallStillPng: fromDataUrl(drawn.smallStillDataUrl),
666
+ framePngs: drawn.frameDataUrls.map((dataUrl) => fromDataUrl(dataUrl)),
667
+ shimmerPngs: drawn.shimmerDataUrls.map((dataUrl) => fromDataUrl(dataUrl)),
668
+ sheetPng: fromDataUrl(drawn.sheetDataUrl),
669
+ };
670
+ }
671
+
672
+ /**
673
+ * The most flashes in any one second of frames (WCAG 2.3.1's general flash): a flash is a pair of opposing changes in mean
674
+ * relative luminance of at least 0.1, the second within 3 frames of the first, while the darker side is under 0.8.
675
+ */
676
+ export function mostFlashesInOneSecond(frameLuminances, frameStepSec = SHADER_LIMITS.checkFrameStepSec) {
677
+ const MINIMUM_CHANGE_NUMBER = 0.1;
678
+ const MOST_FRAMES_BETWEEN_COUNT = 3;
679
+ // Each change of at least 0.1 from the last extreme, in turn: up, down, up…
680
+ const changes = [];
681
+ let direction = null;
682
+ let extremeLuminanceNumber = frameLuminances[0] ?? 0;
683
+ let lowestLuminanceNumber = extremeLuminanceNumber;
684
+ let highestLuminanceNumber = extremeLuminanceNumber;
685
+ frameLuminances.forEach((luminanceNumber, frameIndex) => {
686
+ if (direction === null) {
687
+ lowestLuminanceNumber = Math.min(lowestLuminanceNumber, luminanceNumber);
688
+ highestLuminanceNumber = Math.max(highestLuminanceNumber, luminanceNumber);
689
+ if (luminanceNumber - lowestLuminanceNumber >= MINIMUM_CHANGE_NUMBER) changes.push({ frameIndex, direction: (direction = "up"), darkerLuminanceNumber: lowestLuminanceNumber });
690
+ else if (highestLuminanceNumber - luminanceNumber >= MINIMUM_CHANGE_NUMBER) changes.push({ frameIndex, direction: (direction = "down"), darkerLuminanceNumber: luminanceNumber });
691
+ if (direction !== null) extremeLuminanceNumber = luminanceNumber;
692
+ return;
693
+ }
694
+ const isFurther = direction === "up" ? luminanceNumber > extremeLuminanceNumber : luminanceNumber < extremeLuminanceNumber;
695
+ if (isFurther) {
696
+ extremeLuminanceNumber = luminanceNumber;
697
+ return;
698
+ }
699
+ if (Math.abs(luminanceNumber - extremeLuminanceNumber) < MINIMUM_CHANGE_NUMBER) return;
700
+ changes.push({ frameIndex, direction: (direction = direction === "up" ? "down" : "up"), darkerLuminanceNumber: Math.min(luminanceNumber, extremeLuminanceNumber) });
701
+ extremeLuminanceNumber = luminanceNumber;
702
+ });
703
+ // A flash: two changes back to back, close together, from a dark enough side. Each change counts in one flash.
704
+ const flashFrameIndexes = [];
705
+ for (let changeIndex = 1; changeIndex < changes.length; changeIndex++) {
706
+ const earlier = changes[changeIndex - 1];
707
+ const later = changes[changeIndex];
708
+ if (later.frameIndex - earlier.frameIndex > MOST_FRAMES_BETWEEN_COUNT || Math.min(earlier.darkerLuminanceNumber, later.darkerLuminanceNumber) >= 0.8) continue;
709
+ flashFrameIndexes.push(later.frameIndex);
710
+ changeIndex++;
711
+ }
712
+ const frameCountPerSec = Math.round(1 / frameStepSec);
713
+ let mostFlashCount = 0;
714
+ for (const startIndex of flashFrameIndexes) mostFlashCount = Math.max(mostFlashCount, flashFrameIndexes.filter((frameIndex) => frameIndex >= startIndex && frameIndex < startIndex + frameCountPerSec).length);
715
+ return mostFlashCount;
716
+ }
717
+
718
+ const median = (values) => {
719
+ const sorted = [...values].sort((firstNumber, secondNumber) => firstNumber - secondNumber);
720
+ return sorted.length ? sorted[Math.floor(sorted.length / 2)] : 0;
721
+ };
722
+ const roundedMs = (ms) => Math.round(ms * 10) / 10;
723
+
724
+ /** Each level the renderer timed, scaled to its speed on the reference, and the first that's too slow (cut short, or over its most). */
725
+ export function measureQualityLevels(drawn) {
726
+ const speedScaleNumber = drawn.referenceFrameTimesMs.length ? SHADER_LIMITS.referenceFrameMs / Math.max(0.1, median(drawn.referenceFrameTimesMs)) : 1;
727
+ const qualityChecks = [];
728
+ let tooSlow = null;
729
+ for (const level of drawn.levels) {
730
+ const maximumCheckFrameMs = SHADER_LIMITS.qualityLevels.find((each) => each.qualityLevel === level.qualityLevel).maximumCheckFrameMs;
731
+ const isCut = level.frameTimesMs.length < SHADER_LIMITS.checkFrameCount;
732
+ // Cut short, the frames it drew past the first (which compiles) say how slow; a renderer that ran out of time gave only its time.
733
+ const cutFrameTimesMs = level.frameTimesMs.length > 1 ? level.frameTimesMs.slice(1) : level.frameTimesMs;
734
+ const qualityCheck = { quality_level: level.qualityLevel, check_frame_ms: roundedMs(median(isCut ? cutFrameTimesMs : level.frameTimesMs) * speedScaleNumber), maximum_check_frame_ms: maximumCheckFrameMs };
735
+ qualityChecks.push(qualityCheck);
736
+ if (!tooSlow && (isCut || qualityCheck.check_frame_ms > maximumCheckFrameMs)) tooSlow = qualityCheck;
737
+ }
738
+ return { qualityChecks, tooSlow };
739
+ }
740
+
741
+ /** The most flashes at any level it drew. */
742
+ export const mostFlashes = (drawn) => Math.max(0, ...drawn.levels.map((level) => mostFlashesInOneSecond(level.frameLuminances)));
743
+
744
+ /**
745
+ * Shimmer: fine detail that flickers from frame to frame when it's drawn small, as speckle in the change between two frames rather than
746
+ * smooth motion. Each pixel's change is compared with its neighbours'; a tile is speckled when that difference is high across it, and a
747
+ * shader shimmers when speckled tiles cover most of the frame. Set Oct 23, 2026 in Chromium at 640 × 360 and 360 × 640: the ten stand-in
748
+ * worlds (STAND_IN_BACKGROUNDS) and Zaisma's own reach at most 1.7 in any tile and none may trip it; a twinkling starfield of 2-pixel
749
+ * stars reaches 4, stripes finer than a pixel 33 to 75, and noise picked anew each frame 55 in every tile.
750
+ */
751
+ export const SHIMMER_LIMITS = {
752
+ acrossTileCount: 16,
753
+ downTileCount: 9,
754
+ /** A tile's mean speckle, in 0 to 255 steps of a channel, above which it's speckled. */
755
+ speckledTileNumber: 4,
756
+ /** The share of tiles speckled from which the frame shimmers: most of it. */
757
+ shimmeringTilePct: 50,
758
+ };
759
+
760
+ /** How much two frames (RGBA, the same size) speckle: each tile's mean speckle, and the share of tiles over SHIMMER_LIMITS.speckledTileNumber. */
761
+ export function frameShimmer(first, second, widthPx, heightPx) {
762
+ const change = new Float32Array(widthPx * heightPx);
763
+ let changeSumNumber = 0;
764
+ for (let pixelIndex = 0; pixelIndex < widthPx * heightPx; pixelIndex++) {
765
+ const byteIndex = pixelIndex * 4;
766
+ change[pixelIndex] = (Math.abs(first[byteIndex] - second[byteIndex]) + Math.abs(first[byteIndex + 1] - second[byteIndex + 1]) + Math.abs(first[byteIndex + 2] - second[byteIndex + 2])) / 3;
767
+ changeSumNumber += change[pixelIndex];
768
+ }
769
+ const { acrossTileCount, downTileCount } = SHIMMER_LIMITS;
770
+ const sums = new Float64Array(acrossTileCount * downTileCount), counts = new Float64Array(acrossTileCount * downTileCount);
771
+ for (let rowIndex = 1; rowIndex < heightPx - 1; rowIndex++) {
772
+ for (let columnIndex = 1; columnIndex < widthPx - 1; columnIndex++) {
773
+ const pixelIndex = rowIndex * widthPx + columnIndex;
774
+ const neighbourNumber = (change[pixelIndex - 1] + change[pixelIndex + 1] + change[pixelIndex - widthPx] + change[pixelIndex + widthPx]) / 4;
775
+ const tileIndex = Math.min(downTileCount - 1, Math.floor((rowIndex * downTileCount) / heightPx)) * acrossTileCount + Math.min(acrossTileCount - 1, Math.floor((columnIndex * acrossTileCount) / widthPx));
776
+ sums[tileIndex] += Math.abs(change[pixelIndex] - neighbourNumber);
777
+ counts[tileIndex] += 1;
778
+ }
779
+ }
780
+ const tileSpeckleNumbers = Array.from(sums, (sumNumber, tileIndex) => sumNumber / Math.max(1, counts[tileIndex]));
781
+ const speckledTileCount = tileSpeckleNumbers.filter((speckleNumber) => speckleNumber > SHIMMER_LIMITS.speckledTileNumber).length;
782
+ return { meanChangeNumber: changeSumNumber / Math.max(1, widthPx * heightPx), speckledTilePct: (speckledTileCount * 100) / tileSpeckleNumbers.length, tileSpeckleNumbers };
783
+ }
784
+
785
+ /*
786
+ * A background's tone: its average color and the glass Zaisma puts over it, measured once from the whole picture (a background
787
+ * picture, when it's added) or the still (a shader, when the check draws it) and kept on its row (apps/site/src/background-tone.ts).
788
+ * The rule is the backdrop script's pickGlass (apps/site/src/components/backdrop-script.ts), which measures backgrounds kept before
789
+ * tones were, and the sheet's pickGlass on SHADER_CHECK_PAGE; keep the three in step: light glass (dark words) or smoked glass (light
790
+ * words), whichever can be thinner while every word keeps its contrast against the harsh side of what's behind.
791
+ */
792
+
793
+ function luminance(color) {
794
+ const linear = (channelNumber) => { const shareNumber = channelNumber / 255; return shareNumber <= 0.03928 ? shareNumber / 12.92 : Math.pow((shareNumber + 0.055) / 1.055, 2.4); };
795
+ return 0.2126 * linear(color[0]) + 0.7152 * linear(color[1]) + 0.0722 * linear(color[2]);
796
+ }
797
+ function contrast(first, second) {
798
+ const firstNumber = luminance(first), secondNumber = luminance(second);
799
+ return (Math.max(firstNumber, secondNumber) + 0.05) / (Math.min(firstNumber, secondNumber) + 0.05);
800
+ }
801
+ function blend(from, to, shareNumber) {
802
+ return [from[0] + (to[0] - from[0]) * shareNumber, from[1] + (to[1] - from[1]) * shareNumber, from[2] + (to[2] - from[2]) * shareNumber];
803
+ }
804
+ const LIGHT_GLASS_BASE = [255, 255, 255], SMOKED_GLASS_BASE = [12, 15, 20];
805
+ /** How much of the average a kind of glass takes into its tint. */
806
+ const AVERAGE_SHARE = { light: 0.1, smoked: 0.3 };
807
+
808
+ function thinnestShare(isSmoked, base, sorted) {
809
+ const harsh = isSmoked ? sorted[Math.floor(sorted.length * 0.75)] : sorted[Math.floor(sorted.length * 0.25)];
810
+ for (let shareNumber = 0.3; shareNumber <= 0.95; shareNumber += 0.02) {
811
+ const seen = blend(harsh, base, shareNumber), ink = isSmoked ? [247, 249, 252] : [20, 23, 28], quiet = isSmoked ? blend(seen, ink, 0.7) : [89, 96, 106];
812
+ if (contrast(seen, quiet) >= 4.5 && contrast(seen, ink) >= 6) return shareNumber;
813
+ }
814
+ return 0.95;
815
+ }
816
+
817
+ const hex = (color) => "#" + color.map((channelNumber) => Math.round(channelNumber).toString(16).padStart(2, "0")).join("").toUpperCase();
818
+ const fromHex = (hexColor) => [parseInt(hexColor.slice(1, 3), 16), parseInt(hexColor.slice(3, 5), 16), parseInt(hexColor.slice(5, 7), 16)];
819
+
820
+ /** The tone of a picture's pixels (RGBA, 8 bits each), sampled evenly. */
821
+ export function toneOfPixels(rgba) {
822
+ const pixelCount = Math.floor(rgba.length / 4);
823
+ if (!pixelCount) return null;
824
+ const skippedPixelCount = Math.max(1, Math.floor(pixelCount / 2400)), colors = [];
825
+ for (let pixelIndex = 0; pixelIndex < pixelCount; pixelIndex += skippedPixelCount) colors.push([rgba[pixelIndex * 4], rgba[pixelIndex * 4 + 1], rgba[pixelIndex * 4 + 2]]);
826
+ const sum = colors.reduce((total, color) => [total[0] + color[0], total[1] + color[1], total[2] + color[2]], [0, 0, 0]);
827
+ const average = [sum[0] / colors.length, sum[1] / colors.length, sum[2] / colors.length];
828
+ const sorted = colors.slice().sort((first, second) => luminance(first) - luminance(second));
829
+ const lightShareNumber = thinnestShare(false, blend(LIGHT_GLASS_BASE, average, AVERAGE_SHARE.light), sorted);
830
+ const smokedShareNumber = thinnestShare(true, blend(SMOKED_GLASS_BASE, average, AVERAGE_SHARE.smoked), sorted);
831
+ const isSmoked = lightShareNumber > smokedShareNumber;
832
+ return { average_color: hex(average), is_glass_smoked: isSmoked ? 1 : 0, glass_tint_pct: Math.round(Math.min(lightShareNumber, smokedShareNumber) * 100) };
833
+ }
834
+
835
+ /** The tint the glass over it takes, as the backdrop script sets --glass-tint. */
836
+ export function glassTint(tone) {
837
+ const isSmoked = tone.is_glass_smoked === 1;
838
+ const base = blend(isSmoked ? SMOKED_GLASS_BASE : LIGHT_GLASS_BASE, fromHex(tone.average_color), isSmoked ? AVERAGE_SHARE.smoked : AVERAGE_SHARE.light);
839
+ return `rgba(${base.map(Math.round).join(", ")}, ${(tone.glass_tint_pct / 100).toFixed(2)})`;
840
+ }
841
+
842
+ /** A PNG's pixels as RGBA: 8 bits a channel, gray, RGB or RGBA, not interlaced. Anything else answers null. */
843
+ export async function pngPixels(bytes) {
844
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
845
+ if (bytes.length < 33 || view.getUint32(0) !== 0x89504e47) return null;
846
+ let chunkIndex = 8, widthPx = 0, heightPx = 0, colorTypeNumber = -1;
847
+ const compressed = [];
848
+ while (chunkIndex + 8 <= bytes.length) {
849
+ const chunkSizeBytes = view.getUint32(chunkIndex), chunkType = String.fromCharCode(...bytes.subarray(chunkIndex + 4, chunkIndex + 8));
850
+ const chunkBytes = bytes.subarray(chunkIndex + 8, chunkIndex + 8 + chunkSizeBytes);
851
+ if (chunkType === "IHDR") {
852
+ widthPx = view.getUint32(chunkIndex + 8); heightPx = view.getUint32(chunkIndex + 12); colorTypeNumber = chunkBytes[9];
853
+ if (chunkBytes[8] !== 8 || chunkBytes[12] !== 0 || ![0, 2, 4, 6].includes(colorTypeNumber)) return null;
854
+ } else if (chunkType === "IDAT") compressed.push(chunkBytes);
855
+ else if (chunkType === "IEND") break;
856
+ chunkIndex += 12 + chunkSizeBytes;
857
+ }
858
+ if (!widthPx || !heightPx || !compressed.length) return null;
859
+ const channelCount = { 0: 1, 2: 3, 4: 2, 6: 4 }[colorTypeNumber], rowSizeBytes = widthPx * channelCount;
860
+ const filtered = new Uint8Array(await new Response(new Blob(compressed).stream().pipeThrough(new DecompressionStream("deflate"))).arrayBuffer());
861
+ if (filtered.length < (rowSizeBytes + 1) * heightPx) return null;
862
+ // Each row starts with its filter: none, sub (from the left), up, average or Paeth.
863
+ const rows = new Uint8Array(rowSizeBytes * heightPx);
864
+ for (let rowIndex = 0; rowIndex < heightPx; rowIndex++) {
865
+ const filterNumber = filtered[rowIndex * (rowSizeBytes + 1)], source = filtered.subarray(rowIndex * (rowSizeBytes + 1) + 1, (rowIndex + 1) * (rowSizeBytes + 1)), rowStartIndex = rowIndex * rowSizeBytes;
866
+ for (let byteIndex = 0; byteIndex < rowSizeBytes; byteIndex++) {
867
+ const leftNumber = byteIndex >= channelCount ? rows[rowStartIndex + byteIndex - channelCount] : 0;
868
+ const upNumber = rowIndex ? rows[rowStartIndex - rowSizeBytes + byteIndex] : 0;
869
+ const upLeftNumber = rowIndex && byteIndex >= channelCount ? rows[rowStartIndex - rowSizeBytes + byteIndex - channelCount] : 0;
870
+ const predictedNumber = filterNumber === 1 ? leftNumber : filterNumber === 2 ? upNumber : filterNumber === 3 ? (leftNumber + upNumber) >> 1 : filterNumber === 4 ? paeth(leftNumber, upNumber, upLeftNumber) : 0;
871
+ rows[rowStartIndex + byteIndex] = (source[byteIndex] + predictedNumber) & 255;
872
+ }
873
+ }
874
+ const rgba = new Uint8Array(widthPx * heightPx * 4), isGray = channelCount <= 2;
875
+ for (let pixelIndex = 0; pixelIndex < widthPx * heightPx; pixelIndex++) {
876
+ const sourceIndex = pixelIndex * channelCount;
877
+ rgba[pixelIndex * 4] = rows[sourceIndex];
878
+ rgba[pixelIndex * 4 + 1] = isGray ? rows[sourceIndex] : rows[sourceIndex + 1];
879
+ rgba[pixelIndex * 4 + 2] = isGray ? rows[sourceIndex] : rows[sourceIndex + 2];
880
+ rgba[pixelIndex * 4 + 3] = 255;
881
+ }
882
+ return rgba;
883
+ }
884
+ function paeth(leftNumber, upNumber, upLeftNumber) {
885
+ const estimateNumber = leftNumber + upNumber - upLeftNumber;
886
+ const leftDistanceNumber = Math.abs(estimateNumber - leftNumber), upDistanceNumber = Math.abs(estimateNumber - upNumber), upLeftDistanceNumber = Math.abs(estimateNumber - upLeftNumber);
887
+ return leftDistanceNumber <= upDistanceNumber && leftDistanceNumber <= upLeftDistanceNumber ? leftNumber : upDistanceNumber <= upLeftDistanceNumber ? upNumber : upLeftNumber;
888
+ }
889
+
890
+ export async function toneOfPng(bytes) {
891
+ const rgba = await pngPixels(bytes);
892
+ return rgba ? toneOfPixels(rgba) : null;
893
+ }
894
+
895
+ /** The glass tint, in percent, at which a background forces thick glass over it. */
896
+ export const THICK_GLASS_TINT_PCT = 70;
897
+
898
+ /** The notes for what the check drew: its shimmer, from two frames at the check's size, and the glass its still needs. */
899
+ export async function shaderCheckNotes(shimmerPngs, tone, checkWidthPx, checkHeightPx) {
900
+ const notes = [];
901
+ if (shimmerPngs.length === 2) {
902
+ const [first, second] = await Promise.all(shimmerPngs.map((pngBytes) => pngPixels(pngBytes)));
903
+ if (first && second && first.length === second.length && first.length === checkWidthPx * checkHeightPx * 4) {
904
+ const shimmer = frameShimmer(first, second, checkWidthPx, checkHeightPx);
905
+ if (shimmer.speckledTilePct >= SHIMMER_LIMITS.shimmeringTilePct) {
906
+ notes.push({
907
+ code: "shimmers_when_small",
908
+ message: `Fine detail flickers from frame to frame across ${Math.round(shimmer.speckledTilePct)}% of it at ${checkWidthPx} by ${checkHeightPx}, as it will on phones and small windows.`,
909
+ fix: "Blur or fade detail finer than a few pixels (fade it with the pixel size, fwidth, or with iQuality), and move noise smoothly with iTime instead of picking new noise every frame.",
910
+ });
911
+ }
912
+ }
913
+ }
914
+ if (tone && tone.glass_tint_pct >= THICK_GLASS_TINT_PCT) {
915
+ notes.push({
916
+ code: "forces_thick_glass",
917
+ message: `Words over it need ${tone.is_glass_smoked ? "smoked" : "light"} glass tinted ${tone.glass_tint_pct}%, so the glass hides most of it.`,
918
+ fix: "Keep its contrast gentler where Zaisma's glass sits (the left of a wide screen, the bottom half of a phone): fewer bright highlights against deep shadows there, or read iGlassPanes and soften what's under them.",
919
+ });
920
+ }
921
+ return notes;
922
+ }
923
+
924
+ /** A compiler's first line as the check says it. */
925
+ export const compileMessage = (compileError) => `It didn't compile: ${compileError.replace(/[.\s]+$/, "")}.`;
926
+
927
+ /**
928
+ * What a check before sending answers from what the renderer drew (the shader_check, schemas.ts SHADER_CHECK), without its sheet:
929
+ * the compiler's first error, each level's time against its most, flashes, the glass its still needs and the notes. The API keeps the
930
+ * sheet and links it; `zaisma check` saves it beside the folder.
931
+ */
932
+ export async function shaderDraftAnswer(drawn, screen) {
933
+ const answer = { compile_error: null, quality_checks: [], flash_count: null, is_glass_smoked: null, glass_tint_pct: null, notes: [], sheet_url: null, sheet_expires_at: null };
934
+ if (drawn.compileError) return { ...answer, compile_error: compileMessage(drawn.compileError) };
935
+ const { qualityChecks } = measureQualityLevels(drawn);
936
+ const tone = drawn.smallStillPng ? await toneOfPng(drawn.smallStillPng) : null;
937
+ const sizes = checkSizes(screen);
938
+ return {
939
+ ...answer,
940
+ quality_checks: qualityChecks,
941
+ flash_count: drawn.levels.some((level) => level.frameLuminances.length) ? mostFlashes(drawn) : null,
942
+ is_glass_smoked: tone ? tone.is_glass_smoked === 1 : null,
943
+ glass_tint_pct: tone ? tone.glass_tint_pct : null,
944
+ notes: await shaderCheckNotes(drawn.shimmerPngs, tone, sizes.checkWidthPx, sizes.checkHeightPx),
945
+ };
946
+ }
947
+
948
+ /** Whether a check before sending would pass the check when sent, as far as drawing goes: it compiled, keeps to every level's most and doesn't flash. */
949
+ export const isShaderCheckPassing = (shaderCheck) =>
950
+ !shaderCheck.compile_error &&
951
+ shaderCheck.quality_checks.length > 0 &&
952
+ shaderCheck.quality_checks.every((qualityCheck) => qualityCheck.check_frame_ms <= qualityCheck.maximum_check_frame_ms) &&
953
+ (shaderCheck.flash_count ?? 0) <= SHADER_LIMITS.maximumFlashCountPerSec;