Line data Source code
1 : import type {
2 : Size2D,
3 : CompactRect as Rect
4 : } from '@comfyorg/shared-frontend-utils/geometry'
5 : import { modeUniforms } from './modeCodes'
6 : import type {
7 : Compositor,
8 : CompositeInput,
9 : CompositorInit,
10 : FBOHandle,
11 : NodeTexture
12 : } from '#/compositor'
13 : import LAYER_BLEND_FRAG from './shaders/layerBlend.frag?raw'
14 :
15 2 : const VERT = `#version 300 es
16 : out vec2 v_texCoord;
17 : void main() {
18 : vec2 v[3] = vec2[](vec2(-1.0,-1.0), vec2(3.0,-1.0), vec2(-1.0,3.0));
19 : v_texCoord = v[gl_VertexID] * 0.5 + 0.5;
20 : gl_Position = vec4(v[gl_VertexID], 0.0, 1.0);
21 : }`
22 :
23 2 : const PRESENT_FRAG = `#version 300 es
24 : precision highp float;
25 : uniform sampler2D u_tex;
26 : in vec2 v_texCoord;
27 : out vec4 fragColor;
28 : float lin2srgb(float c){ c = clamp(c, 0.0, 1.0); return c <= 0.0031308 ? 12.92*c : 1.055*pow(c,1.0/2.4)-0.055; }
29 : void main(){
30 : vec4 c = texture(u_tex, v_texCoord);
31 : fragColor = vec4(lin2srgb(c.r), lin2srgb(c.g), lin2srgb(c.b), clamp(c.a, 0.0, 1.0));
32 : }`
33 :
34 2 : const COPY_FRAG = `#version 300 es
35 : precision highp float;
36 : uniform sampler2D u_tex;
37 : in vec2 v_texCoord;
38 : out vec4 fragColor;
39 : void main(){ fragColor = texture(u_tex, v_texCoord); }`
40 :
41 2 : const ADJUST_FRAG = `#version 300 es
42 : precision highp float;
43 : uniform sampler2D u_backdrop;
44 : uniform sampler2D u_mask;
45 : uniform sampler2D u_lut;
46 : uniform bool u_hasMask;
47 : uniform float u_opacity;
48 : uniform int u_op;
49 : uniform vec4 u_p0;
50 : uniform vec4 u_p1;
51 : uniform vec4 u_p2;
52 : in vec2 v_texCoord;
53 : out vec4 fragColor;
54 :
55 : float s2l(float c){ return c <= 0.04045 ? c / 12.92 : pow((c + 0.055) / 1.055, 2.4); }
56 : float l2s(float c){ c = clamp(c, 0.0, 1.0); return c <= 0.0031308 ? 12.92*c : 1.055*pow(c,1.0/2.4)-0.055; }
57 : vec3 s2l(vec3 c){ return vec3(s2l(c.r), s2l(c.g), s2l(c.b)); }
58 : vec3 l2s(vec3 c){ return vec3(l2s(c.r), l2s(c.g), l2s(c.b)); }
59 :
60 : float bc(float v, float b, float c){
61 : float hb = b * 0.5;
62 : float o = hb < 0.0 ? v * (1.0 + hb) : v + (1.0 - v) * hb;
63 : return (o - 0.5) * tan((c + 1.0) * 0.78539816) + 0.5;
64 : }
65 :
66 : vec3 rgb2hsl(vec3 c){
67 : float mx = max(max(c.r, c.g), c.b);
68 : float mn = min(min(c.r, c.g), c.b);
69 : float l = (mx + mn) * 0.5;
70 : if (mx == mn) return vec3(0.0, 0.0, l);
71 : float d = mx - mn;
72 : float s = l > 0.5 ? d / (2.0 - mx - mn) : d / (mx + mn);
73 : float h;
74 : if (mx == c.r) h = (c.g - c.b) / d + (c.g < c.b ? 6.0 : 0.0);
75 : else if (mx == c.g) h = (c.b - c.r) / d + 2.0;
76 : else h = (c.r - c.g) / d + 4.0;
77 : return vec3(h / 6.0, s, l);
78 : }
79 :
80 : float hue2rgb(float p, float q, float t){
81 : float x = t;
82 : if (x < 0.0) x += 1.0;
83 : if (x > 1.0) x -= 1.0;
84 : if (x < 1.0/6.0) return p + (q - p) * 6.0 * x;
85 : if (x < 0.5) return q;
86 : if (x < 2.0/3.0) return p + (q - p) * (2.0/3.0 - x) * 6.0;
87 : return p;
88 : }
89 :
90 : vec3 hsl2rgb(vec3 hsl){
91 : if (hsl.y == 0.0) return vec3(hsl.z);
92 : float q = hsl.z < 0.5 ? hsl.z * (1.0 + hsl.y) : hsl.z + hsl.y - hsl.z * hsl.y;
93 : float p = 2.0 * hsl.z - q;
94 : return vec3(hue2rgb(p, q, hsl.x + 1.0/3.0), hue2rgb(p, q, hsl.x), hue2rgb(p, q, hsl.x - 1.0/3.0));
95 : }
96 :
97 : float lev(float v){
98 : float t = clamp((v - u_p0.x) / max(u_p0.y - u_p0.x, 1e-4), 0.0, 1.0);
99 : return u_p0.w + pow(t, 1.0 / max(u_p0.z, 1e-4)) * (u_p1.x - u_p0.w);
100 : }
101 :
102 : float balComp(float v, float l, float s, float m, float h){
103 : const float a = 4.0;
104 : const float b = 0.333;
105 : const float sc = 0.7;
106 : float sw = s * clamp((b - l) * a + 0.5, 0.0, 1.0) * sc;
107 : float mw = m * clamp((l - b) * a + 0.5, 0.0, 1.0) * clamp((1.0 - l - b) * a + 0.5, 0.0, 1.0) * sc;
108 : float hw = h * clamp((l + b - 1.0) * a + 0.5, 0.0, 1.0) * sc;
109 : return clamp(v + sw + mw + hw, 0.0, 1.0);
110 : }
111 :
112 : float hfun(float n, float h, float s, float l){
113 : float a = s * min(l, 1.0 - l);
114 : float k = mod(n + h / 30.0, 12.0);
115 : return clamp(l - a * max(min(min(k - 3.0, 9.0 - k), 1.0), -1.0), 0.0, 1.0);
116 : }
117 :
118 : vec3 preservel(vec3 c, float l){
119 : float mx = max(c.r, max(c.g, c.b));
120 : float mn = min(c.r, min(c.g, c.b));
121 : float h;
122 : if (c.r == c.g && c.g == c.b) h = 0.0;
123 : else if (mx == c.r) h = 60.0 * ((c.g - c.b) / (mx - mn));
124 : else if (mx == c.g) h = 60.0 * (2.0 + (c.b - c.r) / (mx - mn));
125 : else h = 60.0 * (4.0 + (c.r - c.g) / (mx - mn));
126 : if (h < 0.0) h += 360.0;
127 : float lOut = (mx + mn) * 0.5;
128 : float denom = 1.0 - abs(2.0 * lOut - 1.0);
129 : float s = denom <= 1e-6 ? 0.0 : (mx - mn) / denom;
130 : return vec3(hfun(0.0, h, s, l), hfun(8.0, h, s, l), hfun(4.0, h, s, l));
131 : }
132 :
133 : float lutAt(float v, int ch){
134 : float x = (floor(clamp(v, 0.0, 1.0) * 255.0 + 0.5) + 0.5) / 256.0;
135 : vec4 s = texture(u_lut, vec2(x, 0.5));
136 : return ch == 0 ? s.r : ch == 1 ? s.g : s.b;
137 : }
138 :
139 : void main(){
140 : vec4 bg = texture(u_backdrop, v_texCoord);
141 : vec3 adjusted;
142 : if (u_op == 0) {
143 : adjusted = vec3(bc(bg.r, u_p0.x, u_p0.y), bc(bg.g, u_p0.x, u_p0.y), bc(bg.b, u_p0.x, u_p0.y));
144 : } else if (u_op == 5) {
145 : adjusted = clamp((bg.rgb - vec3(u_p0.x)) * u_p0.y, 0.0, 1.0);
146 : } else {
147 : vec3 g = l2s(clamp(bg.rgb, 0.0, 1.0));
148 : vec3 o;
149 : if (u_op == 1) {
150 : vec3 hsl = rgb2hsl(g);
151 : hsl.x = fract(hsl.x + u_p0.x + 1.0);
152 : hsl.y = clamp(hsl.y * (1.0 + u_p0.y), 0.0, 1.0);
153 : hsl.z = clamp(u_p0.z > 0.0 ? hsl.z + u_p0.z * (1.0 - hsl.z) : hsl.z + u_p0.z * hsl.z, 0.0, 1.0);
154 : o = hsl2rgb(hsl);
155 : } else if (u_op == 2) {
156 : o = vec3(1.0) - g;
157 : } else if (u_op == 3) {
158 : o = vec3(lev(g.r), lev(g.g), lev(g.b));
159 : } else if (u_op == 4) {
160 : o = mix(g, g * u_p0.xyz, u_p0.w);
161 : } else if (u_op == 6) {
162 : float l = (max(g.r, max(g.g, g.b)) + min(g.r, min(g.g, g.b))) * 0.5;
163 : o = vec3(
164 : balComp(g.r, l, u_p0.x, u_p0.w, u_p1.z),
165 : balComp(g.g, l, u_p0.y, u_p1.x, u_p1.w),
166 : balComp(g.b, l, u_p0.z, u_p1.y, u_p2.x));
167 : o = preservel(o, l);
168 : } else if (u_op == 7) {
169 : float n = max(u_p0.x, 2.0) - 1.0;
170 : o = floor(g * n + 0.5) / n;
171 : } else if (u_op == 8) {
172 : float y = dot(g, vec3(0.2126, 0.7152, 0.0722));
173 : o = vec3(y >= u_p0.x ? 1.0 : 0.0);
174 : } else if (u_op == 9) {
175 : float sat = max(g.r, max(g.g, g.b)) - min(g.r, min(g.g, g.b));
176 : float luma = g.g * 0.715158 + g.r * 0.212656 + g.b * 0.072186;
177 : float s = u_p0.x > 0.0 ? 1.0 : -1.0;
178 : float k = 1.0 + u_p0.x * (1.0 + s * sat);
179 : o = clamp(vec3(luma) + (g - vec3(luma)) * k, 0.0, 1.0);
180 : } else {
181 : o = vec3(lutAt(g.r, 0), lutAt(g.g, 1), lutAt(g.b, 2));
182 : }
183 : adjusted = s2l(clamp(o, 0.0, 1.0));
184 : }
185 : float t = u_opacity * (u_hasMask ? texture(u_mask, v_texCoord).r : 1.0);
186 : fragColor = vec4(mix(bg.rgb, adjusted, t), bg.a);
187 : }`
188 :
189 : interface Target extends Size2D {
190 : fbo: WebGLFramebuffer
191 : tex: WebGLTexture
192 : }
193 :
194 10 : function compile(
195 : gl: WebGL2RenderingContext,
196 : type: number,
197 : src: string
198 : ): WebGLShader {
199 10 : const sh = gl.createShader(type)!
200 10 : gl.shaderSource(sh, src)
201 10 : gl.compileShader(sh)
202 10 : if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) {
203 0 : const log = gl.getShaderInfoLog(sh) ?? 'compile failed'
204 0 : gl.deleteShader(sh)
205 0 : throw new Error(log)
206 : }
207 10 : return sh
208 : }
209 :
210 8 : function link(
211 : gl: WebGL2RenderingContext,
212 : vs: WebGLShader,
213 : fs: WebGLShader
214 : ): WebGLProgram {
215 8 : const p = gl.createProgram()
216 8 : gl.attachShader(p, vs)
217 8 : gl.attachShader(p, fs)
218 8 : gl.linkProgram(p)
219 8 : if (!gl.getProgramParameter(p, gl.LINK_STATUS)) {
220 0 : const log = gl.getProgramInfoLog(p) ?? 'link failed'
221 0 : gl.deleteProgram(p)
222 0 : throw new Error(log)
223 : }
224 8 : return p
225 : }
226 :
227 2 : export function createWebGLCompositor(): Compositor {
228 2 : let canvas: OffscreenCanvas | HTMLCanvasElement | null = null
229 2 : let gl: WebGL2RenderingContext | null = null
230 2 : let blendProg: WebGLProgram | null = null
231 2 : let presentProg: WebGLProgram | null = null
232 2 : let copyProg: WebGLProgram | null = null
233 2 : let adjustProg: WebGLProgram | null = null
234 2 : let ping: Target | null = null
235 2 : let pong: Target | null = null
236 2 : let result: Target | null = null
237 2 : let resultValid = false
238 2 : let scratch2d: HTMLCanvasElement | null = null
239 2 : let lastSweepGen = 0
240 2 : let fallback: WebGLTexture | null = null
241 2 : let lutTex: WebGLTexture | null = null
242 2 : let width = 0
243 2 : let height = 0
244 2 : let nextHandle = 1
245 2 : let generation = 0
246 2 : let contextLost = false
247 2 : let disposed = false
248 2 : let lastRecover = -Infinity
249 2 : let onRestored: (() => void) | undefined
250 2 : const targets = new Map<number, Target>()
251 2 : const texCache = new Map<
252 : string,
253 : { tex: WebGLTexture; gen: number; version?: number }
254 : >()
255 2 : let uniformCache = new WeakMap<
256 : WebGLProgram,
257 : Map<string, WebGLUniformLocation | null>
258 : >()
259 :
260 267 : function loc(prog: WebGLProgram, name: string): WebGLUniformLocation | null {
261 267 : let m = uniformCache.get(prog)
262 267 : if (!m) {
263 6 : m = new Map()
264 6 : uniformCache.set(prog, m)
265 : }
266 267 : if (!m.has(name)) m.set(name, gl!.getUniformLocation(prog, name))
267 267 : return m.get(name)!
268 : }
269 :
270 12 : function makeTarget(w: number, h: number): Target | null {
271 12 : const g = gl!
272 12 : const tex = g.createTexture()
273 12 : g.bindTexture(g.TEXTURE_2D, tex)
274 12 : g.texImage2D(
275 : g.TEXTURE_2D,
276 : 0,
277 : g.RGBA16F,
278 : w,
279 : h,
280 : 0,
281 : g.RGBA,
282 : g.HALF_FLOAT,
283 : null
284 : )
285 12 : g.texParameteri(g.TEXTURE_2D, g.TEXTURE_MIN_FILTER, g.LINEAR)
286 12 : g.texParameteri(g.TEXTURE_2D, g.TEXTURE_MAG_FILTER, g.LINEAR)
287 12 : g.texParameteri(g.TEXTURE_2D, g.TEXTURE_WRAP_S, g.CLAMP_TO_EDGE)
288 12 : g.texParameteri(g.TEXTURE_2D, g.TEXTURE_WRAP_T, g.CLAMP_TO_EDGE)
289 12 : const fbo = g.createFramebuffer()
290 12 : g.bindFramebuffer(g.FRAMEBUFFER, fbo)
291 12 : g.framebufferTexture2D(
292 : g.FRAMEBUFFER,
293 : g.COLOR_ATTACHMENT0,
294 : g.TEXTURE_2D,
295 : tex,
296 : 0
297 : )
298 12 : const complete =
299 : g.checkFramebufferStatus(g.FRAMEBUFFER) === g.FRAMEBUFFER_COMPLETE
300 12 : g.bindFramebuffer(g.FRAMEBUFFER, null)
301 12 : if (!complete) {
302 0 : g.deleteFramebuffer(fbo)
303 0 : g.deleteTexture(tex)
304 0 : return null
305 : }
306 12 : return { fbo, tex, width: w, height: h }
307 : }
308 :
309 6 : function freeTargetObj(t: Target): void {
310 6 : gl?.deleteFramebuffer(t.fbo)
311 6 : gl?.deleteTexture(t.tex)
312 : }
313 :
314 51 : function drawFullscreen(): void {
315 51 : gl!.drawArrays(gl!.TRIANGLES, 0, 3)
316 : }
317 :
318 24 : function resolveTexture(
319 : nt: NodeTexture,
320 : temps: WebGLTexture[]
321 : ): WebGLTexture {
322 24 : if (nt.source instanceof WebGLTexture) return nt.source
323 24 : if (nt.key) {
324 24 : const hit = texCache.get(nt.key)
325 24 : if (hit) {
326 16 : hit.gen = generation
327 16 : if (nt.version === undefined || hit.version === nt.version)
328 16 : return hit.tex
329 16 : if (
330 : hit.version === nt.version - 1 &&
331 : nt.dirtyRects &&
332 : partialUploadAll(hit.tex, nt.source, nt.dirtyRects)
333 : ) {
334 0 : hit.version = nt.version
335 0 : return hit.tex
336 : }
337 0 : uploadInto(hit.tex, nt.source)
338 0 : hit.version = nt.version
339 0 : return hit.tex
340 : }
341 8 : const tex = uploadSource(nt.source)
342 8 : texCache.set(nt.key, { tex, gen: generation, version: nt.version })
343 8 : return tex
344 : }
345 0 : const tex = uploadSource(nt.source)
346 0 : temps.push(tex)
347 0 : return tex
348 : }
349 :
350 0 : function partialUploadAll(
351 : tex: WebGLTexture,
352 : src: HTMLCanvasElement | ImageBitmap | OffscreenCanvas,
353 : rects: Rect[]
354 : ): boolean {
355 0 : let area = 0
356 0 : for (const r of rects) area += Math.max(0, r.w) * Math.max(0, r.h)
357 0 : if (area > (src.width * src.height) / 2) return false
358 0 : for (const r of rects) {
359 0 : if (!partialUpload(tex, src, r)) return false
360 : }
361 0 : return true
362 : }
363 :
364 0 : function partialUpload(
365 : tex: WebGLTexture,
366 : src: HTMLCanvasElement | ImageBitmap | OffscreenCanvas,
367 : rect: Rect
368 : ): boolean {
369 0 : const g = gl!
370 0 : const x = Math.max(0, Math.floor(rect.x))
371 0 : const y = Math.max(0, Math.floor(rect.y))
372 0 : const w = Math.min(src.width, Math.ceil(rect.x + rect.w)) - x
373 0 : const h = Math.min(src.height, Math.ceil(rect.y + rect.h)) - y
374 0 : if (w <= 0 || h <= 0) return true
375 0 : if (!scratch2d) scratch2d = document.createElement('canvas')
376 0 : scratch2d.width = w
377 0 : scratch2d.height = h
378 0 : const sctx = scratch2d.getContext('2d')
379 0 : if (!sctx) return false
380 0 : sctx.clearRect(0, 0, w, h)
381 0 : sctx.drawImage(src, x, y, w, h, 0, 0, w, h)
382 0 : g.bindTexture(g.TEXTURE_2D, tex)
383 0 : g.pixelStorei(g.UNPACK_FLIP_Y_WEBGL, true)
384 0 : g.texSubImage2D(
385 : g.TEXTURE_2D,
386 : 0,
387 : x,
388 : src.height - (y + h),
389 : g.RGBA,
390 : g.UNSIGNED_BYTE,
391 : scratch2d
392 : )
393 0 : g.pixelStorei(g.UNPACK_FLIP_Y_WEBGL, false)
394 0 : return true
395 : }
396 :
397 0 : function uploadInto(
398 : tex: WebGLTexture,
399 : src: HTMLCanvasElement | ImageBitmap | OffscreenCanvas
400 : ): void {
401 0 : const g = gl!
402 0 : g.bindTexture(g.TEXTURE_2D, tex)
403 0 : g.pixelStorei(g.UNPACK_FLIP_Y_WEBGL, true)
404 0 : g.texImage2D(g.TEXTURE_2D, 0, g.RGBA, g.RGBA, g.UNSIGNED_BYTE, src)
405 0 : g.pixelStorei(g.UNPACK_FLIP_Y_WEBGL, false)
406 : }
407 :
408 18 : function sweepTexCache(): void {
409 18 : if (generation - lastSweepGen < 8) return
410 1 : lastSweepGen = generation
411 12 : for (const [key, entry] of texCache) {
412 4 : if (entry.gen < generation - 3) {
413 0 : gl?.deleteTexture(entry.tex)
414 0 : texCache.delete(key)
415 : }
416 : }
417 : }
418 :
419 8 : function uploadSource(
420 : src: HTMLCanvasElement | ImageBitmap | OffscreenCanvas
421 : ): WebGLTexture {
422 8 : const g = gl!
423 8 : const tex = g.createTexture()
424 8 : g.bindTexture(g.TEXTURE_2D, tex)
425 8 : g.pixelStorei(g.UNPACK_FLIP_Y_WEBGL, true)
426 8 : g.texImage2D(g.TEXTURE_2D, 0, g.RGBA, g.RGBA, g.UNSIGNED_BYTE, src)
427 8 : g.pixelStorei(g.UNPACK_FLIP_Y_WEBGL, false)
428 8 : g.texParameteri(g.TEXTURE_2D, g.TEXTURE_MIN_FILTER, g.LINEAR)
429 8 : g.texParameteri(g.TEXTURE_2D, g.TEXTURE_MAG_FILTER, g.LINEAR)
430 8 : g.texParameteri(g.TEXTURE_2D, g.TEXTURE_WRAP_S, g.CLAMP_TO_EDGE)
431 8 : g.texParameteri(g.TEXTURE_2D, g.TEXTURE_WRAP_T, g.CLAMP_TO_EDGE)
432 8 : return tex
433 : }
434 :
435 24 : function getFallback(): WebGLTexture {
436 24 : if (!fallback) {
437 2 : const g = gl!
438 2 : fallback = g.createTexture()!
439 2 : g.bindTexture(g.TEXTURE_2D, fallback)
440 2 : g.texImage2D(
441 : g.TEXTURE_2D,
442 : 0,
443 : g.RGBA,
444 : 1,
445 : 1,
446 : 0,
447 : g.RGBA,
448 : g.UNSIGNED_BYTE,
449 : new Uint8Array([0, 0, 0, 0])
450 : )
451 : }
452 24 : return fallback
453 : }
454 :
455 0 : function getLutTex(lut?: Uint8Array): WebGLTexture {
456 0 : if (!lut) return getFallback()
457 0 : const g = gl!
458 0 : if (!lutTex) {
459 0 : lutTex = g.createTexture()!
460 0 : g.bindTexture(g.TEXTURE_2D, lutTex)
461 0 : g.texParameteri(g.TEXTURE_2D, g.TEXTURE_MIN_FILTER, g.NEAREST)
462 0 : g.texParameteri(g.TEXTURE_2D, g.TEXTURE_MAG_FILTER, g.NEAREST)
463 0 : g.texParameteri(g.TEXTURE_2D, g.TEXTURE_WRAP_S, g.CLAMP_TO_EDGE)
464 0 : g.texParameteri(g.TEXTURE_2D, g.TEXTURE_WRAP_T, g.CLAMP_TO_EDGE)
465 : } else {
466 0 : g.bindTexture(g.TEXTURE_2D, lutTex)
467 : }
468 0 : g.texImage2D(
469 : g.TEXTURE_2D,
470 : 0,
471 : g.RGBA,
472 : 256,
473 : 1,
474 : 0,
475 : g.RGBA,
476 : g.UNSIGNED_BYTE,
477 : lut
478 : )
479 0 : return lutTex
480 : }
481 :
482 42 : function clearTarget(t: Target): void {
483 42 : const g = gl!
484 42 : g.bindFramebuffer(g.FRAMEBUFFER, t.fbo)
485 42 : g.viewport(0, 0, t.width, t.height)
486 42 : g.clearColor(0, 0, 0, 0)
487 42 : g.clear(g.COLOR_BUFFER_BIT)
488 : }
489 :
490 0 : function dropContextState(): void {
491 0 : targets.clear()
492 0 : texCache.clear()
493 0 : uniformCache = new WeakMap()
494 0 : ping = pong = result = null
495 0 : resultValid = false
496 0 : fallback = null
497 0 : lutTex = null
498 0 : blendProg = presentProg = copyProg = adjustProg = null
499 0 : gl = null
500 0 : canvas = null
501 : }
502 :
503 2 : function setupContext(): boolean {
504 2 : try {
505 2 : const c =
506 : typeof OffscreenCanvas !== 'undefined'
507 : ? new OffscreenCanvas(width, height)
508 : : document.createElement('canvas')
509 2 : if (!(c instanceof OffscreenCanvas)) {
510 0 : c.width = width
511 0 : c.height = height
512 : }
513 2 : const attributes: WebGLContextAttributes = {
514 : alpha: true,
515 : premultipliedAlpha: false,
516 : preserveDrawingBuffer: true
517 : }
518 : // Same call either way, but made per concrete type: through the union,
519 : // TypeScript 6 resolves getContext to the generic string overload and
520 : // loses the WebGL2RenderingContext return type.
521 2 : const ctx =
522 : c instanceof OffscreenCanvas
523 : ? c.getContext('webgl2', attributes)
524 : : c.getContext('webgl2', attributes)
525 2 : if (!ctx) return false
526 2 : if (!ctx.getExtension('EXT_color_buffer_float')) return false
527 2 : canvas = c
528 2 : gl = ctx
529 2 : contextLost = false
530 2 : c.addEventListener('webglcontextlost', (e: Event) => {
531 0 : e.preventDefault()
532 0 : if (canvas !== c) return
533 0 : contextLost = true
534 0 : if (disposed) return
535 0 : console.warn('[LayerEditor] WebGL context lost — recreating')
536 0 : queueMicrotask(() => {
537 0 : if (recover()) onRestored?.()
538 : })
539 : })
540 2 : const vs = compile(gl, gl.VERTEX_SHADER, VERT)
541 2 : blendProg = link(
542 : gl,
543 : vs,
544 : compile(gl, gl.FRAGMENT_SHADER, LAYER_BLEND_FRAG)
545 : )
546 2 : presentProg = link(gl, vs, compile(gl, gl.FRAGMENT_SHADER, PRESENT_FRAG))
547 2 : copyProg = link(gl, vs, compile(gl, gl.FRAGMENT_SHADER, COPY_FRAG))
548 2 : adjustProg = link(gl, vs, compile(gl, gl.FRAGMENT_SHADER, ADJUST_FRAG))
549 2 : ping = makeTarget(width, height)
550 2 : pong = makeTarget(width, height)
551 2 : return !!ping && !!pong
552 : } catch {
553 0 : dropContextState()
554 0 : return false
555 : }
556 : }
557 :
558 0 : function recover(): boolean {
559 0 : if (disposed) return false
560 0 : const now = typeof performance !== 'undefined' ? performance.now() : 0
561 0 : if (now - lastRecover < 1000) return false
562 0 : lastRecover = now
563 0 : dropContextState()
564 0 : return setupContext()
565 : }
566 :
567 29 : function ensureHealthy(): boolean {
568 29 : if (disposed) return false
569 29 : if (gl && !contextLost && !gl.isContextLost()) return true
570 0 : contextLost = true
571 0 : if (!recover()) return false
572 0 : if (onRestored) queueMicrotask(onRestored)
573 0 : return true
574 : }
575 :
576 2 : return {
577 : init(opts: CompositorInit): boolean {
578 2 : if (gl) {
579 0 : if (!gl.isContextLost())
580 0 : gl.getExtension('WEBGL_lose_context')?.loseContext()
581 0 : dropContextState()
582 : }
583 2 : width = opts.width
584 2 : height = opts.height
585 2 : onRestored = opts.onContextRestored
586 2 : disposed = false
587 2 : if (setupContext()) return true
588 0 : dropContextState()
589 0 : return false
590 : },
591 :
592 : beginFrame(): void {
593 18 : generation += 1
594 : },
595 :
596 : resize(w: number, h: number): void {
597 2 : if (w === width && h === height) return
598 2 : width = w
599 2 : height = h
600 2 : if (!ensureHealthy() || !gl) return
601 2 : if (canvas) {
602 2 : canvas.width = w
603 2 : canvas.height = h
604 : }
605 2 : if (ping) freeTargetObj(ping)
606 2 : if (pong) freeTargetObj(pong)
607 2 : if (result) freeTargetObj(result)
608 2 : ping = makeTarget(w, h)
609 2 : pong = makeTarget(w, h)
610 2 : result = null
611 2 : resultValid = false
612 : },
613 :
614 : composite(
615 : inputs: CompositeInput[],
616 : target?: FBOHandle | null,
617 : region?: Rect
618 : ): void {
619 18 : if (!ensureHealthy()) return
620 18 : if (!gl || !blendProg || !ping || !pong) return
621 18 : const g = gl
622 18 : g.disable(g.SCISSOR_TEST)
623 :
624 18 : let clip: Rect | null = null
625 18 : if (!target && region && resultValid && result) {
626 0 : const x = Math.max(0, Math.floor(region.x))
627 0 : const y = Math.max(0, Math.floor(region.y))
628 0 : const w = Math.min(width, Math.ceil(region.x + region.w)) - x
629 0 : const h = Math.min(height, Math.ceil(region.y + region.h)) - y
630 0 : if (w <= 0 || h <= 0) return
631 0 : if (w < width || h < height) clip = { x, y, w, h }
632 : }
633 18 : if (clip) {
634 0 : g.enable(g.SCISSOR_TEST)
635 0 : g.scissor(clip.x, height - (clip.y + clip.h), clip.w, clip.h)
636 : }
637 :
638 18 : let read = ping
639 18 : let write = pong
640 18 : clearTarget(read)
641 18 : const temps: WebGLTexture[] = []
642 :
643 18 : for (const input of inputs) {
644 24 : clearTarget(write)
645 24 : g.bindFramebuffer(g.FRAMEBUFFER, write.fbo)
646 24 : g.viewport(0, 0, write.width, write.height)
647 :
648 24 : if ('adjust' in input) {
649 0 : if (!adjustProg) continue
650 0 : g.useProgram(adjustProg)
651 0 : g.activeTexture(g.TEXTURE0)
652 0 : g.bindTexture(g.TEXTURE_2D, read.tex)
653 0 : g.uniform1i(loc(adjustProg, 'u_backdrop'), 0)
654 0 : g.activeTexture(g.TEXTURE2)
655 0 : g.bindTexture(
656 : g.TEXTURE_2D,
657 : input.mask ? resolveTexture(input.mask, temps) : getFallback()
658 : )
659 0 : g.uniform1i(loc(adjustProg, 'u_mask'), 2)
660 0 : g.uniform1i(loc(adjustProg, 'u_hasMask'), input.mask ? 1 : 0)
661 0 : g.uniform1f(loc(adjustProg, 'u_opacity'), input.opacity)
662 0 : g.uniform1i(loc(adjustProg, 'u_op'), input.adjust.op)
663 0 : const p = input.adjust.params
664 0 : g.uniform4f(
665 : loc(adjustProg, 'u_p0'),
666 : p[0] ?? 0,
667 : p[1] ?? 0,
668 : p[2] ?? 0,
669 : p[3] ?? 0
670 : )
671 0 : g.uniform4f(
672 : loc(adjustProg, 'u_p1'),
673 : p[4] ?? 0,
674 : p[5] ?? 0,
675 : p[6] ?? 0,
676 : p[7] ?? 0
677 : )
678 0 : g.uniform4f(
679 : loc(adjustProg, 'u_p2'),
680 : p[8] ?? 0,
681 : p[9] ?? 0,
682 : p[10] ?? 0,
683 : p[11] ?? 0
684 : )
685 0 : g.activeTexture(g.TEXTURE1)
686 0 : g.bindTexture(g.TEXTURE_2D, getLutTex(input.adjust.lut))
687 0 : g.uniform1i(loc(adjustProg, 'u_lut'), 1)
688 : } else {
689 24 : g.useProgram(blendProg)
690 24 : g.activeTexture(g.TEXTURE0)
691 24 : g.bindTexture(g.TEXTURE_2D, read.tex)
692 24 : g.uniform1i(loc(blendProg, 'u_backdrop'), 0)
693 :
694 24 : g.activeTexture(g.TEXTURE1)
695 24 : g.bindTexture(g.TEXTURE_2D, resolveTexture(input.texture, temps))
696 24 : g.uniform1i(loc(blendProg, 'u_layer'), 1)
697 :
698 24 : g.activeTexture(g.TEXTURE2)
699 24 : g.bindTexture(
700 : g.TEXTURE_2D,
701 : input.mask ? resolveTexture(input.mask, temps) : getFallback()
702 : )
703 24 : g.uniform1i(loc(blendProg, 'u_mask'), 2)
704 24 : g.uniform1i(loc(blendProg, 'u_hasMask'), input.mask ? 1 : 0)
705 :
706 24 : g.uniform1i(
707 : loc(blendProg, 'u_srgbLayer'),
708 : input.texture.linear ? 0 : 1
709 : )
710 24 : g.uniform1f(loc(blendProg, 'u_opacity'), input.opacity)
711 24 : const u = modeUniforms(input.mode)
712 24 : g.uniform1i(loc(blendProg, 'u_blend'), u.blend)
713 24 : g.uniform1i(loc(blendProg, 'u_composite'), u.composite)
714 24 : g.uniform1i(loc(blendProg, 'u_blendSpace'), u.blendSpace)
715 24 : g.uniform1i(loc(blendProg, 'u_compositeSpace'), u.compositeSpace)
716 : }
717 :
718 24 : drawFullscreen()
719 24 : const tmp = read
720 24 : read = write
721 24 : write = tmp
722 : }
723 :
724 18 : for (const tex of temps) g.deleteTexture(tex)
725 18 : sweepTexCache()
726 :
727 18 : if (target) {
728 0 : const dst = targets.get(target.id)
729 0 : if (dst) blit(read, dst)
730 0 : return
731 : }
732 :
733 18 : if (!result || result.width !== width || result.height !== height) {
734 4 : if (result) freeTargetObj(result)
735 4 : result = makeTarget(width, height)
736 4 : resultValid = false
737 : }
738 18 : if (result) {
739 18 : blit(read, result)
740 18 : resultValid = true
741 : }
742 18 : if (clip) g.disable(g.SCISSOR_TEST)
743 : },
744 :
745 : allocTarget(w: number, h: number): FBOHandle {
746 0 : const id = nextHandle++
747 0 : if (gl) {
748 0 : const target = makeTarget(w, h)
749 0 : if (target) targets.set(id, target)
750 : }
751 0 : return { id, width: w, height: h }
752 : },
753 :
754 : freeTarget(handle: FBOHandle): void {
755 0 : const t = targets.get(handle.id)
756 0 : if (t) {
757 0 : freeTargetObj(t)
758 0 : targets.delete(handle.id)
759 : }
760 : },
761 :
762 : targetTexture(handle: FBOHandle): WebGLTexture | null {
763 0 : return targets.get(handle.id)?.tex ?? null
764 : },
765 :
766 : upload(
767 : source: HTMLCanvasElement | ImageBitmap | OffscreenCanvas
768 : ): WebGLTexture {
769 0 : return uploadSource(source)
770 : },
771 :
772 : readback(region?: Rect): ImageData {
773 9 : const empty = () => new ImageData(Math.max(1, width), Math.max(1, height))
774 9 : if (!ensureHealthy() || !gl || !ping) return empty()
775 9 : const g = gl
776 :
777 9 : let clip: Rect | null = null
778 9 : if (region) {
779 0 : const x = Math.max(0, Math.floor(region.x))
780 0 : const y = Math.max(0, Math.floor(region.y))
781 0 : const w = Math.min(width, Math.ceil(region.x + region.w)) - x
782 0 : const h = Math.min(height, Math.ceil(region.y + region.h)) - y
783 0 : if (w <= 0 || h <= 0) return new ImageData(1, 1)
784 0 : if (w < width || h < height) clip = { x, y, w, h }
785 : }
786 :
787 9 : presentToDefault(result ?? ping, clip)
788 9 : g.bindFramebuffer(g.FRAMEBUFFER, null)
789 9 : if (clip) {
790 0 : const px = new Uint8ClampedArray(clip.w * clip.h * 4)
791 0 : g.readPixels(
792 : clip.x,
793 : height - (clip.y + clip.h),
794 : clip.w,
795 : clip.h,
796 : g.RGBA,
797 : g.UNSIGNED_BYTE,
798 : px
799 : )
800 0 : flipRows(px, clip.w, clip.h)
801 0 : return new ImageData(px, clip.w, clip.h)
802 : }
803 9 : const px = new Uint8ClampedArray(width * height * 4)
804 9 : g.readPixels(0, 0, width, height, g.RGBA, g.UNSIGNED_BYTE, px)
805 9 : flipRows(px, width, height)
806 9 : return new ImageData(px, width, height)
807 : },
808 :
809 : async toBlob(): Promise<Blob> {
810 0 : const data = this.readback()
811 0 : const c = document.createElement('canvas')
812 0 : c.width = data.width
813 0 : c.height = data.height
814 0 : c.getContext('2d')!.putImageData(data, 0, 0)
815 0 : return await new Promise<Blob>((res, rej) =>
816 : c.toBlob(
817 : (b) => (b ? res(b) : rej(new Error('toBlob failed'))),
818 : 'image/png'
819 : )
820 : )
821 : },
822 :
823 : getCanvas(): HTMLCanvasElement | OffscreenCanvas | null {
824 0 : return canvas
825 : },
826 :
827 : dispose(): void {
828 0 : disposed = true
829 0 : if (!gl) return
830 0 : if (ping) freeTargetObj(ping)
831 0 : if (pong) freeTargetObj(pong)
832 0 : if (result) freeTargetObj(result)
833 0 : for (const t of targets.values()) freeTargetObj(t)
834 0 : targets.clear()
835 0 : for (const entry of texCache.values()) gl.deleteTexture(entry.tex)
836 0 : texCache.clear()
837 0 : if (fallback) gl.deleteTexture(fallback)
838 0 : if (lutTex) gl.deleteTexture(lutTex)
839 0 : if (blendProg) gl.deleteProgram(blendProg)
840 0 : if (presentProg) gl.deleteProgram(presentProg)
841 0 : if (copyProg) gl.deleteProgram(copyProg)
842 0 : if (adjustProg) gl.deleteProgram(adjustProg)
843 0 : gl.getExtension('WEBGL_lose_context')?.loseContext()
844 0 : gl = null
845 0 : ping = pong = result = null
846 0 : lutTex = null
847 0 : fallback = blendProg = presentProg = copyProg = adjustProg = null
848 : }
849 : }
850 :
851 9 : function presentToDefault(src: Target, clip?: Rect | null): void {
852 9 : const g = gl!
853 9 : g.disable(g.SCISSOR_TEST)
854 9 : if (clip) {
855 0 : g.enable(g.SCISSOR_TEST)
856 0 : g.scissor(clip.x, height - (clip.y + clip.h), clip.w, clip.h)
857 : }
858 9 : g.useProgram(presentProg)
859 9 : g.bindFramebuffer(g.FRAMEBUFFER, null)
860 9 : g.viewport(0, 0, width, height)
861 9 : g.clearColor(0, 0, 0, 0)
862 9 : g.clear(g.COLOR_BUFFER_BIT)
863 9 : g.activeTexture(g.TEXTURE0)
864 9 : g.bindTexture(g.TEXTURE_2D, src.tex)
865 9 : g.uniform1i(loc(presentProg!, 'u_tex'), 0)
866 9 : drawFullscreen()
867 9 : if (clip) g.disable(g.SCISSOR_TEST)
868 : }
869 :
870 18 : function blit(src: Target, dst: Target): void {
871 18 : const g = gl!
872 18 : g.useProgram(copyProg)
873 18 : g.bindFramebuffer(g.FRAMEBUFFER, dst.fbo)
874 18 : g.viewport(0, 0, dst.width, dst.height)
875 18 : g.activeTexture(g.TEXTURE0)
876 18 : g.bindTexture(g.TEXTURE_2D, src.tex)
877 18 : g.uniform1i(loc(copyProg!, 'u_tex'), 0)
878 18 : drawFullscreen()
879 : }
880 : }
881 :
882 9 : function flipRows(px: Uint8ClampedArray, w: number, h: number): void {
883 9 : const row = w * 4
884 9 : const tmp = new Uint8ClampedArray(row)
885 9 : for (let y = 0; y < h >> 1; y++) {
886 2208 : const top = y * row
887 2208 : const bot = (h - 1 - y) * row
888 2208 : tmp.set(px.subarray(top, top + row))
889 2208 : px.copyWithin(top, bot, bot + row)
890 2208 : px.set(tmp, bot)
891 : }
892 : }
|