Line data Source code
1 : import { detectPassCount } from '@/renderer/glsl/glslUtils'
2 : import { acquireSharedGL } from '@/renderer/glsl/sharedGLContext'
3 :
4 : import type { SharedGLHandle } from '@/renderer/glsl/sharedGLContext'
5 :
6 2355 : const VERTEX_SHADER_SOURCE = `#version 300 es
7 : out vec2 v_texCoord;
8 : void main() {
9 : vec2 verts[3] = vec2[](vec2(-1, -1), vec2(3, -1), vec2(-1, 3));
10 : v_texCoord = verts[gl_VertexID] * 0.5 + 0.5;
11 : gl_Position = vec4(verts[gl_VertexID], 0, 1);
12 : }
13 : `
14 :
15 2355 : const MAX_PASSES = 32
16 :
17 : export interface GLSLRendererConfig {
18 : maxInputs: number
19 : maxFloatUniforms: number
20 : maxIntUniforms: number
21 : maxBoolUniforms: number
22 : maxCurves: number
23 : }
24 :
25 2355 : const DEFAULT_CONFIG: GLSLRendererConfig = {
26 : maxInputs: 5,
27 : maxFloatUniforms: 20,
28 : maxIntUniforms: 20,
29 : maxBoolUniforms: 10,
30 : maxCurves: 4
31 : }
32 :
33 : interface CompileResult {
34 : success: boolean
35 : log: string
36 : }
37 :
38 38 : function createTexture(gl: WebGL2RenderingContext): WebGLTexture | null {
39 38 : return gl.createTexture()
40 : }
41 :
42 36 : function createFramebuffer(
43 : gl: WebGL2RenderingContext
44 : ): WebGLFramebuffer | null {
45 36 : return gl.createFramebuffer()
46 : }
47 :
48 16 : function createProgram(gl: WebGL2RenderingContext): WebGLProgram | null {
49 16 : return gl.createProgram()
50 : }
51 :
52 31 : function compileShader(
53 : gl: WebGL2RenderingContext,
54 : type: GLenum,
55 : source: string
56 : ): WebGLShader {
57 31 : const shader = gl.createShader(type)
58 31 : if (!shader) throw new Error('Failed to create shader')
59 :
60 31 : gl.shaderSource(shader, source)
61 31 : gl.compileShader(shader)
62 :
63 31 : if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
64 1 : const log = gl.getShaderInfoLog(shader) ?? 'Compilation failed'
65 1 : gl.deleteShader(shader)
66 1 : throw new Error(log)
67 : }
68 30 : return shader
69 : }
70 :
71 14 : export function useGLSLRenderer(config: GLSLRendererConfig = DEFAULT_CONFIG) {
72 14 : const {
73 : maxInputs,
74 : maxFloatUniforms,
75 : maxIntUniforms,
76 : maxBoolUniforms,
77 : maxCurves
78 : } = config
79 :
80 14 : const uniformNames = [
81 : 'u_resolution',
82 : 'u_pass',
83 : ...Array.from({ length: maxInputs }, (_, i) => `u_image${i}`),
84 : ...Array.from({ length: maxFloatUniforms }, (_, i) => `u_float${i}`),
85 : ...Array.from({ length: maxIntUniforms }, (_, i) => `u_int${i}`),
86 : ...Array.from({ length: maxBoolUniforms }, (_, i) => `u_bool${i}`),
87 : ...Array.from({ length: maxCurves }, (_, i) => `u_curve${i}`)
88 : ]
89 :
90 14 : let sharedGL: SharedGLHandle | null = null
91 14 : let canvas: OffscreenCanvas | null = null
92 14 : let gl: WebGL2RenderingContext | null = null
93 14 : let vertexShader: WebGLShader | null = null
94 14 : let program: WebGLProgram | null = null
95 14 : let fragmentShader: WebGLShader | null = null
96 14 : let pingPongFBOs: [WebGLFramebuffer, WebGLFramebuffer] | null = null
97 14 : let pingPongTextures: [WebGLTexture, WebGLTexture] | null = null
98 14 : let fallbackTexture: WebGLTexture | null = null
99 14 : const inputTextures: (WebGLTexture | null)[] = Array.from<null>({
100 : length: maxInputs
101 : }).fill(null)
102 14 : const curveTextures: (WebGLTexture | null)[] = Array.from<null>({
103 : length: maxCurves
104 : }).fill(null)
105 14 : const uniformLocations = new Map<string, WebGLUniformLocation | null>()
106 14 : let passCount = 1
107 14 : let disposed = false
108 14 : let lastCompiledSource: string | null = null
109 14 : let fboWidth = 0
110 14 : let fboHeight = 0
111 :
112 18 : function initPingPongFBOs(
113 : ctx: WebGL2RenderingContext,
114 : width: number,
115 : height: number
116 : ): void {
117 18 : const fbos: WebGLFramebuffer[] = []
118 18 : const textures: WebGLTexture[] = []
119 :
120 18 : try {
121 18 : for (let i = 0; i < 2; i++) {
122 36 : const tex = createTexture(ctx)
123 36 : if (!tex) throw new Error('Failed to create ping-pong texture')
124 36 : ctx.bindTexture(ctx.TEXTURE_2D, tex)
125 36 : ctx.texImage2D(
126 : ctx.TEXTURE_2D,
127 : 0,
128 : ctx.RGBA16F,
129 : width,
130 : height,
131 : 0,
132 : ctx.RGBA,
133 : ctx.HALF_FLOAT,
134 : null
135 : )
136 36 : ctx.texParameteri(ctx.TEXTURE_2D, ctx.TEXTURE_MIN_FILTER, ctx.LINEAR)
137 36 : ctx.texParameteri(ctx.TEXTURE_2D, ctx.TEXTURE_MAG_FILTER, ctx.LINEAR)
138 36 : ctx.texParameteri(ctx.TEXTURE_2D, ctx.TEXTURE_WRAP_S, ctx.CLAMP_TO_EDGE)
139 36 : ctx.texParameteri(ctx.TEXTURE_2D, ctx.TEXTURE_WRAP_T, ctx.CLAMP_TO_EDGE)
140 :
141 36 : const fbo = createFramebuffer(ctx)
142 36 : if (!fbo) throw new Error('Failed to create ping-pong framebuffer')
143 36 : ctx.bindFramebuffer(ctx.FRAMEBUFFER, fbo)
144 36 : ctx.framebufferTexture2D(
145 : ctx.FRAMEBUFFER,
146 : ctx.COLOR_ATTACHMENT0,
147 : ctx.TEXTURE_2D,
148 : tex,
149 : 0
150 : )
151 36 : const status = ctx.checkFramebufferStatus(ctx.FRAMEBUFFER)
152 36 : if (status !== ctx.FRAMEBUFFER_COMPLETE)
153 0 : throw new Error(`Ping-pong framebuffer incomplete: ${status}`)
154 :
155 36 : fbos.push(fbo)
156 36 : textures.push(tex)
157 : }
158 : } catch (error) {
159 0 : for (const fbo of fbos) ctx.deleteFramebuffer(fbo)
160 0 : for (const tex of textures) ctx.deleteTexture(tex)
161 0 : ctx.bindFramebuffer(ctx.FRAMEBUFFER, null)
162 0 : ctx.bindTexture(ctx.TEXTURE_2D, null)
163 0 : throw error
164 : }
165 :
166 18 : ctx.bindFramebuffer(ctx.FRAMEBUFFER, null)
167 18 : ctx.bindTexture(ctx.TEXTURE_2D, null)
168 :
169 18 : pingPongFBOs = fbos as [WebGLFramebuffer, WebGLFramebuffer]
170 18 : pingPongTextures = textures as [WebGLTexture, WebGLTexture]
171 : }
172 :
173 4 : function destroyPingPongFBOs(): void {
174 4 : if (!gl) return
175 4 : if (pingPongFBOs) {
176 8 : for (const fbo of pingPongFBOs) gl.deleteFramebuffer(fbo)
177 4 : pingPongFBOs = null
178 : }
179 4 : if (pingPongTextures) {
180 8 : for (const tex of pingPongTextures) gl.deleteTexture(tex)
181 4 : pingPongTextures = null
182 : }
183 : }
184 :
185 16 : function cacheUniformLocations(): void {
186 16 : if (!program || !gl) return
187 16 : for (const name of uniformNames) {
188 976 : uniformLocations.set(name, gl.getUniformLocation(program, name))
189 : }
190 : }
191 :
192 0 : function getFallbackTexture(): WebGLTexture {
193 0 : if (!gl) throw new Error('Renderer not initialized')
194 0 : if (!fallbackTexture) {
195 0 : const tex = createTexture(gl)
196 0 : if (!tex) throw new Error('Failed to create fallback texture')
197 0 : fallbackTexture = tex
198 0 : gl.bindTexture(gl.TEXTURE_2D, fallbackTexture)
199 0 : gl.texImage2D(
200 : gl.TEXTURE_2D,
201 : 0,
202 : gl.RGBA,
203 : 1,
204 : 1,
205 : 0,
206 : gl.RGBA,
207 : gl.UNSIGNED_BYTE,
208 : new Uint8Array([0, 0, 0, 255])
209 : )
210 : }
211 0 : return fallbackTexture
212 : }
213 :
214 14 : function init(width: number, height: number): boolean {
215 14 : if (disposed) return false
216 :
217 14 : try {
218 14 : sharedGL = acquireSharedGL()
219 14 : if (!sharedGL) return false
220 :
221 14 : canvas = sharedGL.canvas
222 14 : gl = sharedGL.gl
223 :
224 14 : canvas.width = width
225 14 : canvas.height = height
226 14 : gl.viewport(0, 0, width, height)
227 :
228 14 : vertexShader = compileShader(gl, gl.VERTEX_SHADER, VERTEX_SHADER_SOURCE)
229 14 : initPingPongFBOs(gl, width, height)
230 14 : fboWidth = width
231 14 : fboHeight = height
232 14 : return true
233 : } catch {
234 0 : dispose()
235 0 : return false
236 : }
237 : }
238 :
239 26 : function compileFragment(source: string): CompileResult {
240 26 : if (disposed || !gl) return { success: false, log: 'Engine disposed' }
241 :
242 26 : passCount = Math.min(detectPassCount(source), MAX_PASSES)
243 :
244 26 : if (source === lastCompiledSource && program) {
245 9 : return { success: true, log: '' }
246 : }
247 17 : lastCompiledSource = source
248 :
249 26 : if (fragmentShader) {
250 2 : gl.deleteShader(fragmentShader)
251 2 : fragmentShader = null
252 : }
253 26 : if (program) {
254 2 : gl.deleteProgram(program)
255 2 : program = null
256 : }
257 17 : uniformLocations.clear()
258 :
259 26 : try {
260 17 : fragmentShader = compileShader(gl, gl.FRAGMENT_SHADER, source)
261 : } catch (e: unknown) {
262 : const msg = e instanceof Error ? e.message : String(e)
263 1 : return { success: false, log: msg }
264 : }
265 :
266 16 : const prog = createProgram(gl)
267 26 : if (!prog) return { success: false, log: 'Failed to create program' }
268 :
269 16 : gl.attachShader(prog, vertexShader!)
270 16 : gl.attachShader(prog, fragmentShader)
271 16 : gl.linkProgram(prog)
272 :
273 26 : if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) {
274 0 : const log = gl.getProgramInfoLog(prog) ?? 'Link failed'
275 0 : gl.deleteProgram(prog)
276 0 : return { success: false, log }
277 : }
278 :
279 16 : program = prog
280 16 : cacheUniformLocations()
281 16 : return { success: true, log: '' }
282 : }
283 :
284 25 : function setResolution(width: number, height: number): void {
285 25 : if (disposed || !gl || !canvas) return
286 25 : if (canvas.width !== width || canvas.height !== height) {
287 4 : canvas.width = width
288 4 : canvas.height = height
289 : }
290 25 : gl.viewport(0, 0, width, height)
291 25 : if (fboWidth !== width || fboHeight !== height) {
292 4 : destroyPingPongFBOs()
293 4 : initPingPongFBOs(gl, width, height)
294 4 : fboWidth = width
295 4 : fboHeight = height
296 : }
297 : }
298 :
299 5 : function setFloatUniform(index: number, value: number): void {
300 5 : if (disposed || !program || !gl) return
301 5 : const loc = uniformLocations.get(`u_float${index}`)
302 5 : if (loc != null) {
303 5 : gl.useProgram(program)
304 5 : gl.uniform1f(loc, value)
305 : }
306 : }
307 :
308 2 : function setIntUniform(index: number, value: number): void {
309 2 : if (disposed || !program || !gl) return
310 2 : const loc = uniformLocations.get(`u_int${index}`)
311 2 : if (loc != null) {
312 2 : gl.useProgram(program)
313 2 : gl.uniform1i(loc, value)
314 : }
315 : }
316 :
317 2 : function setBoolUniform(index: number, value: boolean): void {
318 2 : if (disposed || !program || !gl) return
319 2 : const loc = uniformLocations.get(`u_bool${index}`)
320 2 : if (loc != null) {
321 2 : gl.useProgram(program)
322 2 : gl.uniform1i(loc, value ? 1 : 0)
323 : }
324 : }
325 :
326 0 : function bindCurveTexture(index: number, lut: Float32Array): void {
327 0 : if (disposed || !gl) return
328 0 : if (index < 0 || index >= maxCurves) return
329 :
330 0 : if (curveTextures[index]) {
331 0 : gl.deleteTexture(curveTextures[index])
332 0 : curveTextures[index] = null
333 : }
334 :
335 0 : const texture = createTexture(gl)
336 0 : if (!texture) return
337 :
338 0 : const unit = maxInputs + index
339 0 : gl.activeTexture(gl.TEXTURE0 + unit)
340 0 : gl.bindTexture(gl.TEXTURE_2D, texture)
341 0 : gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false)
342 0 : gl.texImage2D(
343 : gl.TEXTURE_2D,
344 : 0,
345 : gl.R16F,
346 : lut.length,
347 : 1,
348 : 0,
349 : gl.RED,
350 : gl.FLOAT,
351 : lut
352 : )
353 0 : gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true)
354 0 : gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
355 0 : gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
356 0 : gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
357 0 : gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
358 :
359 0 : curveTextures[index] = texture
360 : }
361 :
362 2 : function bindInputImage(
363 : index: number,
364 : image: HTMLImageElement | ImageBitmap
365 : ): void {
366 2 : if (disposed || !gl) return
367 2 : if (index < 0 || index >= maxInputs) {
368 0 : throw new Error(
369 : `Input index ${index} out of range (max ${maxInputs - 1})`
370 : )
371 : }
372 :
373 2 : if (inputTextures[index]) {
374 0 : gl.deleteTexture(inputTextures[index])
375 0 : inputTextures[index] = null
376 : }
377 :
378 2 : const texture = createTexture(gl)
379 2 : if (!texture) return
380 :
381 2 : gl.activeTexture(gl.TEXTURE0 + index)
382 2 : gl.bindTexture(gl.TEXTURE_2D, texture)
383 2 : gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
384 2 : gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
385 2 : gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
386 2 : gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
387 2 : gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image)
388 :
389 2 : inputTextures[index] = texture
390 : }
391 :
392 40 : function clearInputImage(index: number): void {
393 40 : if (disposed || !gl) return
394 40 : if (index < 0 || index >= maxInputs) return
395 40 : const texture = inputTextures[index]
396 40 : if (texture) {
397 0 : gl.deleteTexture(texture)
398 0 : inputTextures[index] = null
399 : }
400 : }
401 :
402 12 : function isContextLost(): boolean {
403 12 : return gl?.isContextLost() ?? false
404 : }
405 :
406 25 : function render(): void {
407 25 : if (disposed || !program || !pingPongFBOs || !gl || !canvas) return
408 :
409 25 : if (canvas.width !== fboWidth || canvas.height !== fboHeight) {
410 0 : canvas.width = fboWidth
411 0 : canvas.height = fboHeight
412 : }
413 25 : gl.viewport(0, 0, fboWidth, fboHeight)
414 :
415 25 : gl.useProgram(program)
416 25 : gl.disable(gl.BLEND)
417 :
418 25 : const resLoc = uniformLocations.get('u_resolution')
419 25 : if (resLoc != null) {
420 0 : gl.uniform2f(resLoc, canvas.width, canvas.height)
421 : }
422 :
423 25 : for (let i = 0; i < maxInputs; i++) {
424 125 : const loc = uniformLocations.get(`u_image${i}`)
425 125 : if (loc != null) {
426 1 : gl.activeTexture(gl.TEXTURE0 + i)
427 1 : gl.bindTexture(gl.TEXTURE_2D, inputTextures[i] ?? getFallbackTexture())
428 1 : gl.uniform1i(loc, i)
429 : }
430 : }
431 :
432 25 : for (let i = 0; i < maxCurves; i++) {
433 100 : const loc = uniformLocations.get(`u_curve${i}`)
434 100 : if (loc != null && curveTextures[i]) {
435 0 : const unit = maxInputs + i
436 0 : gl.activeTexture(gl.TEXTURE0 + unit)
437 0 : gl.bindTexture(gl.TEXTURE_2D, curveTextures[i])
438 0 : gl.uniform1i(loc, unit)
439 : }
440 : }
441 :
442 25 : for (let pass = 0; pass < passCount; pass++) {
443 25 : const passLoc = uniformLocations.get('u_pass')
444 25 : if (passLoc != null) gl.uniform1i(passLoc, pass)
445 :
446 25 : const isLastPass = pass === passCount - 1
447 25 : const writeIdx = pass % 2
448 :
449 25 : if (isLastPass) {
450 25 : gl.bindFramebuffer(gl.FRAMEBUFFER, null)
451 25 : gl.drawBuffers([gl.BACK])
452 : } else {
453 0 : gl.bindFramebuffer(gl.FRAMEBUFFER, pingPongFBOs[writeIdx])
454 0 : gl.drawBuffers([gl.COLOR_ATTACHMENT0])
455 : }
456 :
457 : // Match backend behavior: pass > 0 binds previous pass output to
458 : // texture unit 0, overriding u_image0 so shaders read the previous
459 : // pass result via the same sampler.
460 25 : if (pass > 0) {
461 0 : const sourceTexture = pingPongTextures![(pass - 1) % 2]
462 0 : gl.activeTexture(gl.TEXTURE0)
463 0 : gl.bindTexture(gl.TEXTURE_2D, sourceTexture)
464 : }
465 :
466 25 : gl.clearColor(0, 0, 0, 0)
467 25 : gl.clear(gl.COLOR_BUFFER_BIT)
468 25 : gl.drawArrays(gl.TRIANGLES, 0, 3)
469 : }
470 : }
471 :
472 0 : function readPixels(): ImageData {
473 0 : if (!gl || !canvas) throw new Error('Renderer not initialized')
474 0 : const w = canvas.width
475 0 : const h = canvas.height
476 0 : const pixels = new Uint8ClampedArray(w * h * 4)
477 :
478 0 : gl.pixelStorei(gl.PACK_ROW_LENGTH, 0)
479 0 : gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, pixels)
480 :
481 0 : return new ImageData(pixels, w, h)
482 : }
483 :
484 25 : async function toBlob(): Promise<Blob> {
485 25 : if (!canvas) throw new Error('Renderer not initialized')
486 25 : return canvas.convertToBlob({ type: 'image/webp', quality: 0.92 })
487 : }
488 :
489 0 : function dispose(): void {
490 0 : if (disposed) return
491 0 : disposed = true
492 0 : if (!gl) return
493 :
494 0 : for (const tex of inputTextures) {
495 0 : if (tex) gl.deleteTexture(tex)
496 : }
497 0 : inputTextures.fill(null)
498 :
499 0 : for (const tex of curveTextures) {
500 0 : if (tex) gl.deleteTexture(tex)
501 : }
502 0 : curveTextures.fill(null)
503 :
504 0 : if (fallbackTexture) {
505 0 : gl.deleteTexture(fallbackTexture)
506 0 : fallbackTexture = null
507 : }
508 :
509 0 : destroyPingPongFBOs()
510 :
511 0 : if (fragmentShader) {
512 0 : gl.deleteShader(fragmentShader)
513 0 : fragmentShader = null
514 : }
515 0 : if (vertexShader) {
516 0 : gl.deleteShader(vertexShader)
517 0 : vertexShader = null
518 : }
519 :
520 0 : if (program) {
521 0 : gl.deleteProgram(program)
522 0 : program = null
523 : }
524 :
525 0 : uniformLocations.clear()
526 :
527 0 : sharedGL?.release()
528 0 : sharedGL = null
529 0 : gl = null
530 0 : canvas = null
531 : }
532 :
533 14 : return {
534 : init,
535 : compileFragment,
536 : setResolution,
537 : setFloatUniform,
538 : setIntUniform,
539 : setBoolUniform,
540 : bindCurveTexture,
541 : bindInputImage,
542 : clearInputImage,
543 : isContextLost,
544 : render,
545 : readPixels,
546 : toBlob,
547 : dispose
548 : }
549 : }
|