class GLContext { constructor (canvas) { this.canvas = canvas; const attrs = { alpha: true, premultipliedAlpha: false, antialias: true }; this.gl = canvas.getContext("webgl", attrs) || canvas.getContext("experimental-webgl", attrs); if (!this.gl) { throw new Error("WebGL is not supported in this browser."); } const gl = this.gl; gl.enable(gl.BLEND); gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); gl.disable(gl.DEPTH_TEST); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); this.defaultShader = new Shader(Shader.DEFAULT_VERT, Shader.DEFAULT_FRAG); this.screenCopyShader = new Shader(Shader.SCREEN_VERT, Shader.SCREEN_COPY_FRAG); this.textures = new WeakMap(); this.positionBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.positionBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, 0.5 ]), gl.STATIC_DRAW); this.texCoordBuffer = gl.createBuffer(); // Fullscreen NDC quad (triangle strip) + UVs (v=0 at bottom, matches FBO sampling). this.screenPositionBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.screenPositionBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ -1, -1, 1, -1, -1, 1, 1, 1 ]), gl.STATIC_DRAW); this.screenTexCoordBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.screenTexCoordBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ 0, 0, 1, 0, 0, 1, 1, 1 ]), gl.STATIC_DRAW); // [0] = scene (stable during post), [1]/[2] = ping-pong for effect passes. this.framebuffers = [null, null, null]; this.colorTextures = [null, null, null]; this._offscreenIndex = 0; this._lastWidth = 0; this._lastHeight = 0; this.setSize(canvas.width, canvas.height); } setSize (width, height) { const gl = this.gl; width = Math.max(1, width | 0); height = Math.max(1, height | 0); if (width !== this._lastWidth || height !== this._lastHeight) { this._lastWidth = width; this._lastHeight = height; gl.viewport(0, 0, width, height); this._rebuildFramebuffers(width, height); } } _destroyFramebuffers () { const gl = this.gl; for (let i = 0; i < this.framebuffers.length; i++) { if (this.framebuffers[i]) { gl.deleteFramebuffer(this.framebuffers[i]); this.framebuffers[i] = null; } if (this.colorTextures[i]) { gl.deleteTexture(this.colorTextures[i]); this.colorTextures[i] = null; } } } _rebuildFramebuffers (width, height) { const gl = this.gl; this._destroyFramebuffers(); for (let i = 0; i < 3; i++) { const texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); const fb = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, fb); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER); if (status !== gl.FRAMEBUFFER_COMPLETE) { console.error("Framebuffer incomplete:", status); } this.framebuffers[i] = fb; this.colorTextures[i] = texture; } gl.bindFramebuffer(gl.FRAMEBUFFER, null); gl.bindTexture(gl.TEXTURE_2D, null); } clear (r, g, b, a = 1) { const gl = this.gl; gl.clearColor(r / 255, g / 255, b / 255, a); gl.clear(gl.COLOR_BUFFER_BIT); } clearTransparent () { const gl = this.gl; gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT); } beginOffscreenPass () { const gl = this.gl; this._offscreenIndex = 0; gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffers[0]); gl.viewport(0, 0, this._lastWidth, this._lastHeight); gl.enable(gl.BLEND); gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); } endOffscreenPass () { const gl = this.gl; gl.bindFramebuffer(gl.FRAMEBUFFER, null); } /** * @param {Array} passes * @param {Object} builtins * @param {{ toCanvas?: boolean }} options - toCanvas true writes the last pass to the canvas. * @returns {WebGLTexture|null} final color texture when not drawing to canvas */ applyPostShaders (passes, builtins = {}, options = {}) { if (!passes || !passes.length) { return this.colorTextures[0]; } const gl = this.gl; const toCanvas = !!options.toCanvas; const sceneTexture = this.colorTextures[0]; let read = 0; gl.disable(gl.BLEND); for (let i = 0; i < passes.length; i++) { const pass = passes[i]; const isLast = i === passes.length - 1; // Never overwrite the scene buffer (index 0); ping-pong on 1/2. let write = 1; if (read === 1) { write = 2; } else if (read === 2) { write = 1; } if (isLast && toCanvas) { gl.bindFramebuffer(gl.FRAMEBUFFER, null); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffers[write]); } gl.viewport(0, 0, this._lastWidth, this._lastHeight); gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT); const uniforms = Object.assign({}, builtins, pass.uniforms || {}); this.drawFullscreen(pass.shader, this.colorTextures[read], uniforms, sceneTexture); if (!isLast || !toCanvas) { read = write; } } this._offscreenIndex = read; gl.enable(gl.BLEND); gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); gl.bindFramebuffer(gl.FRAMEBUFFER, null); return toCanvas ? null : this.colorTextures[read]; } blitToCanvas (texture, composite = "alpha") { if (!texture) { return; } const gl = this.gl; gl.bindFramebuffer(gl.FRAMEBUFFER, null); gl.viewport(0, 0, this._lastWidth, this._lastHeight); gl.enable(gl.BLEND); if (composite === "add") { gl.blendFunc(gl.ONE, gl.ONE); } else { gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); } this.drawFullscreen(this.screenCopyShader, texture, null, null); gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); } drawFullscreen (shader, texture, uniforms, sceneTexture) { const gl = this.gl; const info = shader.getProgramInfo(gl); if (!info || !texture) { return; } gl.useProgram(info.program); gl.bindBuffer(gl.ARRAY_BUFFER, this.screenPositionBuffer); if (info.attribs.position >= 0) { gl.enableVertexAttribArray(info.attribs.position); gl.vertexAttribPointer(info.attribs.position, 2, gl.FLOAT, false, 0, 0); } gl.bindBuffer(gl.ARRAY_BUFFER, this.screenTexCoordBuffer); if (info.attribs.texCoord >= 0) { gl.enableVertexAttribArray(info.attribs.texCoord); gl.vertexAttribPointer(info.attribs.texCoord, 2, gl.FLOAT, false, 0, 0); } gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, texture); this._setUniform(info, "u_texture", 0); this._setUniform(info, "u_alpha", 1); if (sceneTexture && info.uniforms.u_scene) { gl.activeTexture(gl.TEXTURE1); gl.bindTexture(gl.TEXTURE_2D, sceneTexture); this._setUniform(info, "u_scene", 1); } if (uniforms) { for (const name in uniforms) { if (!Object.prototype.hasOwnProperty.call(uniforms, name)) { continue; } this._setUniform(info, name, uniforms[name]); } } gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); } getTexture (htmlImage) { if (!htmlImage) { return null; } let texture = this.textures.get(htmlImage); if (texture) { return texture; } const gl = this.gl; texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, htmlImage); this.textures.set(htmlImage, texture); return texture; } drawSprite (options) { const gl = this.gl; const width = this._lastWidth; const height = this._lastHeight; if (width <= 0 || height <= 0) { return; } const shader = options.shader || this.defaultShader; const info = shader.getProgramInfo(gl); if (!info) { return; } const texture = options.texture; if (!texture) { return; } gl.useProgram(info.program); gl.bindBuffer(gl.ARRAY_BUFFER, this.positionBuffer); if (info.attribs.position >= 0) { gl.enableVertexAttribArray(info.attribs.position); gl.vertexAttribPointer(info.attribs.position, 2, gl.FLOAT, false, 0, 0); } const uv = options.uvRect || { u0: 0, v0: 0, u1: 1, v1: 1 }; gl.bindBuffer(gl.ARRAY_BUFFER, this.texCoordBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ uv.u0, uv.v0, uv.u1, uv.v0, uv.u0, uv.v1, uv.u1, uv.v1 ]), gl.DYNAMIC_DRAW); if (info.attribs.texCoord >= 0) { gl.enableVertexAttribArray(info.attribs.texCoord); gl.vertexAttribPointer(info.attribs.texCoord, 2, gl.FLOAT, false, 0, 0); } const matrix = GLContext._buildSpriteMatrix( options.x, options.y, options.w, options.h, options.rotationDeg || 0, options.mirrorX, options.mirrorY, width, height ); this._setUniform(info, "u_matrix", matrix); this._setUniform(info, "u_alpha", options.alpha == null ? 1 : options.alpha); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, texture); this._setUniform(info, "u_texture", 0); if (options.uniforms) { for (const name in options.uniforms) { if (!Object.prototype.hasOwnProperty.call(options.uniforms, name)) { continue; } this._setUniform(info, name, options.uniforms[name]); } } gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); } _setUniform (info, name, value) { const entry = info.uniforms[name]; if (!entry || entry.location == null) { return; } const gl = this.gl; const loc = entry.location; if (typeof value === "number") { if (entry.type === gl.INT || entry.type === gl.SAMPLER_2D) { gl.uniform1i(loc, value); } else { gl.uniform1f(loc, value); } return; } if (value instanceof Float32Array) { if (value.length === 16) { gl.uniformMatrix4fv(loc, false, value); } else if (value.length === 9) { gl.uniformMatrix3fv(loc, false, value); } else if (value.length === 4) { gl.uniform4fv(loc, value); } else if (value.length === 3) { gl.uniform3fv(loc, value); } else if (value.length === 2) { gl.uniform2fv(loc, value); } return; } if (Array.isArray(value)) { if (value.length === 4) { gl.uniform4fv(loc, value); } else if (value.length === 3) { gl.uniform3fv(loc, value); } else if (value.length === 2) { gl.uniform2fv(loc, value); } else if (value.length === 1) { gl.uniform1f(loc, value[0]); } } } // Column-major mat4: projection (canvas Y-down) * T * R * S static _buildSpriteMatrix (x, y, w, h, rotationDeg, mirrorX, mirrorY, canvasW, canvasH) { const sx = (mirrorX ? -1 : 1) * w; const sy = (mirrorY ? -1 : 1) * h; const rad = rotationDeg * Math.PI / 180; const c = Math.cos(rad); const s = Math.sin(rad); // Model maps unit quad [-0.5,0.5] into pixel space. const m00 = c * sx; const m01 = -s * sy; const m10 = s * sx; const m11 = c * sy; const m30 = x; const m31 = y; const pr0 = 2 / canvasW; const pr5 = -2 / canvasH; const pr12 = -1; const pr13 = 1; // P * M (only 2D affine terms matter) return new Float32Array([ pr0 * m00, pr5 * m10, 0, 0, pr0 * m01, pr5 * m11, 0, 0, 0, 0, -1, 0, pr0 * m30 + pr12, pr5 * m31 + pr13, 0, 1 ]); } }