class GLRenderer { constructor (canvas, vertexShaderSource = "default_vert", fragmentShaderSource = "default_frag") { this.canvas = canvas; this.gl = canvas.getContext('webgl'); if (!this.gl) { console.error('WebGL not supported, falling back on experimental-webgl'); this.gl = canvas.getContext('experimental-webgl'); } if (!this.gl) { throw new Error('Your browser does not support WebGL'); } this.program = null; this.positionLocation = null; this.texCoordLocation = null; this.matrixLocation = null; this.uniformLocations = {}; // Create buffers for vertex positions and texture coordinates this.positionBuffer = this.gl.createBuffer(); this.texCoordBuffer = this.gl.createBuffer(); // Default vertices for a quad this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.positionBuffer); const positions = [ -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, 0.5, ]; this.gl.bufferData(this.gl.ARRAY_BUFFER, new Float32Array(positions), this.gl.STATIC_DRAW); // Default texture coordinates this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.texCoordBuffer); const texCoords = [ 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, ]; this.gl.bufferData(this.gl.ARRAY_BUFFER, new Float32Array(texCoords), this.gl.STATIC_DRAW); // Asynchronously load shaders this.initShaders(vertexShaderSource, fragmentShaderSource); } async initShaders (vertexShaderSource, fragmentShaderSource) { // Once shaders are loaded, compile them and create the program this.program = this.createProgram(game_shaders[vertexShaderSource], game_shaders[fragmentShaderSource]); const numUniforms = this.gl.getProgramParameter(this.program, this.gl.ACTIVE_UNIFORMS); for (let i = 0; i < numUniforms; i++) { const uniformInfo = this.gl.getActiveUniform(this.program, i); if (uniformInfo) { const { name } = uniformInfo; const location = this.gl.getUniformLocation(this.program, name); if (location) { this.uniformLocations[name] = location; } } } // Get the locations of attributes and uniforms after the program is created this.positionLocation = this.gl.getAttribLocation(this.program, 'a_position'); this.texCoordLocation = this.gl.getAttribLocation(this.program, 'a_texCoord'); this.matrixLocation = this.gl.getUniformLocation(this.program, 'u_matrix'); } createShader (type, source) { const shader = this.gl.createShader(type); this.gl.shaderSource(shader, source); this.gl.compileShader(shader); if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { console.error('An error occurred compiling the shaders:', this.gl.getShaderInfoLog(shader)); this.gl.deleteShader(shader); return null; } return shader; } createProgram (vertexShaderSource, fragmentShaderSource) { const vertexShader = this.createShader(this.gl.VERTEX_SHADER, vertexShaderSource); const fragmentShader = this.createShader(this.gl.FRAGMENT_SHADER, fragmentShaderSource); const program = this.gl.createProgram(); this.gl.attachShader(program, vertexShader); this.gl.attachShader(program, fragmentShader); this.gl.linkProgram(program); if (!this.gl.getProgramParameter(program, this.gl.LINK_STATUS)) { console.error('Unable to initialize the shader program:', this.gl.getProgramInfoLog(program)); this.gl.deleteProgram(program); return null; } return program; } loadTexture (image) { const texture = this.gl.createTexture(); this.gl.bindTexture(this.gl.TEXTURE_2D, texture); this.gl.texImage2D(this.gl.TEXTURE_2D, 0, this.gl.RGBA, this.gl.RGBA, this.gl.UNSIGNED_BYTE, image); this.gl.generateMipmap(this.gl.TEXTURE_2D); return texture; } bindTexture (texture, unit) { this.gl.activeTexture(unit); this.gl.bindTexture(this.gl.TEXTURE_2D, texture); } setUniform (name, value) { const location = this.uniformLocations[name]; if (location !== undefined) { if (value instanceof Float32Array) { this.gl.uniformMatrix4fv(location, false, value); } else if (typeof value === 'number') { this.gl.uniform1f(location, value); } else if (Array.isArray(value)) { if (value.length === 2) { this.gl.uniform2fv(location, value); } else if (value.length === 3) { this.gl.uniform3fv(location, value); } else if (value.length === 4) { this.gl.uniform4fv(location, value); } } else if (value.unit) { // This is for textures, so we use a specific uniform location for texture unit this.gl.uniform1i(location, value.unit); } } else { console.warn(`Uniform location for ${name} not found`); } } render (texture, position, scale, angle, canvasWidth, canvasHeight, uniforms = {}) { if (!this.program) { console.warn('Shaders not initialized yet.'); return; } this.gl.clear(this.gl.COLOR_BUFFER_BIT); this.gl.useProgram(this.program); // Convert from world coordinates to WebGL normalized device coordinates const normalizedPositionX = (position.x / canvasWidth) * 2 - 1; const normalizedPositionY = 1 - (position.y / canvasHeight) * 2; // Flip Y-axis // Bind buffers for vertices and texture coordinates this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.positionBuffer); this.gl.enableVertexAttribArray(this.positionLocation); this.gl.vertexAttribPointer(this.positionLocation, 2, this.gl.FLOAT, false, 0, 0); this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.texCoordBuffer); this.gl.enableVertexAttribArray(this.texCoordLocation); this.gl.vertexAttribPointer(this.texCoordLocation, 2, this.gl.FLOAT, false, 0, 0); // Set the transformation matrix (using normalized position) const matrix = this.createTransformationMatrix( { x: normalizedPositionX, y: normalizedPositionY }, scale, angle ); this.setUniform('u_matrix', matrix); // Bind the texture if (texture) { this.bindTexture(texture, this.gl.TEXTURE0); this.setUniform('u_texture', { unit: 0 }); } // Set any additional uniforms Object.entries(uniforms).forEach(([name, value]) => { this.setUniform(name, value); }); // Draw the sprite this.gl.drawArrays(this.gl.TRIANGLE_STRIP, 0, 4); } createTransformationMatrix (position, scale, angle) { const rad = angle * Math.PI / 180; const cos = Math.cos(rad); const sin = Math.sin(rad); // Apply rotation, scaling, and translation const matrix = new Float32Array([ cos * scale.x, -sin * scale.y, 0, 0, sin * scale.x, cos * scale.y, 0, 0, 0, 0, 1, 0, position.x, position.y, 0, 1 ]); return matrix; } }