@utsp/render
Version:
UTSP Render - Browser-based rendering engine for terminal graphics
105 lines (90 loc) • 58.5 kB
JavaScript
"use strict";var B=Object.defineProperty;var k=Object.getOwnPropertyDescriptor;var X=Object.getOwnPropertyNames;var V=Object.prototype.hasOwnProperty;var q=(v,t,e)=>t in v?B(v,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):v[t]=e;var T=(v,t)=>B(v,"name",{value:t,configurable:!0});var j=(v,t)=>{for(var e in t)B(v,e,{get:t[e],enumerable:!0})},Q=(v,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of X(t))!V.call(v,i)&&i!==e&&B(v,i,{get:()=>t[i],enumerable:!(r=k(t,i))||r.enumerable});return v};var Z=v=>Q(B({},"__esModule",{value:!0}),v);var a=(v,t,e)=>(q(v,typeof t!="symbol"?t+"":t,e),e);var J={};j(J,{AutoplayOverlay:()=>M,BitmapFontAtlas:()=>I,DEFAULT_PALETTE:()=>D,GridOverlay:()=>y,Terminal2D:()=>L,TerminalGL:()=>U,colorToPaletteIndex:()=>N,paletteIndexToColor:()=>$,version:()=>K});module.exports=Z(J);var D=["#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 $(v,t=D){return v<0||v>=t.length?"#ff00ff":t[v]}T($,"paletteIndexToColor");function N(v,t=D){let e=t.indexOf(v.toLowerCase());return e>=0?e:0}T(N,"colorToPaletteIndex");var _=class _{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 r=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: ${r} !important;
pointer-events: none !important;
image-rendering: pixelated !important;
image-rendering: crisp-edges !important;
`,this.container.appendChild(this.canvas);let i=this.canvas.getContext("2d");if(!i)throw new Error("[GridOverlay] Impossible de cr\xE9er le contexte 2D");this.ctx=i,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,r,i,s=0,n=0){this.cols=t,this.rows=e,this.cellWidth=r,this.cellHeight=i,this.offsetX=s,this.offsetY=n}setCanvasSize(t,e){let r=window.devicePixelRatio||1;this.canvas.width=t*r,this.canvas.height=e*r,this.ctx.setTransform(1,0,0,1,0,0),this.ctx.scale(r,r)}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 r=0;r<=this.cols;r++){let i=this.offsetX+r*this.cellWidth;if(r===0){let s=i+this.innerPadding+.5;this.ctx.moveTo(s,this.offsetY+this.innerPadding),this.ctx.lineTo(s,this.offsetY+e-this.innerPadding)}else if(r===this.cols){let s=i-this.innerPadding+.5;this.ctx.moveTo(s,this.offsetY+this.innerPadding),this.ctx.lineTo(s,this.offsetY+e-this.innerPadding)}else{let s=i+.5;this.ctx.moveTo(s,this.offsetY+this.innerPadding),this.ctx.lineTo(s,this.offsetY+e-this.innerPadding)}}for(let r=0;r<=this.rows;r++){let i=this.offsetY+r*this.cellHeight;if(r===0){let s=i+this.innerPadding+.5;this.ctx.moveTo(this.offsetX+this.innerPadding,s),this.ctx.lineTo(this.offsetX+t-this.innerPadding,s)}else if(r===this.rows){let s=i-this.innerPadding+.5;this.ctx.moveTo(this.offsetX+this.innerPadding,s),this.ctx.lineTo(this.offsetX+t-this.innerPadding,s)}else{let s=i+.5;this.ctx.moveTo(this.offsetX+this.innerPadding,s),this.ctx.lineTo(this.offsetX+t-this.innerPadding,s)}}this.ctx.stroke()}update(t,e,r,i,s,n,l=0,o=0){this.setDimensions(t,e,r,i,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}};T(_,"GridOverlay");var y=_;var F=class F{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 r=e.cols*e.rows,i=F.checkCompatibility();if(i.errors.length>0)throw new Error(`TerminalGL: WebGL incompatible - ${i.errors.join(", ")}`);let s=e.forceUint16??!1;if(s&&r>i.maxCellsUint16)throw new Error(`TerminalGL: Terminal size ${e.cols}\xD7${e.rows} (${r} cells) exceeds Uint16 limit of ${i.maxCellsUint16} cells. Maximum size with Uint16: ${Math.floor(Math.sqrt(i.maxCellsUint16))}\xD7${Math.floor(Math.sqrt(i.maxCellsUint16))} (or smaller rectangles like 127\xD764)`);if(!i.uint32Indices&&r>i.maxCellsUint16)throw new Error(`TerminalGL: Terminal size ${e.cols}\xD7${e.rows} (${r} cells) exceeds device limit of ${i.maxCellsUint16} cells (OES_element_index_uint not supported). Maximum size: ${Math.floor(Math.sqrt(i.maxCellsUint16))}\xD7${Math.floor(Math.sqrt(i.maxCellsUint16))}`);r>i.recommendedMaxCells&&console.warn(`[TerminalGL] \u26A0\uFE0F Large terminal size ${e.cols}\xD7${e.rows} (${r} cells) exceeds recommended limit of ${i.recommendedMaxCells} cells. Performance may be impacted.`),i.warnings.length>0&&console.warn("[TerminalGL] WebGL Compatibility Warnings:",i.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 ${i.maxCellsUint16} cells)`):console.warn(`[TerminalGL] \u{1F4CA} Using Uint32 indices (max ${i.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"),r=e.getContext("webgl")||e.getContext("experimental-webgl");if(!r||!(r instanceof WebGLRenderingContext))return t.errors.push("\u274C WebGL 1.0 not supported by this browser/device"),t;let i=r;t.webgl1=!0;try{t.maxTextureSize=i.getParameter(i.MAX_TEXTURE_SIZE);let o=i.getParameter(i.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=i.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]}`),i.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,r=this.glyphOffsetX,i=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 C=Math.round(m+r),A=Math.round(f+i),b=Math.round(C+s),E=Math.round(A+n);this.renderPositions[l++]=C,this.renderPositions[l++]=A,this.renderPositions[l++]=b,this.renderPositions[l++]=A,this.renderPositions[l++]=C,this.renderPositions[l++]=E,this.renderPositions[l++]=b,this.renderPositions[l++]=E,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 r=`
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);
}
}
`,i=this.compileShader(t.VERTEX_SHADER,e),s=this.compileShader(t.FRAGMENT_SHADER,r);if(!i||!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,i),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 r=this.gl,i=r.createShader(t);return i?(r.shaderSource(i,e),r.compileShader(i),r.getShaderParameter(i,r.COMPILE_STATUS)?i:(console.error("Shader compilation error:",r.getShaderInfoLog(i)),r.deleteShader(i),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,r=t/this.cols,i=e/this.rows;this.gridOverlay.update(this.cols,this.rows,r,i,t,e,0,0)}setBitmapFont(t,e,r,i,s){this.bitmapFont=t,this.charWidth=Math.round(e),this.charHeight=Math.round(r),this.cellWidth=Math.round(i),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 r=Math.ceil(e/this.atlasColumns),i=this.atlasColumns*this.charWidth,s=r*this.charHeight;this.atlasCanvas=document.createElement("canvas"),this.atlasCanvas.width=i,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,i,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 C=1<<7-p;m&C&&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,r)=>e-r);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,r=this.cachedAtlasHeight,i=.5/e,s=.5/r;for(let n=0;n<t;n++){let l=n%this.atlasColumns,o=Math.floor(n/this.atlasColumns),h=(l*this.charWidth+i)/e,c=(o*this.charHeight+s)/r,d=((l+1)*this.charWidth-i)/e,f=((o+1)*this.charHeight-s)/r,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),r=0,i=0,s=0;return e.length===3?(r=parseInt(e[0]+e[0],16),i=parseInt(e[1]+e[1],16),s=parseInt(e[2]+e[2],16)):e.length===6&&(r=parseInt(e.slice(0,2),16),i=parseInt(e.slice(2,4),16),s=parseInt(e.slice(4,6),16)),[r/255,i/255,s/255,1]}if(t.startsWith("rgb")){let e=t.match(/rgba?\(([^)]+)\)/);if(e){let r=e[1].split(",").map(i=>parseFloat(i.trim()));return[r[0]/255,r[1]/255,r[2]/255,r[3]!==void 0?r[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 r=Math.floor(t/this.cellWidth),i=Math.floor(e/this.cellHeight),s=r/this.cols,n=i/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 r=0;r<Math.min(t.length,256);r++){let i=t[r];e=(e<<5)-e+i.r,e=(e<<5)-e+i.g,e=(e<<5)-e+i.b,e=(e<<5)-e+i.a,e=e|0}if(e!==this.paletteHash){this.paletteHash=e;for(let r=0;r<t.length&&r<256;r++){let i=t[r],s=r*4;this.paletteFloat[s]=i.r/255,this.paletteFloat[s+1]=i.g/255,this.paletteFloat[s+2]=i.b/255,this.paletteFloat[s+3]=i.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 r=0;r<256;r++){let i=r*4;e[i]=this.paletteFloat[i]*255,e[i+1]=this.paletteFloat[i+1]*255,e[i+2]=this.paletteFloat[i+2]*255,e[i+3]=this.paletteFloat[i+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 r=this.parseColor(this.canvasBgColor);e.clearColor(r[0],r[1],r[2],r[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,r=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 i=t.width*t.height;if(this.useUint16Indices&&i>8191){console.warn(`[TerminalGL] \u26A0\uFE0F Terminal too large for instanced rendering with Uint16 (${i} 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,C=this.canvasBgColor!==null&&m===255,A=u.char===" "||p===255;if(!C){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),E=this.charCodeToAtlasIndex[b];if(E!==65535){if(s>=n){console.error(`[TerminalGL] \u274C Instance buffer overflow! instanceIdx=${s}, max=${n}`);break}let R=E*4,x=s*8;this.instanceData[x]=g,this.instanceData[x+1]=f,this.instanceData[x+2]=this.atlasUVs[R],this.instanceData[x+3]=this.atlasUVs[R+1],this.instanceData[x+4]=this.atlasUVs[R+2],this.instanceData[x+5]=this.atlasUVs[R+3],this.instanceData[x+6]=0,this.instanceData[x+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),r.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),r.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),r.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),r.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),r.drawElementsInstancedANGLE(e.TRIANGLES,6,e.UNSIGNED_SHORT,0,s),r.vertexAttribDivisorANGLE(this.aPosition,0),r.vertexAttribDivisorANGLE(o,0),r.vertexAttribDivisorANGLE(h,0),r.vertexAttribDivisorANGLE(c,0)}renderDirectBuffers(t){let e=this.gl,r=t.width*t.height,i=r*2;if(i>this.maxCells){console.error(`[TerminalGL] \u274C Buffer overflow detected! Trying to render ${i} 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=r;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 x=0;x<4;x++)this.renderTexCoords[s++]=b,this.renderTexCoords[s++]=b,this.renderColorIndices[n++]=A;let E=m.fgColorIndex,R=m.char;if(R===" "||E===255)for(let x=0;x<4;x++)this.renderTexCoords[s++]=0,this.renderTexCoords[s++]=0,this.renderColorIndices[n++]=255;else{let x=R.charCodeAt(0),W=this.charCodeToAtlasIndex[x];if(W!==65535){let w=W*4,H=this.atlasUVs[w],O=this.atlasUVs[w+1],z=this.atlasUVs[w+2],Y=this.atlasUVs[w+3];this.renderTexCoords[s++]=H,this.renderTexCoords[s++]=O,this.renderColorIndices[n++]=E,this.renderTexCoords[s++]=z,this.renderTexCoords[s++]=O,this.renderColorIndices[n++]=E,this.renderTexCoords[s++]=H,this.renderTexCoords[s++]=Y,this.renderColorIndices[n++]=E,this.renderTexCoords[s++]=z,this.renderTexCoords[s++]=Y,this.renderColorIndices[n++]=E}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 r=t*e,i=this.useUint16Indices?8191:262144;if(r>i){let c=Math.floor(Math.sqrt(i));console.error(`[TerminalGL] \u274C Cannot resize to ${t}\xD7${e} (${r} cells). Device limit: ${i} cells (max ~${c}\xD7${c}). ${this.useUint16Indices?"Device lacks OES_element_index_uint extension.":""}`);return}let s=F.checkCompatibility();r>s.recommendedMaxCells&&console.warn(`[TerminalGL] \u26A0\uFE0F Resizing to ${t}\xD7${e} (${r} 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)}};T(F,"TerminalGL");var U=F;var G=class G{constructor(t,e,r,i,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=r,this.baseCellWidth=i??e,this.baseCellHeight=s??r,this.charMap=new Map,this.atlases=new Map,this.generateAtlases()}generateAtlases(){this.atlasColumns=16;let t=0;for(let[e,r]of this.font){let i=t%this.atlasColumns,s=Math.floor(t/this.atlasColumns);this.charMap.set(e,{x:i*this.baseCharWidth,y:s*this.baseCharHeight});for(let n of this.SCALES){let l=this.getOrCreateAtlas(n),o=i*l.charWidth,h=s*l.charHeight;this.renderBitmapToAtlas(l,r,o,h)}t++}}getOrCreateAtlas(t){let e=this.atlases.get(t);if(!e){let r=this.baseCharWidth*t,i=this.baseCharHeight*t,n=Math.ceil(256/this.atlasColumns),l=document.createElement("canvas");l.width=this.atlasColumns*r,l.height=n*i;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:r,charHeight:i},this.atlases.set(t,e)}return e}renderBitmapToAtlas(t,e,r,i){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(r+h*s,i+l*s,s,s)}}}drawChar(t,e,r,i,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 C=this.createColoredGlyph(e,l,o);if(!C)return;c={canvas:C,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,r+g,i+u,m,p)}createColoredGlyph(t,e,r){let i=this.atlases.get(1);if(!i)return null;let s=i.ctx.getImageData(r.x,r.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 i={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 i?{r:i[0],g:i[1],b:i[2]}:{r:255,g:255,b:255}}evictLRU(){let t=null,e=1/0;for(let[r,i]of this.colorCache)i.lastUsed<e&&(e=i.lastUsed,t=r);if(t){let r=this.colorCache.get(t);r&&(r.canvas.width=0,r.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()}};T(G,"BitmapFontAtlas");var I=G;var P=class P{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 r=this.canvas.getContext("2d",{alpha:!0,desynchronized:!1});if(!r)throw new Error("UTSPRender: Impossible d'obtenir le contexte 2D du canvas");this.ctx=r,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 r=this.cols*this.cellWidth,i=this.rows*this.cellHeight;this.offsetX=Math.floor((t-r)/2),this.offsetY=Math.floor((e-i)/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 r=[];for(let i=0;i<this.cols;i++)r.push({char:" ",fgColor:this.defaultFgColor,bgColor:this.defaultBgColor});t.push(r)}return t}enableAutoResize(){this.resizeObserver=new ResizeObserver(()=>{let t=this.cols,e=this.rows;if(this.calculateGridSize(),this.cols!==t||this.rows!==e){let r=this.cells;this.cells=this.createEmptyGrid();let i=Math.min(t,this.cols),s=Math.min(e,this.rows);for(let n=0;n<s;n++)for(let l=0;l<i;l++)this.cells[n][l]=r[n][l]}this.render()}),this.resizeObserver.observe(this.parentElement)}setCell(t,e,r,i,s){if(e<0||e>=this.rows||t<0||t>=this.cols)return;let n=r&&typeof r=="string"?r.charAt(0):" ";this.cells[e][t]={char:n,fgColor:i??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,r,i,s){for(let n=0;n<r.length;n++)this.setCell(t+n,e,r[n],i,s)}fillRect(t,e,r,i,s=" ",n,l){for(let o=e;o<e+i;o++)for(let h=t;h<t+r;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 r=0;for(let i=0;i<t.height;i++)for(let s=0;s<t.width;s++){let n=t.cells[r];i<this.rows&&s<this.cols&&this.setCell(s,i,n.char,n.fgColor,n.bgColor),r++}}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 r=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 C=h*this.bitmapCharWidth+p,b=((o*this.bitmapCharHeight+m)*t+C)*4,E=!1;if(u&&m<u.length){let R=u[m],x=1<<7-p;E=(R&x)!==0}E?(r[b]=f.r,r[b+1]=f.g,r[b+2]=f.b,r[b+3]=f.a):(r[b]=d.r,r[b+1]=d.g,r[b+2]=d.b,r[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 i=document.createElement("canvas");i.width=t,i.height=e,i.getContext("2d").putImageData(this.imageDataBuffer,0,0);let n=this.cols*this.cellWidth,l=this.rows*this.cellHeight;this.ctx.drawImage(i,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 i={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 i?{r:i[0],g:i[1],b:i[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 r=this.cells[t][e],i=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-i,h=l-s;if((this.canvasBgColor!==null||r.bgColor!==this.defaultBgColor)&&(this.ctx.fillStyle=r.bgColor,this.ctx.fillRect(i,s,o,h)),r.char!==" "