class GLContext { static MAX_LIGHTS = 16; constructor (canvas) { this.canvas = canvas; // 2D sprites do not benefit from MSAA; disabling avoids extra GPU cost. const attrs = { alpha: true, premultipliedAlpha: false, antialias: false }; 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(); // Defaults for getTexture uploads. Games can switch to NEAREST for pixel art. this.textureMinFilter = gl.LINEAR; this.textureMagFilter = gl.LINEAR; // Reused per-sprite uploads (avoid allocating Float32Array every draw). this._uvData = new Float32Array(8); this._matrixData = new Float32Array(16); 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(); gl.bindBuffer(gl.ARRAY_BUFFER, this.texCoordBuffer); gl.bufferData(gl.ARRAY_BUFFER, this._uvData, gl.DYNAMIC_DRAW); // 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] = full-res ping-pong, // [3]/[4] = half-res ping-pong for pass.scale < 1 blur. this.framebuffers = [null, null, null, null, null]; this.colorTextures = [null, null, null, null, null]; this._offscreenIndex = 0; this._lastWidth = 0; this._lastHeight = 0; this._halfWidth = 0; this._halfHeight = 0; this._postUniforms = {}; this._resUniform = [0, 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; this._halfWidth = Math.max(1, width >> 1); this._halfHeight = Math.max(1, height >> 1); 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(); this._halfWidth = Math.max(1, width >> 1); this._halfHeight = Math.max(1, height >> 1); for (let i = 0; i < 5; i++) { const texW = i < 3 ? width : this._halfWidth; const texH = i < 3 ? height : this._halfHeight; 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, texW, texH, 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; let readIsHalf = false; gl.disable(gl.BLEND); for (let i = 0; i < passes.length; i++) { const pass = passes[i]; const isLast = i === passes.length - 1; const wantHalf = pass.scale != null && pass.scale < 1; let write; let writeW; let writeH; if (wantHalf) { // Half-res ping-pong on indices 3/4. if (readIsHalf) { write = (read === 3) ? 4 : 3; } else { write = 3; } writeW = this._halfWidth; writeH = this._halfHeight; } else { // Full-res ping-pong on 1/2 (never overwrite scene buffer 0). // When leaving half-res, read half texture into a full write target. if (read === 1) { write = 2; } else if (read === 2) { write = 1; } else { write = 1; } writeW = this._lastWidth; writeH = this._lastHeight; } if (isLast && toCanvas) { gl.bindFramebuffer(gl.FRAMEBUFFER, null); writeW = this._lastWidth; writeH = this._lastHeight; } else { gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffers[write]); } gl.viewport(0, 0, writeW, writeH); gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT); const uniforms = this._postUniforms; for (const key in uniforms) { if (Object.prototype.hasOwnProperty.call(uniforms, key)) { delete uniforms[key]; } } if (builtins) { for (const key in builtins) { if (Object.prototype.hasOwnProperty.call(builtins, key)) { uniforms[key] = builtins[key]; } } } const passUniforms = pass.uniforms; if (passUniforms) { for (const key in passUniforms) { if (Object.prototype.hasOwnProperty.call(passUniforms, key)) { uniforms[key] = passUniforms[key]; } } } this._resUniform[0] = writeW; this._resUniform[1] = writeH; uniforms.u_resolution = this._resUniform; this.drawFullscreen(pass.shader, this.colorTextures[read], uniforms, sceneTexture); if (!isLast || !toCanvas) { read = write; readIsHalf = wantHalf && !(isLast && toCanvas); } } 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); } /** * Default min/mag filter applied when creating textures in {@link getTexture}. * Does not rewrite textures that were already uploaded. */ setDefaultTextureFilter (minFilter, magFilter) { const gl = this.gl; this.textureMinFilter = minFilter ?? gl.LINEAR; this.textureMagFilter = magFilter ?? gl.LINEAR; } 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, this.textureMinFilter); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, this.textureMagFilter); 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 }; const uvData = this._uvData; uvData[0] = uv.u0; uvData[1] = uv.v0; uvData[2] = uv.u1; uvData[3] = uv.v0; uvData[4] = uv.u0; uvData[5] = uv.v1; uvData[6] = uv.u1; uvData[7] = uv.v1; gl.bindBuffer(gl.ARRAY_BUFFER, this.texCoordBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, uvData); 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._matrixData ); this._setUniform(info, "u_matrix", matrix); this._setUniform(info, "u_alpha", options.alpha == null ? 1 : options.alpha); this._setUniform(info, "u_worldCenter", [options.x, options.y]); this._setUniform(info, "u_worldSize", [options.w, options.h]); this._setUniform(info, "u_rotationRad", (options.rotationDeg || 0) * Math.PI / 180); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, texture); this._setUniform(info, "u_texture", 0); let nextUnit = 1; if (options.textures) { for (const name in options.textures) { if (!Object.prototype.hasOwnProperty.call(options.textures, name)) { continue; } const extra = options.textures[name]; if (!extra) { continue; } gl.activeTexture(gl.TEXTURE0 + nextUnit); gl.bindTexture(gl.TEXTURE_2D, extra); this._setUniform(info, name, nextUnit); nextUnit++; } } if (options.lights) { this._setLights(info, options.lights); } else if (info.uniforms.u_lightCount) { this._setUniform(info, "u_lightCount", 0); } // Sensible bump defaults when the shader asks for them. if (info.uniforms.u_ambient && (!options.uniforms || options.uniforms.u_ambient == null)) { this._setUniform(info, "u_ambient", 0.35); } if (info.uniforms.u_specular && (!options.uniforms || options.uniforms.u_specular == null)) { this._setUniform(info, "u_specular", 0.25); } if (info.uniforms.u_bumpMode && (!options.uniforms || options.uniforms.u_bumpMode == null)) { this._setUniform(info, "u_bumpMode", 1); } 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); } _setLights (info, lights) { const gl = this.gl; const max = GLContext.MAX_LIGHTS; const count = Math.max(0, Math.min(lights.length, max)); this._setUniform(info, "u_lightCount", count); const posEntry = info.uniforms["u_lightPos[0]"] || info.uniforms.u_lightPos; const colEntry = info.uniforms["u_lightColor[0]"] || info.uniforms.u_lightColor; if (!posEntry || !colEntry || count === 0) { if (count === 0) { this._setUniform(info, "u_lightCount", 0); } return; } const pos = new Float32Array(max * 2); const col = new Float32Array(max * 3); for (let i = 0; i < count; i++) { const light = lights[i] || {}; pos[i * 2] = light.x != null ? light.x : (light.position ? light.position.x : 0); pos[i * 2 + 1] = light.y != null ? light.y : (light.position ? light.position.y : 0); const c = light.color != null ? light.color : [1, 1, 1]; if (Array.isArray(c)) { col[i * 3] = c[0] != null ? c[0] : 0; col[i * 3 + 1] = c[1] != null ? c[1] : 0; col[i * 3 + 2] = c[2] != null ? c[2] : 0; } else { col[i * 3] = (c.r != null ? c.r : 1); col[i * 3 + 1] = (c.g != null ? c.g : 1); col[i * 3 + 2] = (c.b != null ? c.b : 1); } // Allow 0–255 style colors. if (col[i * 3] > 1 || col[i * 3 + 1] > 1 || col[i * 3 + 2] > 1) { col[i * 3] /= 255; col[i * 3 + 1] /= 255; col[i * 3 + 2] /= 255; } } gl.uniform2fv(posEntry.location, pos); gl.uniform3fv(colEntry.location, col); } _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, out) { 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; const matrix = out || new Float32Array(16); // P * M (only 2D affine terms matter) matrix[0] = pr0 * m00; matrix[1] = pr5 * m10; matrix[2] = 0; matrix[3] = 0; matrix[4] = pr0 * m01; matrix[5] = pr5 * m11; matrix[6] = 0; matrix[7] = 0; matrix[8] = 0; matrix[9] = 0; matrix[10] = -1; matrix[11] = 0; matrix[12] = pr0 * m30 + pr12; matrix[13] = pr5 * m31 + pr13; matrix[14] = 0; matrix[15] = 1; return matrix; } }