@utsp/render 0.16.1 → 0.17.0-nightly.20260120215017.712755a

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,11 +1,11 @@
1
- "use strict";var L=Object.defineProperty;var ht=Object.getOwnPropertyDescriptor;var ct=Object.getOwnPropertyNames;var dt=Object.prototype.hasOwnProperty;var ft=(g,t,e)=>t in g?L(g,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):g[t]=e;var v=(g,t)=>L(g,"name",{value:t,configurable:!0});var ut=(g,t)=>{for(var e in t)L(g,e,{get:t[e],enumerable:!0})},mt=(g,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ct(t))!dt.call(g,s)&&s!==e&&L(g,s,{get:()=>t[s],enumerable:!(i=ht(t,s))||i.enumerable});return g};var gt=g=>mt(L({},"__esModule",{value:!0}),g);var l=(g,t,e)=>(ft(g,typeof t!="symbol"?t+"":t,e),e);var xt={};ut(xt,{AutoplayOverlay:()=>z,BitmapFontAtlas:()=>D,DEFAULT_PALETTE:()=>P,GridOverlay:()=>w,ImageFontAtlas:()=>F,PostProcessOverlay:()=>k,ScalingMode:()=>y.ScalingMode,Terminal2D:()=>O,TerminalANSI:()=>$,TerminalGL:()=>_,colorToPaletteIndex:()=>st,createTestRenderState:()=>lt,getAtlasColumns:()=>M,getCharGridPosition:()=>I,getMaxCharCode:()=>S,hexToRGB:()=>at,paletteIndexToColor:()=>it,rgbToHex:()=>ot,version:()=>Ct});module.exports=gt(xt);var P=["#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 it(g,t=P){return g<0||g>=t.length?"#ff00ff":t[g]}v(it,"paletteIndexToColor");function st(g,t=P){let e=t.indexOf(g.toLowerCase());return e>=0?e:0}v(st,"colorToPaletteIndex");var N=class N{constructor(t,e){l(this,"canvas");l(this,"ctx");l(this,"container");l(this,"cols",0);l(this,"rows",0);l(this,"cellWidth",0);l(this,"cellHeight",0);l(this,"offsetX",0);l(this,"offsetY",0);l(this,"strokeColor","rgba(80, 80, 80, 0.4)");l(this,"lineWidth",1);this.container=t,this.canvas=document.createElement("canvas"),this.canvas.className="grid-overlay-canvas";let i=e?.zIndex??10;this.canvas.style.cssText=`
1
+ "use strict";var D=Object.defineProperty;var ot=Object.getOwnPropertyDescriptor;var lt=Object.getOwnPropertyNames;var ht=Object.prototype.hasOwnProperty;var ct=(f,t,e)=>t in f?D(f,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):f[t]=e;var p=(f,t)=>D(f,"name",{value:t,configurable:!0});var dt=(f,t)=>{for(var e in t)D(f,e,{get:t[e],enumerable:!0})},ut=(f,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of lt(t))!ht.call(f,s)&&s!==e&&D(f,s,{get:()=>t[s],enumerable:!(i=ot(t,s))||i.enumerable});return f};var ft=f=>ut(D({},"__esModule",{value:!0}),f);var l=(f,t,e)=>(ct(f,typeof t!="symbol"?t+"":t,e),e);var vt={};dt(vt,{AutoplayOverlay:()=>P,DEFAULT_PALETTE:()=>G,GridOverlay:()=>y,ImageFontAtlas:()=>U,PostProcessOverlay:()=>H,ScalingMode:()=>C.ScalingMode,Terminal2D:()=>W,TerminalANSI:()=>O,TerminalGL:()=>_,colorToPaletteIndex:()=>et,createTestRenderState:()=>at,getAtlasColumns:()=>R,getCharGridPosition:()=>M,getMaxCharCode:()=>B,hexToRGB:()=>rt,paletteIndexToColor:()=>tt,rgbToHex:()=>nt,version:()=>pt});module.exports=ft(vt);var G=["#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 tt(f,t=G){return f<0||f>=t.length?"#ff00ff":t[f]}p(tt,"paletteIndexToColor");function et(f,t=G){let e=t.indexOf(f.toLowerCase());return e>=0?e:0}p(et,"colorToPaletteIndex");var k=class k{constructor(t,e){l(this,"canvas");l(this,"ctx");l(this,"container");l(this,"cols",0);l(this,"rows",0);l(this,"cellWidth",0);l(this,"cellHeight",0);l(this,"offsetX",0);l(this,"offsetY",0);l(this,"strokeColor","rgba(80, 80, 80, 0.4)");l(this,"lineWidth",1);this.container=t,this.canvas=document.createElement("canvas"),this.canvas.className="grid-overlay-canvas";let i=e?.zIndex??10;this.canvas.style.cssText=`
2
2
  display: block !important;
3
3
  position: absolute !important;
4
4
  pointer-events: none !important;
5
5
  image-rendering: pixelated !important;
6
6
  image-rendering: crisp-edges !important;
7
7
  z-index: ${i} !important;
8
- `,this.container.appendChild(this.canvas);let s=this.canvas.getContext("2d");if(!s)throw new Error("[GridOverlay] Impossible de cr\xE9er le contexte 2D");this.ctx=s,e&&(e.strokeColor&&(this.strokeColor=e.strokeColor),e.lineWidth!==void 0&&(this.lineWidth=e.lineWidth))}setDimensions(t,e,i,s,n=0,r=0){this.cols=t,this.rows=e,this.cellWidth=i,this.cellHeight=s,this.offsetX=n,this.offsetY=r}setCanvasSize(t,e){this.canvas.width=t,this.canvas.height=e,this.ctx.setTransform(1,0,0,1,0,0)}setStyle(t){t.strokeColor&&(this.strokeColor=t.strokeColor),t.lineWidth!==void 0&&(this.lineWidth=t.lineWidth)}setTransform(t,e,i,s,n){let r=s.left-n.left,a=s.top-n.top,o=s.width,h=s.height;(this.canvas.width!==o||this.canvas.height!==h)&&(this.canvas.width=o,this.canvas.height=h);let c=this.canvas.style;c.width=`${o}px`,c.height=`${h}px`,c.left=`${r}px`,c.top=`${a}px`}render(){if(!this.ctx)return;let t=this.cols*this.cellWidth,e=this.rows*this.cellHeight,i=t>0?this.canvas.width/t:1,s=e>0?this.canvas.height/e:1,n=Math.min(i,s),r=this.cellWidth*n,a=this.cellHeight*n,o=this.cols*r,h=this.rows*a,c=this.offsetX*n,d=this.offsetY*n;if(!(o===0||h===0)){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.strokeStyle=this.strokeColor,this.ctx.lineWidth=Math.max(1,this.lineWidth*n),this.ctx.beginPath();for(let f=0;f<=this.cols;f++){let u=c+f*r+.5;this.ctx.moveTo(u,d),this.ctx.lineTo(u,d+h)}for(let f=0;f<=this.rows;f++){let u=d+f*a+.5;this.ctx.moveTo(c,u),this.ctx.lineTo(c+o,u)}this.ctx.stroke()}}update(t,e,i,s,n,r,a=0,o=0){this.setDimensions(t,e,i,s,a,o),this.setCanvasSize(n,r),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}};v(N,"GridOverlay");var w=N;function M(g){return Math.sqrt(g)*16}v(M,"getAtlasColumns");function S(g){return g*256-1}v(S,"getMaxCharCode");function I(g,t){let e=Math.floor(g/256),i=g%256,s=Math.sqrt(t),n=e%s,r=Math.floor(e/s),a=i%16,o=Math.floor(i/16);return{col:n*16+a,row:r*16+o}}v(I,"getCharGridPosition");var y=require("@utsp/types");var W=class W{constructor(t,e){l(this,"canvas");l(this,"gl");l(this,"parentElement");l(this,"containerDiv");l(this,"cols");l(this,"rows");l(this,"charWidth");l(this,"charHeight");l(this,"cellWidth",8);l(this,"cellHeight",8);l(this,"glyphOffsetX",0);l(this,"glyphOffsetY",0);l(this,"canvasBgColor");l(this,"showGrid");l(this,"supportsUint32Indices",!1);l(this,"useUint16Indices",!1);l(this,"gridOverlay");l(this,"bitmapFont");l(this,"atlasTexture",null);l(this,"atlasCanvas");l(this,"atlasColumns",0);l(this,"fontLoaded",!1);l(this,"paletteTexture",null);l(this,"program",null);l(this,"positionBuffer",null);l(this,"texCoordBuffer",null);l(this,"colorIndexBuffer",null);l(this,"indexBuffer",null);l(this,"aPosition");l(this,"aTexCoord");l(this,"aColorIndex");l(this,"uResolution",null);l(this,"uTexture",null);l(this,"uPalette",null);l(this,"resizeObserver");l(this,"charCodeToAtlasIndex",new Uint16Array(65536).fill(65535));l(this,"atlasUVs",new Float32Array(0));l(this,"cachedAtlasWidth",0);l(this,"cachedAtlasHeight",0);l(this,"paletteFloat",new Float32Array(256*4));l(this,"maxCells",0);l(this,"renderPositions",new Float32Array(0));l(this,"renderTexCoords",new Float32Array(0));l(this,"renderColorIndices",new Float32Array(0));l(this,"renderIndices",new Uint32Array(0));l(this,"cachedResolution",[0,0]);l(this,"cachedTextureUnit",-1);l(this,"cachedPaletteUnit",-1);l(this,"cachedTextureUniform",!1);l(this,"cachedPaletteUniform",!1);l(this,"paletteHash",0);l(this,"currentScale",1);l(this,"scalingMode",y.ScalingMode.None);l(this,"ambientEffectEnabled",!1);l(this,"ambientEffectCanvas",null);l(this,"ambientEffectCtx",null);l(this,"ambientEffectBlur",y.POST_PROCESS_DEFAULTS.ambientEffect.blur);l(this,"ambientEffectScale",y.POST_PROCESS_DEFAULTS.ambientEffect.scale);l(this,"ambientEffectOpacity",.7);l(this,"onResizeCallback");l(this,"staticPositionsInitialized",!1);l(this,"vaoExtension",null);l(this,"vao",null);l(this,"instancedExtension",null);l(this,"useInstancing",!1);l(this,"instanceDataBuffer",null);l(this,"instanceData",new Float32Array(0));l(this,"templateQuadPositions",new Float32Array(0));l(this,"templateQuadIndices",new Uint16Array(0));l(this,"aInstanceOffset",-1);l(this,"aInstanceUVs",-1);l(this,"aInstanceColors",-1);l(this,"uCellSize",null);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,s=W.checkCompatibility();if(s.errors.length>0)throw new Error(`TerminalGL: WebGL incompatible - ${s.errors.join(", ")}`);let n=e.forceUint16??!1;if(n&&i>s.maxCellsUint16)throw new Error(`TerminalGL: Terminal size ${e.cols}\xD7${e.rows} (${i} cells) exceeds Uint16 limit of ${s.maxCellsUint16} cells. Maximum size with Uint16: ${Math.floor(Math.sqrt(s.maxCellsUint16))}\xD7${Math.floor(Math.sqrt(s.maxCellsUint16))} (or smaller rectangles like 127\xD764)`);if(!s.uint32Indices&&i>s.maxCellsUint16)throw new Error(`TerminalGL: Terminal size ${e.cols}\xD7${e.rows} (${i} cells) exceeds device limit of ${s.maxCellsUint16} cells (OES_element_index_uint not supported). Maximum size: ${Math.floor(Math.sqrt(s.maxCellsUint16))}\xD7${Math.floor(Math.sqrt(s.maxCellsUint16))}`);i>s.recommendedMaxCells&&console.warn(`[TerminalGL] \u26A0\uFE0F Large terminal size ${e.cols}\xD7${e.rows} (${i} cells) exceeds recommended limit of ${s.recommendedMaxCells} cells. Performance may be impacted.`),s.warnings.length>0&&console.warn("[TerminalGL] WebGL Compatibility Warnings:",s.warnings);let r=e.charWidth??8,a=e.charHeight??8;if(!Number.isFinite(r)||r<=0)throw new Error(`TerminalGL: Invalid charWidth: ${r}. Must be a positive number.`);if(!Number.isFinite(a)||a<=0)throw new Error(`TerminalGL: Invalid charHeight: ${a}. Must be a positive number.`);for(this.parentElement=t,this.cols=e.cols,this.rows=e.rows,this.charWidth=r,this.charHeight=a,this.canvasBgColor=e.canvasBgColor!==void 0?e.canvasBgColor:null,this.showGrid=e.showGrid??!1,this.scalingMode=e.scalingMode??y.ScalingMode.None,e.ambientEffect&&(this.ambientEffectEnabled=!0,typeof e.ambientEffect=="object"&&(this.ambientEffectBlur=e.ambientEffect.blur??y.POST_PROCESS_DEFAULTS.ambientEffect.blur,this.ambientEffectScale=e.ambientEffect.scale??y.POST_PROCESS_DEFAULTS.ambientEffect.scale,this.ambientEffectOpacity=e.ambientEffect.opacity??.7));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=`
8
+ `,this.container.appendChild(this.canvas);let s=this.canvas.getContext("2d");if(!s)throw new Error("[GridOverlay] Impossible de cr\xE9er le contexte 2D");this.ctx=s,e&&(e.strokeColor&&(this.strokeColor=e.strokeColor),e.lineWidth!==void 0&&(this.lineWidth=e.lineWidth))}setDimensions(t,e,i,s,a=0,r=0){this.cols=t,this.rows=e,this.cellWidth=i,this.cellHeight=s,this.offsetX=a,this.offsetY=r}setCanvasSize(t,e){this.canvas.width=t,this.canvas.height=e,this.ctx.setTransform(1,0,0,1,0,0)}setStyle(t){t.strokeColor&&(this.strokeColor=t.strokeColor),t.lineWidth!==void 0&&(this.lineWidth=t.lineWidth)}setTransform(t,e,i,s,a){let r=s.left-a.left,n=s.top-a.top,o=s.width,h=s.height;(this.canvas.width!==o||this.canvas.height!==h)&&(this.canvas.width=o,this.canvas.height=h);let c=this.canvas.style;c.width=`${o}px`,c.height=`${h}px`,c.left=`${r}px`,c.top=`${n}px`}render(){if(!this.ctx)return;let t=this.cols*this.cellWidth,e=this.rows*this.cellHeight,i=t>0?this.canvas.width/t:1,s=e>0?this.canvas.height/e:1,a=Math.min(i,s),r=this.cellWidth*a,n=this.cellHeight*a,o=this.cols*r,h=this.rows*n,c=this.offsetX*a,d=this.offsetY*a;if(!(o===0||h===0)){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.strokeStyle=this.strokeColor,this.ctx.lineWidth=Math.max(1,this.lineWidth*a),this.ctx.beginPath();for(let u=0;u<=this.cols;u++){let m=c+u*r+.5;this.ctx.moveTo(m,d),this.ctx.lineTo(m,d+h)}for(let u=0;u<=this.rows;u++){let m=d+u*n+.5;this.ctx.moveTo(c,m),this.ctx.lineTo(c+o,m)}this.ctx.stroke()}}update(t,e,i,s,a,r,n=0,o=0){this.setDimensions(t,e,i,s,n,o),this.setCanvasSize(a,r),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}};p(k,"GridOverlay");var y=k;function R(f){return Math.sqrt(f)*16}p(R,"getAtlasColumns");function B(f){return f*256-1}p(B,"getMaxCharCode");function M(f,t){let e=Math.floor(f/256),i=f%256,s=Math.sqrt(t),a=e%s,r=Math.floor(e/s),n=i%16,o=Math.floor(i/16);return{col:a*16+n,row:r*16+o}}p(M,"getCharGridPosition");var C=require("@utsp/types");var F=class F{constructor(t,e){l(this,"canvas");l(this,"gl");l(this,"parentElement");l(this,"containerDiv");l(this,"cols");l(this,"rows");l(this,"charWidth");l(this,"charHeight");l(this,"cellWidth",8);l(this,"cellHeight",8);l(this,"glyphOffsetX",0);l(this,"glyphOffsetY",0);l(this,"canvasBgColor");l(this,"showGrid");l(this,"supportsUint32Indices",!1);l(this,"useUint16Indices",!1);l(this,"gridOverlay");l(this,"bitmapFont");l(this,"atlasTexture",null);l(this,"atlasCanvas");l(this,"atlasColumns",0);l(this,"fontLoaded",!1);l(this,"paletteTexture",null);l(this,"program",null);l(this,"positionBuffer",null);l(this,"texCoordBuffer",null);l(this,"colorIndexBuffer",null);l(this,"indexBuffer",null);l(this,"aPosition");l(this,"aTexCoord");l(this,"aColorIndex");l(this,"uResolution",null);l(this,"uTexture",null);l(this,"uPalette",null);l(this,"resizeObserver");l(this,"charCodeToAtlasIndex",new Uint16Array(65536).fill(65535));l(this,"atlasUVs",new Float32Array(0));l(this,"cachedAtlasWidth",0);l(this,"cachedAtlasHeight",0);l(this,"paletteFloat",new Float32Array(256*4));l(this,"maxCells",0);l(this,"renderPositions",new Float32Array(0));l(this,"renderTexCoords",new Float32Array(0));l(this,"renderColorIndices",new Float32Array(0));l(this,"renderIndices",new Uint32Array(0));l(this,"cachedResolution",[0,0]);l(this,"cachedTextureUnit",-1);l(this,"cachedPaletteUnit",-1);l(this,"cachedTextureUniform",!1);l(this,"cachedPaletteUniform",!1);l(this,"paletteHash",0);l(this,"currentScale",1);l(this,"scalingMode",C.ScalingMode.None);l(this,"ambientEffectEnabled",!1);l(this,"ambientEffectCanvas",null);l(this,"ambientEffectCtx",null);l(this,"ambientEffectBlur",C.POST_PROCESS_DEFAULTS.ambientEffect.blur);l(this,"ambientEffectScale",C.POST_PROCESS_DEFAULTS.ambientEffect.scale);l(this,"ambientEffectOpacity",.7);l(this,"onResizeCallback");l(this,"staticPositionsInitialized",!1);l(this,"vaoExtension",null);l(this,"vao",null);l(this,"instancedExtension",null);l(this,"useInstancing",!1);l(this,"instanceDataBuffer",null);l(this,"instanceData",new Float32Array(0));l(this,"templateQuadPositions",new Float32Array(0));l(this,"templateQuadIndices",new Uint16Array(0));l(this,"aInstanceOffset",-1);l(this,"aInstanceUVs",-1);l(this,"aInstanceColors",-1);l(this,"uCellSize",null);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,s=F.checkCompatibility();if(s.errors.length>0)throw new Error(`TerminalGL: WebGL incompatible - ${s.errors.join(", ")}`);let a=e.forceUint16??!1;if(a&&i>s.maxCellsUint16)throw new Error(`TerminalGL: Terminal size ${e.cols}\xD7${e.rows} (${i} cells) exceeds Uint16 limit of ${s.maxCellsUint16} cells. Maximum size with Uint16: ${Math.floor(Math.sqrt(s.maxCellsUint16))}\xD7${Math.floor(Math.sqrt(s.maxCellsUint16))} (or smaller rectangles like 127\xD764)`);if(!s.uint32Indices&&i>s.maxCellsUint16)throw new Error(`TerminalGL: Terminal size ${e.cols}\xD7${e.rows} (${i} cells) exceeds device limit of ${s.maxCellsUint16} cells (OES_element_index_uint not supported). Maximum size: ${Math.floor(Math.sqrt(s.maxCellsUint16))}\xD7${Math.floor(Math.sqrt(s.maxCellsUint16))}`);i>s.recommendedMaxCells&&console.warn(`[TerminalGL] \u26A0\uFE0F Large terminal size ${e.cols}\xD7${e.rows} (${i} cells) exceeds recommended limit of ${s.recommendedMaxCells} cells. Performance may be impacted.`),s.warnings.length>0&&console.warn("[TerminalGL] WebGL Compatibility Warnings:",s.warnings);let r=e.charWidth??8,n=e.charHeight??8;if(!Number.isFinite(r)||r<=0)throw new Error(`TerminalGL: Invalid charWidth: ${r}. Must be a positive number.`);if(!Number.isFinite(n)||n<=0)throw new Error(`TerminalGL: Invalid charHeight: ${n}. Must be a positive number.`);for(this.parentElement=t,this.cols=e.cols,this.rows=e.rows,this.charWidth=r,this.charHeight=n,this.canvasBgColor=e.canvasBgColor!==void 0?e.canvasBgColor:null,this.showGrid=e.showGrid??!1,this.scalingMode=e.scalingMode??C.ScalingMode.None,e.ambientEffect&&(this.ambientEffectEnabled=!0,typeof e.ambientEffect=="object"&&(this.ambientEffectBlur=e.ambientEffect.blur??C.POST_PROCESS_DEFAULTS.ambientEffect.blur,this.ambientEffectScale=e.ambientEffect.scale??C.POST_PROCESS_DEFAULTS.ambientEffect.scale,this.ambientEffectOpacity=e.ambientEffect.opacity??.7));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=`
9
9
  position: absolute !important;
10
10
  top: 0 !important;
11
11
  left: 0 !important;
@@ -35,7 +35,7 @@
35
35
  z-index: 1 !important;
36
36
  pointer-events: auto !important;
37
37
  touch-action: none !important;
38
- `;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=n||!this.supportsUint32Indices,this.useUint16Indices?console.warn(`[TerminalGL] \u{1F4CA} Using Uint16 indices (max ${s.maxCellsUint16} cells)`):console.warn(`[TerminalGL] \u{1F4CA} Using Uint32 indices (max ${s.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.ambientEffectEnabled&&(this.createAmbientEffectCanvas(),console.warn("[TerminalGL] \u{1F308} Ambient effect enabled at startup")),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 s=i;t.webgl1=!0;try{t.maxTextureSize=s.getParameter(s.MAX_TEXTURE_SIZE);let o=s.getParameter(s.MAX_VIEWPORT_DIMS);t.maxViewportDims=[o[0],o[1]]}catch(o){return t.errors.push(`\u274C Failed to query WebGL parameters: ${o}`),t}let n=s.getExtension("OES_element_index_uint");t.uint32Indices=!!n;let r=8;if(t.maxCellsUint16=Math.floor(65535/r),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]}`),s.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),this.instanceData=new Float32Array(this.maxCells*8),console.warn(`[TerminalGL] \u{1F680} initInstancedBuffers: maxCells=${this.maxCells}, instanceData.length=${this.instanceData.length}`),t.bindBuffer(t.ARRAY_BUFFER,this.instanceDataBuffer),t.bufferData(t.ARRAY_BUFFER,this.instanceData.byteLength,t.DYNAMIC_DRAW)}initRenderBuffers(){let t=this.cols*this.rows*2;this.maxCells=Math.ceil(t*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,s=this.glyphOffsetY,n=this.charWidth,r=this.charHeight,a=0,o=0,h=0;for(let d=0;d<this.rows;d++){let f=Math.round(d*e),u=Math.round(f+e);for(let b=0;b<this.cols;b++){let m=Math.round(b*t),p=Math.round(m+t);this.renderPositions[a++]=m,this.renderPositions[a++]=f,this.renderPositions[a++]=p,this.renderPositions[a++]=f,this.renderPositions[a++]=m,this.renderPositions[a++]=u,this.renderPositions[a++]=p,this.renderPositions[a++]=u,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+i),x=Math.round(f+s),B=Math.round(C+n),E=Math.round(x+r);this.renderPositions[a++]=C,this.renderPositions[a++]=x,this.renderPositions[a++]=B,this.renderPositions[a++]=x,this.renderPositions[a++]=C,this.renderPositions[a++]=E,this.renderPositions[a++]=B,this.renderPositions[a++]=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=`
38
+ `;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=a||!this.supportsUint32Indices,this.useUint16Indices?console.warn(`[TerminalGL] \u{1F4CA} Using Uint16 indices (max ${s.maxCellsUint16} cells)`):console.warn(`[TerminalGL] \u{1F4CA} Using Uint32 indices (max ${s.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.ambientEffectEnabled&&(this.createAmbientEffectCanvas(),console.warn("[TerminalGL] \u{1F308} Ambient effect enabled at startup")),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 s=i;t.webgl1=!0;try{t.maxTextureSize=s.getParameter(s.MAX_TEXTURE_SIZE);let o=s.getParameter(s.MAX_VIEWPORT_DIMS);t.maxViewportDims=[o[0],o[1]]}catch(o){return t.errors.push(`\u274C Failed to query WebGL parameters: ${o}`),t}let a=s.getExtension("OES_element_index_uint");t.uint32Indices=!!a;let r=8;if(t.maxCellsUint16=Math.floor(65535/r),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]}`),s.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),this.instanceData=new Float32Array(this.maxCells*8),console.warn(`[TerminalGL] \u{1F680} initInstancedBuffers: maxCells=${this.maxCells}, instanceData.length=${this.instanceData.length}`),t.bindBuffer(t.ARRAY_BUFFER,this.instanceDataBuffer),t.bufferData(t.ARRAY_BUFFER,this.instanceData.byteLength,t.DYNAMIC_DRAW)}initRenderBuffers(){let t=this.cols*this.rows*2;this.maxCells=Math.ceil(t*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,s=this.glyphOffsetY,a=this.charWidth,r=this.charHeight,n=0,o=0,h=0;for(let d=0;d<this.rows;d++){let u=Math.round(d*e),m=Math.round(u+e);for(let b=0;b<this.cols;b++){let g=Math.round(b*t),v=Math.round(g+t);this.renderPositions[n++]=g,this.renderPositions[n++]=u,this.renderPositions[n++]=v,this.renderPositions[n++]=u,this.renderPositions[n++]=g,this.renderPositions[n++]=m,this.renderPositions[n++]=v,this.renderPositions[n++]=m,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 E=Math.round(g+i),x=Math.round(u+s),S=Math.round(E+a),A=Math.round(x+r);this.renderPositions[n++]=E,this.renderPositions[n++]=x,this.renderPositions[n++]=S,this.renderPositions[n++]=x,this.renderPositions[n++]=E,this.renderPositions[n++]=A,this.renderPositions[n++]=S,this.renderPositions[n++]=A,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=`
39
39
  // Per-vertex attributes (template quad)
40
40
  attribute vec2 aPosition; // Local quad position (0,0 to cellW,cellH)
41
41
 
@@ -116,7 +116,7 @@
116
116
  gl_FragColor = vec4(texColor.rgb * vColor.rgb, texColor.a);
117
117
  }
118
118
  }
119
- `,s=this.compileShader(t.VERTEX_SHADER,e),n=this.compileShader(t.FRAGMENT_SHADER,i);if(!s||!n)throw new Error("Shader compilation error");let r=t.createProgram();if(!r)throw new Error("Unable to create WebGL program");if(t.attachShader(r,s),t.attachShader(r,n),t.linkProgram(r),!t.getProgramParameter(r,t.LINK_STATUS)){let a=t.getProgramInfoLog(r);throw new Error("Program linking error: "+a)}this.program=r,this.cachedTextureUniform=!1,this.cachedPaletteUniform=!1,this.aPosition=t.getAttribLocation(r,"aPosition"),this.useInstancing?(this.aInstanceOffset=t.getAttribLocation(r,"aInstanceOffset"),this.aInstanceUVs=t.getAttribLocation(r,"aInstanceUVs"),this.aInstanceColors=t.getAttribLocation(r,"aInstanceColors"),this.uCellSize=t.getUniformLocation(r,"uCellSize"),this.instanceDataBuffer=t.createBuffer(),this.aTexCoord=this.aInstanceOffset,this.aColorIndex=this.aInstanceUVs):(this.aTexCoord=t.getAttribLocation(r,"aTexCoord"),this.aColorIndex=t.getAttribLocation(r,"aColorIndex")),this.uResolution=t.getUniformLocation(r,"uResolution"),this.uTexture=t.getUniformLocation(r,"uTexture"),this.uPalette=t.getUniformLocation(r,"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,s=i.createShader(t);return s?(i.shaderSource(s,e),i.compileShader(s),i.getShaderParameter(s,i.COMPILE_STATUS)?s:(console.error("Shader compilation error:",i.getShaderInfoLog(s)),i.deleteShader(s),null)):null}initGridOverlay(){this.gridOverlay=new w(this.containerDiv,{strokeColor:"rgba(144, 24, 24, 1)",lineWidth:1,zIndex:10}),this.updateGridOverlay()}updateGridOverlay(){if(!this.gridOverlay)return;let t=this.cols*this.cellWidth,e=this.rows*this.cellHeight,i=this.canvas.getBoundingClientRect(),s=this.containerDiv.getBoundingClientRect();this.gridOverlay.setDimensions(this.cols,this.rows,this.cellWidth,this.cellHeight,0,0),this.gridOverlay.setTransform(this.currentScale,t,e,i,s),this.gridOverlay.render()}setBitmapFont(t,e,i,s,n){this.bitmapFont=t,this.fontLoaded=!0,this.charWidth=Math.round(e),this.charHeight=Math.round(i),this.cellWidth=Math.round(s),this.cellHeight=Math.round(n),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(r){throw console.error("[TerminalGL] \u274C Failed to generate atlas:",r),r}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()}async setImageFont(t,e,i,s,n,r){this.fontLoaded=!0,this.charWidth=Math.round(e),this.charHeight=Math.round(i),this.cellWidth=Math.round(s),this.cellHeight=Math.round(n),this.atlasColumns=M(r);let a=S(r);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 for ImageFont..."),this.initInstancedBuffers()),await this.loadImageFontAtlas(t),this.charCodeToAtlasIndex.fill(65535);for(let o=0;o<=a;o++)this.charCodeToAtlasIndex[o]=o;this.precomputeImageFontUVs(r),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()}async loadImageFontAtlas(t){return new Promise((e,i)=>{let s=new Uint8Array(t),n=new Blob([s],{type:"image/png"}),r=URL.createObjectURL(n),a=new Image;a.onload=()=>{URL.revokeObjectURL(r),this.atlasCanvas=document.createElement("canvas"),this.atlasCanvas.width=a.width,this.atlasCanvas.height=a.height;let o=this.atlasCanvas.getContext("2d");if(!o){i(new Error("Failed to create 2D context for atlas"));return}o.drawImage(a,0,0),this.cachedAtlasWidth=a.width,this.cachedAtlasHeight=a.height,this.createAtlasTexture(),e()},a.onerror=()=>{URL.revokeObjectURL(r),i(new Error("Failed to load PNG image for ImageFont atlas"))},a.src=r})}precomputeImageFontUVs(t){let e=t*256;this.atlasUVs=new Float32Array(e*4);let i=this.cachedAtlasWidth,s=this.cachedAtlasHeight,n=.5/i,r=.5/s;for(let a=0;a<e;a++){let{col:o,row:h}=I(a,t),c=(o*this.charWidth+n)/i,d=(h*this.charHeight+r)/s,f=((o+1)*this.charWidth-n)/i,u=((h+1)*this.charHeight-r)/s,b=a*4;this.atlasUVs[b]=c,this.atlasUVs[b+1]=d,this.atlasUVs[b+2]=f,this.atlasUVs[b+3]=u}}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),s=this.atlasColumns*this.charWidth,n=i*this.charHeight;this.atlasCanvas=document.createElement("canvas"),this.atlasCanvas.width=s,this.atlasCanvas.height=n;let r=this.atlasCanvas.getContext("2d");if(!r)throw new Error("Unable to create 2D context for atlas");r.clearRect(0,0,s,n),r.fillStyle="#ffffff";let a=0;for(let o of t){let h=this.bitmapFont.get(o);if(!h)continue;let c=a%this.atlasColumns,d=Math.floor(a/this.atlasColumns),f=c*this.charWidth,u=d*this.charHeight;for(let b=0;b<Math.min(h.length,this.charHeight);b++){let m=h[b];for(let p=0;p<this.charWidth;p++){let C=1<<7-p;m&C&&r.fillRect(f+p,u+b,1,1)}}a++}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,s=.5/e,n=.5/i;for(let r=0;r<t;r++){let a=r%this.atlasColumns,o=Math.floor(r/this.atlasColumns),h=(a*this.charWidth+s)/e,c=(o*this.charHeight+n)/i,d=((a+1)*this.charWidth-s)/e,f=((o+1)*this.charHeight-n)/i,u=r*4;this.atlasUVs[u]=h,this.atlasUVs[u+1]=c,this.atlasUVs[u+2]=d,this.atlasUVs[u+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,s=0,n=0;return e.length===3?(i=parseInt(e[0]+e[0],16),s=parseInt(e[1]+e[1],16),n=parseInt(e[2]+e[2],16)):e.length===6&&(i=parseInt(e.slice(0,2),16),s=parseInt(e.slice(2,4),16),n=parseInt(e.slice(4,6),16)),[i/255,s/255,n/255,1]}if(t.startsWith("rgb")){let e=t.match(/rgba?\(([^)]+)\)/);if(e){let i=e[1].split(",").map(s=>parseFloat(s.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=this.cols*this.cellWidth,s=this.rows*this.cellHeight;if(i===0||s===0)return;let n=t/i,r=e/s,a=Math.min(n,r),o;switch(this.scalingMode){case y.ScalingMode.Integer:o=Math.max(1,Math.floor(a));break;case y.ScalingMode.Half:o=Math.max(1,Math.floor(a*2)/2);break;case y.ScalingMode.Quarter:o=Math.max(1,Math.floor(a*4)/4);break;case y.ScalingMode.Eighth:o=Math.max(1,Math.floor(a*8)/8);break;case y.ScalingMode.Responsive:o=1;break;case y.ScalingMode.None:default:o=Math.max(.1,a);break}if(this.canvas.style.transform=`scale(${o})`,this.ambientEffectEnabled&&this.ambientEffectCanvas){let h=o*this.ambientEffectScale;this.ambientEffectCanvas.style.transform=`scale(${h})`}this.currentScale=o,this.onResizeCallback&&this.onResizeCallback(),this.showGrid&&this.gridOverlay&&this.updateGridOverlay()}updateAmbientEffect(){!this.ambientEffectCanvas||!this.ambientEffectCtx||this.ambientEffectCtx.drawImage(this.canvas,0,0)}setPalette(t){let e=0;for(let i=0;i<Math.min(t.length,256);i++){let s=t[i];e=(e<<5)-e+s.r,e=(e<<5)-e+s.g,e=(e<<5)-e+s.b,e=(e<<5)-e+s.a,e=e|0}if(e!==this.paletteHash){this.paletteHash=e;for(let i=0;i<t.length&&i<256;i++){let s=t[i],n=i*4;this.paletteFloat[n]=s.r/255,this.paletteFloat[n+1]=s.g/255,this.paletteFloat[n+2]=s.b/255,this.paletteFloat[n+3]=s.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 s=i*4;e[s]=this.paletteFloat[s]*255,e[s+1]=this.paletteFloat[s+1]*255,e[s+2]=this.paletteFloat[s+2]*255,e[s+3]=this.paletteFloat[s+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),t.passes&&t.passes.length>0?this.renderMultiPass(t,t.passes):this.renderDirect(t),this.ambientEffectEnabled&&this.ambientEffectCanvas&&this.ambientEffectCtx&&this.updateAmbientEffect()}catch(e){console.error("[TerminalGL] \u274C Error rendering display data:",e)}}renderMultiPass(t,e){for(let i=0;i<e.length;i++){let s=e[i],n={id:t.id,width:t.width,height:t.height,palette:t.palette,cells:s.cells};this.renderDirect(n,i===0)}}renderDirect(t,e=!0){let i=this.gl;if(!this.staticPositionsInitialized&&!this.useInstancing&&this.precomputeStaticPositions(),e){if(this.canvasBgColor!==null){let s=this.parseColor(this.canvasBgColor);i.clearColor(s[0],s[1],s[2],s[3])}else i.clearColor(0,0,0,0);i.clear(i.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.renderDirectBuffers(t);return}let s=0,n=this.instanceData.length/8,r=t.width*t.height*2;if(r>n){console.error(`[TerminalGL] \u274C Instance buffer too small! Need ${r}, have ${n}. Display size: ${t.width}\xD7${t.height}, buffer was sized for smaller terminal.`),this.renderDirectBuffers(t);return}for(let o=0;o<t.height;o++)for(let h=0;h<t.width;h++){let c=t.cells[o*t.width+h],d=c.bgColorIndex,f=c.fgColorIndex,u=this.canvasBgColor!==null&&d===255,b=c.char===" "||f===255;if(!u){if(s>=n){console.error(`[TerminalGL] \u274C Instance buffer overflow! instanceIdx=${s}, max=${n}`);break}let m=s*8;this.instanceData[m]=h,this.instanceData[m+1]=o,this.instanceData[m+2]=0,this.instanceData[m+3]=0,this.instanceData[m+4]=0,this.instanceData[m+5]=0,this.instanceData[m+6]=d,this.instanceData[m+7]=0,s++}if(!b){let m=c.char.charCodeAt(0),p=this.charCodeToAtlasIndex[m];if(p!==65535){if(s>=n){console.error(`[TerminalGL] \u274C Instance buffer overflow! instanceIdx=${s}, max=${n}`);break}let C=p*4,x=s*8;this.instanceData[x]=h,this.instanceData[x+1]=o,this.instanceData[x+2]=this.atlasUVs[C],this.instanceData[x+3]=this.atlasUVs[C+1],this.instanceData[x+4]=this.atlasUVs[C+2],this.instanceData[x+5]=this.atlasUVs[C+3],this.instanceData[x+6]=0,this.instanceData[x+7]=f,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 a=8*Float32Array.BYTES_PER_ELEMENT;e.enableVertexAttribArray(this.aInstanceOffset),e.vertexAttribPointer(this.aInstanceOffset,2,e.FLOAT,!1,a,0),i.vertexAttribDivisorANGLE(this.aInstanceOffset,1),e.enableVertexAttribArray(this.aInstanceUVs),e.vertexAttribPointer(this.aInstanceUVs,4,e.FLOAT,!1,a,2*Float32Array.BYTES_PER_ELEMENT),i.vertexAttribDivisorANGLE(this.aInstanceUVs,1),e.enableVertexAttribArray(this.aInstanceColors),e.vertexAttribPointer(this.aInstanceColors,2,e.FLOAT,!1,a,6*Float32Array.BYTES_PER_ELEMENT),i.vertexAttribDivisorANGLE(this.aInstanceColors,1),e.uniform2f(this.uResolution,this.canvas.width,this.canvas.height),e.uniform2f(this.uCellSize,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(this.aInstanceOffset,0),i.vertexAttribDivisorANGLE(this.aInstanceUVs,0),i.vertexAttribDivisorANGLE(this.aInstanceColors,0)}renderDirectBuffers(t){let e=this.gl,i=t.width*t.height,s=i*2;if(s>this.maxCells){console.error(`[TerminalGL] \u274C Buffer overflow detected! Trying to render ${s} quads but buffer capacity is ${this.maxCells}. This should not happen - resize() should have reallocated.`);return}let n=0,r=0,a=t.cells,o=i;for(let b=0;b<o;b++){let m=a[b],p=m.bgColorIndex,x=this.canvasBgColor!==null&&p===255?255:p,B=0;for(let A=0;A<4;A++)this.renderTexCoords[n++]=B,this.renderTexCoords[n++]=B,this.renderColorIndices[r++]=x;let E=m.fgColorIndex,U=m.char;if(U===" "||E===255)for(let A=0;A<4;A++)this.renderTexCoords[n++]=0,this.renderTexCoords[n++]=0,this.renderColorIndices[r++]=255;else{let A=U.charCodeAt(0),G=this.charCodeToAtlasIndex[A];if(G!==65535){let T=G*4,K=this.atlasUVs[T],J=this.atlasUVs[T+1],tt=this.atlasUVs[T+2],et=this.atlasUVs[T+3];this.renderTexCoords[n++]=K,this.renderTexCoords[n++]=J,this.renderColorIndices[r++]=E,this.renderTexCoords[n++]=tt,this.renderTexCoords[n++]=J,this.renderColorIndices[r++]=E,this.renderTexCoords[n++]=K,this.renderTexCoords[n++]=et,this.renderColorIndices[r++]=E,this.renderTexCoords[n++]=tt,this.renderTexCoords[n++]=et,this.renderColorIndices[r++]=E}else for(let T=0;T<4;T++)this.renderTexCoords[n++]=0,this.renderTexCoords[n++]=0,this.renderColorIndices[r++]=255}}(n!==o*2*4*2||r!==o*2*4)&&console.error("[TerminalGL] \u274C Buffer index mismatch!",{texIdx:n,colorIdx:r,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,n)),e.bindBuffer(e.ARRAY_BUFFER,this.colorIndexBuffer),e.bufferSubData(e.ARRAY_BUFFER,0,this.renderColorIndices.subarray(0,r))):(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,n)),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,r)),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,u=this.useUint16Indices?e.UNSIGNED_SHORT:e.UNSIGNED_INT;e.drawElements(e.TRIANGLES,f,u,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,s=this.useInstancing?262144:this.useUint16Indices?8191:262144;if(i>s){let c=Math.floor(Math.sqrt(s));console.error(`[TerminalGL] \u274C Cannot resize to ${t}\xD7${e} (${i} cells). Device limit: ${s} cells (max ~${c}\xD7${c}). ${!this.useInstancing&&this.useUint16Indices?"Device lacks OES_element_index_uint extension.":""}`);return}let n=W.checkCompatibility();i>n.recommendedMaxCells&&console.warn(`[TerminalGL] \u26A0\uFE0F Resizing to ${t}\xD7${e} (${i} cells) exceeds recommended limit (${n.recommendedMaxCells} cells). Performance may degrade.`),this.cols=t,this.rows=e,this.staticPositionsInitialized=!1;let r=this.cols*this.rows*2,a=Math.ceil(r*1.5),o=r>this.maxCells,h=this.maxCells>a*4;if(console.warn(`[TerminalGL] \u{1F4D0} resize check: cols=${t}, rows=${e}, newMaxCells=${r}, this.maxCells=${this.maxCells}, needGrow=${o}, needShrink=${h}`),o||h){let c=this.maxCells;if(this.maxCells=a,console.warn(`[TerminalGL] \u{1F4D0} resize realloc: ${c} \u2192 ${this.maxCells} (needGrow=${o}, needShrink=${h})`),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.useInstancing&&this.instanceDataBuffer){this.instanceData=new Float32Array(this.maxCells*8);let m=this.gl;m.bindBuffer(m.ARRAY_BUFFER,this.instanceDataBuffer),m.bufferData(m.ARRAY_BUFFER,this.instanceData.byteLength,m.DYNAMIC_DRAW)}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),this.useInstancing||(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",u=c*160/1048576,b=this.maxCells*160/1048576;console.warn(`[TerminalGL] ${f} buffers: ${u.toFixed(2)}MB \u2192 ${b.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.canvas.style.width=`${this.canvas.width}px`,this.canvas.style.height=`${this.canvas.height}px`,this.ambientEffectEnabled&&this.ambientEffectCanvas&&(this.ambientEffectCanvas.width=this.canvas.width,this.ambientEffectCanvas.height=this.canvas.height,this.ambientEffectCanvas.style.width=`${this.canvas.width}px`,this.ambientEffectCanvas.style.height=`${this.canvas.height}px`),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}getCurrentScale(){return this.currentScale}getBaseDimensions(){return{width:this.cols*this.cellWidth,height:this.rows*this.cellHeight}}setOnResizeCallback(t){this.onResizeCallback=t}clearOnResizeCallback(){this.onResizeCallback=void 0}getAvailableSize(){return{width:this.parentElement.clientWidth,height:this.parentElement.clientHeight}}setScalingMode(t){this.scalingMode!==t&&(this.scalingMode=t,this.updateCanvasSize())}getScalingMode(){return this.scalingMode}setCellSize(t,e){let i=Math.max(1,Math.min(255,Math.round(t))),s=Math.max(1,Math.min(255,Math.round(e)));this.cellWidth===i&&this.cellHeight===s||(this.cellWidth=i,this.cellHeight=s,this.charWidth=i,this.charHeight=s,this.glyphOffsetX=Math.round((this.cellWidth-this.charWidth)/2),this.glyphOffsetY=Math.round((this.cellHeight-this.charHeight)/2),this.fontLoaded&&this.generateAtlas(),this.useInstancing&&this.initInstancedBuffers(),this.updateCanvasSize())}getCellSize(){return{cellWidth:this.cellWidth,cellHeight:this.cellHeight}}getMaxCells(){return this.useInstancing?262144:this.useUint16Indices?8191:262144}setGrid(t){t.enabled?(this.gridOverlay?this.gridOverlay.setStyle({strokeColor:t.color,lineWidth:t.lineWidth}):this.gridOverlay=new w(this.containerDiv,{strokeColor:t.color??"rgba(144, 24, 24, 1)",lineWidth:t.lineWidth??1,zIndex:10}),this.showGrid=!0,this.gridOverlay.setVisible(!0),this.updateGridOverlay()):(this.showGrid=!1,this.gridOverlay&&this.gridOverlay.setVisible(!1))}isGridEnabled(){return this.showGrid}setAmbientEffect(t){typeof t=="boolean"?this.ambientEffectEnabled=t:(this.ambientEffectEnabled=!0,t.blur!==void 0&&(this.ambientEffectBlur=t.blur),t.scale!==void 0&&(this.ambientEffectScale=t.scale)),this.ambientEffectEnabled&&!this.ambientEffectCanvas&&this.createAmbientEffectCanvas(),this.ambientEffectCanvas&&(this.ambientEffectEnabled?(this.ambientEffectCanvas.style.display="block",this.ambientEffectCanvas.style.filter=`blur(${this.ambientEffectBlur}px)`,this.ambientEffectCanvas.style.transform=`scale(${this.ambientEffectScale})`,this.updateAmbientEffect()):this.ambientEffectCanvas.style.display="none")}createAmbientEffectCanvas(){this.ambientEffectCanvas||(this.ambientEffectCanvas=document.createElement("canvas"),this.ambientEffectCanvas.className="terminalgl-ambient-effect-canvas",this.ambientEffectCanvas.width=this.canvas.width,this.ambientEffectCanvas.height=this.canvas.height,this.ambientEffectCanvas.style.cssText=`
119
+ `,s=this.compileShader(t.VERTEX_SHADER,e),a=this.compileShader(t.FRAGMENT_SHADER,i);if(!s||!a)throw new Error("Shader compilation error");let r=t.createProgram();if(!r)throw new Error("Unable to create WebGL program");if(t.attachShader(r,s),t.attachShader(r,a),t.linkProgram(r),!t.getProgramParameter(r,t.LINK_STATUS)){let n=t.getProgramInfoLog(r);throw new Error("Program linking error: "+n)}this.program=r,this.cachedTextureUniform=!1,this.cachedPaletteUniform=!1,this.aPosition=t.getAttribLocation(r,"aPosition"),this.useInstancing?(this.aInstanceOffset=t.getAttribLocation(r,"aInstanceOffset"),this.aInstanceUVs=t.getAttribLocation(r,"aInstanceUVs"),this.aInstanceColors=t.getAttribLocation(r,"aInstanceColors"),this.uCellSize=t.getUniformLocation(r,"uCellSize"),this.instanceDataBuffer=t.createBuffer(),this.aTexCoord=this.aInstanceOffset,this.aColorIndex=this.aInstanceUVs):(this.aTexCoord=t.getAttribLocation(r,"aTexCoord"),this.aColorIndex=t.getAttribLocation(r,"aColorIndex")),this.uResolution=t.getUniformLocation(r,"uResolution"),this.uTexture=t.getUniformLocation(r,"uTexture"),this.uPalette=t.getUniformLocation(r,"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,s=i.createShader(t);return s?(i.shaderSource(s,e),i.compileShader(s),i.getShaderParameter(s,i.COMPILE_STATUS)?s:(console.error("Shader compilation error:",i.getShaderInfoLog(s)),i.deleteShader(s),null)):null}initGridOverlay(){this.gridOverlay=new y(this.containerDiv,{strokeColor:"rgba(144, 24, 24, 1)",lineWidth:1,zIndex:10}),this.updateGridOverlay()}updateGridOverlay(){if(!this.gridOverlay)return;let t=this.cols*this.cellWidth,e=this.rows*this.cellHeight,i=this.canvas.getBoundingClientRect(),s=this.containerDiv.getBoundingClientRect();this.gridOverlay.setDimensions(this.cols,this.rows,this.cellWidth,this.cellHeight,0,0),this.gridOverlay.setTransform(this.currentScale,t,e,i,s),this.gridOverlay.render()}setBitmapFont(t,e,i,s=e,a=i){this.bitmapFont=t,this.fontLoaded=!0,this.charWidth=e,this.charHeight=i,this.cellWidth=s,this.cellHeight=a,this.glyphOffsetX=Math.round((this.cellWidth-this.charWidth)/2),this.glyphOffsetY=Math.round((this.cellHeight-this.charHeight)/2),this.useInstancing&&this.initInstancedBuffers(),this.generateAtlas(),this.updateCanvasSize()}generateAtlas(){if(!this.bitmapFont)return;this.atlasColumns=16;let t=256,e=this.atlasColumns*this.charWidth,s=Math.ceil(t/this.atlasColumns)*this.charHeight;this.atlasCanvas=document.createElement("canvas"),this.atlasCanvas.width=e,this.atlasCanvas.height=s;let a=this.atlasCanvas.getContext("2d",{willReadFrequently:!0});if(!a)return;a.clearRect(0,0,e,s);let r=Array.from(this.bitmapFont.keys());for(let n of r){let o=this.bitmapFont.get(n);if(!o)continue;let h=n%this.atlasColumns,c=Math.floor(n/this.atlasColumns),d=h*this.charWidth,u=c*this.charHeight;for(let m=0;m<this.charHeight&&!(m>=o.length);m++){let b=o[m];for(let g=0;g<this.charWidth;g++){let v=1<<7-g;b&v&&(a.fillStyle="#FFFFFF",a.fillRect(d+g,u+m,1,1))}}}this.cachedAtlasWidth=e,this.cachedAtlasHeight=s,this.createAtlasTexture(),this.charCodeToAtlasIndex.fill(65535);for(let n=0;n<t;n++)this.charCodeToAtlasIndex[n]=n}async setImageFontStructure(t,e,i,s,a){let r=this.atlasCanvas&&this.fontLoaded&&this.charWidth===Math.round(t)&&this.charHeight===Math.round(e),n=this.atlasCanvas;this.fontLoaded=!0,this.charWidth=Math.round(t),this.charHeight=Math.round(e),this.cellWidth=Math.round(i),this.cellHeight=Math.round(s),this.atlasColumns=R(a);let o=B(a);this.glyphOffsetX=Math.round((this.cellWidth-this.charWidth)/2),this.glyphOffsetY=Math.round((this.cellHeight-this.charHeight)/2),this.useInstancing&&this.initInstancedBuffers();let h=R(a);if(this.cachedAtlasWidth=h*this.charWidth,this.cachedAtlasHeight=h*this.charHeight,this.allocateAtlasTexture(this.cachedAtlasWidth,this.cachedAtlasHeight),r&&n){console.warn("[TerminalGL] \u267B\uFE0F Preserving existing BitmapFont as Block 0");let c=this.gl;c.bindTexture(c.TEXTURE_2D,this.atlasTexture),c.texSubImage2D(c.TEXTURE_2D,0,0,0,c.RGBA,c.UNSIGNED_BYTE,n)}this.charCodeToAtlasIndex.fill(65535);for(let c=0;c<=o;c++)this.charCodeToAtlasIndex[c]=c;this.precomputeImageFontUVs(a),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()}async setImageFontBlock(t,e){let i=this.gl;if(!this.atlasTexture)return;let s=new Blob([e],{type:"image/png"}),a=await createImageBitmap(s),r=this.atlasColumns/16,n=t%r,o=Math.floor(t/r),h=n*16*this.charWidth,c=o*16*this.charHeight;i.bindTexture(i.TEXTURE_2D,this.atlasTexture),i.texSubImage2D(i.TEXTURE_2D,0,h,c,i.RGBA,i.UNSIGNED_BYTE,a),a.close()}async setImageFont(t,e,i,s,a,r){this.fontLoaded=!0,this.charWidth=Math.round(e),this.charHeight=Math.round(i),this.cellWidth=Math.round(s),this.cellHeight=Math.round(a),this.atlasColumns=R(r);let n=B(r);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 for ImageFont..."),this.initInstancedBuffers()),await this.loadImageFontAtlas(t),this.charCodeToAtlasIndex.fill(65535);for(let o=0;o<=n;o++)this.charCodeToAtlasIndex[o]=o;this.precomputeImageFontUVs(r),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()}async loadImageFontAtlas(t){return new Promise((e,i)=>{let s=new Uint8Array(t),a=new Blob([s],{type:"image/png"}),r=URL.createObjectURL(a),n=new Image;n.onload=()=>{URL.revokeObjectURL(r),this.atlasCanvas=document.createElement("canvas"),this.atlasCanvas.width=n.width,this.atlasCanvas.height=n.height;let o=this.atlasCanvas.getContext("2d");if(!o){i(new Error("Failed to create 2D context for atlas"));return}o.drawImage(n,0,0),this.cachedAtlasWidth=n.width,this.cachedAtlasHeight=n.height,this.createAtlasTexture(),e()},n.onerror=()=>{URL.revokeObjectURL(r),i(new Error("Failed to load PNG image for ImageFont atlas"))},n.src=r})}precomputeImageFontUVs(t){let e=t*256;this.atlasUVs=new Float32Array(e*4);let i=this.cachedAtlasWidth,s=this.cachedAtlasHeight,a=.5/i,r=.5/s;for(let n=0;n<e;n++){let{col:o,row:h}=M(n,t),c=(o*this.charWidth+a)/i,d=(h*this.charHeight+r)/s,u=((o+1)*this.charWidth-a)/i,m=((h+1)*this.charHeight-r)/s,b=n*4;this.atlasUVs[b]=c,this.atlasUVs[b+1]=d,this.atlasUVs[b+2]=u,this.atlasUVs[b+3]=m}}allocateAtlasTexture(t,e){try{let i=this.gl,s=i.createTexture();if(!s)throw new Error("Unable to create texture");i.bindTexture(i.TEXTURE_2D,s),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,t,e,0,i.RGBA,i.UNSIGNED_BYTE,null),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST),this.atlasTexture=s}catch(i){throw console.error("[TerminalGL] \u274C Failed to create atlas texture:",i),i}}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,s=0,a=0;return e.length===3?(i=parseInt(e[0]+e[0],16),s=parseInt(e[1]+e[1],16),a=parseInt(e[2]+e[2],16)):e.length===6&&(i=parseInt(e.slice(0,2),16),s=parseInt(e.slice(2,4),16),a=parseInt(e.slice(4,6),16)),[i/255,s/255,a/255,1]}if(t.startsWith("rgb")){let e=t.match(/rgba?\(([^)]+)\)/);if(e){let i=e[1].split(",").map(s=>parseFloat(s.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=this.cols*this.cellWidth,s=this.rows*this.cellHeight;if(i===0||s===0)return;let a=t/i,r=e/s,n=Math.min(a,r),o;switch(this.scalingMode){case C.ScalingMode.Integer:o=Math.max(1,Math.floor(n));break;case C.ScalingMode.Half:o=Math.max(1,Math.floor(n*2)/2);break;case C.ScalingMode.Quarter:o=Math.max(1,Math.floor(n*4)/4);break;case C.ScalingMode.Eighth:o=Math.max(1,Math.floor(n*8)/8);break;case C.ScalingMode.Responsive:o=1;break;case C.ScalingMode.None:default:o=Math.max(.1,n);break}if(this.canvas.style.transform=`scale(${o})`,this.ambientEffectEnabled&&this.ambientEffectCanvas){let h=o*this.ambientEffectScale;this.ambientEffectCanvas.style.transform=`scale(${h})`}this.currentScale=o,this.onResizeCallback&&this.onResizeCallback(),this.showGrid&&this.gridOverlay&&this.updateGridOverlay()}updateAmbientEffect(){!this.ambientEffectCanvas||!this.ambientEffectCtx||this.ambientEffectCtx.drawImage(this.canvas,0,0)}setPalette(t){let e=0;for(let i=0;i<Math.min(t.length,256);i++){let s=t[i];e=(e<<5)-e+s.r,e=(e<<5)-e+s.g,e=(e<<5)-e+s.b,e=(e<<5)-e+s.a,e=e|0}if(e!==this.paletteHash){this.paletteHash=e;for(let i=0;i<t.length&&i<256;i++){let s=t[i],a=i*4;this.paletteFloat[a]=s.r/255,this.paletteFloat[a+1]=s.g/255,this.paletteFloat[a+2]=s.b/255,this.paletteFloat[a+3]=s.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 s=i*4;e[s]=this.paletteFloat[s]*255,e[s+1]=this.paletteFloat[s+1]*255,e[s+2]=this.paletteFloat[s+2]*255,e[s+3]=this.paletteFloat[s+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),t.passes&&t.passes.length>0?this.renderMultiPass(t,t.passes):this.renderDirect(t),this.ambientEffectEnabled&&this.ambientEffectCanvas&&this.ambientEffectCtx&&this.updateAmbientEffect()}catch(e){console.error("[TerminalGL] \u274C Error rendering display data:",e)}}renderMultiPass(t,e){for(let i=0;i<e.length;i++){let s=e[i],a={id:t.id,width:t.width,height:t.height,palette:t.palette,cells:s.cells};this.renderDirect(a,i===0)}}renderDirect(t,e=!0){let i=this.gl;if(!this.staticPositionsInitialized&&!this.useInstancing&&this.precomputeStaticPositions(),e){if(this.canvasBgColor!==null){let s=this.parseColor(this.canvasBgColor);i.clearColor(s[0],s[1],s[2],s[3])}else i.clearColor(0,0,0,0);i.clear(i.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.renderDirectBuffers(t);return}let s=0,a=this.instanceData.length/8,r=t.width*t.height*2;if(r>a){console.error(`[TerminalGL] \u274C Instance buffer too small! Need ${r}, have ${a}. Display size: ${t.width}\xD7${t.height}, buffer was sized for smaller terminal.`),this.renderDirectBuffers(t);return}for(let o=0;o<t.height;o++)for(let h=0;h<t.width;h++){let c=t.cells[o*t.width+h],d=c.bgColorIndex,u=c.fgColorIndex,m=this.canvasBgColor!==null&&d===255,b=c.char===" "||u===255;if(!m){if(s>=a){console.error(`[TerminalGL] \u274C Instance buffer overflow! instanceIdx=${s}, max=${a}`);break}let g=s*8;this.instanceData[g]=h,this.instanceData[g+1]=o,this.instanceData[g+2]=0,this.instanceData[g+3]=0,this.instanceData[g+4]=0,this.instanceData[g+5]=0,this.instanceData[g+6]=d,this.instanceData[g+7]=0,s++}if(!b){let g=c.char.charCodeAt(0),v=this.charCodeToAtlasIndex[g];if(v!==65535){if(s>=a){console.error(`[TerminalGL] \u274C Instance buffer overflow! instanceIdx=${s}, max=${a}`);break}let E=v*4,x=s*8;this.instanceData[x]=h,this.instanceData[x+1]=o,this.instanceData[x+2]=this.atlasUVs[E],this.instanceData[x+3]=this.atlasUVs[E+1],this.instanceData[x+4]=this.atlasUVs[E+2],this.instanceData[x+5]=this.atlasUVs[E+3],this.instanceData[x+6]=0,this.instanceData[x+7]=u,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 n=8*Float32Array.BYTES_PER_ELEMENT;e.enableVertexAttribArray(this.aInstanceOffset),e.vertexAttribPointer(this.aInstanceOffset,2,e.FLOAT,!1,n,0),i.vertexAttribDivisorANGLE(this.aInstanceOffset,1),e.enableVertexAttribArray(this.aInstanceUVs),e.vertexAttribPointer(this.aInstanceUVs,4,e.FLOAT,!1,n,2*Float32Array.BYTES_PER_ELEMENT),i.vertexAttribDivisorANGLE(this.aInstanceUVs,1),e.enableVertexAttribArray(this.aInstanceColors),e.vertexAttribPointer(this.aInstanceColors,2,e.FLOAT,!1,n,6*Float32Array.BYTES_PER_ELEMENT),i.vertexAttribDivisorANGLE(this.aInstanceColors,1),e.uniform2f(this.uResolution,this.canvas.width,this.canvas.height),e.uniform2f(this.uCellSize,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(this.aInstanceOffset,0),i.vertexAttribDivisorANGLE(this.aInstanceUVs,0),i.vertexAttribDivisorANGLE(this.aInstanceColors,0)}renderDirectBuffers(t){let e=this.gl,i=t.width*t.height,s=i*2;if(s>this.maxCells){console.error(`[TerminalGL] \u274C Buffer overflow detected! Trying to render ${s} quads but buffer capacity is ${this.maxCells}. This should not happen - resize() should have reallocated.`);return}let a=0,r=0,n=t.cells,o=i;for(let b=0;b<o;b++){let g=n[b],v=g.bgColorIndex,x=this.canvasBgColor!==null&&v===255?255:v,S=0;for(let T=0;T<4;T++)this.renderTexCoords[a++]=S,this.renderTexCoords[a++]=S,this.renderColorIndices[r++]=x;let A=g.fgColorIndex,q=g.char;if(q===" "||A===255)for(let T=0;T<4;T++)this.renderTexCoords[a++]=0,this.renderTexCoords[a++]=0,this.renderColorIndices[r++]=255;else{let T=q.charCodeAt(0),j=this.charCodeToAtlasIndex[T];if(j!==65535){let I=j*4,Q=this.atlasUVs[I],Z=this.atlasUVs[I+1],K=this.atlasUVs[I+2],J=this.atlasUVs[I+3];this.renderTexCoords[a++]=Q,this.renderTexCoords[a++]=Z,this.renderColorIndices[r++]=A,this.renderTexCoords[a++]=K,this.renderTexCoords[a++]=Z,this.renderColorIndices[r++]=A,this.renderTexCoords[a++]=Q,this.renderTexCoords[a++]=J,this.renderColorIndices[r++]=A,this.renderTexCoords[a++]=K,this.renderTexCoords[a++]=J,this.renderColorIndices[r++]=A}else for(let I=0;I<4;I++)this.renderTexCoords[a++]=0,this.renderTexCoords[a++]=0,this.renderColorIndices[r++]=255}}(a!==o*2*4*2||r!==o*2*4)&&console.error("[TerminalGL] \u274C Buffer index mismatch!",{texIdx:a,colorIdx:r,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,a)),e.bindBuffer(e.ARRAY_BUFFER,this.colorIndexBuffer),e.bufferSubData(e.ARRAY_BUFFER,0,this.renderColorIndices.subarray(0,r))):(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,a)),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,r)),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 u=t.width*t.height*2*6,m=this.useUint16Indices?e.UNSIGNED_SHORT:e.UNSIGNED_INT;e.drawElements(e.TRIANGLES,u,m,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,s=this.useInstancing?262144:this.useUint16Indices?8191:262144;if(i>s){let c=Math.floor(Math.sqrt(s));console.error(`[TerminalGL] \u274C Cannot resize to ${t}\xD7${e} (${i} cells). Device limit: ${s} cells (max ~${c}\xD7${c}). ${!this.useInstancing&&this.useUint16Indices?"Device lacks OES_element_index_uint extension.":""}`);return}let a=F.checkCompatibility();i>a.recommendedMaxCells&&console.warn(`[TerminalGL] \u26A0\uFE0F Resizing to ${t}\xD7${e} (${i} cells) exceeds recommended limit (${a.recommendedMaxCells} cells). Performance may degrade.`),this.cols=t,this.rows=e,this.staticPositionsInitialized=!1;let r=this.cols*this.rows*2,n=Math.ceil(r*1.5),o=r>this.maxCells,h=this.maxCells>n*4;if(console.warn(`[TerminalGL] \u{1F4D0} resize check: cols=${t}, rows=${e}, newMaxCells=${r}, this.maxCells=${this.maxCells}, needGrow=${o}, needShrink=${h}`),o||h){let c=this.maxCells;if(this.maxCells=n,console.warn(`[TerminalGL] \u{1F4D0} resize realloc: ${c} \u2192 ${this.maxCells} (needGrow=${o}, needShrink=${h})`),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.useInstancing&&this.instanceDataBuffer){this.instanceData=new Float32Array(this.maxCells*8);let g=this.gl;g.bindBuffer(g.ARRAY_BUFFER,this.instanceDataBuffer),g.bufferData(g.ARRAY_BUFFER,this.instanceData.byteLength,g.DYNAMIC_DRAW)}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),this.useInstancing||(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 u=o?"\u{1F4C8} Growing":"\u{1F4C9} Shrinking",m=c*160/1048576,b=this.maxCells*160/1048576;console.warn(`[TerminalGL] ${u} buffers: ${m.toFixed(2)}MB \u2192 ${b.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.canvas.style.width=`${this.canvas.width}px`,this.canvas.style.height=`${this.canvas.height}px`,this.ambientEffectEnabled&&this.ambientEffectCanvas&&(this.ambientEffectCanvas.width=this.canvas.width,this.ambientEffectCanvas.height=this.canvas.height,this.ambientEffectCanvas.style.width=`${this.canvas.width}px`,this.ambientEffectCanvas.style.height=`${this.canvas.height}px`),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}getCurrentScale(){return this.currentScale}getBaseDimensions(){return{width:this.cols*this.cellWidth,height:this.rows*this.cellHeight}}setOnResizeCallback(t){this.onResizeCallback=t}clearOnResizeCallback(){this.onResizeCallback=void 0}getAvailableSize(){return{width:this.parentElement.clientWidth,height:this.parentElement.clientHeight}}setScalingMode(t){this.scalingMode!==t&&(this.scalingMode=t,this.updateCanvasSize())}getScalingMode(){return this.scalingMode}setCellSize(t,e){let i=Math.max(1,Math.min(255,Math.round(t))),s=Math.max(1,Math.min(255,Math.round(e)));this.cellWidth===i&&this.cellHeight===s||(this.cellWidth=i,this.cellHeight=s,this.charWidth=i,this.charHeight=s,this.glyphOffsetX=Math.round((this.cellWidth-this.charWidth)/2),this.glyphOffsetY=Math.round((this.cellHeight-this.charHeight)/2),this.useInstancing&&this.initInstancedBuffers(),this.updateCanvasSize())}getCellSize(){return{cellWidth:this.cellWidth,cellHeight:this.cellHeight}}getMaxCells(){return this.useInstancing?262144:this.useUint16Indices?8191:262144}setGrid(t){t.enabled?(this.gridOverlay?this.gridOverlay.setStyle({strokeColor:t.color,lineWidth:t.lineWidth}):this.gridOverlay=new y(this.containerDiv,{strokeColor:t.color??"rgba(144, 24, 24, 1)",lineWidth:t.lineWidth??1,zIndex:10}),this.showGrid=!0,this.gridOverlay.setVisible(!0),this.updateGridOverlay()):(this.showGrid=!1,this.gridOverlay&&this.gridOverlay.setVisible(!1))}isGridEnabled(){return this.showGrid}setAmbientEffect(t){typeof t=="boolean"?this.ambientEffectEnabled=t:(this.ambientEffectEnabled=!0,t.blur!==void 0&&(this.ambientEffectBlur=t.blur),t.scale!==void 0&&(this.ambientEffectScale=t.scale)),this.ambientEffectEnabled&&!this.ambientEffectCanvas&&this.createAmbientEffectCanvas(),this.ambientEffectCanvas&&(this.ambientEffectEnabled?(this.ambientEffectCanvas.style.display="block",this.ambientEffectCanvas.style.filter=`blur(${this.ambientEffectBlur}px)`,this.ambientEffectCanvas.style.transform=`scale(${this.ambientEffectScale})`,this.updateAmbientEffect()):this.ambientEffectCanvas.style.display="none")}createAmbientEffectCanvas(){this.ambientEffectCanvas||(this.ambientEffectCanvas=document.createElement("canvas"),this.ambientEffectCanvas.className="terminalgl-ambient-effect-canvas",this.ambientEffectCanvas.width=this.canvas.width,this.ambientEffectCanvas.height=this.canvas.height,this.ambientEffectCanvas.style.cssText=`
120
120
  display: block !important;
121
121
  position: absolute !important;
122
122
  width: ${this.canvas.width}px !important;
@@ -127,7 +127,7 @@
127
127
  transform: scale(${this.ambientEffectScale}) !important;
128
128
  pointer-events: none !important;
129
129
  z-index: 0 !important;
130
- `,this.ambientEffectCtx=this.ambientEffectCanvas.getContext("2d",{alpha:!0}),this.containerDiv.insertBefore(this.ambientEffectCanvas,this.canvas),console.warn("[TerminalGL] \u{1F308} ambient effect canvas created dynamically"))}isAmbientEffectEnabled(){return this.ambientEffectEnabled}getAmbientEffectConfig(){return{enabled:this.ambientEffectEnabled,blur:this.ambientEffectBlur,scale:this.ambientEffectScale}}getCols(){return this.cols}getRows(){return this.rows}isReady(){return!!(this.fontLoaded&&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.ambientEffectCanvas&&(this.ambientEffectCanvas.width=0,this.ambientEffectCanvas.height=0,this.ambientEffectCanvas=null),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)}};v(W,"TerminalGL");var _=W;var Y=class Y{constructor(t,e,i,s,n){l(this,"atlases");l(this,"charMap");l(this,"baseCharWidth");l(this,"baseCharHeight");l(this,"baseCellWidth");l(this,"baseCellHeight");l(this,"atlasColumns",16);l(this,"font");l(this,"SCALES",[1,2,4,8]);l(this,"colorCache",new Map);l(this,"MAX_CACHE_SIZE",512);this.font=t,this.baseCharWidth=e,this.baseCharHeight=i,this.baseCellWidth=s??e,this.baseCellHeight=n??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 s=t%this.atlasColumns,n=Math.floor(t/this.atlasColumns);this.charMap.set(e,{x:s*this.baseCharWidth,y:n*this.baseCharHeight});for(let r of this.SCALES){let a=this.getOrCreateAtlas(r),o=s*a.charWidth,h=n*a.charHeight;this.renderBitmapToAtlas(a,i,o,h)}t++}}getOrCreateAtlas(t){let e=this.atlases.get(t);if(!e){let i=this.baseCharWidth*t,s=this.baseCharHeight*t,r=Math.ceil(256/this.atlasColumns),a=document.createElement("canvas");a.width=this.atlasColumns*i,a.height=r*s;let o=a.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:a,ctx:o,scale:t,charWidth:i,charHeight:s},this.atlases.set(t,e)}return e}renderBitmapToAtlas(t,e,i,s){let n=t.scale,r=t.ctx;r.fillStyle="#ffffff";for(let a=0;a<Math.min(e.length,this.baseCharHeight);a++){let o=e[a];for(let h=0;h<this.baseCharWidth;h++){let c=1<<7-h;o&c&&r.fillRect(i+h*n,s+a*n,n,n)}}}drawChar(t,e,i,s,n,r,a){let o=this.charMap.get(e);if(!o)return;let h=`${e}:${a}`,c=this.colorCache.get(h);if(c)c.lastUsed=performance.now();else{let C=this.createColoredGlyph(e,a,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=n/this.baseCellWidth,f=r/this.baseCellHeight,u=(this.baseCellWidth-this.baseCharWidth)/2*d,b=(this.baseCellHeight-this.baseCharHeight)/2*f,m=this.baseCharWidth*d,p=this.baseCharHeight*f;t.drawImage(c.canvas,i+u,s+b,m,p)}createColoredGlyph(t,e,i){let s=this.atlases.get(1);if(!s)return null;let n=s.ctx.getImageData(i.x,i.y,this.baseCharWidth,this.baseCharHeight),r=n.data,a=this.hexToRgb(e);for(let c=0;c<r.length;c+=4)r[c+3]>0&&(r[c]=a.r,r[c+1]=a.g,r[c+2]=a.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(n,0,0),o):null}hexToRgb(t){if(t.startsWith("#")){let n=/^#?([a-f\d])([a-f\d])([a-f\d])$/i;t=t.replace(n,(a,o,h,c)=>o+o+h+h+c+c);let r=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return r?{r:parseInt(r[1],16),g:parseInt(r[2],16),b:parseInt(r[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 s={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 s?{r:s[0],g:s[1],b:s[2]}:{r:255,g:255,b:255}}evictLRU(){let t=null,e=1/0;for(let[i,s]of this.colorCache)s.lastUsed<e&&(e=s.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()}};v(Y,"BitmapFontAtlas");var D=Y;var V=class V{constructor(t){l(this,"atlasCanvas",null);l(this,"atlasCtx",null);l(this,"atlasImage",null);l(this,"glyphWidth");l(this,"glyphHeight");l(this,"cellWidth");l(this,"cellHeight");l(this,"atlasBlocks");l(this,"atlasColumns");l(this,"maxCharCode");l(this,"isLoaded",!1);l(this,"colorCache",new Map);l(this,"MAX_CACHE_SIZE",1024);this.glyphWidth=t.glyphWidth,this.glyphHeight=t.glyphHeight,this.cellWidth=t.cellWidth??t.glyphWidth,this.cellHeight=t.cellHeight??t.glyphHeight,this.atlasBlocks=t.atlasBlocks,this.atlasColumns=M(t.atlasBlocks),this.maxCharCode=S(t.atlasBlocks)}async loadFromPNG(t){return new Promise((e,i)=>{let s=new Uint8Array(t),n=new Blob([s],{type:"image/png"}),r=URL.createObjectURL(n),a=new Image;a.onload=()=>{URL.revokeObjectURL(r);let o=this.atlasColumns*this.glyphWidth,h=this.atlasColumns*this.glyphHeight;if((a.width!==o||a.height!==h)&&console.warn(`ImageFontAtlas: Image size ${a.width}\xD7${a.height} doesn't match expected ${o}\xD7${h} for ${this.atlasBlocks} block(s) with ${this.glyphWidth}\xD7${this.glyphHeight} glyphs`),this.atlasCanvas=document.createElement("canvas"),this.atlasCanvas.width=a.width,this.atlasCanvas.height=a.height,this.atlasCtx=this.atlasCanvas.getContext("2d",{alpha:!0,willReadFrequently:!0}),!this.atlasCtx){i(new Error("Failed to create 2D context for atlas"));return}this.atlasCtx.imageSmoothingEnabled=!1,this.atlasCtx.drawImage(a,0,0),this.atlasImage=a,this.isLoaded=!0,e()},a.onerror=()=>{URL.revokeObjectURL(r),i(new Error("Failed to load PNG image for atlas"))},a.src=r})}isReady(){return this.isLoaded}getGlyphPosition(t){if(t<0||t>this.maxCharCode)return null;let{col:e,row:i}=I(t,this.atlasBlocks);return{x:e*this.glyphWidth,y:i*this.glyphHeight}}getCharUV(t){if(t<0||t>this.maxCharCode)return null;let{col:e,row:i}=I(t,this.atlasBlocks),s=e/this.atlasColumns,n=i/this.atlasColumns,r=(e+1)/this.atlasColumns,a=(i+1)/this.atlasColumns;return{u1:s,v1:n,u2:r,v2:a}}drawChar(t,e,i,s,n,r,a){if(!this.isLoaded||!this.atlasCanvas)return;let o=this.getGlyphPosition(e);if(!o)return;let h=`${e}:${a}`,c=this.colorCache.get(h);if(c)c.lastUsed=performance.now();else{let f=this.createColoredGlyph(e,a,o);if(!f)return;c={canvas:f,lastUsed:performance.now()},this.colorCache.set(h,c),this.colorCache.size>this.MAX_CACHE_SIZE&&this.evictLRU()}if(t.imageSmoothingEnabled=!1,n===this.cellWidth&&r===this.cellHeight){let f=Math.floor((this.cellWidth-this.glyphWidth)/2),u=Math.floor((this.cellHeight-this.glyphHeight)/2);t.drawImage(c.canvas,Math.floor(i)+f,Math.floor(s)+u)}else{let f=n/this.cellWidth,u=r/this.cellHeight,b=Math.floor((this.cellWidth-this.glyphWidth)/2*f),m=Math.floor((this.cellHeight-this.glyphHeight)/2*u),p=Math.ceil(this.glyphWidth*f),C=Math.ceil(this.glyphHeight*u);t.drawImage(c.canvas,Math.floor(i)+b,Math.floor(s)+m,p,C)}}createColoredGlyph(t,e,i){if(!this.atlasCtx)return null;let s=this.atlasCtx.getImageData(i.x,i.y,this.glyphWidth,this.glyphHeight),n=s.data,r=this.parseColor(e);for(let h=0;h<n.length;h+=4)n[h+3]>0&&(n[h]=r.r,n[h+1]=r.g,n[h+2]=r.b);let a=document.createElement("canvas");a.width=this.glyphWidth,a.height=this.glyphHeight;let o=a.getContext("2d",{alpha:!0});return o?(o.putImageData(s,0,0),a):null}parseColor(t){if(t.startsWith("#")){let i=t.slice(1);return i.length===3&&(i=i[0]+i[0]+i[1]+i[1]+i[2]+i[2]),{r:parseInt(i.slice(0,2),16),g:parseInt(i.slice(2,4),16),b:parseInt(i.slice(4,6),16)}}let e=/rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(t);return e?{r:parseInt(e[1],10),g:parseInt(e[2],10),b:parseInt(e[3],10)}:{r:255,g:255,b:255}}evictLRU(){let t=null,e=1/0;for(let[i,s]of this.colorCache)s.lastUsed<e&&(e=s.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(){return this.atlasCanvas}getAtlasImage(){return this.atlasImage}getConfig(){return{glyphWidth:this.glyphWidth,glyphHeight:this.glyphHeight,cellWidth:this.cellWidth,cellHeight:this.cellHeight,atlasBlocks:this.atlasBlocks}}getGlyphDimensions(){return{width:this.glyphWidth,height:this.glyphHeight}}getCellDimensions(){return{width:this.cellWidth,height:this.cellHeight}}getAtlasDimensions(){return{width:this.atlasColumns*this.glyphWidth,height:this.atlasColumns*this.glyphHeight}}getAtlasColumns(){return this.atlasColumns}getMaxCharCode(){return this.maxCharCode}isValidCharCode(t){return t>=0&&t<=this.maxCharCode}clearCache(){for(let t of this.colorCache.values())t.canvas.width=0,t.canvas.height=0;this.colorCache.clear()}getCacheStats(){return{size:this.colorCache.size,maxSize:this.MAX_CACHE_SIZE}}destroy(){this.clearCache(),this.atlasCanvas&&(this.atlasCanvas.width=0,this.atlasCanvas.height=0,this.atlasCanvas=null),this.atlasCtx=null,this.atlasImage=null,this.isLoaded=!1}};v(V,"ImageFontAtlas");var F=V;var R=require("@utsp/types");var X=class X{constructor(t,e={}){l(this,"containerDiv");l(this,"canvas");l(this,"ctx");l(this,"parentElement");l(this,"cells");l(this,"cols",0);l(this,"rows",0);l(this,"fontSize");l(this,"fontFamily");l(this,"defaultFgColor");l(this,"defaultBgColor");l(this,"canvasBgColor");l(this,"cellWidth");l(this,"cellHeight");l(this,"offsetX",0);l(this,"offsetY",0);l(this,"fontType","web");l(this,"bitmapFont");l(this,"bitmapAtlas");l(this,"imageAtlas");l(this,"bitmapCharWidth",8);l(this,"bitmapCharHeight",8);l(this,"showDebugGrid");l(this,"debugGridColor");l(this,"gridOverlay");l(this,"fixedGridMode");l(this,"fixedCols");l(this,"fixedRows");l(this,"cellAspectRatio");l(this,"resizeObserver");l(this,"imageDataBuffer");l(this,"useImageDataRendering",!1);l(this,"paletteCache");l(this,"scalingMode",R.ScalingMode.None);l(this,"currentScale",1);l(this,"customCellSize",!1);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??1,this.cellWidth=e.cellWidth??8,this.cellHeight=e.cellHeight??8,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.scalingMode=e.scalingMode??R.ScalingMode.None,window.getComputedStyle(this.parentElement).position==="static"&&(this.parentElement.style.position="relative"),this.containerDiv=document.createElement("div"),this.containerDiv.className="terminal2d-container",this.containerDiv.style.cssText=`
130
+ `,this.ambientEffectCtx=this.ambientEffectCanvas.getContext("2d",{alpha:!0}),this.containerDiv.insertBefore(this.ambientEffectCanvas,this.canvas),console.warn("[TerminalGL] \u{1F308} ambient effect canvas created dynamically"))}isAmbientEffectEnabled(){return this.ambientEffectEnabled}getAmbientEffectConfig(){return{enabled:this.ambientEffectEnabled,blur:this.ambientEffectBlur,scale:this.ambientEffectScale}}getCols(){return this.cols}getRows(){return this.rows}isReady(){return!!(this.fontLoaded&&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.ambientEffectCanvas&&(this.ambientEffectCanvas.width=0,this.ambientEffectCanvas.height=0,this.ambientEffectCanvas=null),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)}};p(F,"TerminalGL");var _=F;var z=class z{constructor(t){l(this,"atlasCanvas",null);l(this,"atlasCtx",null);l(this,"atlasImage",null);l(this,"glyphWidth");l(this,"glyphHeight");l(this,"cellWidth");l(this,"cellHeight");l(this,"atlasBlocks");l(this,"atlasColumns");l(this,"maxCharCode");l(this,"isLoaded",!1);l(this,"colorCache",new Map);l(this,"MAX_CACHE_SIZE",1024);this.glyphWidth=t.glyphWidth,this.glyphHeight=t.glyphHeight,this.cellWidth=t.cellWidth??t.glyphWidth,this.cellHeight=t.cellHeight??t.glyphHeight,this.atlasBlocks=t.atlasBlocks,this.atlasColumns=R(t.atlasBlocks),this.maxCharCode=B(t.atlasBlocks)}getCanvas(){return this.atlasCanvas}getGlyphWidth(){return this.glyphWidth}getGlyphHeight(){return this.glyphHeight}prepare(){let t=this.atlasColumns*this.glyphWidth,e=this.atlasColumns*this.glyphHeight;this.atlasCanvas=document.createElement("canvas"),this.atlasCanvas.width=t,this.atlasCanvas.height=e,this.atlasCtx=this.atlasCanvas.getContext("2d",{alpha:!0,willReadFrequently:!0}),this.atlasCtx&&(this.atlasCtx.imageSmoothingEnabled=!1,this.atlasCtx.clearRect(0,0,t,e)),this.isLoaded=!0}async loadBlock(t,e){return(!this.atlasCanvas||!this.atlasCtx)&&this.prepare(),new Promise((i,s)=>{let a=new Uint8Array(e),r=new Blob([a],{type:"image/png"}),n=URL.createObjectURL(r),o=new Image;o.onload=()=>{URL.revokeObjectURL(n);let h=Math.sqrt(this.atlasBlocks),c=t%h,d=Math.floor(t/h),u=c*16*this.glyphWidth,m=d*16*this.glyphHeight;this.atlasCtx.drawImage(o,u,m),this.colorCache.clear(),i()},o.onerror=()=>{URL.revokeObjectURL(n),s(new Error(`Failed to load PNG for block ${t}`))},o.src=n})}async loadFromPNG(t){return new Promise((e,i)=>{let s=new Uint8Array(t),a=new Blob([s],{type:"image/png"}),r=URL.createObjectURL(a),n=new Image;n.onload=()=>{URL.revokeObjectURL(r);let o=this.atlasColumns*this.glyphWidth,h=this.atlasColumns*this.glyphHeight;if((n.width!==o||n.height!==h)&&console.warn(`ImageFontAtlas: Image size ${n.width}\xD7${n.height} doesn't match expected ${o}\xD7${h} for ${this.atlasBlocks} block(s) with ${this.glyphWidth}\xD7${this.glyphHeight} glyphs`),this.atlasCanvas=document.createElement("canvas"),this.atlasCanvas.width=n.width,this.atlasCanvas.height=n.height,this.atlasCtx=this.atlasCanvas.getContext("2d",{alpha:!0,willReadFrequently:!0}),!this.atlasCtx){i(new Error("Failed to create 2D context for atlas"));return}this.atlasCtx.imageSmoothingEnabled=!1,this.atlasCtx.drawImage(n,0,0),this.atlasImage=n,this.isLoaded=!0,e()},n.onerror=()=>{URL.revokeObjectURL(r),i(new Error("Failed to load PNG image for atlas"))},n.src=r})}isReady(){return this.isLoaded}getGlyphPosition(t){if(t<0||t>this.maxCharCode)return null;let{col:e,row:i}=M(t,this.atlasBlocks);return{x:e*this.glyphWidth,y:i*this.glyphHeight}}getCharUV(t){if(t<0||t>this.maxCharCode)return null;let{col:e,row:i}=M(t,this.atlasBlocks),s=e/this.atlasColumns,a=i/this.atlasColumns,r=(e+1)/this.atlasColumns,n=(i+1)/this.atlasColumns;return{u1:s,v1:a,u2:r,v2:n}}drawChar(t,e,i,s,a,r,n){if(!this.isLoaded||!this.atlasCanvas)return;let o=this.getGlyphPosition(e);if(!o)return;let h=`${e}:${n}`,c=this.colorCache.get(h);if(c)c.lastUsed=performance.now();else{let u=this.createColoredGlyph(e,n,o);if(!u)return;c={canvas:u,lastUsed:performance.now()},this.colorCache.set(h,c),this.colorCache.size>this.MAX_CACHE_SIZE&&this.evictLRU()}if(t.imageSmoothingEnabled=!1,a===this.cellWidth&&r===this.cellHeight){let u=Math.floor((this.cellWidth-this.glyphWidth)/2),m=Math.floor((this.cellHeight-this.glyphHeight)/2);t.drawImage(c.canvas,Math.floor(i)+u,Math.floor(s)+m)}else{let u=a/this.cellWidth,m=r/this.cellHeight,b=Math.floor((this.cellWidth-this.glyphWidth)/2*u),g=Math.floor((this.cellHeight-this.glyphHeight)/2*m),v=Math.ceil(this.glyphWidth*u),E=Math.ceil(this.glyphHeight*m);t.drawImage(c.canvas,Math.floor(i)+b,Math.floor(s)+g,v,E)}}createColoredGlyph(t,e,i){if(!this.atlasCtx)return null;let s=this.atlasCtx.getImageData(i.x,i.y,this.glyphWidth,this.glyphHeight),a=s.data,r=this.parseColor(e);for(let h=0;h<a.length;h+=4)a[h+3]>0&&(a[h]=a[h]*r.r/255,a[h+1]=a[h+1]*r.g/255,a[h+2]=a[h+2]*r.b/255);let n=document.createElement("canvas");n.width=this.glyphWidth,n.height=this.glyphHeight;let o=n.getContext("2d",{alpha:!0});return o?(o.putImageData(s,0,0),n):null}parseColor(t){if(t.startsWith("#")){let i=t.slice(1);return i.length===3&&(i=i[0]+i[0]+i[1]+i[1]+i[2]+i[2]),{r:parseInt(i.slice(0,2),16),g:parseInt(i.slice(2,4),16),b:parseInt(i.slice(4,6),16)}}let e=/rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(t);return e?{r:parseInt(e[1],10),g:parseInt(e[2],10),b:parseInt(e[3],10)}:{r:255,g:255,b:255}}evictLRU(){let t=null,e=1/0;for(let[i,s]of this.colorCache)s.lastUsed<e&&(e=s.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(){return this.atlasCanvas}getAtlasImage(){return this.atlasImage}getConfig(){return{glyphWidth:this.glyphWidth,glyphHeight:this.glyphHeight,cellWidth:this.cellWidth,cellHeight:this.cellHeight,atlasBlocks:this.atlasBlocks}}getGlyphDimensions(){return{width:this.glyphWidth,height:this.glyphHeight}}getCellDimensions(){return{width:this.cellWidth,height:this.cellHeight}}getAtlasDimensions(){return{width:this.atlasColumns*this.glyphWidth,height:this.atlasColumns*this.glyphHeight}}getAtlasColumns(){return this.atlasColumns}getMaxCharCode(){return this.maxCharCode}isValidCharCode(t){return t>=0&&t<=this.maxCharCode}clearCache(){for(let t of this.colorCache.values())t.canvas.width=0,t.canvas.height=0;this.colorCache.clear()}getCacheStats(){return{size:this.colorCache.size,maxSize:this.MAX_CACHE_SIZE}}destroy(){this.clearCache(),this.atlasCanvas&&(this.atlasCanvas.width=0,this.atlasCanvas.height=0,this.atlasCanvas=null),this.atlasCtx=null,this.atlasImage=null,this.isLoaded=!1}};p(z,"ImageFontAtlas");var U=z;var w=require("@utsp/types");var $=class ${constructor(t,e={}){l(this,"containerDiv");l(this,"canvas");l(this,"ctx");l(this,"parentElement");l(this,"cells");l(this,"cols",0);l(this,"rows",0);l(this,"defaultFgColor");l(this,"defaultBgColor");l(this,"canvasBgColor");l(this,"cellWidth");l(this,"cellHeight");l(this,"offsetX",0);l(this,"offsetY",0);l(this,"imageAtlas");l(this,"showDebugGrid");l(this,"debugGridColor");l(this,"gridOverlay");l(this,"fixedGridMode");l(this,"fixedCols");l(this,"fixedRows");l(this,"cellAspectRatio");l(this,"resizeObserver");l(this,"paletteCache");l(this,"scalingMode",w.ScalingMode.None);l(this,"currentScale",1);l(this,"customCellSize",!1);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??1,this.cellWidth=e.cellWidth??8,this.cellHeight=e.cellHeight??8,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.scalingMode=e.scalingMode??w.ScalingMode.None,window.getComputedStyle(this.parentElement).position==="static"&&(this.parentElement.style.position="relative"),this.containerDiv=document.createElement("div"),this.containerDiv.className="terminal2d-container",this.containerDiv.style.cssText=`
131
131
  position: absolute !important;
132
132
  top: 0 !important;
133
133
  left: 0 !important;
@@ -142,7 +142,7 @@
142
142
  align-items: center !important;
143
143
  isolation: isolate !important;
144
144
  pointer-events: none !important;
145
- `,this.canvas=document.createElement("canvas"),this.canvas.className="terminal2d-canvas",e.className&&(this.canvas.className+=" "+e.className),e.style&&Object.assign(this.canvas.style,e.style),this.canvas.style.imageRendering="pixelated",this.canvas.style.imageRendering="crisp-edges",this.containerDiv.appendChild(this.canvas),this.parentElement.appendChild(this.containerDiv);let s=this.canvas.getContext("2d",{alpha:!0,desynchronized:!1});if(!s)throw new Error("UTSPRender: Impossible d'obtenir le contexte 2D du canvas");this.ctx=s,this.ctx.imageSmoothingEnabled=!1,this.calculateGridSize(),this.cells=this.createEmptyGrid(),this.showDebugGrid&&(this.gridOverlay=new w(this.parentElement,{strokeColor:this.debugGridColor,lineWidth:1,zIndex:10})),this.enableAutoResize(),this.render()}calculateGridSize(){let t=this.parentElement.clientWidth||800,e=this.parentElement.clientHeight||600;if(!this.customCellSize){let h,c;if(this.fontType==="image"&&this.imageAtlas){let d=this.imageAtlas.getCellDimensions();h=d.width,c=d.height}else this.fontType==="bitmap"?(h=this.bitmapCharWidth,c=this.bitmapCharHeight):(h=Math.round(this.cellWidth)||10,c=Math.round(this.cellHeight)||14);this.cellWidth=Math.round(h),this.cellHeight=Math.round(c)}this.scalingMode===R.ScalingMode.Responsive?(this.cols=Math.floor(t/this.cellWidth)||1,this.rows=Math.floor(e/this.cellHeight)||1):this.fixedGridMode&&this.fixedCols&&this.fixedRows?(this.cols=this.fixedCols,this.rows=this.fixedRows):(this.cols=Math.floor(t/this.cellWidth)||1,this.rows=Math.floor(e/this.cellHeight)||1);let i=this.cols*this.cellWidth,s=this.rows*this.cellHeight,n=t/i,r=e/s,a=Math.min(n,r),o;switch(this.scalingMode){case R.ScalingMode.Integer:o=Math.max(1,Math.floor(a));break;case R.ScalingMode.Half:o=Math.max(.5,Math.floor(a*2)/2);break;case R.ScalingMode.Quarter:o=Math.max(.25,Math.floor(a*4)/4);break;case R.ScalingMode.Eighth:o=Math.max(.125,Math.floor(a*8)/8);break;case R.ScalingMode.Responsive:o=1;break;case R.ScalingMode.None:default:o=Math.max(.1,a);break}this.currentScale=o,this.canvas.width=i,this.canvas.height=s,this.ctx.imageSmoothingEnabled=!1,this.canvas.style.cssText=`
145
+ `,this.canvas=document.createElement("canvas"),this.canvas.className="terminal2d-canvas",e.className&&(this.canvas.className+=" "+e.className),e.style&&Object.assign(this.canvas.style,e.style),this.canvas.style.imageRendering="pixelated",this.canvas.style.imageRendering="crisp-edges",this.containerDiv.appendChild(this.canvas),this.parentElement.appendChild(this.containerDiv);let s=this.canvas.getContext("2d",{alpha:!0,desynchronized:!1});if(!s)throw new Error("UTSPRender: Impossible d'obtenir le contexte 2D du canvas");this.ctx=s,this.ctx.imageSmoothingEnabled=!1,this.calculateGridSize(),this.cells=this.createEmptyGrid(),this.showDebugGrid&&(this.gridOverlay=new y(this.parentElement,{strokeColor:this.debugGridColor,lineWidth:1,zIndex:10})),this.enableAutoResize(),this.render()}calculateGridSize(){let t=this.parentElement.clientWidth||800,e=this.parentElement.clientHeight||600;if(!this.customCellSize){let h,c;if(this.imageAtlas){let d=this.imageAtlas.getCellDimensions();h=d.width,c=d.height}else h=this.cellWidth,c=this.cellHeight;this.cellWidth=Math.round(h),this.cellHeight=Math.round(c)}this.scalingMode===w.ScalingMode.Responsive?(this.cols=Math.floor(t/this.cellWidth)||1,this.rows=Math.floor(e/this.cellHeight)||1):this.fixedGridMode&&this.fixedCols&&this.fixedRows?(this.cols=this.fixedCols,this.rows=this.fixedRows):(this.cols=Math.floor(t/this.cellWidth)||1,this.rows=Math.floor(e/this.cellHeight)||1);let i=this.cols*this.cellWidth,s=this.rows*this.cellHeight,a=t/i,r=e/s,n=Math.min(a,r),o;switch(this.scalingMode){case w.ScalingMode.Integer:o=Math.max(1,Math.floor(n));break;case w.ScalingMode.Half:o=Math.max(.5,Math.floor(n*2)/2);break;case w.ScalingMode.Quarter:o=Math.max(.25,Math.floor(n*4)/4);break;case w.ScalingMode.Eighth:o=Math.max(.125,Math.floor(n*8)/8);break;case w.ScalingMode.Responsive:o=1;break;case w.ScalingMode.None:default:o=Math.max(.1,n);break}this.currentScale=o,this.canvas.width=i,this.canvas.height=s,this.ctx.imageSmoothingEnabled=!1,this.canvas.style.cssText=`
146
146
  flex-shrink: 0 !important;
147
147
  flex-grow: 0 !important;
148
148
  width: ${i}px !important;
@@ -156,7 +156,7 @@
156
156
  backface-visibility: hidden !important;
157
157
  pointer-events: auto !important;
158
158
  touch-action: none !important;
159
- `,this.fontType==="web"&&(this.fontSize=Math.round(this.cellHeight/14*12)),this.offsetX=0,this.offsetY=0}createEmptyGrid(){let t=[];for(let e=0;e<this.rows;e++){let i=[];for(let s=0;s<this.cols;s++)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 s=Math.min(t,this.cols),n=Math.min(e,this.rows);for(let r=0;r<n;r++)for(let a=0;a<s;a++)this.cells[r][a]=i[r][a]}this.render()}),this.resizeObserver.observe(this.parentElement)}setCell(t,e,i,s,n){if(e<0||e>=this.rows||t<0||t>=this.cols)return;let r=i&&typeof i=="string"?i.charAt(0):" ";this.cells[e][t]={char:r,fgColor:s??this.defaultFgColor,bgColor:n??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,s,n){for(let r=0;r<i.length;r++)this.setCell(t+r,e,i[r],s,n)}fillRect(t,e,i,s,n=" ",r,a){for(let o=e;o<e+s;o++)for(let h=t;h<t+i;h++)this.setCell(h,o,n,r,a)}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 s=0;s<t.height;s++)for(let n=0;n<t.width;n++){let r=t.cells[i];s<this.rows&&n<this.cols&&this.setCell(n,s,r.char,r.fgColor,r.bgColor),i++}}render(t=!0){if(this.fontType==="bitmap"&&this.bitmapFont&&this.useImageDataRendering){this.renderWithImageData(t);return}this.renderClassic(t)}renderWithImageData(t=!0){if(!this.bitmapFont)return;let e=this.cols*this.bitmapCharWidth,i=this.rows*this.bitmapCharHeight;(!this.imageDataBuffer||this.imageDataBuffer.width!==e||this.imageDataBuffer.height!==i)&&(this.imageDataBuffer=this.ctx.createImageData(e,i));let s=this.imageDataBuffer.data;for(let h=0;h<this.rows;h++)for(let c=0;c<this.cols;c++){let d=this.cells[h][c],f=this.parseColorToRGB(d.bgColor),u=this.parseColorToRGB(d.fgColor),b=d.char.charCodeAt(0),m=this.bitmapFont.get(b);for(let p=0;p<this.bitmapCharHeight;p++)for(let C=0;C<this.bitmapCharWidth;C++){let x=c*this.bitmapCharWidth+C,E=((h*this.bitmapCharHeight+p)*e+x)*4,U=!1;if(m&&p<m.length){let A=m[p],G=1<<7-C;U=(A&G)!==0}U?(s[E]=u.r,s[E+1]=u.g,s[E+2]=u.b,s[E+3]=u.a):(s[E]=f.r,s[E+1]=f.g,s[E+2]=f.b,s[E+3]=f.a)}}t&&(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 n=document.createElement("canvas");n.width=e,n.height=i,n.getContext("2d").putImageData(this.imageDataBuffer,0,0);let a=this.cols*this.cellWidth,o=this.rows*this.cellHeight;this.ctx.drawImage(n,0,0,e,i,this.offsetX,this.offsetY,a,o),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 n=/^#?([a-f\d])([a-f\d])([a-f\d])$/i;t=t.replace(n,(a,o,h,c)=>o+o+h+h+c+c);let r=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);if(r)return{r:parseInt(r[1],16),g:parseInt(r[2],16),b:parseInt(r[3],16),a:255}}let s={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 s?{r:s[0],g:s[1],b:s[2],a:t==="transparent"?0:255}:{r:255,g:255,b:255,a:255}}renderClassic(t=!0){t&&(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.fontType==="image"?(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 e=0;e<this.rows;e++)for(let i=0;i<this.cols;i++){let s=this.cells[e][i],n=Math.floor(this.offsetX+i*this.cellWidth),r=Math.floor(this.offsetY+e*this.cellHeight),a=Math.floor(this.offsetX+(i+1)*this.cellWidth),o=Math.floor(this.offsetY+(e+1)*this.cellHeight),h=a-n,c=o-r;if((this.canvasBgColor!==null||s.bgColor!==this.defaultBgColor)&&(this.ctx.fillStyle=s.bgColor,this.ctx.fillRect(n,r,h,c)),s.char!==" ")if(this.fontType==="image"&&this.imageAtlas){let f=s.char.charCodeAt(0);this.imageAtlas.drawChar(this.ctx,f,n,r,h,c,s.fgColor)}else if(this.fontType==="bitmap"&&this.bitmapFont)this.drawBitmapChar(s.char,n,r,h,c,s.fgColor);else{this.ctx.fillStyle=s.fgColor;let f=n+(h-this.ctx.measureText(s.char).width)/2,u=r+(c-this.fontSize)/2;this.ctx.fillText(s.char,f,u)}}this.showDebugGrid&&this.drawDebugGrid()}drawBitmapChar(t,e,i,s,n,r){let a=t.charCodeAt(0);if(this.bitmapAtlas){this.bitmapAtlas.drawChar(this.ctx,a,e,i,s,n,r);return}if(!this.bitmapFont)return;let o=this.bitmapFont.get(a);if(!o)return;let h=s/this.bitmapCharWidth,c=n/this.bitmapCharHeight;this.ctx.fillStyle=r;for(let d=0;d<Math.min(o.length,this.bitmapCharHeight);d++){let f=o[d],u=i+d*c,b=i+(d+1)*c;for(let m=0;m<this.bitmapCharWidth;m++){let p=1<<7-m;if(f&p){let C=e+m*h,x=e+(m+1)*h;this.ctx.fillRect(C,u,x-C,b-u)}}}}drawDebugGrid(){if(!this.gridOverlay)return;let t=this.parentElement.clientWidth||800,e=this.parentElement.clientHeight||600;this.gridOverlay.update(this.cols,this.rows,this.cellWidth,this.cellHeight,t,e,this.offsetX,this.offsetY)}getCanvas(){return this.canvas}getContext(){return this.ctx}getDimensions(){return{cols:this.cols,rows:this.rows}}getCellDimensions(){return{cellWidth:this.cellWidth,cellHeight:this.cellHeight}}getCellWidth(){return this.cellWidth}getCellHeight(){return this.cellHeight}getCurrentScale(){return this.currentScale}getScalingMode(){return this.scalingMode}getOffsets(){return{offsetX:this.offsetX,offsetY:this.offsetY}}setDebugGrid(t){this.showDebugGrid=t,t&&!this.gridOverlay?(this.gridOverlay=new w(this.parentElement,{strokeColor:this.debugGridColor,lineWidth:1,zIndex:10}),this.drawDebugGrid()):!t&&this.gridOverlay?(this.gridOverlay.destroy(),this.gridOverlay=void 0):t&&this.gridOverlay&&this.gridOverlay.setVisible(!0)}setCanvasBackgroundColor(t){this.canvasBgColor=t}getCanvasBackgroundColor(){return this.canvasBgColor}setFixedGrid(t,e,i){this.fixedGridMode=!0,this.fixedCols=t,this.fixedRows=e,i!==void 0&&(this.cellAspectRatio=i);let s=this.cols,n=this.rows,r=this.cells;if(this.calculateGridSize(),this.cols!==s||this.rows!==n){this.cells=this.createEmptyGrid();let a=Math.min(s,this.cols),o=Math.min(n,this.rows);for(let h=0;h<o;h++)for(let c=0;c<a;c++)this.cells[h][c]=r[h][c]}this.render()}setAdaptiveGrid(t,e){this.fixedGridMode=!1,this.fixedCols=void 0,this.fixedRows=void 0,t!==void 0&&(this.cellWidth=t),e!==void 0&&(this.cellHeight=e);let i=this.cols,s=this.rows,n=this.cells;if(this.calculateGridSize(),this.cols!==i||this.rows!==s){this.cells=this.createEmptyGrid();let r=Math.min(i,this.cols),a=Math.min(s,this.rows);for(let o=0;o<a;o++)for(let h=0;h<r;h++)this.cells[o][h]=n[o][h]}this.render()}isFixedGridMode(){return this.fixedGridMode}setDebugGridColor(t){this.debugGridColor=t}isDebugGridEnabled(){return this.showDebugGrid}setImageDataRendering(t){this.useImageDataRendering=t,t&&this.fontType==="bitmap"?console.warn("[Render] ImageData rendering enabled (optimized for benchmarks)"):t&&(console.warn("[Render] ImageData rendering requires bitmap font, keeping classic mode"),this.useImageDataRendering=!1)}isImageDataRenderingEnabled(){return this.useImageDataRendering}setWebFont(t,e){this.fontType="web",this.fontFamily=t,e!==void 0&&(this.fontSize=e),this.bitmapFont=void 0,this.bitmapAtlas=void 0,this.useImageDataRendering=!1,this.calculateGridSize(),this.cells=this.createEmptyGrid()}setBitmapFont(t,e,i,s,n){this.fontType="bitmap",this.bitmapFont=t,this.bitmapCharWidth=e,this.bitmapCharHeight=i,this.bitmapAtlas=new D(t,e,i,s,n),this.cellWidth=s,this.cellHeight=n,this.calculateGridSize(),this.cells=this.createEmptyGrid()}async setImageFont(t,e,i,s,n,r){this.fontType="image",this.imageAtlas=new F({glyphWidth:e,glyphHeight:i,cellWidth:s,cellHeight:n,atlasBlocks:r}),await this.imageAtlas.loadFromPNG(t),this.cellWidth=s,this.cellHeight=n,this.bitmapCharWidth=e,this.bitmapCharHeight=i,this.calculateGridSize(),this.cells=this.createEmptyGrid()}getFontType(){return this.fontType}getBitmapFont(){return this.bitmapFont}getBitmapCharDimensions(){return this.fontType!=="bitmap"?null:{width:this.bitmapCharWidth,height:this.bitmapCharHeight}}setPalette(t){this.paletteCache=t}convertColor(t,e){if(t==null||isNaN(t))return this.defaultFgColor;if(t===255)return"rgba(0, 0, 0, 0)";if(t<0||t>=e.length)return this.defaultFgColor;let i=e[t];return!i||typeof i.r!="number"?this.defaultFgColor:`rgba(${i.r}, ${i.g}, ${i.b}, ${i.a/255})`}renderDirect(t,e,i,s,n){for(let r=0;r<e&&r<this.rows;r++)for(let a=0;a<t&&a<this.cols;a++){let o=r*t+a;if(o>=i.length)break;let h=i[o];if(!h)continue;let c=this.convertColor(h.fgColorIndex,s),d=this.convertColor(h.bgColorIndex,s);this.setCell(a,r,h.char??" ",c,d)}this.render(n)}renderDisplayData(t){if(!t||!t.cells||t.cells.length===0){console.warn("[Terminal2D] Empty display data");return}if(t.width===0||t.height===0){console.warn("[Terminal2D] Invalid display dimensions:",t.width,t.height);return}(t.width!==this.cols||t.height!==this.rows)&&this.setFixedGrid(t.width,t.height,this.cellAspectRatio);let e=this.paletteCache??t.palette;if(!e||e.length===0){console.error("[Terminal2D] No palette available (neither cached nor in display)");return}if(t.passes&&t.passes.length>0)for(let i=0;i<t.passes.length;i++){let s=t.passes[i];this.renderDirect(t.width,t.height,s.cells,e,i===0)}else this.renderDirect(t.width,t.height,t.cells,e,!0)}isReady(){return!0}getCols(){return this.cols}getRows(){return this.rows}resize(t,e){this.setFixedGrid(t,e)}setScalingMode(t){if(this.scalingMode===t)return;let e=this.cols,i=this.rows;if(this.scalingMode=t,this.calculateGridSize(),this.cols!==e||this.rows!==i){let s=this.cells;if(this.cells=this.createEmptyGrid(),s&&s.length>0){let n=Math.min(e,this.cols),r=Math.min(i,this.rows);for(let a=0;a<r;a++)for(let o=0;o<n;o++)s[a]&&s[a][o]&&(this.cells[a][o]=s[a][o])}}this.render()}setCellSize(t,e){let i=Math.max(1,Math.min(255,Math.round(t))),s=Math.max(1,Math.min(255,Math.round(e)));if(this.cellWidth===i&&this.cellHeight===s)return;let n=this.cols,r=this.rows;if(this.cellWidth=i,this.cellHeight=s,this.customCellSize=!0,this.calculateGridSize(),this.cols!==n||this.rows!==r){let a=this.cells;if(this.cells=this.createEmptyGrid(),a&&a.length>0){let o=Math.min(n,this.cols),h=Math.min(r,this.rows);for(let c=0;c<h;c++)for(let d=0;d<o;d++)a[c]&&a[c][d]&&(this.cells[c][d]=a[c][d])}}this.render()}getCellSize(){return{cellWidth:this.cellWidth,cellHeight:this.cellHeight}}getAvailableSize(){return{width:this.parentElement.clientWidth,height:this.parentElement.clientHeight}}getMaxCells(){return 65536}destroy(){this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=void 0),this.gridOverlay&&(this.gridOverlay.destroy(),this.gridOverlay=void 0),this.containerDiv.parentElement&&this.containerDiv.parentElement.removeChild(this.containerDiv)}};v(X,"Terminal2D");var O=X;var q=class q{constructor(t,e={}){l(this,"container");l(this,"overlayDiv",null);l(this,"button",null);l(this,"options");l(this,"started",!1);l(this,"onStartCallback");this.container=t,this.options={buttonText:e.buttonText??"Click to Start",onStart:e.onStart??(()=>{}),backgroundColor:e.backgroundColor??"rgba(0, 0, 0, 0.8)",buttonColor:e.buttonColor??"#4a90d9",buttonHoverColor:e.buttonHoverColor??"#357abd",buttonTextColor:e.buttonTextColor??"#ffffff",zIndex:e.zIndex??1e3},this.onStartCallback=e.onStart,this.createOverlay()}createOverlay(){let t=window.getComputedStyle(this.container).position;t!=="relative"&&t!=="absolute"&&t!=="fixed"&&(this.container.style.position="relative"),this.overlayDiv=document.createElement("div"),this.overlayDiv.className="utsp-autoplay-overlay",this.overlayDiv.style.cssText=`
159
+ `,this.offsetX=0,this.offsetY=0}createEmptyGrid(){let t=[];for(let e=0;e<this.rows;e++){let i=[];for(let s=0;s<this.cols;s++)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 s=Math.min(t,this.cols),a=Math.min(e,this.rows);for(let r=0;r<a;r++)for(let n=0;n<s;n++)this.cells[r][n]=i[r][n]}this.render()}),this.resizeObserver.observe(this.parentElement)}setCell(t,e,i,s,a){if(e<0||e>=this.rows||t<0||t>=this.cols)return;let r=i&&typeof i=="string"?i.charAt(0):" ";this.cells[e][t]={char:r,fgColor:s??this.defaultFgColor,bgColor:a??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,s,a){for(let r=0;r<i.length;r++)this.setCell(t+r,e,i[r],s,a)}fillRect(t,e,i,s,a=" ",r,n){for(let o=e;o<e+s;o++)for(let h=t;h<t+i;h++)this.setCell(h,o,a,r,n)}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 s=0;s<t.height;s++)for(let a=0;a<t.width;a++){let r=t.cells[i];s<this.rows&&a<this.cols&&this.setCell(a,s,r.char,r.fgColor,r.bgColor),i++}}render(t=!0){this.renderClassic(t)}renderClassic(t=!0){t&&(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";for(let e=0;e<this.rows;e++)for(let i=0;i<this.cols;i++){let s=this.cells[e][i],a=Math.floor(this.offsetX+i*this.cellWidth),r=Math.floor(this.offsetY+e*this.cellHeight),n=Math.floor(this.offsetX+(i+1)*this.cellWidth),o=Math.floor(this.offsetY+(e+1)*this.cellHeight),h=n-a,c=o-r;if((this.canvasBgColor!==null||s.bgColor!==this.defaultBgColor)&&(this.ctx.fillStyle=s.bgColor,this.ctx.fillRect(a,r,h,c)),s.char!==" "&&this.imageAtlas){let u=s.char.charCodeAt(0);this.imageAtlas.drawChar(this.ctx,u,a,r,h,c,s.fgColor)}}this.showDebugGrid&&this.drawDebugGrid()}drawDebugGrid(){if(!this.gridOverlay)return;let t=this.parentElement.clientWidth||800,e=this.parentElement.clientHeight||600;this.gridOverlay.update(this.cols,this.rows,this.cellWidth,this.cellHeight,t,e,this.offsetX,this.offsetY)}getCanvas(){return this.canvas}getContext(){return this.ctx}getDimensions(){return{cols:this.cols,rows:this.rows}}getCellDimensions(){return{cellWidth:this.cellWidth,cellHeight:this.cellHeight}}getCellWidth(){return this.cellWidth}getCellHeight(){return this.cellHeight}getCurrentScale(){return this.currentScale}getScalingMode(){return this.scalingMode}getOffsets(){return{offsetX:this.offsetX,offsetY:this.offsetY}}setDebugGrid(t){this.showDebugGrid=t,t&&!this.gridOverlay?(this.gridOverlay=new y(this.parentElement,{strokeColor:this.debugGridColor,lineWidth:1,zIndex:10}),this.drawDebugGrid()):!t&&this.gridOverlay?(this.gridOverlay.destroy(),this.gridOverlay=void 0):t&&this.gridOverlay&&this.gridOverlay.setVisible(!0)}setCanvasBackgroundColor(t){this.canvasBgColor=t}getCanvasBackgroundColor(){return this.canvasBgColor}setFixedGrid(t,e,i){this.fixedGridMode=!0,this.fixedCols=t,this.fixedRows=e,i!==void 0&&(this.cellAspectRatio=i);let s=this.cols,a=this.rows,r=this.cells;if(this.calculateGridSize(),this.cols!==s||this.rows!==a){this.cells=this.createEmptyGrid();let n=Math.min(s,this.cols),o=Math.min(a,this.rows);for(let h=0;h<o;h++)for(let c=0;c<n;c++)this.cells[h][c]=r[h][c]}this.render()}setAdaptiveGrid(t,e){this.fixedGridMode=!1,this.fixedCols=void 0,this.fixedRows=void 0,t!==void 0&&(this.cellWidth=t),e!==void 0&&(this.cellHeight=e);let i=this.cols,s=this.rows,a=this.cells;if(this.calculateGridSize(),this.cols!==i||this.rows!==s){this.cells=this.createEmptyGrid();let r=Math.min(i,this.cols),n=Math.min(s,this.rows);for(let o=0;o<n;o++)for(let h=0;h<r;h++)this.cells[o][h]=a[o][h]}this.render()}isFixedGridMode(){return this.fixedGridMode}setDebugGridColor(t){this.debugGridColor=t}isDebugGridEnabled(){return this.showDebugGrid}async setImageFont(t,e,i,s,a,r){this.imageAtlas=new U({glyphWidth:e,glyphHeight:i,cellWidth:s,cellHeight:a,atlasBlocks:r}),await this.imageAtlas.loadFromPNG(t),this.cellWidth=s,this.cellHeight=a,this.calculateGridSize(),this.fixedGridMode||(this.calculateGridSize(),this.cells=this.createEmptyGrid()),this.render()}async setImageFontStructure(t,e,i,s,a){let r=this.imageAtlas;if(this.imageAtlas=new U({glyphWidth:t,glyphHeight:e,cellWidth:i,cellHeight:s,atlasBlocks:a}),this.imageAtlas.prepare(),r){let n=r.getCanvas();if(n&&r.getGlyphWidth()===t&&r.getGlyphHeight()===e){let h=this.imageAtlas.getCanvas()?.getContext("2d");if(h){let c=16*t,d=16*e;n.width>=c&&n.height>=d&&h.drawImage(n,0,0,c,d,0,0,c,d)}}}this.cellWidth=i,this.cellHeight=s,this.fixedGridMode||(this.calculateGridSize(),this.cells=this.createEmptyGrid())}async setImageFontBlock(t,e){if(!this.imageAtlas){console.warn("[Terminal2D] Cannot load block: no atlas initialized");return}await this.imageAtlas.loadBlock(t,e),this.render()}setPalette(t){this.paletteCache=t}convertColor(t,e){if(t==null||isNaN(t))return this.defaultFgColor;if(t===255)return"rgba(0, 0, 0, 0)";if(t<0||t>=e.length)return this.defaultFgColor;let i=e[t];return!i||typeof i.r!="number"?this.defaultFgColor:`rgba(${i.r}, ${i.g}, ${i.b}, ${i.a/255})`}renderDirect(t,e,i,s,a){for(let r=0;r<e&&r<this.rows;r++)for(let n=0;n<t&&n<this.cols;n++){let o=r*t+n;if(o>=i.length)break;let h=i[o];if(!h)continue;let c=this.convertColor(h.fgColorIndex,s),d=this.convertColor(h.bgColorIndex,s);this.setCell(n,r,h.char??" ",c,d)}this.render(a)}renderDisplayData(t){if(!t||!t.cells||t.cells.length===0){console.warn("[Terminal2D] Empty display data");return}if(t.width===0||t.height===0){console.warn("[Terminal2D] Invalid display dimensions:",t.width,t.height);return}(t.width!==this.cols||t.height!==this.rows)&&this.setFixedGrid(t.width,t.height,this.cellAspectRatio);let e=this.paletteCache??t.palette;if(!e||e.length===0){console.error("[Terminal2D] No palette available (neither cached nor in display)");return}if(t.passes&&t.passes.length>0)for(let i=0;i<t.passes.length;i++){let s=t.passes[i];this.renderDirect(t.width,t.height,s.cells,e,i===0)}else this.renderDirect(t.width,t.height,t.cells,e,!0)}isReady(){return!0}getCols(){return this.cols}getRows(){return this.rows}resize(t,e){this.setFixedGrid(t,e)}setScalingMode(t){if(this.scalingMode===t)return;let e=this.cols,i=this.rows;if(this.scalingMode=t,this.calculateGridSize(),this.cols!==e||this.rows!==i){let s=this.cells;if(this.cells=this.createEmptyGrid(),s&&s.length>0){let a=Math.min(e,this.cols),r=Math.min(i,this.rows);for(let n=0;n<r;n++)for(let o=0;o<a;o++)s[n]&&s[n][o]&&(this.cells[n][o]=s[n][o])}}this.render()}setCellSize(t,e){let i=Math.max(1,Math.min(255,Math.round(t))),s=Math.max(1,Math.min(255,Math.round(e)));if(this.cellWidth===i&&this.cellHeight===s)return;let a=this.cols,r=this.rows;if(this.cellWidth=i,this.cellHeight=s,this.customCellSize=!0,this.calculateGridSize(),this.cols!==a||this.rows!==r){let n=this.cells;if(this.cells=this.createEmptyGrid(),n&&n.length>0){let o=Math.min(a,this.cols),h=Math.min(r,this.rows);for(let c=0;c<h;c++)for(let d=0;d<o;d++)n[c]&&n[c][d]&&(this.cells[c][d]=n[c][d])}}this.render()}getCellSize(){return{cellWidth:this.cellWidth,cellHeight:this.cellHeight}}getAvailableSize(){return{width:this.parentElement.clientWidth,height:this.parentElement.clientHeight}}getMaxCells(){return 65536}destroy(){this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=void 0),this.gridOverlay&&(this.gridOverlay.destroy(),this.gridOverlay=void 0),this.containerDiv.parentElement&&this.containerDiv.parentElement.removeChild(this.containerDiv)}};p($,"Terminal2D");var W=$;var N=class N{constructor(t,e={}){l(this,"container");l(this,"overlayDiv",null);l(this,"button",null);l(this,"options");l(this,"started",!1);l(this,"onStartCallback");this.container=t,this.options={buttonText:e.buttonText??"Click to Start",onStart:e.onStart??(()=>{}),backgroundColor:e.backgroundColor??"rgba(0, 0, 0, 0.8)",buttonColor:e.buttonColor??"#4a90d9",buttonHoverColor:e.buttonHoverColor??"#357abd",buttonTextColor:e.buttonTextColor??"#ffffff",zIndex:e.zIndex??1e3},this.onStartCallback=e.onStart,this.createOverlay()}createOverlay(){let t=window.getComputedStyle(this.container).position;t!=="relative"&&t!=="absolute"&&t!=="fixed"&&(this.container.style.position="relative"),this.overlayDiv=document.createElement("div"),this.overlayDiv.className="utsp-autoplay-overlay",this.overlayDiv.style.cssText=`
160
160
  position: absolute !important;
161
161
  top: 0 !important;
162
162
  left: 0 !important;
@@ -180,7 +180,7 @@
180
180
  cursor: pointer !important;
181
181
  transition: background-color 0.2s ease, transform 0.1s ease !important;
182
182
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3) !important;
183
- `,this.button.addEventListener("mouseenter",()=>{this.button&&(this.button.style.backgroundColor=`${this.options.buttonHoverColor} !important`,this.button.style.transform="scale(1.05)")}),this.button.addEventListener("mouseleave",()=>{this.button&&(this.button.style.backgroundColor=`${this.options.buttonColor} !important`,this.button.style.transform="scale(1)")}),this.button.addEventListener("click",e=>{e.stopPropagation(),this.start()}),this.overlayDiv.addEventListener("click",()=>{this.start()}),this.overlayDiv.appendChild(this.button),this.container.appendChild(this.overlayDiv)}start(){this.started||(this.started=!0,this.overlayDiv&&(this.overlayDiv.style.transition="opacity 0.3s ease",this.overlayDiv.style.opacity="0",setTimeout(()=>{this.removeOverlay()},300)),this.onStartCallback&&this.onStartCallback())}isStarted(){return this.started}isVisible(){return this.overlayDiv!==null&&!this.started}removeOverlay(){this.overlayDiv&&this.overlayDiv.parentElement&&this.overlayDiv.parentElement.removeChild(this.overlayDiv),this.overlayDiv=null,this.button=null}setButtonText(t){this.options.buttonText=t,this.button&&(this.button.textContent=t)}setOnStart(t){this.onStartCallback=t}destroy(){this.removeOverlay(),this.started=!1}};v(q,"AutoplayOverlay");var z=q;var H=require("@utsp/types");var j=class j{constructor(t,e){l(this,"canvas");l(this,"ctx");l(this,"containerDiv");l(this,"parentElement");l(this,"resizeObserver");l(this,"width",0);l(this,"height",0);l(this,"currentConfig",null);l(this,"configHash","");this.parentElement=t,this.containerDiv=document.createElement("div"),this.containerDiv.className="postprocess-container",this.containerDiv.style.cssText=`
183
+ `,this.button.addEventListener("mouseenter",()=>{this.button&&(this.button.style.backgroundColor=`${this.options.buttonHoverColor} !important`,this.button.style.transform="scale(1.05)")}),this.button.addEventListener("mouseleave",()=>{this.button&&(this.button.style.backgroundColor=`${this.options.buttonColor} !important`,this.button.style.transform="scale(1)")}),this.button.addEventListener("click",e=>{e.stopPropagation(),this.start()}),this.overlayDiv.addEventListener("click",()=>{this.start()}),this.overlayDiv.appendChild(this.button),this.container.appendChild(this.overlayDiv)}start(){this.started||(this.started=!0,this.overlayDiv&&(this.overlayDiv.style.transition="opacity 0.3s ease",this.overlayDiv.style.opacity="0",setTimeout(()=>{this.removeOverlay()},300)),this.onStartCallback&&this.onStartCallback())}isStarted(){return this.started}isVisible(){return this.overlayDiv!==null&&!this.started}removeOverlay(){this.overlayDiv&&this.overlayDiv.parentElement&&this.overlayDiv.parentElement.removeChild(this.overlayDiv),this.overlayDiv=null,this.button=null}setButtonText(t){this.options.buttonText=t,this.button&&(this.button.textContent=t)}setOnStart(t){this.onStartCallback=t}destroy(){this.removeOverlay(),this.started=!1}};p(N,"AutoplayOverlay");var P=N;var L=require("@utsp/types");var Y=class Y{constructor(t,e){l(this,"canvas");l(this,"ctx");l(this,"containerDiv");l(this,"parentElement");l(this,"resizeObserver");l(this,"width",0);l(this,"height",0);l(this,"currentConfig",null);l(this,"configHash","");this.parentElement=t,this.containerDiv=document.createElement("div"),this.containerDiv.className="postprocess-container",this.containerDiv.style.cssText=`
184
184
  position: absolute !important;
185
185
  top: 0 !important;
186
186
  left: 0 !important;
@@ -198,5 +198,5 @@
198
198
  width: 100% !important;
199
199
  height: 100% !important;
200
200
  pointer-events: none !important;
201
- `;let i=this.canvas.getContext("2d",{alpha:!0});if(!i)throw new Error("PostProcessOverlay: Failed to get 2D context");this.ctx=i,this.containerDiv.appendChild(this.canvas),this.parentElement.appendChild(this.containerDiv),this.resizeObserver=new ResizeObserver(n=>{for(let r of n){let{width:a,height:o}=r.contentRect;a>0&&o>0&&this.handleResize(Math.floor(a),Math.floor(o))}}),this.resizeObserver.observe(this.parentElement);let s=this.parentElement.getBoundingClientRect();s.width>0&&s.height>0&&this.handleResize(Math.floor(s.width),Math.floor(s.height)),this.hide()}handleResize(t,e){this.width===t&&this.height===e||(this.width=t,this.height=e,this.canvas.width=t,this.canvas.height=e,this.currentConfig&&this.isActive()&&this.render())}setConfig(t){let e=this.hashConfig(t);if(e!==this.configHash){if(this.currentConfig=t,this.configHash=e,!t||!this.isActiveConfig(t)){this.clear(),this.hide();return}this.show(),this.render()}}setScanlines(t){t===null?this.setConfig({scanlines:{enabled:!1}}):this.setConfig({scanlines:t})}setScanlinesEnabled(t){if(t){let e=this.currentConfig?.scanlines;this.setScanlines({enabled:!0,opacity:e?.opacity??H.POST_PROCESS_DEFAULTS.scanlines.opacity,pattern:e?.pattern??"horizontal",spacing:e?.spacing??2,thickness:e?.thickness??1,color:e?.color??{r:0,g:0,b:0}})}else this.setScanlines({enabled:!1})}setScanlinesOpacity(t){let e=Math.max(0,Math.min(1,t)),i=this.currentConfig?.scanlines;this.setScanlines({enabled:i?.enabled??!0,opacity:e,pattern:i?.pattern??"horizontal",spacing:i?.spacing??2,thickness:i?.thickness??1,color:i?.color??{r:0,g:0,b:0}})}setScanlinesPattern(t){let e=this.currentConfig?.scanlines;this.setScanlines({enabled:e?.enabled??!0,opacity:e?.opacity??H.POST_PROCESS_DEFAULTS.scanlines.opacity,pattern:t,spacing:e?.spacing??2,thickness:e?.thickness??1,color:e?.color??{r:0,g:0,b:0}})}setScanlinesSpacing(t){let e=Math.max(2,Math.round(t)),i=this.currentConfig?.scanlines;this.setScanlines({enabled:i?.enabled??!0,opacity:i?.opacity??H.POST_PROCESS_DEFAULTS.scanlines.opacity,pattern:i?.pattern??"horizontal",spacing:e,thickness:i?.thickness??1,color:i?.color??{r:0,g:0,b:0}})}getConfig(){return this.currentConfig}isActive(){return this.isActiveConfig(this.currentConfig)}destroy(){this.resizeObserver.disconnect(),this.containerDiv.parentElement&&this.containerDiv.parentElement.removeChild(this.containerDiv)}syncWithRenderer(t){}resize(t,e){}setCellDimensions(t,e){}show(){this.containerDiv.style.display="block"}hide(){this.containerDiv.style.display="none"}clear(){this.ctx.clearRect(0,0,this.width,this.height)}isActiveConfig(t){return t?.scanlines?.enabled??!1}render(){this.clear(),this.currentConfig?.scanlines?.enabled&&this.renderScanlines(this.currentConfig.scanlines)}renderScanlines(t){let e=t.opacity??H.POST_PROCESS_DEFAULTS.scanlines.opacity,i=t.pattern??"horizontal",s=t.spacing??2,n=t.thickness??1,r=t.color??{r:0,g:0,b:0},a=this.ctx;switch(a.fillStyle=`rgba(${r.r}, ${r.g}, ${r.b}, ${e})`,i){case"horizontal":for(let o=s-1;o<this.height;o+=s)a.fillRect(0,o,this.width,n);break;case"vertical":for(let o=s-1;o<this.width;o+=s)a.fillRect(o,0,n,this.height);break;case"grid":for(let o=s-1;o<this.height;o+=s)a.fillRect(0,o,this.width,n);for(let o=s-1;o<this.width;o+=s)a.fillRect(o,0,n,this.height);break}}hashConfig(t){return t?JSON.stringify(t):"null"}};v(j,"PostProcessOverlay");var k=j;var Q="\x1B[0m",rt="\x1B[H",bt="\x1B[2J",nt="\x1B[?25l",pt="\x1B[?25h",vt=`
202
- `,Z=class Z{constructor(t={}){l(this,"options");l(this,"fgCache",[]);l(this,"bgCache",[]);l(this,"lastPalette",null);this.options={optimizeColors:t.optimizeColors??!0,includeHome:t.includeHome??!0,hideCursor:t.hideCursor??!0,includeNewlines:t.includeNewlines??!0,includeReset:t.includeReset??!0}}buildColorCache(t){if(this.lastPalette!==t){this.fgCache=new Array(t.length),this.bgCache=new Array(t.length);for(let e=0;e<t.length;e++){let i=t[e];this.fgCache[e]=`\x1B[38;2;${i.r};${i.g};${i.b}m`,this.bgCache[e]=`\x1B[48;2;${i.r};${i.g};${i.b}m`}this.lastPalette=t}}render(t){let{width:e,height:i,cells:s,palette:n}=t;this.buildColorCache(n);let r="";this.options.hideCursor&&(r+=nt),this.options.includeHome&&(r+=rt);let a=-1,o=-1,h=this.options.optimizeColors,c=this.options.includeNewlines;for(let d=0;d<i;d++){let f=d*e;for(let u=0;u<e;u++){let b=s[f+u],m=b.fgColorIndex,p=b.bgColorIndex;h?(p!==o&&(r+=this.bgCache[p],o=p),m!==a&&(r+=this.fgCache[m],a=m)):(r+=this.bgCache[p],r+=this.fgCache[m]),r+=b.char||" "}c&&d<i-1&&(r+=vt)}return this.options.includeReset&&(r+=Q),r}renderRow(t,e){let{width:i,cells:s,palette:n}=t;this.buildColorCache(n);let r=`\x1B[${e+1};1H`,a=-1,o=-1,h=this.options.optimizeColors,c=e*i;for(let d=0;d<i;d++){let f=s[c+d],u=f.fgColorIndex,b=f.bgColorIndex;h?(b!==o&&(r+=this.bgCache[b],o=b),u!==a&&(r+=this.fgCache[u],a=u)):(r+=this.bgCache[b],r+=this.fgCache[u]),r+=f.char||" "}return this.options.includeReset&&(r+=Q),r}clear(){return bt+rt}showCursor(){return pt}hideCursor(){return nt}reset(){return Q}moveTo(t,e){return`\x1B[${t+1};${e+1}H`}};v(Z,"TerminalANSI");var $=Z;function at(g){let t=g.startsWith("#")?g.slice(1):g,e=t.length===3?t[0]+t[0]+t[1]+t[1]+t[2]+t[2]:t,i=parseInt(e,16);return{r:i>>16&255,g:i>>8&255,b:i&255,a:255}}v(at,"hexToRGB");function ot(g){let t=g.r.toString(16).padStart(2,"0"),e=g.g.toString(16).padStart(2,"0"),i=g.b.toString(16).padStart(2,"0");return`#${t}${e}${i}`}v(ot,"rgbToHex");function lt(g,t){let e=[{r:0,g:0,b:0,a:255},{r:128,g:0,b:0,a:255},{r:0,g:128,b:0,a:255},{r:128,g:128,b:0,a:255},{r:0,g:0,b:128,a:255},{r:128,g:0,b:128,a:255},{r:0,g:128,b:128,a:255},{r:192,g:192,b:192,a:255},{r:128,g:128,b:128,a:255},{r:255,g:0,b:0,a:255},{r:0,g:255,b:0,a:255},{r:255,g:255,b:0,a:255},{r:0,g:0,b:255,a:255},{r:255,g:0,b:255,a:255},{r:0,g:255,b:255,a:255},{r:255,g:255,b:255,a:255}];for(;e.length<256;)e.push({r:128,g:128,b:128,a:255});let i=[];for(let s=0;s<t;s++)for(let n=0;n<g;n++)i.push({char:String.fromCharCode(65+(n+s)%26),fgColorIndex:15,bgColorIndex:(n+s)%16,fgEmission:0,bgEmission:0});return{id:0,width:g,height:t,cells:i,palette:e}}v(lt,"createTestRenderState");var Ct="0.1.0";
201
+ `;let i=this.canvas.getContext("2d",{alpha:!0});if(!i)throw new Error("PostProcessOverlay: Failed to get 2D context");this.ctx=i,this.containerDiv.appendChild(this.canvas),this.parentElement.appendChild(this.containerDiv),this.resizeObserver=new ResizeObserver(a=>{for(let r of a){let{width:n,height:o}=r.contentRect;n>0&&o>0&&this.handleResize(Math.floor(n),Math.floor(o))}}),this.resizeObserver.observe(this.parentElement);let s=this.parentElement.getBoundingClientRect();s.width>0&&s.height>0&&this.handleResize(Math.floor(s.width),Math.floor(s.height)),this.hide()}handleResize(t,e){this.width===t&&this.height===e||(this.width=t,this.height=e,this.canvas.width=t,this.canvas.height=e,this.currentConfig&&this.isActive()&&this.render())}setConfig(t){let e=this.hashConfig(t);if(e!==this.configHash){if(this.currentConfig=t,this.configHash=e,!t||!this.isActiveConfig(t)){this.clear(),this.hide();return}this.show(),this.render()}}setScanlines(t){t===null?this.setConfig({scanlines:{enabled:!1}}):this.setConfig({scanlines:t})}setScanlinesEnabled(t){if(t){let e=this.currentConfig?.scanlines;this.setScanlines({enabled:!0,opacity:e?.opacity??L.POST_PROCESS_DEFAULTS.scanlines.opacity,pattern:e?.pattern??"horizontal",spacing:e?.spacing??2,thickness:e?.thickness??1,color:e?.color??{r:0,g:0,b:0}})}else this.setScanlines({enabled:!1})}setScanlinesOpacity(t){let e=Math.max(0,Math.min(1,t)),i=this.currentConfig?.scanlines;this.setScanlines({enabled:i?.enabled??!0,opacity:e,pattern:i?.pattern??"horizontal",spacing:i?.spacing??2,thickness:i?.thickness??1,color:i?.color??{r:0,g:0,b:0}})}setScanlinesPattern(t){let e=this.currentConfig?.scanlines;this.setScanlines({enabled:e?.enabled??!0,opacity:e?.opacity??L.POST_PROCESS_DEFAULTS.scanlines.opacity,pattern:t,spacing:e?.spacing??2,thickness:e?.thickness??1,color:e?.color??{r:0,g:0,b:0}})}setScanlinesSpacing(t){let e=Math.max(2,Math.round(t)),i=this.currentConfig?.scanlines;this.setScanlines({enabled:i?.enabled??!0,opacity:i?.opacity??L.POST_PROCESS_DEFAULTS.scanlines.opacity,pattern:i?.pattern??"horizontal",spacing:e,thickness:i?.thickness??1,color:i?.color??{r:0,g:0,b:0}})}getConfig(){return this.currentConfig}isActive(){return this.isActiveConfig(this.currentConfig)}destroy(){this.resizeObserver.disconnect(),this.containerDiv.parentElement&&this.containerDiv.parentElement.removeChild(this.containerDiv)}syncWithRenderer(t){}resize(t,e){}setCellDimensions(t,e){}show(){this.containerDiv.style.display="block"}hide(){this.containerDiv.style.display="none"}clear(){this.ctx.clearRect(0,0,this.width,this.height)}isActiveConfig(t){return t?.scanlines?.enabled??!1}render(){this.clear(),this.currentConfig?.scanlines?.enabled&&this.renderScanlines(this.currentConfig.scanlines)}renderScanlines(t){let e=t.opacity??L.POST_PROCESS_DEFAULTS.scanlines.opacity,i=t.pattern??"horizontal",s=t.spacing??2,a=t.thickness??1,r=t.color??{r:0,g:0,b:0},n=this.ctx;switch(n.fillStyle=`rgba(${r.r}, ${r.g}, ${r.b}, ${e})`,i){case"horizontal":for(let o=s-1;o<this.height;o+=s)n.fillRect(0,o,this.width,a);break;case"vertical":for(let o=s-1;o<this.width;o+=s)n.fillRect(o,0,a,this.height);break;case"grid":for(let o=s-1;o<this.height;o+=s)n.fillRect(0,o,this.width,a);for(let o=s-1;o<this.width;o+=s)n.fillRect(o,0,a,this.height);break}}hashConfig(t){return t?JSON.stringify(t):"null"}};p(Y,"PostProcessOverlay");var H=Y;var X="\x1B[0m",it="\x1B[H",mt="\x1B[2J",st="\x1B[?25l",gt="\x1B[?25h",bt=`
202
+ `,V=class V{constructor(t={}){l(this,"options");l(this,"fgCache",[]);l(this,"bgCache",[]);l(this,"lastPalette",null);this.options={optimizeColors:t.optimizeColors??!0,includeHome:t.includeHome??!0,hideCursor:t.hideCursor??!0,includeNewlines:t.includeNewlines??!0,includeReset:t.includeReset??!0}}buildColorCache(t){if(this.lastPalette!==t){this.fgCache=new Array(t.length),this.bgCache=new Array(t.length);for(let e=0;e<t.length;e++){let i=t[e];this.fgCache[e]=`\x1B[38;2;${i.r};${i.g};${i.b}m`,this.bgCache[e]=`\x1B[48;2;${i.r};${i.g};${i.b}m`}this.lastPalette=t}}render(t){let{width:e,height:i,cells:s,palette:a}=t;this.buildColorCache(a);let r="";this.options.hideCursor&&(r+=st),this.options.includeHome&&(r+=it);let n=-1,o=-1,h=this.options.optimizeColors,c=this.options.includeNewlines;for(let d=0;d<i;d++){let u=d*e;for(let m=0;m<e;m++){let b=s[u+m],g=b.fgColorIndex,v=b.bgColorIndex;h?(v!==o&&(r+=this.bgCache[v],o=v),g!==n&&(r+=this.fgCache[g],n=g)):(r+=this.bgCache[v],r+=this.fgCache[g]),r+=b.char||" "}c&&d<i-1&&(r+=bt)}return this.options.includeReset&&(r+=X),r}renderRow(t,e){let{width:i,cells:s,palette:a}=t;this.buildColorCache(a);let r=`\x1B[${e+1};1H`,n=-1,o=-1,h=this.options.optimizeColors,c=e*i;for(let d=0;d<i;d++){let u=s[c+d],m=u.fgColorIndex,b=u.bgColorIndex;h?(b!==o&&(r+=this.bgCache[b],o=b),m!==n&&(r+=this.fgCache[m],n=m)):(r+=this.bgCache[b],r+=this.fgCache[m]),r+=u.char||" "}return this.options.includeReset&&(r+=X),r}clear(){return mt+it}showCursor(){return gt}hideCursor(){return st}reset(){return X}moveTo(t,e){return`\x1B[${t+1};${e+1}H`}};p(V,"TerminalANSI");var O=V;function rt(f){let t=f.startsWith("#")?f.slice(1):f,e=t.length===3?t[0]+t[0]+t[1]+t[1]+t[2]+t[2]:t,i=parseInt(e,16);return{r:i>>16&255,g:i>>8&255,b:i&255,a:255}}p(rt,"hexToRGB");function nt(f){let t=f.r.toString(16).padStart(2,"0"),e=f.g.toString(16).padStart(2,"0"),i=f.b.toString(16).padStart(2,"0");return`#${t}${e}${i}`}p(nt,"rgbToHex");function at(f,t){let e=[{r:0,g:0,b:0,a:255},{r:128,g:0,b:0,a:255},{r:0,g:128,b:0,a:255},{r:128,g:128,b:0,a:255},{r:0,g:0,b:128,a:255},{r:128,g:0,b:128,a:255},{r:0,g:128,b:128,a:255},{r:192,g:192,b:192,a:255},{r:128,g:128,b:128,a:255},{r:255,g:0,b:0,a:255},{r:0,g:255,b:0,a:255},{r:255,g:255,b:0,a:255},{r:0,g:0,b:255,a:255},{r:255,g:0,b:255,a:255},{r:0,g:255,b:255,a:255},{r:255,g:255,b:255,a:255}];for(;e.length<256;)e.push({r:128,g:128,b:128,a:255});let i=[];for(let s=0;s<t;s++)for(let a=0;a<f;a++)i.push({char:String.fromCharCode(65+(a+s)%26),fgColorIndex:15,bgColorIndex:(a+s)%16,fgEmission:0,bgEmission:0});return{id:0,width:f,height:t,cells:i,palette:e}}p(at,"createTestRenderState");var pt="0.1.0";