UNPKG

@utsp/render

Version:

UTSP Render - Browser-based rendering engine for terminal graphics

105 lines (90 loc) 58.1 kB
var Y=Object.defineProperty;var $=(T,t,e)=>t in T?Y(T,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):T[t]=e;var E=(T,t)=>Y(T,"name",{value:t,configurable:!0});var a=(T,t,e)=>($(T,typeof t!="symbol"?t+"":t,e),e);var F=["#000000","#800000","#008000","#808000","#000080","#800080","#008080","#c0c0c0","#808080","#ff0000","#00ff00","#ffff00","#0000ff","#ff00ff","#00ffff","#ffffff","#080808","#121212","#1c1c1c","#262626","#303030","#3a3a3a","#444444","#4e4e4e","#585858","#626262","#6c6c6c","#767676","#808080","#8a8a8a","#949494","#9e9e9e","#a80000","#00a800","#a8a800","#0000a8","#a800a8","#00a8a8","#a8a8a8","#545454","#fc5454","#54fc54","#fcfc54","#5454fc","#fc54fc","#54fcfc","#fcfcfc","#000000",...Array(192).fill("#808080")];function N(T,t=F){return T<0||T>=t.length?"#ff00ff":t[T]}E(N,"paletteIndexToColor");function k(T,t=F){let e=t.indexOf(T.toLowerCase());return e>=0?e:0}E(k,"colorToPaletteIndex");var D=class D{constructor(t,e){a(this,"canvas");a(this,"ctx");a(this,"container");a(this,"cols",0);a(this,"rows",0);a(this,"cellWidth",0);a(this,"cellHeight",0);a(this,"offsetX",0);a(this,"offsetY",0);a(this,"strokeColor","rgba(80, 80, 80, 0.4)");a(this,"lineWidth",1);a(this,"innerPadding",1);this.container=t,this.canvas=document.createElement("canvas"),this.canvas.className="grid-overlay-canvas";let i=e?.zIndex??10;this.canvas.style.cssText=` position: absolute !important; top: 0 !important; left: 0 !important; width: 100% !important; height: 100% !important; object-fit: contain !important; z-index: ${i} !important; pointer-events: none !important; image-rendering: pixelated !important; image-rendering: crisp-edges !important; `,this.container.appendChild(this.canvas);let r=this.canvas.getContext("2d");if(!r)throw new Error("[GridOverlay] Impossible de cr\xE9er le contexte 2D");this.ctx=r,e&&(e.strokeColor&&(this.strokeColor=e.strokeColor),e.lineWidth!==void 0&&(this.lineWidth=e.lineWidth),e.innerPadding!==void 0&&(this.innerPadding=e.innerPadding))}setDimensions(t,e,i,r,s=0,n=0){this.cols=t,this.rows=e,this.cellWidth=i,this.cellHeight=r,this.offsetX=s,this.offsetY=n}setCanvasSize(t,e){let i=window.devicePixelRatio||1;this.canvas.width=t*i,this.canvas.height=e*i,this.ctx.setTransform(1,0,0,1,0,0),this.ctx.scale(i,i)}setStyle(t){t.strokeColor&&(this.strokeColor=t.strokeColor),t.lineWidth!==void 0&&(this.lineWidth=t.lineWidth),t.innerPadding!==void 0&&(this.innerPadding=t.innerPadding)}render(){if(!this.ctx)return;this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.strokeStyle=this.strokeColor,this.ctx.lineWidth=this.lineWidth;let t=this.cols*this.cellWidth,e=this.rows*this.cellHeight;this.ctx.beginPath();for(let i=0;i<=this.cols;i++){let r=this.offsetX+i*this.cellWidth;if(i===0){let s=r+this.innerPadding+.5;this.ctx.moveTo(s,this.offsetY+this.innerPadding),this.ctx.lineTo(s,this.offsetY+e-this.innerPadding)}else if(i===this.cols){let s=r-this.innerPadding+.5;this.ctx.moveTo(s,this.offsetY+this.innerPadding),this.ctx.lineTo(s,this.offsetY+e-this.innerPadding)}else{let s=r+.5;this.ctx.moveTo(s,this.offsetY+this.innerPadding),this.ctx.lineTo(s,this.offsetY+e-this.innerPadding)}}for(let i=0;i<=this.rows;i++){let r=this.offsetY+i*this.cellHeight;if(i===0){let s=r+this.innerPadding+.5;this.ctx.moveTo(this.offsetX+this.innerPadding,s),this.ctx.lineTo(this.offsetX+t-this.innerPadding,s)}else if(i===this.rows){let s=r-this.innerPadding+.5;this.ctx.moveTo(this.offsetX+this.innerPadding,s),this.ctx.lineTo(this.offsetX+t-this.innerPadding,s)}else{let s=r+.5;this.ctx.moveTo(this.offsetX+this.innerPadding,s),this.ctx.lineTo(this.offsetX+t-this.innerPadding,s)}}this.ctx.stroke()}update(t,e,i,r,s,n,l=0,o=0){this.setDimensions(t,e,i,r,l,o),this.setCanvasSize(s,n),this.render()}setVisible(t){this.canvas.style.display=t?"block":"none"}destroy(){this.canvas.parentElement&&this.canvas.parentElement.removeChild(this.canvas)}getCanvas(){return this.canvas}};E(D,"GridOverlay");var y=D;var I=class I{constructor(t,e){a(this,"canvas");a(this,"gl");a(this,"parentElement");a(this,"containerDiv");a(this,"cols");a(this,"rows");a(this,"charWidth");a(this,"charHeight");a(this,"cellWidth",8);a(this,"cellHeight",8);a(this,"glyphOffsetX",0);a(this,"glyphOffsetY",0);a(this,"canvasBgColor");a(this,"showGrid");a(this,"supportsUint32Indices",!1);a(this,"useUint16Indices",!1);a(this,"gridOverlay");a(this,"bitmapFont");a(this,"atlasTexture",null);a(this,"atlasCanvas");a(this,"atlasColumns",0);a(this,"paletteTexture",null);a(this,"program",null);a(this,"positionBuffer",null);a(this,"texCoordBuffer",null);a(this,"colorIndexBuffer",null);a(this,"indexBuffer",null);a(this,"aPosition");a(this,"aTexCoord");a(this,"aColorIndex");a(this,"uResolution",null);a(this,"uTexture",null);a(this,"uPalette",null);a(this,"resizeObserver");a(this,"charCodeToAtlasIndex",new Uint16Array(65536).fill(65535));a(this,"atlasUVs",new Float32Array(0));a(this,"cachedAtlasWidth",0);a(this,"cachedAtlasHeight",0);a(this,"paletteFloat",new Float32Array(256*4));a(this,"maxCells",0);a(this,"renderPositions",new Float32Array(0));a(this,"renderTexCoords",new Float32Array(0));a(this,"renderColorIndices",new Float32Array(0));a(this,"renderIndices",new Uint32Array(0));a(this,"cachedResolution",[0,0]);a(this,"cachedTextureUnit",-1);a(this,"cachedPaletteUnit",-1);a(this,"cachedTextureUniform",!1);a(this,"cachedPaletteUniform",!1);a(this,"paletteHash",0);a(this,"staticPositionsInitialized",!1);a(this,"vaoExtension",null);a(this,"vao",null);a(this,"instancedExtension",null);a(this,"useInstancing",!1);a(this,"instanceDataBuffer",null);a(this,"instanceData",new Float32Array(0));a(this,"templateQuadPositions",new Float32Array(0));a(this,"templateQuadIndices",new Uint16Array(0));if(!t)throw new Error("TerminalGL: Parent element is required");if(!Number.isInteger(e.cols)||e.cols<=0)throw new Error(`TerminalGL: Invalid cols: ${e.cols}. Must be a positive integer.`);if(!Number.isInteger(e.rows)||e.rows<=0)throw new Error(`TerminalGL: Invalid rows: ${e.rows}. Must be a positive integer.`);let i=e.cols*e.rows,r=I.checkCompatibility();if(r.errors.length>0)throw new Error(`TerminalGL: WebGL incompatible - ${r.errors.join(", ")}`);let s=e.forceUint16??!1;if(s&&i>r.maxCellsUint16)throw new Error(`TerminalGL: Terminal size ${e.cols}\xD7${e.rows} (${i} cells) exceeds Uint16 limit of ${r.maxCellsUint16} cells. Maximum size with Uint16: ${Math.floor(Math.sqrt(r.maxCellsUint16))}\xD7${Math.floor(Math.sqrt(r.maxCellsUint16))} (or smaller rectangles like 127\xD764)`);if(!r.uint32Indices&&i>r.maxCellsUint16)throw new Error(`TerminalGL: Terminal size ${e.cols}\xD7${e.rows} (${i} cells) exceeds device limit of ${r.maxCellsUint16} cells (OES_element_index_uint not supported). Maximum size: ${Math.floor(Math.sqrt(r.maxCellsUint16))}\xD7${Math.floor(Math.sqrt(r.maxCellsUint16))}`);i>r.recommendedMaxCells&&console.warn(`[TerminalGL] \u26A0\uFE0F Large terminal size ${e.cols}\xD7${e.rows} (${i} cells) exceeds recommended limit of ${r.recommendedMaxCells} cells. Performance may be impacted.`),r.warnings.length>0&&console.warn("[TerminalGL] WebGL Compatibility Warnings:",r.warnings);let n=e.charWidth??8,l=e.charHeight??8;if(!Number.isFinite(n)||n<=0)throw new Error(`TerminalGL: Invalid charWidth: ${n}. Must be a positive number.`);if(!Number.isFinite(l)||l<=0)throw new Error(`TerminalGL: Invalid charHeight: ${l}. Must be a positive number.`);for(this.parentElement=t,this.cols=e.cols,this.rows=e.rows,this.charWidth=n,this.charHeight=l,this.canvasBgColor=e.canvasBgColor!==void 0?e.canvasBgColor:null,this.showGrid=e.showGrid??!1;this.parentElement.firstChild;)this.parentElement.removeChild(this.parentElement.firstChild);let o=window.getComputedStyle(this.parentElement).position;o!=="relative"&&o!=="absolute"&&o!=="fixed"&&(this.parentElement.style.position="relative"),this.containerDiv=document.createElement("div"),this.containerDiv.className="terminalgl-container",this.containerDiv.style.cssText=` position: absolute !important; top: 0 !important; left: 0 !important; width: 100% !important; height: 100% !important; overflow: hidden !important; `,this.canvas=document.createElement("canvas"),this.canvas.className="terminalgl-webgl-canvas",this.canvas.width=this.cols*this.cellWidth,this.canvas.height=this.rows*this.cellHeight,this.canvas.style.cssText=` position: absolute !important; top: 0 !important; left: 0 !important; image-rendering: pixelated !important; image-rendering: crisp-edges !important; object-fit: contain !important; `;let h=this.canvas.getContext("webgl",{alpha:this.canvasBgColor===null,premultipliedAlpha:!1});if(!h)throw new Error("TerminalGL: WebGL not supported");this.gl=h,this.supportsUint32Indices=!!h.getExtension("OES_element_index_uint"),this.useUint16Indices=s||!this.supportsUint32Indices,this.useUint16Indices?console.warn(`[TerminalGL] \u{1F4CA} Using Uint16 indices (max ${r.maxCellsUint16} cells)`):console.warn(`[TerminalGL] \u{1F4CA} Using Uint32 indices (max ${r.maxCellsUint32} cells)`),this.vaoExtension=h.getExtension("OES_vertex_array_object"),this.vaoExtension&&console.warn("[TerminalGL] \u2705 VAO extension enabled (faster attribute binding)"),this.instancedExtension=h.getExtension("ANGLE_instanced_arrays"),this.instancedExtension?(this.useInstancing=!0,console.warn("[TerminalGL] \u{1F680} Instanced rendering enabled (massive draw call reduction)")):console.warn("[TerminalGL] \u26A0\uFE0F Instanced rendering not available (fallback to standard rendering)"),this.containerDiv.appendChild(this.canvas),this.parentElement.appendChild(this.containerDiv),this.initRenderBuffers();try{this.initWebGL()}catch(c){throw console.error("[TerminalGL] \u274C Failed to initialize WebGL:",c),c}this.showGrid&&this.initGridOverlay(),this.setupResizeObserver()}static checkCompatibility(){let t={webgl1:!1,uint32Indices:!1,maxTextureSize:0,maxViewportDims:[0,0],maxCellsUint16:0,maxCellsUint32:0,recommendedMaxCells:0,warnings:[],errors:[]},e=document.createElement("canvas"),i=e.getContext("webgl")||e.getContext("experimental-webgl");if(!i||!(i instanceof WebGLRenderingContext))return t.errors.push("\u274C WebGL 1.0 not supported by this browser/device"),t;let r=i;t.webgl1=!0;try{t.maxTextureSize=r.getParameter(r.MAX_TEXTURE_SIZE);let o=r.getParameter(r.MAX_VIEWPORT_DIMS);t.maxViewportDims=[o[0],o[1]]}catch(o){return t.errors.push(`\u274C Failed to query WebGL parameters: ${o}`),t}let s=r.getExtension("OES_element_index_uint");t.uint32Indices=!!s;let n=8;if(t.maxCellsUint16=Math.floor(65535/n),t.uint32Indices){let o=Math.floor(t.maxTextureSize*t.maxTextureSize/64);t.maxCellsUint32=Math.min(o,262144)}else t.maxCellsUint32=t.maxCellsUint16,t.warnings.push(`\u26A0\uFE0F OES_element_index_uint not supported - limited to ${t.maxCellsUint16} cells (e.g., 90\xD790 or 127\xD764)`);return t.recommendedMaxCells=Math.floor((t.uint32Indices?t.maxCellsUint32:t.maxCellsUint16)*.8),t.maxTextureSize<256?t.errors.push(`\u274C MAX_TEXTURE_SIZE too small: ${t.maxTextureSize} (minimum 256 required for font atlas)`):t.maxTextureSize<2048&&t.warnings.push(`\u26A0\uFE0F Small MAX_TEXTURE_SIZE: ${t.maxTextureSize} (may limit font atlas)`),(t.maxViewportDims[0]<1024||t.maxViewportDims[1]<768)&&t.warnings.push(`\u26A0\uFE0F Small MAX_VIEWPORT_DIMS: ${t.maxViewportDims[0]}\xD7${t.maxViewportDims[1]}`),r.getExtension("WEBGL_lose_context")||t.warnings.push("\u26A0\uFE0F WEBGL_lose_context not supported - may cause memory leaks"),t}initInstancedBuffers(){let t=this.gl;this.templateQuadPositions=new Float32Array([0,0,this.cellWidth,0,0,this.cellHeight,this.cellWidth,this.cellHeight]),this.templateQuadIndices=new Uint16Array([0,1,2,2,1,3]),t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,this.templateQuadPositions,t.STATIC_DRAW),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,this.templateQuadIndices,t.STATIC_DRAW);let e=this.cols*this.rows*2;this.instanceData=new Float32Array(e*8),t.bindBuffer(t.ARRAY_BUFFER,this.instanceDataBuffer),t.bufferData(t.ARRAY_BUFFER,this.instanceData.byteLength,t.DYNAMIC_DRAW)}initRenderBuffers(){this.maxCells=this.cols*this.rows*2,this.renderPositions=new Float32Array(this.maxCells*4*2),this.renderTexCoords=new Float32Array(this.maxCells*4*2),this.renderColorIndices=new Float32Array(this.maxCells*4),this.useUint16Indices?this.renderIndices=new Uint16Array(this.maxCells*6):this.renderIndices=new Uint32Array(this.maxCells*6),this.staticPositionsInitialized=!1}precomputeStaticPositions(){let t=this.cellWidth,e=this.cellHeight,i=this.glyphOffsetX,r=this.glyphOffsetY,s=this.charWidth,n=this.charHeight,l=0,o=0,h=0;for(let d=0;d<this.rows;d++){let f=Math.round(d*e),g=Math.round(f+e);for(let u=0;u<this.cols;u++){let m=Math.round(u*t),p=Math.round(m+t);this.renderPositions[l++]=m,this.renderPositions[l++]=f,this.renderPositions[l++]=p,this.renderPositions[l++]=f,this.renderPositions[l++]=m,this.renderPositions[l++]=g,this.renderPositions[l++]=p,this.renderPositions[l++]=g,this.renderIndices[o++]=h,this.renderIndices[o++]=h+1,this.renderIndices[o++]=h+2,this.renderIndices[o++]=h+2,this.renderIndices[o++]=h+1,this.renderIndices[o++]=h+3,h+=4;let x=Math.round(m+i),A=Math.round(f+r),b=Math.round(x+s),C=Math.round(A+n);this.renderPositions[l++]=x,this.renderPositions[l++]=A,this.renderPositions[l++]=b,this.renderPositions[l++]=A,this.renderPositions[l++]=x,this.renderPositions[l++]=C,this.renderPositions[l++]=b,this.renderPositions[l++]=C,this.renderIndices[o++]=h,this.renderIndices[o++]=h+1,this.renderIndices[o++]=h+2,this.renderIndices[o++]=h+2,this.renderIndices[o++]=h+1,this.renderIndices[o++]=h+3,h+=4}}let c=this.gl;c.bindBuffer(c.ARRAY_BUFFER,this.positionBuffer),c.bufferSubData(c.ARRAY_BUFFER,0,this.renderPositions),c.bindBuffer(c.ELEMENT_ARRAY_BUFFER,this.indexBuffer),c.bufferSubData(c.ELEMENT_ARRAY_BUFFER,0,this.renderIndices),this.staticPositionsInitialized=!0}initWebGL(){let t=this.gl,e;this.useInstancing?e=` // Per-vertex attributes (template quad) attribute vec2 aPosition; // Local quad position (0,0 to cellW,cellH) // Per-instance attributes (different for each cell) attribute vec2 aInstanceOffset; // Cell grid position (col, row) attribute vec4 aInstanceUVs; // Atlas UVs (u1, v1, u2, v2) attribute vec2 aInstanceColors; // (bgColorIdx, fgColorIdx) uniform vec2 uResolution; uniform vec2 uCellSize; // (cellWidth, cellHeight) uniform sampler2D uPalette; varying vec2 vTexCoord; varying vec4 vColor; void main() { // Compute world position: instance offset + local quad position vec2 worldPos = aInstanceOffset * uCellSize + aPosition; vec2 clipSpace = (worldPos / uResolution) * 2.0 - 1.0; gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); // Interpolate UVs based on local position vec2 localUV = aPosition / uCellSize; // (0,0) to (1,1) vTexCoord = mix( aInstanceUVs.xy, // top-left (u1, v1) aInstanceUVs.zw, // bottom-right (u2, v2) localUV ); // Choose background or foreground color based on instance UVs // If instance UVs are all (0,0), it's a background quad float isBg = step(length(aInstanceUVs), 0.001); float colorIndex = mix(aInstanceColors.y, aInstanceColors.x, isBg); // Lookup color in palette float paletteU = (colorIndex + 0.5) / 256.0; vColor = texture2D(uPalette, vec2(paletteU, 0.5)); } `:e=` attribute vec2 aPosition; attribute vec2 aTexCoord; attribute float aColorIndex; // \u{1F680} Index dans palette (0-255) uniform vec2 uResolution; uniform sampler2D uPalette; // \u{1F680} Texture palette 256\xD71 RGBA varying vec2 vTexCoord; varying vec4 vColor; void main() { // Convert from pixels to clip space (-1 to 1) vec2 clipSpace = (aPosition / uResolution) * 2.0 - 1.0; gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); vTexCoord = aTexCoord; // \u{1F680} Lookup couleur dans la palette texture (GPU-side) float paletteU = (aColorIndex + 0.5) / 256.0; vColor = texture2D(uPalette, vec2(paletteU, 0.5)); } `;let i=` precision mediump float; uniform sampler2D uTexture; varying vec2 vTexCoord; varying vec4 vColor; void main() { // If texCoord is (0, 0), it's a background without texture if (vTexCoord.x == 0.0 && vTexCoord.y == 0.0) { gl_FragColor = vColor; } else { // Textured character: multiply color by texture alpha vec4 texColor = texture2D(uTexture, vTexCoord); gl_FragColor = vec4(vColor.rgb * texColor.a, texColor.a); } } `,r=this.compileShader(t.VERTEX_SHADER,e),s=this.compileShader(t.FRAGMENT_SHADER,i);if(!r||!s)throw new Error("Shader compilation error");let n=t.createProgram();if(!n)throw new Error("Unable to create WebGL program");if(t.attachShader(n,r),t.attachShader(n,s),t.linkProgram(n),!t.getProgramParameter(n,t.LINK_STATUS)){let l=t.getProgramInfoLog(n);throw new Error("Program linking error: "+l)}this.program=n,this.cachedTextureUniform=!1,this.cachedPaletteUniform=!1,this.aPosition=t.getAttribLocation(n,"aPosition"),this.useInstancing?(this.aTexCoord=t.getAttribLocation(n,"aInstanceOffset"),this.aColorIndex=t.getAttribLocation(n,"aInstanceUVs"),this.instanceDataBuffer=t.createBuffer()):(this.aTexCoord=t.getAttribLocation(n,"aTexCoord"),this.aColorIndex=t.getAttribLocation(n,"aColorIndex")),this.uResolution=t.getUniformLocation(n,"uResolution"),this.uTexture=t.getUniformLocation(n,"uTexture"),this.uPalette=t.getUniformLocation(n,"uPalette"),this.positionBuffer=t.createBuffer(),this.texCoordBuffer=t.createBuffer(),this.colorIndexBuffer=t.createBuffer(),this.indexBuffer=t.createBuffer(),t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,this.renderPositions.byteLength,t.DYNAMIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,this.renderTexCoords.byteLength,t.DYNAMIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,this.colorIndexBuffer),t.bufferData(t.ARRAY_BUFFER,this.renderColorIndices.byteLength,t.DYNAMIC_DRAW),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,this.renderIndices.byteLength,t.DYNAMIC_DRAW),this.vaoExtension&&(this.vao=this.vaoExtension.createVertexArrayOES(),this.vao&&(this.vaoExtension.bindVertexArrayOES(this.vao),t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.enableVertexAttribArray(this.aPosition),t.vertexAttribPointer(this.aPosition,2,t.FLOAT,!1,0,0),t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.enableVertexAttribArray(this.aTexCoord),t.vertexAttribPointer(this.aTexCoord,2,t.FLOAT,!1,0,0),t.bindBuffer(t.ARRAY_BUFFER,this.colorIndexBuffer),t.enableVertexAttribArray(this.aColorIndex),t.vertexAttribPointer(this.aColorIndex,1,t.FLOAT,!1,0,0),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),this.vaoExtension.bindVertexArrayOES(null))),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),t.viewport(0,0,this.canvas.width,this.canvas.height)}compileShader(t,e){let i=this.gl,r=i.createShader(t);return r?(i.shaderSource(r,e),i.compileShader(r),i.getShaderParameter(r,i.COMPILE_STATUS)?r:(console.error("Shader compilation error:",i.getShaderInfoLog(r)),i.deleteShader(r),null)):null}initGridOverlay(){this.gridOverlay=new y(this.containerDiv,{strokeColor:"rgba(144, 24, 24, 1)",lineWidth:1,innerPadding:1,zIndex:10}),this.updateGridOverlay()}updateGridOverlay(){if(!this.gridOverlay)return;let t=parseFloat(this.canvas.style.width)||this.cols*this.charWidth,e=parseFloat(this.canvas.style.height)||this.rows*this.charHeight,i=t/this.cols,r=e/this.rows;this.gridOverlay.update(this.cols,this.rows,i,r,t,e,0,0)}setBitmapFont(t,e,i,r,s){this.bitmapFont=t,this.charWidth=Math.round(e),this.charHeight=Math.round(i),this.cellWidth=Math.round(r),this.cellHeight=Math.round(s),this.glyphOffsetX=Math.round((this.cellWidth-this.charWidth)/2),this.glyphOffsetY=Math.round((this.cellHeight-this.charHeight)/2),this.useInstancing&&(console.warn("[TerminalGL] \u{1F680} Initializing instanced buffers..."),this.initInstancedBuffers());try{this.generateAtlas()}catch(n){throw console.error("[TerminalGL] \u274C Failed to generate atlas:",n),n}this.buildCharCodeMap(),this.precomputeAtlasUVs(),this.canvas.width=this.cols*this.cellWidth,this.canvas.height=this.rows*this.cellHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.useInstancing||this.precomputeStaticPositions(),this.showGrid&&this.gridOverlay&&this.updateGridOverlay()}generateAtlas(){if(!this.bitmapFont)return;let t=Array.from(this.bitmapFont.keys()).sort((o,h)=>o-h),e=t.length;this.atlasColumns=Math.ceil(Math.sqrt(e));let i=Math.ceil(e/this.atlasColumns),r=this.atlasColumns*this.charWidth,s=i*this.charHeight;this.atlasCanvas=document.createElement("canvas"),this.atlasCanvas.width=r,this.atlasCanvas.height=s;let n=this.atlasCanvas.getContext("2d");if(!n)throw new Error("Unable to create 2D context for atlas");n.clearRect(0,0,r,s),n.fillStyle="#ffffff";let l=0;for(let o of t){let h=this.bitmapFont.get(o);if(!h)continue;let c=l%this.atlasColumns,d=Math.floor(l/this.atlasColumns),f=c*this.charWidth,g=d*this.charHeight;for(let u=0;u<Math.min(h.length,this.charHeight);u++){let m=h[u];for(let p=0;p<this.charWidth;p++){let x=1<<7-p;m&x&&n.fillRect(f+p,g+u,1,1)}}l++}this.createAtlasTexture()}buildCharCodeMap(){if(!this.bitmapFont)return;this.charCodeToAtlasIndex.fill(65535);let t=Array.from(this.bitmapFont.keys()).sort((e,i)=>e-i);for(let e=0;e<t.length;e++)this.charCodeToAtlasIndex[t[e]]=e}precomputeAtlasUVs(){if(!this.bitmapFont)return;let t=this.bitmapFont.size;this.atlasUVs=new Float32Array(t*4),this.cachedAtlasWidth=this.atlasColumns*this.charWidth,this.cachedAtlasHeight=Math.ceil(t/this.atlasColumns)*this.charHeight;let e=this.cachedAtlasWidth,i=this.cachedAtlasHeight,r=.5/e,s=.5/i;for(let n=0;n<t;n++){let l=n%this.atlasColumns,o=Math.floor(n/this.atlasColumns),h=(l*this.charWidth+r)/e,c=(o*this.charHeight+s)/i,d=((l+1)*this.charWidth-r)/e,f=((o+1)*this.charHeight-s)/i,g=n*4;this.atlasUVs[g]=h,this.atlasUVs[g+1]=c,this.atlasUVs[g+2]=d,this.atlasUVs[g+3]=f}}createAtlasTexture(){if(this.atlasCanvas)try{let t=this.gl,e=t.createTexture();if(!e)throw new Error("Unable to create texture");t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.atlasCanvas),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),this.atlasTexture=e}catch(t){throw console.error("[TerminalGL] \u274C Failed to create atlas texture:",t),t}}clear(){let t=this.gl;t&&t.clear(t.COLOR_BUFFER_BIT)}parseColor(t){if(t.startsWith("#")){let e=t.slice(1),i=0,r=0,s=0;return e.length===3?(i=parseInt(e[0]+e[0],16),r=parseInt(e[1]+e[1],16),s=parseInt(e[2]+e[2],16)):e.length===6&&(i=parseInt(e.slice(0,2),16),r=parseInt(e.slice(2,4),16),s=parseInt(e.slice(4,6),16)),[i/255,r/255,s/255,1]}if(t.startsWith("rgb")){let e=t.match(/rgba?\(([^)]+)\)/);if(e){let i=e[1].split(",").map(r=>parseFloat(r.trim()));return[i[0]/255,i[1]/255,i[2]/255,i[3]!==void 0?i[3]:1]}}return[1,1,1,1]}setupResizeObserver(){if(!(typeof ResizeObserver>"u"))try{this.resizeObserver=new ResizeObserver(()=>{try{this.updateCanvasSize()}catch(t){console.error("[TerminalGL] \u274C Error in resize callback:",t)}}),this.resizeObserver.observe(this.parentElement),this.updateCanvasSize()}catch(t){console.error("[TerminalGL] \u274C Failed to setup ResizeObserver:",t)}}updateCanvasSize(){let t=this.parentElement.clientWidth,e=this.parentElement.clientHeight;if(t===0||e===0)return;let i=Math.floor(t/this.cellWidth),r=Math.floor(e/this.cellHeight),s=i/this.cols,n=r/this.rows,l=Math.min(s,n),o=Math.max(1,Math.floor(l)),h=this.cols*this.cellWidth*o,c=this.rows*this.cellHeight*o;this.canvas.style.width=`${h}px`,this.canvas.style.height=`${c}px`,this.showGrid&&this.gridOverlay&&this.updateGridOverlay()}setPalette(t){let e=0;for(let i=0;i<Math.min(t.length,256);i++){let r=t[i];e=(e<<5)-e+r.r,e=(e<<5)-e+r.g,e=(e<<5)-e+r.b,e=(e<<5)-e+r.a,e=e|0}if(e!==this.paletteHash){this.paletteHash=e;for(let i=0;i<t.length&&i<256;i++){let r=t[i],s=i*4;this.paletteFloat[s]=r.r/255,this.paletteFloat[s+1]=r.g/255,this.paletteFloat[s+2]=r.b/255,this.paletteFloat[s+3]=r.a/255}this.updatePaletteTexture()}}updatePaletteTexture(){try{let t=this.gl;this.paletteTexture||(this.paletteTexture=t.createTexture()),t.bindTexture(t.TEXTURE_2D,this.paletteTexture);let e=new Uint8Array(256*4);for(let i=0;i<256;i++){let r=i*4;e[r]=this.paletteFloat[r]*255,e[r+1]=this.paletteFloat[r+1]*255,e[r+2]=this.paletteFloat[r+2]*255,e[r+3]=this.paletteFloat[r+3]*255}t.texImage2D(t.TEXTURE_2D,0,t.RGBA,256,1,0,t.RGBA,t.UNSIGNED_BYTE,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.bindTexture(t.TEXTURE_2D,null)}catch(t){throw console.error("[TerminalGL] \u274C Failed to update palette texture:",t),t}}renderDisplayData(t){try{if(!this.isReady()){console.warn("[TerminalGL] \u26A0\uFE0F Not ready: font not loaded yet");return}(t.width!==this.cols||t.height!==this.rows)&&this.resize(t.width,t.height),this.renderDirect(t)}catch(e){console.error("[TerminalGL] \u274C Error rendering display data:",e)}}renderDirect(t){let e=this.gl;if(!this.staticPositionsInitialized&&!this.useInstancing&&this.precomputeStaticPositions(),this.canvasBgColor!==null){let i=this.parseColor(this.canvasBgColor);e.clearColor(i[0],i[1],i[2],i[3])}else e.clearColor(0,0,0,0);e.clear(e.COLOR_BUFFER_BIT),this.useInstancing?this.renderInstanced(t):this.renderDirectBuffers(t)}renderInstanced(t){let e=this.gl,i=this.instancedExtension;if(!this.instanceData||this.instanceData.length===0){console.warn("[TerminalGL] \u26A0\uFE0F Instance data not initialized, falling back to standard rendering"),this.useInstancing=!1,this.renderDirectBuffers(t);return}let r=t.width*t.height;if(this.useUint16Indices&&r>8191){console.warn(`[TerminalGL] \u26A0\uFE0F Terminal too large for instanced rendering with Uint16 (${r} cells > 8191). Falling back to standard rendering.`),this.useInstancing=!1,this.renderDirectBuffers(t);return}let s=0,n=this.instanceData.length/8;for(let f=0;f<t.height;f++)for(let g=0;g<t.width;g++){let u=t.cells[f*t.width+g],m=u.bgColorIndex,p=u.fgColorIndex,x=this.canvasBgColor!==null&&m===255,A=u.char===" "||p===255;if(!x){if(s>=n){console.error(`[TerminalGL] \u274C Instance buffer overflow! instanceIdx=${s}, max=${n}`);break}let b=s*8;this.instanceData[b]=g,this.instanceData[b+1]=f,this.instanceData[b+2]=0,this.instanceData[b+3]=0,this.instanceData[b+4]=0,this.instanceData[b+5]=0,this.instanceData[b+6]=m,this.instanceData[b+7]=0,s++}if(!A){let b=u.char.charCodeAt(0),C=this.charCodeToAtlasIndex[b];if(C!==65535){if(s>=n){console.error(`[TerminalGL] \u274C Instance buffer overflow! instanceIdx=${s}, max=${n}`);break}let R=C*4,v=s*8;this.instanceData[v]=g,this.instanceData[v+1]=f,this.instanceData[v+2]=this.atlasUVs[R],this.instanceData[v+3]=this.atlasUVs[R+1],this.instanceData[v+4]=this.atlasUVs[R+2],this.instanceData[v+5]=this.atlasUVs[R+3],this.instanceData[v+6]=0,this.instanceData[v+7]=p,s++}}}if(s===0){console.warn("[TerminalGL] \u26A0\uFE0F No instances to draw (all cells skipped)");return}e.bindBuffer(e.ARRAY_BUFFER,this.instanceDataBuffer),e.bufferSubData(e.ARRAY_BUFFER,0,this.instanceData.subarray(0,s*8)),e.useProgram(this.program),e.bindBuffer(e.ARRAY_BUFFER,this.positionBuffer),e.enableVertexAttribArray(this.aPosition),e.vertexAttribPointer(this.aPosition,2,e.FLOAT,!1,0,0),i.vertexAttribDivisorANGLE(this.aPosition,0),e.bindBuffer(e.ARRAY_BUFFER,this.instanceDataBuffer);let l=8*Float32Array.BYTES_PER_ELEMENT,o=e.getAttribLocation(this.program,"aInstanceOffset");e.enableVertexAttribArray(o),e.vertexAttribPointer(o,2,e.FLOAT,!1,l,0),i.vertexAttribDivisorANGLE(o,1);let h=e.getAttribLocation(this.program,"aInstanceUVs");e.enableVertexAttribArray(h),e.vertexAttribPointer(h,4,e.FLOAT,!1,l,2*Float32Array.BYTES_PER_ELEMENT),i.vertexAttribDivisorANGLE(h,1);let c=e.getAttribLocation(this.program,"aInstanceColors");e.enableVertexAttribArray(c),e.vertexAttribPointer(c,2,e.FLOAT,!1,l,6*Float32Array.BYTES_PER_ELEMENT),i.vertexAttribDivisorANGLE(c,1),e.uniform2f(this.uResolution,this.canvas.width,this.canvas.height);let d=e.getUniformLocation(this.program,"uCellSize");e.uniform2f(d,this.cellWidth,this.cellHeight),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,this.atlasTexture),e.uniform1i(this.uTexture,0),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,this.paletteTexture),e.uniform1i(this.uPalette,1),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer),i.drawElementsInstancedANGLE(e.TRIANGLES,6,e.UNSIGNED_SHORT,0,s),i.vertexAttribDivisorANGLE(this.aPosition,0),i.vertexAttribDivisorANGLE(o,0),i.vertexAttribDivisorANGLE(h,0),i.vertexAttribDivisorANGLE(c,0)}renderDirectBuffers(t){let e=this.gl,i=t.width*t.height,r=i*2;if(r>this.maxCells){console.error(`[TerminalGL] \u274C Buffer overflow detected! Trying to render ${r} quads but buffer capacity is ${this.maxCells}. This should not happen - resize() should have reallocated.`);return}let s=0,n=0,l=t.cells,o=i;for(let u=0;u<o;u++){let m=l[u],p=m.bgColorIndex,A=this.canvasBgColor!==null&&p===255?255:p,b=0;for(let v=0;v<4;v++)this.renderTexCoords[s++]=b,this.renderTexCoords[s++]=b,this.renderColorIndices[n++]=A;let C=m.fgColorIndex,R=m.char;if(R===" "||C===255)for(let v=0;v<4;v++)this.renderTexCoords[s++]=0,this.renderTexCoords[s++]=0,this.renderColorIndices[n++]=255;else{let v=R.charCodeAt(0),S=this.charCodeToAtlasIndex[v];if(S!==65535){let w=S*4,W=this.atlasUVs[w],H=this.atlasUVs[w+1],O=this.atlasUVs[w+2],z=this.atlasUVs[w+3];this.renderTexCoords[s++]=W,this.renderTexCoords[s++]=H,this.renderColorIndices[n++]=C,this.renderTexCoords[s++]=O,this.renderTexCoords[s++]=H,this.renderColorIndices[n++]=C,this.renderTexCoords[s++]=W,this.renderTexCoords[s++]=z,this.renderColorIndices[n++]=C,this.renderTexCoords[s++]=O,this.renderTexCoords[s++]=z,this.renderColorIndices[n++]=C}else for(let w=0;w<4;w++)this.renderTexCoords[s++]=0,this.renderTexCoords[s++]=0,this.renderColorIndices[n++]=255}}(s!==o*2*4*2||n!==o*2*4)&&console.error("[TerminalGL] \u274C Buffer index mismatch!",{texIdx:s,colorIdx:n,expected:o*2*4}),e.useProgram(this.program),this.vao&&this.vaoExtension?(this.vaoExtension.bindVertexArrayOES(this.vao),e.bindBuffer(e.ARRAY_BUFFER,this.texCoordBuffer),e.bufferSubData(e.ARRAY_BUFFER,0,this.renderTexCoords.subarray(0,s)),e.bindBuffer(e.ARRAY_BUFFER,this.colorIndexBuffer),e.bufferSubData(e.ARRAY_BUFFER,0,this.renderColorIndices.subarray(0,n))):(e.bindBuffer(e.ARRAY_BUFFER,this.positionBuffer),e.enableVertexAttribArray(this.aPosition),e.vertexAttribPointer(this.aPosition,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this.texCoordBuffer),e.bufferSubData(e.ARRAY_BUFFER,0,this.renderTexCoords.subarray(0,s)),e.enableVertexAttribArray(this.aTexCoord),e.vertexAttribPointer(this.aTexCoord,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this.colorIndexBuffer),e.bufferSubData(e.ARRAY_BUFFER,0,this.renderColorIndices.subarray(0,n)),e.enableVertexAttribArray(this.aColorIndex),e.vertexAttribPointer(this.aColorIndex,1,e.FLOAT,!1,0,0));let h=this.canvas.width,c=this.canvas.height;(this.cachedResolution[0]!==h||this.cachedResolution[1]!==c)&&(e.uniform2f(this.uResolution,h,c),this.cachedResolution[0]=h,this.cachedResolution[1]=c),this.cachedTextureUnit!==0&&(e.activeTexture(e.TEXTURE0),this.cachedTextureUnit=0),e.bindTexture(e.TEXTURE_2D,this.atlasTexture),this.cachedTextureUniform||(e.uniform1i(this.uTexture,0),this.cachedTextureUniform=!0),this.cachedPaletteUnit!==1&&(e.activeTexture(e.TEXTURE1),this.cachedPaletteUnit=1),e.bindTexture(e.TEXTURE_2D,this.paletteTexture),this.cachedPaletteUniform||(e.uniform1i(this.uPalette,1),this.cachedPaletteUniform=!0),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer);let f=t.width*t.height*2*6,g=this.useUint16Indices?e.UNSIGNED_SHORT:e.UNSIGNED_INT;e.drawElements(e.TRIANGLES,f,g,0)}resize(t,e){if(!Number.isInteger(t)||t<=0){console.error(`[TerminalGL] \u274C Invalid cols: ${t}. Must be positive integer.`);return}if(!Number.isInteger(e)||e<=0){console.error(`[TerminalGL] \u274C Invalid rows: ${e}. Must be positive integer.`);return}if(t===this.cols&&e===this.rows)return;let i=t*e,r=this.useUint16Indices?8191:262144;if(i>r){let c=Math.floor(Math.sqrt(r));console.error(`[TerminalGL] \u274C Cannot resize to ${t}\xD7${e} (${i} cells). Device limit: ${r} cells (max ~${c}\xD7${c}). ${this.useUint16Indices?"Device lacks OES_element_index_uint extension.":""}`);return}let s=I.checkCompatibility();i>s.recommendedMaxCells&&console.warn(`[TerminalGL] \u26A0\uFE0F Resizing to ${t}\xD7${e} (${i} cells) exceeds recommended limit (${s.recommendedMaxCells} cells). Performance may degrade.`),this.cols=t,this.rows=e,this.staticPositionsInitialized=!1;let n=this.cols*this.rows*2,l=Math.ceil(n*1.5),o=n>this.maxCells,h=this.maxCells>l*4;if(o||h){let c=this.maxCells;this.maxCells=l,this.renderPositions=new Float32Array(this.maxCells*4*2),this.renderTexCoords=new Float32Array(this.maxCells*4*2),this.renderColorIndices=new Float32Array(this.maxCells*4),this.useUint16Indices?this.renderIndices=new Uint16Array(this.maxCells*6):this.renderIndices=new Uint32Array(this.maxCells*6);let d=this.gl;this.useInstancing||(d.bindBuffer(d.ARRAY_BUFFER,this.positionBuffer),d.bufferData(d.ARRAY_BUFFER,this.renderPositions.byteLength,d.DYNAMIC_DRAW)),d.bindBuffer(d.ARRAY_BUFFER,this.texCoordBuffer),d.bufferData(d.ARRAY_BUFFER,this.renderTexCoords.byteLength,d.DYNAMIC_DRAW),d.bindBuffer(d.ARRAY_BUFFER,this.colorIndexBuffer),d.bufferData(d.ARRAY_BUFFER,this.renderColorIndices.byteLength,d.DYNAMIC_DRAW),d.bindBuffer(d.ELEMENT_ARRAY_BUFFER,this.indexBuffer),d.bufferData(d.ELEMENT_ARRAY_BUFFER,this.renderIndices.byteLength,d.DYNAMIC_DRAW),this.vaoExtension&&this.vao&&(this.vaoExtension.deleteVertexArrayOES(this.vao),this.vao=this.vaoExtension.createVertexArrayOES(),this.vao&&(this.vaoExtension.bindVertexArrayOES(this.vao),d.bindBuffer(d.ARRAY_BUFFER,this.positionBuffer),d.enableVertexAttribArray(this.aPosition),d.vertexAttribPointer(this.aPosition,2,d.FLOAT,!1,0,0),d.bindBuffer(d.ARRAY_BUFFER,this.texCoordBuffer),d.enableVertexAttribArray(this.aTexCoord),d.vertexAttribPointer(this.aTexCoord,2,d.FLOAT,!1,0,0),d.bindBuffer(d.ARRAY_BUFFER,this.colorIndexBuffer),d.enableVertexAttribArray(this.aColorIndex),d.vertexAttribPointer(this.aColorIndex,1,d.FLOAT,!1,0,0),d.bindBuffer(d.ELEMENT_ARRAY_BUFFER,this.indexBuffer),this.vaoExtension.bindVertexArrayOES(null)));let f=o?"\u{1F4C8} Growing":"\u{1F4C9} Shrinking",g=c*160/1048576,u=this.maxCells*160/1048576;console.warn(`[TerminalGL] ${f} buffers: ${g.toFixed(2)}MB \u2192 ${u.toFixed(2)}MB (${c} \u2192 ${this.maxCells} quads)`)}this.canvas.width=this.cols*this.cellWidth,this.canvas.height=this.rows*this.cellHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.showGrid&&this.gridOverlay&&this.updateGridOverlay(),this.updateCanvasSize()}getCanvas(){return this.canvas}getGridSize(){return{cols:this.cols,rows:this.rows}}getCellWidth(){return this.cellWidth}getCellHeight(){return this.cellHeight}getCols(){return this.cols}getRows(){return this.rows}isReady(){return!!(this.bitmapFont&&this.atlasTexture&&this.program)}destroy(){this.dispose()}dispose(){this.resizeObserver&&this.resizeObserver.disconnect();let t=this.gl;this.program&&t.deleteProgram(this.program),this.positionBuffer&&t.deleteBuffer(this.positionBuffer),this.texCoordBuffer&&t.deleteBuffer(this.texCoordBuffer),this.colorIndexBuffer&&t.deleteBuffer(this.colorIndexBuffer),this.indexBuffer&&t.deleteBuffer(this.indexBuffer),this.instanceDataBuffer&&t.deleteBuffer(this.instanceDataBuffer),this.atlasTexture&&t.deleteTexture(this.atlasTexture),this.paletteTexture&&t.deleteTexture(this.paletteTexture),this.vao&&this.vaoExtension&&this.vaoExtension.deleteVertexArrayOES(this.vao);let e=t.getExtension("WEBGL_lose_context");e&&e.loseContext(),this.atlasCanvas&&(this.atlasCanvas.width=0,this.atlasCanvas.height=0,this.atlasCanvas=void 0),this.containerDiv.parentElement&&this.containerDiv.parentElement.removeChild(this.containerDiv),this.canvas.width=0,this.canvas.height=0,this.gridOverlay&&(this.gridOverlay.destroy(),this.gridOverlay=void 0),this.renderPositions=new Float32Array(0),this.renderTexCoords=new Float32Array(0),this.renderColorIndices=new Float32Array(0),this.renderIndices=new Uint32Array(0),this.paletteFloat=new Float32Array(0),this.atlasUVs=new Float32Array(0),this.instanceData=new Float32Array(0),this.templateQuadPositions=new Float32Array(0),this.templateQuadIndices=new Uint16Array(0)}};E(I,"TerminalGL");var U=I;var L=class L{constructor(t,e,i,r,s){a(this,"atlases");a(this,"charMap");a(this,"baseCharWidth");a(this,"baseCharHeight");a(this,"baseCellWidth");a(this,"baseCellHeight");a(this,"atlasColumns",16);a(this,"font");a(this,"SCALES",[1,2,4,8]);a(this,"colorCache",new Map);a(this,"MAX_CACHE_SIZE",512);this.font=t,this.baseCharWidth=e,this.baseCharHeight=i,this.baseCellWidth=r??e,this.baseCellHeight=s??i,this.charMap=new Map,this.atlases=new Map,this.generateAtlases()}generateAtlases(){this.atlasColumns=16;let t=0;for(let[e,i]of this.font){let r=t%this.atlasColumns,s=Math.floor(t/this.atlasColumns);this.charMap.set(e,{x:r*this.baseCharWidth,y:s*this.baseCharHeight});for(let n of this.SCALES){let l=this.getOrCreateAtlas(n),o=r*l.charWidth,h=s*l.charHeight;this.renderBitmapToAtlas(l,i,o,h)}t++}}getOrCreateAtlas(t){let e=this.atlases.get(t);if(!e){let i=this.baseCharWidth*t,r=this.baseCharHeight*t,n=Math.ceil(256/this.atlasColumns),l=document.createElement("canvas");l.width=this.atlasColumns*i,l.height=n*r;let o=l.getContext("2d",{alpha:!0,willReadFrequently:!1});if(!o)throw new Error(`Impossible de cr\xE9er le contexte 2D pour l'atlas ${t}x`);o.imageSmoothingEnabled=!1,e={canvas:l,ctx:o,scale:t,charWidth:i,charHeight:r},this.atlases.set(t,e)}return e}renderBitmapToAtlas(t,e,i,r){let s=t.scale,n=t.ctx;n.fillStyle="#ffffff";for(let l=0;l<Math.min(e.length,this.baseCharHeight);l++){let o=e[l];for(let h=0;h<this.baseCharWidth;h++){let c=1<<7-h;o&c&&n.fillRect(i+h*s,r+l*s,s,s)}}}drawChar(t,e,i,r,s,n,l){let o=this.charMap.get(e);if(!o)return;let h=`${e}:${l}`,c=this.colorCache.get(h);if(c)c.lastUsed=performance.now();else{let x=this.createColoredGlyph(e,l,o);if(!x)return;c={canvas:x,lastUsed:performance.now()},this.colorCache.set(h,c),this.colorCache.size>this.MAX_CACHE_SIZE&&this.evictLRU()}let d=s/this.baseCellWidth,f=n/this.baseCellHeight,g=(this.baseCellWidth-this.baseCharWidth)/2*d,u=(this.baseCellHeight-this.baseCharHeight)/2*f,m=this.baseCharWidth*d,p=this.baseCharHeight*f;t.drawImage(c.canvas,i+g,r+u,m,p)}createColoredGlyph(t,e,i){let r=this.atlases.get(1);if(!r)return null;let s=r.ctx.getImageData(i.x,i.y,this.baseCharWidth,this.baseCharHeight),n=s.data,l=this.hexToRgb(e);for(let c=0;c<n.length;c+=4)n[c+3]>0&&(n[c]=l.r,n[c+1]=l.g,n[c+2]=l.b);let o=document.createElement("canvas");o.width=this.baseCharWidth,o.height=this.baseCharHeight;let h=o.getContext("2d",{alpha:!0});return h?(h.imageSmoothingEnabled=!1,h.putImageData(s,0,0),o):null}hexToRgb(t){if(t.startsWith("#")){let s=/^#?([a-f\d])([a-f\d])([a-f\d])$/i;t=t.replace(s,(l,o,h,c)=>o+o+h+h+c+c);let n=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return n?{r:parseInt(n[1],16),g:parseInt(n[2],16),b:parseInt(n[3],16)}:{r:255,g:255,b:255}}let e=/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*[\d.]+)?\)/.exec(t);if(e)return{r:parseInt(e[1],10),g:parseInt(e[2],10),b:parseInt(e[3],10)};let r={white:[255,255,255],black:[0,0,0],red:[255,0,0],green:[0,255,0],blue:[0,0,255],yellow:[255,255,0],cyan:[0,255,255],magenta:[255,0,255]}[t.toLowerCase()];return r?{r:r[0],g:r[1],b:r[2]}:{r:255,g:255,b:255}}evictLRU(){let t=null,e=1/0;for(let[i,r]of this.colorCache)r.lastUsed<e&&(e=r.lastUsed,t=i);if(t){let i=this.colorCache.get(t);i&&(i.canvas.width=0,i.canvas.height=0),this.colorCache.delete(t)}}getAtlasCanvas(t=1){return this.atlases.get(t)?.canvas}getAllAtlases(){return this.atlases}getCharDimensions(){return{width:this.baseCharWidth,height:this.baseCharHeight}}getCharCount(){return this.charMap.size}hasChar(t){return this.charMap.has(t)}getAtlasDimensions(t=1){let e=this.atlases.get(t);if(e)return{width:e.canvas.width,height:e.canvas.height}}toDataURL(t=1,e="image/png"){return this.atlases.get(t)?.canvas.toDataURL(e)}getCacheStats(){return{size:this.colorCache.size,maxSize:this.MAX_CACHE_SIZE}}clearCache(){for(let t of this.colorCache.values())t.canvas.width=0,t.canvas.height=0;this.colorCache.clear()}destroy(){this.charMap.clear();for(let t of this.atlases.values())t.canvas.width=0,t.canvas.height=0;this.atlases.clear(),this.clearCache()}};E(L,"BitmapFontAtlas");var B=L;var _=class _{constructor(t,e={}){a(this,"canvas");a(this,"ctx");a(this,"parentElement");a(this,"cells");a(this,"cols",0);a(this,"rows",0);a(this,"fontSize");a(this,"fontFamily");a(this,"defaultFgColor");a(this,"defaultBgColor");a(this,"canvasBgColor");a(this,"cellWidth");a(this,"cellHeight");a(this,"offsetX",0);a(this,"offsetY",0);a(this,"fontType","web");a(this,"bitmapFont");a(this,"bitmapAtlas");a(this,"bitmapCharWidth",8);a(this,"bitmapCharHeight",8);a(this,"showDebugGrid");a(this,"debugGridColor");a(this,"gridOverlay");a(this,"fixedGridMode");a(this,"fixedCols");a(this,"fixedRows");a(this,"cellAspectRatio");a(this,"resizeObserver");a(this,"imageDataBuffer");a(this,"useImageDataRendering",!1);a(this,"paletteCache");if(!t)throw new Error("Render: L'\xE9l\xE9ment parent est requis");this.parentElement=t,this.fixedGridMode=!!(e.fixedCols&&e.fixedRows),this.fixedCols=e.fixedCols,this.fixedRows=e.fixedRows,this.cellAspectRatio=e.cellAspectRatio??10/14,this.cellWidth=e.cellWidth??10,this.cellHeight=e.cellHeight??14,this.fontSize=e.fontSize??12,this.fontFamily=e.fontFamily??"monospace",this.defaultFgColor=e.defaultFgColor??"#ffffff",this.defaultBgColor=e.defaultBgColor??"#000000",this.canvasBgColor=e.canvasBgColor!==void 0?e.canvasBgColor:null,this.showDebugGrid=e.showDebugGrid??!1,this.debugGridColor=e.debugGridColor??"rgba(144, 24, 24, 1)",this.canvas=document.createElement("canvas"),e.className&&(this.canvas.className=e.className),e.style&&Object.assign(this.canvas.style,e.style),this.canvas.style.imageRendering="auto",this.parentElement.appendChild(this.canvas);let i=this.canvas.getContext("2d",{alpha:!0,desynchronized:!1});if(!i)throw new Error("UTSPRender: Impossible d'obtenir le contexte 2D du canvas");this.ctx=i,this.calculateGridSize(),this.cells=this.createEmptyGrid(),this.showDebugGrid&&(this.gridOverlay=new y(this.parentElement,{strokeColor:this.debugGridColor,lineWidth:1,innerPadding:1,zIndex:10})),this.enableAutoResize(),this.render()}calculateGridSize(){let t=this.parentElement.clientWidth||800,e=this.parentElement.clientHeight||600;if(this.fixedGridMode&&this.fixedCols&&this.fixedRows)if(this.cols=this.fixedCols,this.rows=this.fixedRows,this.fontType==="bitmap"){let n=t/this.cols,l=e/this.rows,o=this.bitmapCharWidth/this.bitmapCharHeight;n/l>o?(this.cellHeight=Math.floor(l),this.cellWidth=Math.floor(this.cellHeight*o)):(this.cellWidth=Math.floor(n),this.cellHeight=Math.floor(this.cellWidth/o))}else{let n=t/this.cols,l=e/this.rows;n/l>this.cellAspectRatio?(this.cellHeight=Math.floor(l*100)/100,this.cellWidth=Math.floor(this.cellHeight*this.cellAspectRatio*100)/100):(this.cellWidth=Math.floor(n*100)/100,this.cellHeight=Math.floor(this.cellWidth/this.cellAspectRatio*100)/100);let o=14,h=12;this.fontSize=Math.floor(this.cellHeight/o*h*100)/100}else this.cols=Math.floor(t/this.cellWidth),this.rows=Math.floor(e/this.cellHeight);let i=this.cols*this.cellWidth,r=this.rows*this.cellHeight;this.offsetX=Math.floor((t-i)/2),this.offsetY=Math.floor((e-r)/2);let s=window.devicePixelRatio||1;this.canvas.style.width=`${t}px`,this.canvas.style.height=`${e}px`,this.canvas.width=t*s,this.canvas.height=e*s,this.ctx.scale(s,s)}createEmptyGrid(){let t=[];for(let e=0;e<this.rows;e++){let i=[];for(let r=0;r<this.cols;r++)i.push({char:" ",fgColor:this.defaultFgColor,bgColor:this.defaultBgColor});t.push(i)}return t}enableAutoResize(){this.resizeObserver=new ResizeObserver(()=>{let t=this.cols,e=this.rows;if(this.calculateGridSize(),this.cols!==t||this.rows!==e){let i=this.cells;this.cells=this.createEmptyGrid();let r=Math.min(t,this.cols),s=Math.min(e,this.rows);for(let n=0;n<s;n++)for(let l=0;l<r;l++)this.cells[n][l]=i[n][l]}this.render()}),this.resizeObserver.observe(this.parentElement)}setCell(t,e,i,r,s){if(e<0||e>=this.rows||t<0||t>=this.cols)return;let n=i&&typeof i=="string"?i.charAt(0):" ";this.cells[e][t]={char:n,fgColor:r??this.defaultFgColor,bgColor:s??this.defaultBgColor}}getCell(t,e){return e<0||e>=this.rows||t<0||t>=this.cols?null:this.cells[e][t]}write(t,e,i,r,s){for(let n=0;n<i.length;n++)this.setCell(t+n,e,i[n],r,s)}fillRect(t,e,i,r,s=" ",n,l){for(let o=e;o<e+r;o++)for(let h=t;h<t+i;h++)this.setCell(h,o,s,n,l)}clear(){this.cells=this.createEmptyGrid()}setFromArray(t){let e=t.width*t.height;if(t.cells.length!==e)throw new Error(`Invalid array length: expected ${e} (${t.width}\xD7${t.height}), got ${t.cells.length}`);let i=0;for(let r=0;r<t.height;r++)for(let s=0;s<t.width;s++){let n=t.cells[i];r<this.rows&&s<this.cols&&this.setCell(s,r,n.char,n.fgColor,n.bgColor),i++}}render(){if(this.fontType==="bitmap"&&this.bitmapFont&&this.useImageDataRendering){this.renderWithImageData();return}this.renderClassic()}renderWithImageData(){if(!this.bitmapFont)return;let t=this.cols*this.bitmapCharWidth,e=this.rows*this.bitmapCharHeight;(!this.imageDataBuffer||this.imageDataBuffer.width!==t||this.imageDataBuffer.height!==e)&&(this.imageDataBuffer=this.ctx.createImageData(t,e));let i=this.imageDataBuffer.data;for(let o=0;o<this.rows;o++)for(let h=0;h<this.cols;h++){let c=this.cells[o][h],d=this.parseColorToRGB(c.bgColor),f=this.parseColorToRGB(c.fgColor),g=c.char.charCodeAt(0),u=this.bitmapFont.get(g);for(let m=0;m<this.bitmapCharHeight;m++)for(let p=0;p<this.bitmapCharWidth;p++){let x=h*this.bitmapCharWidth+p,b=((o*this.bitmapCharHeight+m)*t+x)*4,C=!1;if(u&&m<u.length){let R=u[m],v=1<<7-p;C=(R&v)!==0}C?(i[b]=f.r,i[b+1]=f.g,i[b+2]=f.b,i[b+3]=f.a):(i[b]=d.r,i[b+1]=d.g,i[b+2]=d.b,i[b+3]=d.a)}}this.canvasBgColor!==null?(this.ctx.fillStyle=this.canvasBgColor,this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height)):this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.imageSmoothingEnabled=!1,this.canvas.style.imageRendering="pixelated",this.canvas.style.imageRendering="crisp-edges";let r=document.createElement("canvas");r.width=t,r.height=e,r.getContext("2d").putImageData(this.imageDataBuffer,0,0);let n=this.cols*this.cellWidth,l=this.rows*this.cellHeight;this.ctx.drawImage(r,0,0,t,e,this.offsetX,this.offsetY,n,l),this.showDebugGrid&&this.drawDebugGrid()}parseColorToRGB(t){let e=/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/.exec(t);if(e)return{r:parseInt(e[1],10),g:parseInt(e[2],10),b:parseInt(e[3],10),a:e[4]?Math.round(parseFloat(e[4])*255):255};if(t.startsWith("#")){let s=/^#?([a-f\d])([a-f\d])([a-f\d])$/i;t=t.replace(s,(l,o,h,c)=>o+o+h+h+c+c);let n=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);if(n)return{r:parseInt(n[1],16),g:parseInt(n[2],16),b:parseInt(n[3],16),a:255}}let r={white:[255,255,255],black:[0,0,0],red:[255,0,0],green:[0,255,0],blue:[0,0,255],yellow:[255,255,0],cyan:[0,255,255],magenta:[255,0,255],transparent:[0,0,0]}[t.toLowerCase()];return r?{r:r[0],g:r[1],b:r[2],a:t==="transparent"?0:255}:{r:255,g:255,b:255,a:255}}renderClassic(){this.canvasBgColor!==null?(this.ctx.fillStyle=this.canvasBgColor,this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height)):this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.fontType==="bitmap"?(this.ctx.imageSmoothingEnabled=!1,this.canvas.style.imageRendering="pixelated",this.canvas.style.imageRendering="crisp-edges"):(this.ctx.imageSmoothingEnabled=!0,this.ctx.imageSmoothingQuality="high",this.canvas.style.imageRendering="auto",this.ctx.font=`${this.fontSize}px ${this.fontFamily}`,this.ctx.textBaseline="top",this.ctx.textRendering="optimizeLegibility");for(let t=0;t<this.rows;t++)for(let e=0;e<this.cols;e++){let i=this.cells[t][e],r=Math.floor(this.offsetX+e*this.cellWidth),s=Math.floor(this.offsetY+t*this.cellHeight),n=Math.floor(this.offsetX+(e+1)*this.cellWidth),l=Math.floor(this.offsetY+(t+1)*this.cellHeight),o=n-r,h=l-s;if((this.canvasBgColor!==null||i.bgColor!==this.defaultBgColor)&&(this.ctx.fillStyle=i.bgColor,this.ctx.fillRect(r,s,o,h)),i.char!==" ")if(this.fontType==="bitmap"&&this.bitmapFont)this.drawBitmapChar(i.char,r,s,o,h,i.fgColor);else{this.ctx.fillStyle=i.fgColor;let d=r+(o-this.ctx.measureText(i.char).width)/2,f=s+(h-this.fontSize)/2;this.ctx.fillText(i.char,d,f)}}this.showDebugGrid&&this.drawDebugGrid()}drawBitmapChar(t,e,i,r,s,n){let l=t.charCodeAt(0);if(this.bitmapAtlas){this.bitmapAtlas.drawChar(this.ctx,l,e,i,r,s,n);return}if(!this.bitmapFont)return;let o=this.bitmapFont.get(l);if(!o)return;let h=r/this.bitmapCharWidth,c=s/this.bitmapCharHeight;this.ctx.fillStyle=n;for(let d=0;d<Math.min(o.length,this.bitmapCharHeight);d++){let f=o[d],g=i+