BlueGit

timfa frameworkv3

Files

frameworkv3 / framework / engine / gl / glContext.js

glContext.js

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