BlueGit

timfa frameworkv3

Files

frameworkv3 / framework / engine / gl / glContext.js

glContext.js

glContext.js 11.5 KiB Download Raw
1class GLContext
2{
3 constructor (canvas)
4 {
5 this.canvas = canvas;
6
7 const attrs = { alpha: true, premultipliedAlpha: false, antialias: true };
8 this.gl = canvas.getContext("webgl", attrs) || canvas.getContext("experimental-webgl", attrs);
9
10 if (!this.gl)
11 { throw new Error("WebGL is not supported in this browser."); }
12
13 const gl = this.gl;
14 gl.enable(gl.BLEND);
15 gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
16 gl.disable(gl.DEPTH_TEST);
17 gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
18
19 this.defaultShader = new Shader(Shader.DEFAULT_VERT, Shader.DEFAULT_FRAG);
20 this.screenCopyShader = new Shader(Shader.SCREEN_VERT, Shader.SCREEN_COPY_FRAG);
21 this.textures = new WeakMap();
22
23 this.positionBuffer = gl.createBuffer();
24 gl.bindBuffer(gl.ARRAY_BUFFER, this.positionBuffer);
25 gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
26 -0.5, -0.5,
27 0.5, -0.5,
28 -0.5, 0.5,
29 0.5, 0.5
30 ]), gl.STATIC_DRAW);
31
32 this.texCoordBuffer = gl.createBuffer();
33
34 // Fullscreen NDC quad (triangle strip) + UVs (v=0 at bottom, matches FBO sampling).
35 this.screenPositionBuffer = gl.createBuffer();
36 gl.bindBuffer(gl.ARRAY_BUFFER, this.screenPositionBuffer);
37 gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
38 -1, -1,
39 1, -1,
40 -1, 1,
41 1, 1
42 ]), gl.STATIC_DRAW);
43
44 this.screenTexCoordBuffer = gl.createBuffer();
45 gl.bindBuffer(gl.ARRAY_BUFFER, this.screenTexCoordBuffer);
46 gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
47 0, 0,
48 1, 0,
49 0, 1,
50 1, 1
51 ]), gl.STATIC_DRAW);
52
53 // [0] = scene (stable during post), [1]/[2] = ping-pong for effect passes.
54 this.framebuffers = [null, null, null];
55 this.colorTextures = [null, null, null];
56 this._offscreenIndex = 0;
57 this._lastWidth = 0;
58 this._lastHeight = 0;
59 this.setSize(canvas.width, canvas.height);
60 }
61
62 setSize (width, height)
63 {
64 const gl = this.gl;
65 width = Math.max(1, width | 0);
66 height = Math.max(1, height | 0);
67
68 if (width !== this._lastWidth || height !== this._lastHeight)
69 {
70 this._lastWidth = width;
71 this._lastHeight = height;
72 gl.viewport(0, 0, width, height);
73 this._rebuildFramebuffers(width, height);
74 }
75 }
76
77 _destroyFramebuffers ()
78 {
79 const gl = this.gl;
80 for (let i = 0; i < this.framebuffers.length; i++)
81 {
82 if (this.framebuffers[i])
83 {
84 gl.deleteFramebuffer(this.framebuffers[i]);
85 this.framebuffers[i] = null;
86 }
87
88 if (this.colorTextures[i])
89 {
90 gl.deleteTexture(this.colorTextures[i]);
91 this.colorTextures[i] = null;
92 }
93 }
94 }
95
96 _rebuildFramebuffers (width, height)
97 {
98 const gl = this.gl;
99 this._destroyFramebuffers();
100
101 for (let i = 0; i < 3; i++)
102 {
103 const texture = gl.createTexture();
104 gl.bindTexture(gl.TEXTURE_2D, texture);
105 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
106 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
107 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
108 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
109 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
110
111 const fb = gl.createFramebuffer();
112 gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
113 gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
114
115 const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
116 if (status !== gl.FRAMEBUFFER_COMPLETE)
117 {
118 console.error("Framebuffer incomplete:", status);
119 }
120
121 this.framebuffers[i] = fb;
122 this.colorTextures[i] = texture;
123 }
124
125 gl.bindFramebuffer(gl.FRAMEBUFFER, null);
126 gl.bindTexture(gl.TEXTURE_2D, null);
127 }
128
129 clear (r, g, b, a = 1)
130 {
131 const gl = this.gl;
132 gl.clearColor(r / 255, g / 255, b / 255, a);
133 gl.clear(gl.COLOR_BUFFER_BIT);
134 }
135
136 clearTransparent ()
137 {
138 const gl = this.gl;
139 gl.clearColor(0, 0, 0, 0);
140 gl.clear(gl.COLOR_BUFFER_BIT);
141 }
142
143 beginOffscreenPass ()
144 {
145 const gl = this.gl;
146 this._offscreenIndex = 0;
147 gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffers[0]);
148 gl.viewport(0, 0, this._lastWidth, this._lastHeight);
149 gl.enable(gl.BLEND);
150 gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
151 }
152
153 endOffscreenPass ()
154 {
155 const gl = this.gl;
156 gl.bindFramebuffer(gl.FRAMEBUFFER, null);
157 }
158
159 /**
160 * @param {Array} passes
161 * @param {Object} builtins
162 * @param {{ toCanvas?: boolean }} options - toCanvas true writes the last pass to the canvas.
163 * @returns {WebGLTexture|null} final color texture when not drawing to canvas
164 */
165 applyPostShaders (passes, builtins = {}, options = {})
166 {
167 if (!passes || !passes.length)
168 { return this.colorTextures[0]; }
169
170 const gl = this.gl;
171 const toCanvas = !!options.toCanvas;
172 const sceneTexture = this.colorTextures[0];
173 let read = 0;
174
175 gl.disable(gl.BLEND);
176
177 for (let i = 0; i < passes.length; i++)
178 {
179 const pass = passes[i];
180 const isLast = i === passes.length - 1;
181
182 // Never overwrite the scene buffer (index 0); ping-pong on 1/2.
183 let write = 1;
184 if (read === 1)
185 { write = 2; }
186 else if (read === 2)
187 { write = 1; }
188
189 if (isLast && toCanvas)
190 {
191 gl.bindFramebuffer(gl.FRAMEBUFFER, null);
192 }
193 else
194 {
195 gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffers[write]);
196 }
197
198 gl.viewport(0, 0, this._lastWidth, this._lastHeight);
199 gl.clearColor(0, 0, 0, 0);
200 gl.clear(gl.COLOR_BUFFER_BIT);
201
202 const uniforms = Object.assign({}, builtins, pass.uniforms || {});
203 this.drawFullscreen(pass.shader, this.colorTextures[read], uniforms, sceneTexture);
204
205 if (!isLast || !toCanvas)
206 { read = write; }
207 }
208
209 this._offscreenIndex = read;
210 gl.enable(gl.BLEND);
211 gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
212 gl.bindFramebuffer(gl.FRAMEBUFFER, null);
213
214 return toCanvas ? null : this.colorTextures[read];
215 }
216
217 blitToCanvas (texture, composite = "alpha")
218 {
219 if (!texture)
220 { return; }
221
222 const gl = this.gl;
223 gl.bindFramebuffer(gl.FRAMEBUFFER, null);
224 gl.viewport(0, 0, this._lastWidth, this._lastHeight);
225 gl.enable(gl.BLEND);
226
227 if (composite === "add")
228 { gl.blendFunc(gl.ONE, gl.ONE); }
229 else
230 { gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); }
231
232 this.drawFullscreen(this.screenCopyShader, texture, null, null);
233
234 gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
235 }
236
237 drawFullscreen (shader, texture, uniforms, sceneTexture)
238 {
239 const gl = this.gl;
240 const info = shader.getProgramInfo(gl);
241 if (!info || !texture)
242 { return; }
243
244 gl.useProgram(info.program);
245
246 gl.bindBuffer(gl.ARRAY_BUFFER, this.screenPositionBuffer);
247 if (info.attribs.position >= 0)
248 {
249 gl.enableVertexAttribArray(info.attribs.position);
250 gl.vertexAttribPointer(info.attribs.position, 2, gl.FLOAT, false, 0, 0);
251 }
252
253 gl.bindBuffer(gl.ARRAY_BUFFER, this.screenTexCoordBuffer);
254 if (info.attribs.texCoord >= 0)
255 {
256 gl.enableVertexAttribArray(info.attribs.texCoord);
257 gl.vertexAttribPointer(info.attribs.texCoord, 2, gl.FLOAT, false, 0, 0);
258 }
259
260 gl.activeTexture(gl.TEXTURE0);
261 gl.bindTexture(gl.TEXTURE_2D, texture);
262 this._setUniform(info, "u_texture", 0);
263 this._setUniform(info, "u_alpha", 1);
264
265 if (sceneTexture && info.uniforms.u_scene)
266 {
267 gl.activeTexture(gl.TEXTURE1);
268 gl.bindTexture(gl.TEXTURE_2D, sceneTexture);
269 this._setUniform(info, "u_scene", 1);
270 }
271
272 if (uniforms)
273 {
274 for (const name in uniforms)
275 {
276 if (!Object.prototype.hasOwnProperty.call(uniforms, name))
277 { continue; }
278
279 this._setUniform(info, name, uniforms[name]);
280 }
281 }
282
283 gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
284 }
285
286 getTexture (htmlImage)
287 {
288 if (!htmlImage)
289 { return null; }
290
291 let texture = this.textures.get(htmlImage);
292 if (texture)
293 { return texture; }
294
295 const gl = this.gl;
296 texture = gl.createTexture();
297 gl.bindTexture(gl.TEXTURE_2D, texture);
298 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
299 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
300 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
301 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
302 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, htmlImage);
303
304 this.textures.set(htmlImage, texture);
305 return texture;
306 }
307
308 drawSprite (options)
309 {
310 const gl = this.gl;
311 const width = this._lastWidth;
312 const height = this._lastHeight;
313 if (width <= 0 || height <= 0)
314 { return; }
315
316 const shader = options.shader || this.defaultShader;
317 const info = shader.getProgramInfo(gl);
318 if (!info)
319 { return; }
320
321 const texture = options.texture;
322 if (!texture)
323 { return; }
324
325 gl.useProgram(info.program);
326
327 gl.bindBuffer(gl.ARRAY_BUFFER, this.positionBuffer);
328 if (info.attribs.position >= 0)
329 {
330 gl.enableVertexAttribArray(info.attribs.position);
331 gl.vertexAttribPointer(info.attribs.position, 2, gl.FLOAT, false, 0, 0);
332 }
333
334 const uv = options.uvRect || { u0: 0, v0: 0, u1: 1, v1: 1 };
335 gl.bindBuffer(gl.ARRAY_BUFFER, this.texCoordBuffer);
336 gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
337 uv.u0, uv.v0,
338 uv.u1, uv.v0,
339 uv.u0, uv.v1,
340 uv.u1, uv.v1
341 ]), gl.DYNAMIC_DRAW);
342
343 if (info.attribs.texCoord >= 0)
344 {
345 gl.enableVertexAttribArray(info.attribs.texCoord);
346 gl.vertexAttribPointer(info.attribs.texCoord, 2, gl.FLOAT, false, 0, 0);
347 }
348
349 const matrix = GLContext._buildSpriteMatrix(
350 options.x, options.y,
351 options.w, options.h,
352 options.rotationDeg || 0,
353 options.mirrorX, options.mirrorY,
354 width, height
355 );
356
357 this._setUniform(info, "u_matrix", matrix);
358 this._setUniform(info, "u_alpha", options.alpha == null ? 1 : options.alpha);
359
360 gl.activeTexture(gl.TEXTURE0);
361 gl.bindTexture(gl.TEXTURE_2D, texture);
362 this._setUniform(info, "u_texture", 0);
363
364 if (options.uniforms)
365 {
366 for (const name in options.uniforms)
367 {
368 if (!Object.prototype.hasOwnProperty.call(options.uniforms, name))
369 { continue; }
370
371 this._setUniform(info, name, options.uniforms[name]);
372 }
373 }
374
375 gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
376 }
377
378 _setUniform (info, name, value)
379 {
380 const entry = info.uniforms[name];
381 if (!entry || entry.location == null)
382 { return; }
383
384 const gl = this.gl;
385 const loc = entry.location;
386
387 if (typeof value === "number")
388 {
389 if (entry.type === gl.INT || entry.type === gl.SAMPLER_2D)
390 { gl.uniform1i(loc, value); }
391 else
392 { gl.uniform1f(loc, value); }
393 return;
394 }
395
396 if (value instanceof Float32Array)
397 {
398 if (value.length === 16)
399 { gl.uniformMatrix4fv(loc, false, value); }
400 else if (value.length === 9)
401 { gl.uniformMatrix3fv(loc, false, value); }
402 else if (value.length === 4)
403 { gl.uniform4fv(loc, value); }
404 else if (value.length === 3)
405 { gl.uniform3fv(loc, value); }
406 else if (value.length === 2)
407 { gl.uniform2fv(loc, value); }
408 return;
409 }
410
411 if (Array.isArray(value))
412 {
413 if (value.length === 4)
414 { gl.uniform4fv(loc, value); }
415 else if (value.length === 3)
416 { gl.uniform3fv(loc, value); }
417 else if (value.length === 2)
418 { gl.uniform2fv(loc, value); }
419 else if (value.length === 1)
420 { gl.uniform1f(loc, value[0]); }
421 }
422 }
423
424 // Column-major mat4: projection (canvas Y-down) * T * R * S
425 static _buildSpriteMatrix (x, y, w, h, rotationDeg, mirrorX, mirrorY, canvasW, canvasH)
426 {
427 const sx = (mirrorX ? -1 : 1) * w;
428 const sy = (mirrorY ? -1 : 1) * h;
429 const rad = rotationDeg * Math.PI / 180;
430 const c = Math.cos(rad);
431 const s = Math.sin(rad);
432
433 // Model maps unit quad [-0.5,0.5] into pixel space.
434 const m00 = c * sx;
435 const m01 = -s * sy;
436 const m10 = s * sx;
437 const m11 = c * sy;
438 const m30 = x;
439 const m31 = y;
440
441 const pr0 = 2 / canvasW;
442 const pr5 = -2 / canvasH;
443 const pr12 = -1;
444 const pr13 = 1;
445
446 // P * M (only 2D affine terms matter)
447 return new Float32Array([
448 pr0 * m00, pr5 * m10, 0, 0,
449 pr0 * m01, pr5 * m11, 0, 0,
450 0, 0, -1, 0,
451 pr0 * m30 + pr12, pr5 * m31 + pr13, 0, 1
452 ]);
453 }
454}