BlueGit

timfa frameworkv3

Files

frameworkv3 / framework / engine / gl / glContext.js

glContext.js

glContext.js 17.0 KiB Download Raw
1class GLContext
2{
3 static MAX_LIGHTS = 16;
4
5 constructor (canvas)
6 {
7 this.canvas = canvas;
8
9 // 2D sprites do not benefit from MSAA; disabling avoids extra GPU cost.
10 const attrs = { alpha: true, premultipliedAlpha: false, antialias: false };
11 this.gl = canvas.getContext("webgl", attrs) || canvas.getContext("experimental-webgl", attrs);
12
13 if (!this.gl)
14 { throw new Error("WebGL is not supported in this browser."); }
15
16 const gl = this.gl;
17 gl.enable(gl.BLEND);
18 gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
19 gl.disable(gl.DEPTH_TEST);
20 gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
21
22 this.defaultShader = new Shader(Shader.DEFAULT_VERT, Shader.DEFAULT_FRAG);
23 this.screenCopyShader = new Shader(Shader.SCREEN_VERT, Shader.SCREEN_COPY_FRAG);
24 this.textures = new WeakMap();
25 // Defaults for getTexture uploads. Games can switch to NEAREST for pixel art.
26 this.textureMinFilter = gl.LINEAR;
27 this.textureMagFilter = gl.LINEAR;
28
29 // Reused per-sprite uploads (avoid allocating Float32Array every draw).
30 this._uvData = new Float32Array(8);
31 this._matrixData = new Float32Array(16);
32
33 this.positionBuffer = gl.createBuffer();
34 gl.bindBuffer(gl.ARRAY_BUFFER, this.positionBuffer);
35 gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
36 -0.5, -0.5,
37 0.5, -0.5,
38 -0.5, 0.5,
39 0.5, 0.5
40 ]), gl.STATIC_DRAW);
41
42 this.texCoordBuffer = gl.createBuffer();
43 gl.bindBuffer(gl.ARRAY_BUFFER, this.texCoordBuffer);
44 gl.bufferData(gl.ARRAY_BUFFER, this._uvData, gl.DYNAMIC_DRAW);
45
46 // Fullscreen NDC quad (triangle strip) + UVs (v=0 at bottom, matches FBO sampling).
47 this.screenPositionBuffer = gl.createBuffer();
48 gl.bindBuffer(gl.ARRAY_BUFFER, this.screenPositionBuffer);
49 gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
50 -1, -1,
51 1, -1,
52 -1, 1,
53 1, 1
54 ]), gl.STATIC_DRAW);
55
56 this.screenTexCoordBuffer = gl.createBuffer();
57 gl.bindBuffer(gl.ARRAY_BUFFER, this.screenTexCoordBuffer);
58 gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
59 0, 0,
60 1, 0,
61 0, 1,
62 1, 1
63 ]), gl.STATIC_DRAW);
64
65 // [0] = scene (stable during post), [1]/[2] = full-res ping-pong,
66 // [3]/[4] = half-res ping-pong for pass.scale < 1 blur.
67 this.framebuffers = [null, null, null, null, null];
68 this.colorTextures = [null, null, null, null, null];
69 this._offscreenIndex = 0;
70 this._lastWidth = 0;
71 this._lastHeight = 0;
72 this._halfWidth = 0;
73 this._halfHeight = 0;
74 this._postUniforms = {};
75 this._resUniform = [0, 0];
76 this.setSize(canvas.width, canvas.height);
77 }
78
79 setSize (width, height)
80 {
81 const gl = this.gl;
82 width = Math.max(1, width | 0);
83 height = Math.max(1, height | 0);
84
85 if (width !== this._lastWidth || height !== this._lastHeight)
86 {
87 this._lastWidth = width;
88 this._lastHeight = height;
89 this._halfWidth = Math.max(1, width >> 1);
90 this._halfHeight = Math.max(1, height >> 1);
91 gl.viewport(0, 0, width, height);
92 this._rebuildFramebuffers(width, height);
93 }
94 }
95
96 _destroyFramebuffers ()
97 {
98 const gl = this.gl;
99 for (let i = 0; i < this.framebuffers.length; i++)
100 {
101 if (this.framebuffers[i])
102 {
103 gl.deleteFramebuffer(this.framebuffers[i]);
104 this.framebuffers[i] = null;
105 }
106
107 if (this.colorTextures[i])
108 {
109 gl.deleteTexture(this.colorTextures[i]);
110 this.colorTextures[i] = null;
111 }
112 }
113 }
114
115 _rebuildFramebuffers (width, height)
116 {
117 const gl = this.gl;
118 this._destroyFramebuffers();
119
120 this._halfWidth = Math.max(1, width >> 1);
121 this._halfHeight = Math.max(1, height >> 1);
122
123 for (let i = 0; i < 5; i++)
124 {
125 const texW = i < 3 ? width : this._halfWidth;
126 const texH = i < 3 ? height : this._halfHeight;
127
128 const texture = gl.createTexture();
129 gl.bindTexture(gl.TEXTURE_2D, texture);
130 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
131 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
132 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
133 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
134 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, texW, texH, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
135
136 const fb = gl.createFramebuffer();
137 gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
138 gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
139
140 const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
141 if (status !== gl.FRAMEBUFFER_COMPLETE)
142 {
143 console.error("Framebuffer incomplete:", status);
144 }
145
146 this.framebuffers[i] = fb;
147 this.colorTextures[i] = texture;
148 }
149
150 gl.bindFramebuffer(gl.FRAMEBUFFER, null);
151 gl.bindTexture(gl.TEXTURE_2D, null);
152 }
153
154 clear (r, g, b, a = 1)
155 {
156 const gl = this.gl;
157 gl.clearColor(r / 255, g / 255, b / 255, a);
158 gl.clear(gl.COLOR_BUFFER_BIT);
159 }
160
161 clearTransparent ()
162 {
163 const gl = this.gl;
164 gl.clearColor(0, 0, 0, 0);
165 gl.clear(gl.COLOR_BUFFER_BIT);
166 }
167
168 beginOffscreenPass ()
169 {
170 const gl = this.gl;
171 this._offscreenIndex = 0;
172 gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffers[0]);
173 gl.viewport(0, 0, this._lastWidth, this._lastHeight);
174 gl.enable(gl.BLEND);
175 gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
176 }
177
178 endOffscreenPass ()
179 {
180 const gl = this.gl;
181 gl.bindFramebuffer(gl.FRAMEBUFFER, null);
182 }
183
184 /**
185 * @param {Array} passes
186 * @param {Object} builtins
187 * @param {{ toCanvas?: boolean }} options - toCanvas true writes the last pass to the canvas.
188 * @returns {WebGLTexture|null} final color texture when not drawing to canvas
189 */
190 applyPostShaders (passes, builtins = {}, options = {})
191 {
192 if (!passes || !passes.length)
193 { return this.colorTextures[0]; }
194
195 const gl = this.gl;
196 const toCanvas = !!options.toCanvas;
197 const sceneTexture = this.colorTextures[0];
198 let read = 0;
199 let readIsHalf = false;
200
201 gl.disable(gl.BLEND);
202
203 for (let i = 0; i < passes.length; i++)
204 {
205 const pass = passes[i];
206 const isLast = i === passes.length - 1;
207 const wantHalf = pass.scale != null && pass.scale < 1;
208
209 let write;
210 let writeW;
211 let writeH;
212
213 if (wantHalf)
214 {
215 // Half-res ping-pong on indices 3/4.
216 if (readIsHalf)
217 { write = (read === 3) ? 4 : 3; }
218 else
219 { write = 3; }
220
221 writeW = this._halfWidth;
222 writeH = this._halfHeight;
223 }
224 else
225 {
226 // Full-res ping-pong on 1/2 (never overwrite scene buffer 0).
227 // When leaving half-res, read half texture into a full write target.
228 if (read === 1)
229 { write = 2; }
230 else if (read === 2)
231 { write = 1; }
232 else
233 { write = 1; }
234
235 writeW = this._lastWidth;
236 writeH = this._lastHeight;
237 }
238
239 if (isLast && toCanvas)
240 {
241 gl.bindFramebuffer(gl.FRAMEBUFFER, null);
242 writeW = this._lastWidth;
243 writeH = this._lastHeight;
244 }
245 else
246 {
247 gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffers[write]);
248 }
249
250 gl.viewport(0, 0, writeW, writeH);
251 gl.clearColor(0, 0, 0, 0);
252 gl.clear(gl.COLOR_BUFFER_BIT);
253
254 const uniforms = this._postUniforms;
255 for (const key in uniforms)
256 {
257 if (Object.prototype.hasOwnProperty.call(uniforms, key))
258 { delete uniforms[key]; }
259 }
260 if (builtins)
261 {
262 for (const key in builtins)
263 {
264 if (Object.prototype.hasOwnProperty.call(builtins, key))
265 { uniforms[key] = builtins[key]; }
266 }
267 }
268 const passUniforms = pass.uniforms;
269 if (passUniforms)
270 {
271 for (const key in passUniforms)
272 {
273 if (Object.prototype.hasOwnProperty.call(passUniforms, key))
274 { uniforms[key] = passUniforms[key]; }
275 }
276 }
277 this._resUniform[0] = writeW;
278 this._resUniform[1] = writeH;
279 uniforms.u_resolution = this._resUniform;
280 this.drawFullscreen(pass.shader, this.colorTextures[read], uniforms, sceneTexture);
281
282 if (!isLast || !toCanvas)
283 {
284 read = write;
285 readIsHalf = wantHalf && !(isLast && toCanvas);
286 }
287 }
288
289 this._offscreenIndex = read;
290 gl.enable(gl.BLEND);
291 gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
292 gl.bindFramebuffer(gl.FRAMEBUFFER, null);
293
294 return toCanvas ? null : this.colorTextures[read];
295 }
296
297 blitToCanvas (texture, composite = "alpha")
298 {
299 if (!texture)
300 { return; }
301
302 const gl = this.gl;
303 gl.bindFramebuffer(gl.FRAMEBUFFER, null);
304 gl.viewport(0, 0, this._lastWidth, this._lastHeight);
305 gl.enable(gl.BLEND);
306
307 if (composite === "add")
308 { gl.blendFunc(gl.ONE, gl.ONE); }
309 else
310 { gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); }
311
312 this.drawFullscreen(this.screenCopyShader, texture, null, null);
313
314 gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
315 }
316
317 drawFullscreen (shader, texture, uniforms, sceneTexture)
318 {
319 const gl = this.gl;
320 const info = shader.getProgramInfo(gl);
321 if (!info || !texture)
322 { return; }
323
324 gl.useProgram(info.program);
325
326 gl.bindBuffer(gl.ARRAY_BUFFER, this.screenPositionBuffer);
327 if (info.attribs.position >= 0)
328 {
329 gl.enableVertexAttribArray(info.attribs.position);
330 gl.vertexAttribPointer(info.attribs.position, 2, gl.FLOAT, false, 0, 0);
331 }
332
333 gl.bindBuffer(gl.ARRAY_BUFFER, this.screenTexCoordBuffer);
334 if (info.attribs.texCoord >= 0)
335 {
336 gl.enableVertexAttribArray(info.attribs.texCoord);
337 gl.vertexAttribPointer(info.attribs.texCoord, 2, gl.FLOAT, false, 0, 0);
338 }
339
340 gl.activeTexture(gl.TEXTURE0);
341 gl.bindTexture(gl.TEXTURE_2D, texture);
342 this._setUniform(info, "u_texture", 0);
343 this._setUniform(info, "u_alpha", 1);
344
345 if (sceneTexture && info.uniforms.u_scene)
346 {
347 gl.activeTexture(gl.TEXTURE1);
348 gl.bindTexture(gl.TEXTURE_2D, sceneTexture);
349 this._setUniform(info, "u_scene", 1);
350 }
351
352 if (uniforms)
353 {
354 for (const name in uniforms)
355 {
356 if (!Object.prototype.hasOwnProperty.call(uniforms, name))
357 { continue; }
358
359 this._setUniform(info, name, uniforms[name]);
360 }
361 }
362
363 gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
364 }
365
366 /**
367 * Default min/mag filter applied when creating textures in {@link getTexture}.
368 * Does not rewrite textures that were already uploaded.
369 */
370 setDefaultTextureFilter (minFilter, magFilter)
371 {
372 const gl = this.gl;
373 this.textureMinFilter = minFilter ?? gl.LINEAR;
374 this.textureMagFilter = magFilter ?? gl.LINEAR;
375 }
376
377 getTexture (htmlImage)
378 {
379 if (!htmlImage)
380 { return null; }
381
382 let texture = this.textures.get(htmlImage);
383 if (texture)
384 { return texture; }
385
386 const gl = this.gl;
387 texture = gl.createTexture();
388 gl.bindTexture(gl.TEXTURE_2D, texture);
389 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
390 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
391 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, this.textureMinFilter);
392 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, this.textureMagFilter);
393 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, htmlImage);
394
395 this.textures.set(htmlImage, texture);
396 return texture;
397 }
398
399 drawSprite (options)
400 {
401 const gl = this.gl;
402 const width = this._lastWidth;
403 const height = this._lastHeight;
404 if (width <= 0 || height <= 0)
405 { return; }
406
407 const shader = options.shader || this.defaultShader;
408 const info = shader.getProgramInfo(gl);
409 if (!info)
410 { return; }
411
412 const texture = options.texture;
413 if (!texture)
414 { return; }
415
416 gl.useProgram(info.program);
417
418 gl.bindBuffer(gl.ARRAY_BUFFER, this.positionBuffer);
419 if (info.attribs.position >= 0)
420 {
421 gl.enableVertexAttribArray(info.attribs.position);
422 gl.vertexAttribPointer(info.attribs.position, 2, gl.FLOAT, false, 0, 0);
423 }
424
425 const uv = options.uvRect || { u0: 0, v0: 0, u1: 1, v1: 1 };
426 const uvData = this._uvData;
427 uvData[0] = uv.u0; uvData[1] = uv.v0;
428 uvData[2] = uv.u1; uvData[3] = uv.v0;
429 uvData[4] = uv.u0; uvData[5] = uv.v1;
430 uvData[6] = uv.u1; uvData[7] = uv.v1;
431 gl.bindBuffer(gl.ARRAY_BUFFER, this.texCoordBuffer);
432 gl.bufferSubData(gl.ARRAY_BUFFER, 0, uvData);
433
434 if (info.attribs.texCoord >= 0)
435 {
436 gl.enableVertexAttribArray(info.attribs.texCoord);
437 gl.vertexAttribPointer(info.attribs.texCoord, 2, gl.FLOAT, false, 0, 0);
438 }
439
440 const matrix = GLContext._buildSpriteMatrix(
441 options.x, options.y,
442 options.w, options.h,
443 options.rotationDeg || 0,
444 options.mirrorX, options.mirrorY,
445 width, height,
446 this._matrixData
447 );
448
449 this._setUniform(info, "u_matrix", matrix);
450 this._setUniform(info, "u_alpha", options.alpha == null ? 1 : options.alpha);
451 this._setUniform(info, "u_worldCenter", [options.x, options.y]);
452 this._setUniform(info, "u_worldSize", [options.w, options.h]);
453 this._setUniform(info, "u_rotationRad", (options.rotationDeg || 0) * Math.PI / 180);
454
455 gl.activeTexture(gl.TEXTURE0);
456 gl.bindTexture(gl.TEXTURE_2D, texture);
457 this._setUniform(info, "u_texture", 0);
458
459 let nextUnit = 1;
460 if (options.textures)
461 {
462 for (const name in options.textures)
463 {
464 if (!Object.prototype.hasOwnProperty.call(options.textures, name))
465 { continue; }
466
467 const extra = options.textures[name];
468 if (!extra)
469 { continue; }
470
471 gl.activeTexture(gl.TEXTURE0 + nextUnit);
472 gl.bindTexture(gl.TEXTURE_2D, extra);
473 this._setUniform(info, name, nextUnit);
474 nextUnit++;
475 }
476 }
477
478 if (options.lights)
479 { this._setLights(info, options.lights); }
480 else if (info.uniforms.u_lightCount)
481 { this._setUniform(info, "u_lightCount", 0); }
482
483 // Sensible bump defaults when the shader asks for them.
484 if (info.uniforms.u_ambient && (!options.uniforms || options.uniforms.u_ambient == null))
485 { this._setUniform(info, "u_ambient", 0.35); }
486 if (info.uniforms.u_specular && (!options.uniforms || options.uniforms.u_specular == null))
487 { this._setUniform(info, "u_specular", 0.25); }
488 if (info.uniforms.u_bumpMode && (!options.uniforms || options.uniforms.u_bumpMode == null))
489 { this._setUniform(info, "u_bumpMode", 1); }
490
491 if (options.uniforms)
492 {
493 for (const name in options.uniforms)
494 {
495 if (!Object.prototype.hasOwnProperty.call(options.uniforms, name))
496 { continue; }
497
498 this._setUniform(info, name, options.uniforms[name]);
499 }
500 }
501
502 gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
503 }
504
505 _setLights (info, lights)
506 {
507 const gl = this.gl;
508 const max = GLContext.MAX_LIGHTS;
509 const count = Math.max(0, Math.min(lights.length, max));
510 this._setUniform(info, "u_lightCount", count);
511
512 const posEntry = info.uniforms["u_lightPos[0]"] || info.uniforms.u_lightPos;
513 const colEntry = info.uniforms["u_lightColor[0]"] || info.uniforms.u_lightColor;
514 if (!posEntry || !colEntry || count === 0)
515 {
516 if (count === 0)
517 { this._setUniform(info, "u_lightCount", 0); }
518 return;
519 }
520
521 const pos = new Float32Array(max * 2);
522 const col = new Float32Array(max * 3);
523
524 for (let i = 0; i < count; i++)
525 {
526 const light = lights[i] || {};
527 pos[i * 2] = light.x != null ? light.x : (light.position ? light.position.x : 0);
528 pos[i * 2 + 1] = light.y != null ? light.y : (light.position ? light.position.y : 0);
529
530 const c = light.color != null ? light.color : [1, 1, 1];
531 if (Array.isArray(c))
532 {
533 col[i * 3] = c[0] != null ? c[0] : 0;
534 col[i * 3 + 1] = c[1] != null ? c[1] : 0;
535 col[i * 3 + 2] = c[2] != null ? c[2] : 0;
536 }
537 else
538 {
539 col[i * 3] = (c.r != null ? c.r : 1);
540 col[i * 3 + 1] = (c.g != null ? c.g : 1);
541 col[i * 3 + 2] = (c.b != null ? c.b : 1);
542 }
543
544 // Allow 0–255 style colors.
545 if (col[i * 3] > 1 || col[i * 3 + 1] > 1 || col[i * 3 + 2] > 1)
546 {
547 col[i * 3] /= 255;
548 col[i * 3 + 1] /= 255;
549 col[i * 3 + 2] /= 255;
550 }
551 }
552
553 gl.uniform2fv(posEntry.location, pos);
554 gl.uniform3fv(colEntry.location, col);
555 }
556
557 _setUniform (info, name, value)
558 {
559 const entry = info.uniforms[name];
560 if (!entry || entry.location == null)
561 { return; }
562
563 const gl = this.gl;
564 const loc = entry.location;
565
566 if (typeof value === "number")
567 {
568 if (entry.type === gl.INT || entry.type === gl.SAMPLER_2D)
569 { gl.uniform1i(loc, value); }
570 else
571 { gl.uniform1f(loc, value); }
572 return;
573 }
574
575 if (value instanceof Float32Array)
576 {
577 if (value.length === 16)
578 { gl.uniformMatrix4fv(loc, false, value); }
579 else if (value.length === 9)
580 { gl.uniformMatrix3fv(loc, false, value); }
581 else if (value.length === 4)
582 { gl.uniform4fv(loc, value); }
583 else if (value.length === 3)
584 { gl.uniform3fv(loc, value); }
585 else if (value.length === 2)
586 { gl.uniform2fv(loc, value); }
587 return;
588 }
589
590 if (Array.isArray(value))
591 {
592 if (value.length === 4)
593 { gl.uniform4fv(loc, value); }
594 else if (value.length === 3)
595 { gl.uniform3fv(loc, value); }
596 else if (value.length === 2)
597 { gl.uniform2fv(loc, value); }
598 else if (value.length === 1)
599 { gl.uniform1f(loc, value[0]); }
600 }
601 }
602
603 // Column-major mat4: projection (canvas Y-down) * T * R * S
604 static _buildSpriteMatrix (x, y, w, h, rotationDeg, mirrorX, mirrorY, canvasW, canvasH, out)
605 {
606 const sx = (mirrorX ? -1 : 1) * w;
607 const sy = (mirrorY ? -1 : 1) * h;
608 const rad = rotationDeg * Math.PI / 180;
609 const c = Math.cos(rad);
610 const s = Math.sin(rad);
611
612 // Model maps unit quad [-0.5,0.5] into pixel space.
613 const m00 = c * sx;
614 const m01 = -s * sy;
615 const m10 = s * sx;
616 const m11 = c * sy;
617 const m30 = x;
618 const m31 = y;
619
620 const pr0 = 2 / canvasW;
621 const pr5 = -2 / canvasH;
622 const pr12 = -1;
623 const pr13 = 1;
624
625 const matrix = out || new Float32Array(16);
626 // P * M (only 2D affine terms matter)
627 matrix[0] = pr0 * m00;
628 matrix[1] = pr5 * m10;
629 matrix[2] = 0;
630 matrix[3] = 0;
631 matrix[4] = pr0 * m01;
632 matrix[5] = pr5 * m11;
633 matrix[6] = 0;
634 matrix[7] = 0;
635 matrix[8] = 0;
636 matrix[9] = 0;
637 matrix[10] = -1;
638 matrix[11] = 0;
639 matrix[12] = pr0 * m30 + pr12;
640 matrix[13] = pr5 * m31 + pr13;
641 matrix[14] = 0;
642 matrix[15] = 1;
643 return matrix;
644 }
645}