textmode.js 0.1.4-beta.2 → 0.1.4-beta.3

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.
@@ -1,10 +1,10 @@
1
- (function(v,p){typeof exports=="object"&&typeof module<"u"?p(exports):typeof define=="function"&&define.amd?define(["exports"],p):(v=typeof globalThis<"u"?globalThis:v||self,p(v.textmode={}))})(this,function(v){"use strict";var Ne=Object.defineProperty;var We=(v,p,E)=>p in v?Ne(v,p,{enumerable:!0,configurable:!0,writable:!0,value:E}):v[p]=E;var o=(v,p,E)=>We(v,typeof p!="symbol"?p+"":p,E);class p extends Error{constructor(t,r,i={}){const s=p.createFormattedMessage(t,i);super(s);o(this,"originalError");o(this,"context");this.name="TextmodeError",this.originalError=r,this.context=i}static createFormattedMessage(t,r){let i=t;if(r&&Object.keys(r).length>0){i+=`
1
+ (function(v,p){typeof exports=="object"&&typeof module<"u"?p(exports):typeof define=="function"&&define.amd?define(["exports"],p):(v=typeof globalThis<"u"?globalThis:v||self,p(v.textmode={}))})(this,function(v){"use strict";var Ne=Object.defineProperty;var We=(v,p,E)=>p in v?Ne(v,p,{enumerable:!0,configurable:!0,writable:!0,value:E}):v[p]=E;var a=(v,p,E)=>We(v,typeof p!="symbol"?p+"":p,E);class p extends Error{constructor(t,r,i={}){const s=p.createFormattedMessage(t,i);super(s);a(this,"originalError");a(this,"context");this.name="TextmodeError",this.originalError=r,this.context=i}static createFormattedMessage(t,r){let i=t;if(r&&Object.keys(r).length>0){i+=`
2
2
 
3
- 📋 Context:`;for(const[s,n]of Object.entries(r)){const a=p.formatValue(n);i+=`
4
- - ${s}: ${a}`}}return i+=`
3
+ 📋 Context:`;for(const[s,n]of Object.entries(r)){const o=p.formatValue(n);i+=`
4
+ - ${s}: ${o}`}}return i+=`
5
5
 
6
6
  `,i+="↓".repeat(24)+`
7
- `,i}static formatValue(t){if(t===null)return"null";if(t===void 0)return"undefined";if(typeof t=="string")return`"${t}"`;if(typeof t=="number"||typeof t=="boolean")return String(t);if(Array.isArray(t))return t.length===0?"[]":t.length<=5?`[${t.map(r=>p.formatValue(r)).join(", ")}]`:`[${t.slice(0,3).map(r=>p.formatValue(r)).join(", ")}, ... +${t.length-3} more]`;if(typeof t=="object"){const r=Object.keys(t);return r.length===0?"{}":r.length<=3?`{ ${r.map(n=>`${n}: ${p.formatValue(t[n])}`).join(", ")} }`:`{ ${r.slice(0,2).map(s=>`${s}: ${p.formatValue(t[s])}`).join(", ")}, ... +${r.length-2} more }`}return String(t)}}var E=(h=>(h[h.SILENT=0]="SILENT",h[h.WARNING=1]="WARNING",h[h.ERROR=2]="ERROR",h[h.THROW=3]="THROW",h))(E||{});const U=class U{constructor(){o(this,"_options",{globalLevel:3})}static getInstance(){return U._instance||(U._instance=new U),U._instance}_handle(e,t,r){const i="[textmode.js]";switch(this._options.globalLevel){case 0:return!1;case 1:return console.group(`%c${i} Oops! (╯°□°)╯︵ Something went wrong in your code.`,"color: #f44336; font-weight: bold; background: #ffebee; padding: 2px 6px; border-radius: 3px;"),console.warn(p.createFormattedMessage(e,t)),console.groupEnd(),!1;case 2:return console.group(`%c${i} Oops! (╯°□°)╯︵ Something went wrong in your code.`,"color: #f44336; font-weight: bold; background: #ffebee; padding: 2px 6px; border-radius: 3px;"),console.error(p.createFormattedMessage(e,t)),console.groupEnd(),!1;case 3:default:const s=new p(e,r,t);throw console.group(`%c${i} Oops! (╯°□°)╯︵ Something went wrong in your code.`,"color: #d32f2f; font-weight: bold; background: #ffcdd2; padding: 2px 6px; border-radius: 3px;"),s}}validate(e,t,r){return e?!0:(this._handle(t,r),!1)}setGlobalLevel(e){this._options.globalLevel=e}};o(U,"_instance",null);let V=U;const b=V.getInstance();class ie{constructor(e,t,r=t,i={}){o(this,"gl");o(this,"_framebuffer");o(this,"_texture");o(this,"_width");o(this,"_height");o(this,"options");o(this,"previousState",null);o(this,"_pixels",null);this.gl=e,this._width=t,this._height=r,this.options={filter:"nearest",wrap:"clamp",format:"rgba",type:"unsigned_byte",...i},this._texture=this.createTexture(),this._framebuffer=e.createFramebuffer(),this.attachTexture()}createTexture(){const{gl:e}=this,t=e.createTexture();e.bindTexture(e.TEXTURE_2D,t);const r=this.options.filter==="linear"?e.LINEAR:e.NEAREST,i=this.options.wrap==="repeat"?e.REPEAT:e.CLAMP_TO_EDGE;return e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,r),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,r),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,i),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,i),this.updateTextureSize(),t}updateTextureSize(){const{gl:e}=this,t=e.RGBA,r=e.RGBA,i=this.options.type==="float"?e.FLOAT:e.UNSIGNED_BYTE;e.texImage2D(e.TEXTURE_2D,0,t,this._width,this._height,0,r,i,null)}attachTexture(){const{gl:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this._framebuffer),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this._texture,0),e.bindFramebuffer(e.FRAMEBUFFER,null)}update(e){const{gl:t}=this;e instanceof HTMLVideoElement&&e.readyState<2||(t.bindTexture(t.TEXTURE_2D,this._texture),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),t.bindTexture(t.TEXTURE_2D,null))}updatePixels(e,t,r){const{gl:i}=this;i.bindTexture(i.TEXTURE_2D,this._texture),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,t,r,0,i.RGBA,i.UNSIGNED_BYTE,e),i.bindTexture(i.TEXTURE_2D,null)}resize(e,t){const{gl:r}=this;this._width=e,this._height=t,r.bindTexture(r.TEXTURE_2D,this._texture),this.updateTextureSize(),r.bindTexture(r.TEXTURE_2D,null)}begin(){const{gl:e}=this;this.previousState={framebuffer:e.getParameter(e.FRAMEBUFFER_BINDING),viewport:e.getParameter(e.VIEWPORT)},e.bindFramebuffer(e.FRAMEBUFFER,this._framebuffer),e.viewport(0,0,this._width,this._height)}end(){if(!this.previousState)return;const{gl:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.previousState.framebuffer),e.viewport(...this.previousState.viewport),this.previousState=null}loadPixels(){const{gl:e}=this;this._pixels||(this._pixels=new Uint8Array(this._width*this._height*4));const t=e.getParameter(e.FRAMEBUFFER_BINDING);e.bindFramebuffer(e.FRAMEBUFFER,this._framebuffer),e.readPixels(0,0,this._width,this._height,e.RGBA,e.UNSIGNED_BYTE,this._pixels),e.bindFramebuffer(e.FRAMEBUFFER,t)}get(e,t,r,i){const{gl:s}=this;if(e===void 0&&t===void 0){const n=new Uint8Array(this._width*this._height*4),a=s.getParameter(s.FRAMEBUFFER_BINDING);return s.bindFramebuffer(s.FRAMEBUFFER,this._framebuffer),s.readPixels(0,0,this._width,this._height,s.RGBA,s.UNSIGNED_BYTE,n),s.bindFramebuffer(s.FRAMEBUFFER,a),n}else if(r===void 0&&i===void 0){(e<0||t<0||e>=this._width||t>=this._height)&&(console.warn("The x and y values passed to Framebuffer.get are outside of its range and will be clamped."),e=Math.max(0,Math.min(e,this._width-1)),t=Math.max(0,Math.min(t,this._height-1)));const n=new Uint8Array(4),a=s.getParameter(s.FRAMEBUFFER_BINDING);return s.bindFramebuffer(s.FRAMEBUFFER,this._framebuffer),s.readPixels(e,t,1,1,s.RGBA,s.UNSIGNED_BYTE,n),s.bindFramebuffer(s.FRAMEBUFFER,a),[n[0],n[1],n[2],n[3]]}else{e=Math.max(0,Math.min(e,this._width-1)),t=Math.max(0,Math.min(t,this._height-1)),r=Math.max(1,Math.min(r,this._width-e)),i=Math.max(1,Math.min(i,this._height-t));const n=new Uint8Array(r*i*4),a=s.getParameter(s.FRAMEBUFFER_BINDING);return s.bindFramebuffer(s.FRAMEBUFFER,this._framebuffer),s.readPixels(e,t,r,i,s.RGBA,s.UNSIGNED_BYTE,n),s.bindFramebuffer(s.FRAMEBUFFER,a),n}}dispose(){const{gl:e}=this;this._framebuffer&&(e.deleteFramebuffer(this._framebuffer),this._framebuffer=null),this._texture&&(e.deleteTexture(this._texture),this._texture=null),this._pixels=null}get isDisposed(){return this._framebuffer===null||this._texture===null}get framebuffer(){return this._framebuffer}get texture(){return this._texture}get width(){return this._width}get height(){return this._height}get pixels(){return this._pixels}}class j{constructor(e,t,r){o(this,"gl");o(this,"x");o(this,"y");this.gl=e,this.x=t,this.y=r}}class M{constructor(e,t,r,i,s){o(this,"gl");o(this,"vertexBuffer");o(this,"vertexCount",6);o(this,"bytesPerVertex");this.gl=e,this.bytesPerVertex=16;const n=e.getParameter(e.VIEWPORT),a=n[2],l=n[3],c=e.getParameter(e.FRAMEBUFFER_BINDING)!==null,u=t/a*2-1,d=(t+i)/a*2-1;let f,g;c?(f=r/l*2-1,g=(r+s)/l*2-1):(f=1-r/l*2,g=1-(r+s)/l*2);let x,_,F,w;x=u,F=d,_=f,w=g;const C=this.generateVertices(x,_,F,w);this.vertexBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer),e.bufferData(e.ARRAY_BUFFER,C,e.STATIC_DRAW)}generateVertices(e,t,r,i){return new Float32Array([e,i,0,1,r,i,1,1,e,t,0,0,e,t,0,0,r,i,1,1,r,t,1,0])}render(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer);const e=this.gl.getParameter(this.gl.CURRENT_PROGRAM);let t=this.gl.getAttribLocation(e,"a_position"),r=this.gl.getAttribLocation(e,"a_texCoord");this.gl.enableVertexAttribArray(t),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,this.bytesPerVertex,0),this.gl.enableVertexAttribArray(r),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,this.bytesPerVertex,8),this.gl.drawArrays(this.gl.TRIANGLES,0,this.vertexCount),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r)}}class se extends j{constructor(t,r,i,s,n){super(t,r,i);o(this,"width");o(this,"height");this.width=s,this.height=n}renderFill(){new M(this.gl,this.x,this.y,this.width,this.height).render()}renderStroke(t){if(t<=0)return;const r=new M(this.gl,this.x,this.y,this.width,t),i=new M(this.gl,this.x+this.width-t,this.y,t,this.height),s=new M(this.gl,this.x,this.y+this.height-t,this.width,t),n=new M(this.gl,this.x,this.y,t,this.height);r.render(),i.render(),s.render(),n.render()}}class ne{constructor(e,t,r,i,s,n){o(this,"gl");o(this,"vertexBuffer");o(this,"vertexCount",6);o(this,"bytesPerVertex");this.gl=e,this.bytesPerVertex=16;const a=e.getParameter(e.VIEWPORT),l=a[2],c=a[3],u=e.getParameter(e.FRAMEBUFFER_BINDING)!==null,d=i-t,f=s-r,g=Math.sqrt(d*d+f*f);if(g===0){const Oe=this.generateVertices(0,0,0,0);this.vertexBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer),e.bufferData(e.ARRAY_BUFFER,Oe,e.STATIC_DRAW);return}const x=d/g,F=-(f/g),w=x,C=n/2,y=t+F*C,B=r+w*C,D=t-F*C,R=r-w*C,H=i+F*C,G=s+w*C,ke=i-F*C,re=s-w*C,ze=y/l*2-1,$e=D/l*2-1,Le=H/l*2-1,Xe=ke/l*2-1;let O,N,W,Y;u?(O=B/c*2-1,N=R/c*2-1,W=G/c*2-1,Y=re/c*2-1):(O=1-B/c*2,N=1-R/c*2,W=1-G/c*2,Y=1-re/c*2);const He=this.generateLineVertices(ze,O,$e,N,Le,W,Xe,Y);this.vertexBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer),e.bufferData(e.ARRAY_BUFFER,He,e.STATIC_DRAW)}generateVertices(e,t,r,i){return new Float32Array([e,i,0,1,r,i,1,1,e,t,0,0,e,t,0,0,r,i,1,1,r,t,1,0])}generateLineVertices(e,t,r,i,s,n,a,l){return new Float32Array([e,t,0,0,r,i,0,1,s,n,1,0,r,i,0,1,a,l,1,1,s,n,1,0])}render(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer);const e=this.gl.getParameter(this.gl.CURRENT_PROGRAM);let t=this.gl.getAttribLocation(e,"a_position"),r=this.gl.getAttribLocation(e,"a_texCoord");this.gl.enableVertexAttribArray(t),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,this.bytesPerVertex,0),this.gl.enableVertexAttribArray(r),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,this.bytesPerVertex,8),this.gl.drawArrays(this.gl.TRIANGLES,0,this.vertexCount),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r)}}class ae extends j{constructor(t,r,i,s,n){super(t,r,i);o(this,"x2");o(this,"y2");this.x2=s,this.y2=n}renderFill(){}renderStroke(t){if(t<=0)return;new ne(this.gl,this.x,this.y,this.x2,this.y2,t).render()}}class T{constructor(e,t,r){o(this,"gl");o(this,"program");o(this,"uniformLocations",new Map);o(this,"attributeLocations",new Map);o(this,"textureUnitCounter",0);this.gl=e,this.program=this.createProgram(t,r),this.cacheLocations()}createProgram(e,t){const r=this.createShader(this.gl.VERTEX_SHADER,e),i=this.createShader(this.gl.FRAGMENT_SHADER,t),s=this.gl.createProgram();if(this.gl.attachShader(s,r),this.gl.attachShader(s,i),this.gl.linkProgram(s),!this.gl.getProgramParameter(s,this.gl.LINK_STATUS)){const n=this.gl.getProgramInfoLog(s);throw new Error(`Shader program link error: ${n}`)}return this.gl.deleteShader(r),this.gl.deleteShader(i),s}createShader(e,t){const r=this.gl.createShader(e);if(this.gl.shaderSource(r,t),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS)){const i=this.gl.getShaderInfoLog(r);throw this.gl.deleteShader(r),new Error(`Shader compilation error: ${i}`)}return r}cacheLocations(){const e=this.gl.getProgramParameter(this.program,this.gl.ACTIVE_UNIFORMS);for(let r=0;r<e;r++){const i=this.gl.getActiveUniform(this.program,r);if(i){const s=this.gl.getUniformLocation(this.program,i.name);s&&this.uniformLocations.set(i.name,s)}}const t=this.gl.getProgramParameter(this.program,this.gl.ACTIVE_ATTRIBUTES);for(let r=0;r<t;r++){const i=this.gl.getActiveAttrib(this.program,r);if(i){const s=this.gl.getAttribLocation(this.program,i.name);this.attributeLocations.set(i.name,s)}}}use(){this.gl.useProgram(this.program),this.resetTextureUnits()}setUniform(e,t){const r=this.uniformLocations.get(e);if(!r)return;const i=this.getUniformInfo(e);if(typeof t=="number")i&&i.type===this.gl.INT?this.gl.uniform1i(r,Math.floor(t)):this.gl.uniform1f(r,t);else if(typeof t=="boolean")this.gl.uniform1i(r,t?1:0);else if(Array.isArray(t))if(i&&(i.type===this.gl.INT_VEC2||i.type===this.gl.INT_VEC3||i.type===this.gl.INT_VEC4)){const s=t.map(n=>Math.floor(n));switch(s.length){case 2:this.gl.uniform2iv(r,s);break;case 3:this.gl.uniform3iv(r,s);break;case 4:this.gl.uniform4iv(r,s);break;default:console.warn(`Unsupported array length ${s.length} for uniform '${e}'`)}}else switch(t.length){case 2:this.gl.uniform2f(r,t[0],t[1]);break;case 3:this.gl.uniform3f(r,t[0],t[1],t[2]);break;case 4:this.gl.uniform4f(r,t[0],t[1],t[2],t[3]);break;default:console.warn(`Unsupported array length ${t.length} for uniform '${e}'`)}else if(t instanceof WebGLTexture){const s=this.getNextTextureUnit();this.gl.uniform1i(r,s),this.gl.activeTexture(this.gl.TEXTURE0+s),this.gl.bindTexture(this.gl.TEXTURE_2D,t)}else if(t&&typeof t=="object"&&"texture"in t){const s=this.getNextTextureUnit();this.gl.uniform1i(r,s),this.gl.activeTexture(this.gl.TEXTURE0+s),this.gl.bindTexture(this.gl.TEXTURE_2D,t.texture)}else console.warn(`Unsupported uniform type for '${e}':`,typeof t)}getUniformInfo(e){const t=this.gl.getProgramParameter(this.program,this.gl.ACTIVE_UNIFORMS);for(let r=0;r<t;r++){const i=this.gl.getActiveUniform(this.program,r);if(i&&i.name===e)return i}return null}getNextTextureUnit(){return this.textureUnitCounter++}hasUniform(e){return this.uniformLocations.has(e)}hasAttribute(e){return this.attributeLocations.has(e)}get glProgram(){return this.program}dispose(){this.program&&(this.gl.deleteProgram(this.program),this.program=null),this.uniformLocations.clear(),this.attributeLocations.clear(),this.textureUnitCounter=0}get isDisposed(){return this.program===null}resetTextureUnits(){this.textureUnitCounter=0}}var S="attribute vec2 a_position;attribute vec2 a_texCoord;varying vec2 v_uv;uniform float u_rotation;uniform vec2 u_center;uniform float u_aspectRatio;mat2 rotate2D(float angle){float s=sin(angle);float c=cos(angle);return mat2(c,-s,s,c);}void main(){v_uv=a_texCoord;vec2 pos=a_position;pos-=u_center;pos.x*=u_aspectRatio;pos=rotate2D(-u_rotation)*pos;pos.x/=u_aspectRatio;pos+=u_center;gl_Position=vec4(pos,0.0,1.0);}",oe="precision lowp float;uniform sampler2D u_texture;varying vec2 v_uv;void main(){gl_FragColor=texture2D(u_texture,v_uv);}",he="precision lowp float;uniform vec4 u_color;void main(){gl_FragColor=u_color;}";class le{constructor(e){o(this,"gl");o(this,"imageShader");o(this,"solidColorShader");o(this,"currentShader",null);o(this,"currentFillColor",[1,1,1,1]);o(this,"fillMode",!0);o(this,"currentStrokeColor",[0,0,0,1]);o(this,"currentStrokeWeight",1);o(this,"strokeMode",!0);o(this,"currentRotation",0);o(this,"stateStack",[]);this.gl=e,this.imageShader=new T(this.gl,S,oe),this.solidColorShader=new T(this.gl,S,he),this.gl.enable(this.gl.BLEND),this.gl.blendEquation(this.gl.FUNC_ADD),this.gl.blendFunc(this.gl.ONE,this.gl.ONE_MINUS_SRC_ALPHA)}shader(e){this.currentShader=e,e.use()}fill(e,t,r,i){if(this.fillMode=!0,t===void 0&&r===void 0&&i===void 0){const s=e/255;this.currentFillColor=[s,s,s,1]}else if(r!==void 0&&i===void 0)this.currentFillColor=[e/255,t/255,r/255,1];else if(r!==void 0&&i!==void 0)this.currentFillColor=[e/255,t/255,r/255,i/255];else throw new Error("Invalid fill parameters. Use fill(gray), fill(r,g,b), or fill(r,g,b,a)")}stroke(e,t,r,i){if(this.strokeMode=!0,t===void 0&&r===void 0&&i===void 0){const s=e/255;this.currentStrokeColor=[s,s,s,1]}else if(r!==void 0&&i===void 0)this.currentStrokeColor=[e/255,t/255,r/255,1];else if(r!==void 0&&i!==void 0)this.currentStrokeColor=[e/255,t/255,r/255,i/255];else throw new Error("Invalid stroke parameters. Use stroke(gray), stroke(r,g,b), or stroke(r,g,b,a)")}strokeWeight(e){if(e<0)throw new Error("Stroke weight must be non-negative");this.currentStrokeWeight=e}noStroke(){this.strokeMode=!1}noFill(){this.fillMode=!1}rotate(e){this.currentRotation=e}push(){this.stateStack.push({fillColor:[...this.currentFillColor],fillMode:this.fillMode,strokeColor:[...this.currentStrokeColor],strokeWeight:this.currentStrokeWeight,strokeMode:this.strokeMode,rotation:this.currentRotation})}pop(){const e=this.stateStack.pop();e?(this.currentFillColor=e.fillColor,this.fillMode=e.fillMode,this.currentStrokeColor=e.strokeColor,this.currentStrokeWeight=e.strokeWeight,this.strokeMode=e.strokeMode,this.currentRotation=e.rotation):console.warn("pop() called without matching push()")}reset(){this.currentShader=null,this.stateStack=[],this.currentRotation=0,this.fillMode=!0,this.strokeMode=!0,this.currentFillColor=[1,1,1,1],this.currentStrokeColor=[0,0,0,1],this.currentStrokeWeight=1}createShader(e,t){return new T(this.gl,e,t)}setUniform(e,t){this.currentShader.setUniform(e,t)}rect(e,t,r,i){const s=new se(this.gl,e,t,r,i);if(this.currentShader!==null){if(this.currentRotation!==0){const{centerX:d,centerY:f,radians:g,aspectRatio:x}=this.calculateRotationParams(e,t,r,i);this.setUniform("u_rotation",g),this.setUniform("u_center",[d,f]),this.setUniform("u_aspectRatio",x)}else this.setUniform("u_rotation",0),this.setUniform("u_center",[0,0]),this.setUniform("u_aspectRatio",1);s.renderFill(),this.currentShader=null;return}const n=this.solidColorShader,{centerX:a,centerY:l,radians:c,aspectRatio:u}=this.calculateRotationParams(e,t,r,i);this.fillMode&&(this.shader(n),this.setUniform("u_color",this.currentFillColor),this.setUniform("u_rotation",c),this.setUniform("u_center",[a,l]),this.setUniform("u_aspectRatio",u),s.renderFill()),this.strokeMode&&(this.shader(n),this.setUniform("u_color",this.currentStrokeColor),this.setUniform("u_rotation",c),this.setUniform("u_center",[a,l]),this.setUniform("u_aspectRatio",u),s.renderStroke(this.currentStrokeWeight)),this.currentShader=null}line(e,t,r,i){if(!this.strokeMode)return;const s=new ae(this.gl,e,t,r,i);if(this.currentShader!==null){if(this.currentRotation!==0){const _=(e+r)/2,F=(t+i)/2,w=Math.abs(r-e),C=Math.abs(i-t),{centerX:y,centerY:B,radians:D,aspectRatio:R}=this.calculateRotationParams(_-w/2,F-C/2,w,C);this.setUniform("u_rotation",D),this.setUniform("u_center",[y,B]),this.setUniform("u_aspectRatio",R)}else this.setUniform("u_rotation",0),this.setUniform("u_center",[0,0]),this.setUniform("u_aspectRatio",1);s.renderStroke(this.currentStrokeWeight),this.currentShader=null;return}const n=this.solidColorShader,a=(e+r)/2,l=(t+i)/2,c=Math.abs(r-e),u=Math.abs(i-t),{centerX:d,centerY:f,radians:g,aspectRatio:x}=this.calculateRotationParams(a-c/2,l-u/2,c,u);this.shader(n),this.setUniform("u_color",this.currentStrokeColor),this.setUniform("u_rotation",g),this.setUniform("u_center",[d,f]),this.setUniform("u_aspectRatio",x),s.renderStroke(this.currentStrokeWeight),this.currentShader=null}calculateRotationParams(e,t,r,i){const s=this.gl.getParameter(this.gl.VIEWPORT),n=s[2],a=s[3],l=n/a,c=this.gl.getParameter(this.gl.FRAMEBUFFER_BINDING)!==null,u=e+r/2,d=t+i/2,f=u/n*2-1;let g;c?g=d/a*2-1:g=1-d/a*2;const x=this.currentRotation*Math.PI/180;return{centerX:f,centerY:g,radians:x,aspectRatio:l}}createFramebuffer(e,t,r={}){return new ie(this.gl,e,t,r)}background(e,t=e,r=e,i=255){this.clear(e/255,t/255,r/255,i/255)}clear(e=0,t=0,r=0,i=0){this.gl.clearColor(e,t,r,i),this.gl.clear(this.gl.COLOR_BUFFER_BIT)}resetViewport(){this.gl.viewport(0,0,this.gl.canvas.width,this.gl.canvas.height)}get context(){return this.gl}dispose(){this.imageShader&&!this.imageShader.isDisposed&&this.imageShader.dispose(),this.solidColorShader&&!this.solidColorShader.isDisposed&&this.solidColorShader.dispose(),this.imageShader=null,this.solidColorShader=null,this.currentShader=null,this.stateStack=[]}get isDisposed(){return this.imageShader===null||this.solidColorShader===null}image(e,t,r,i,s){this.shader(this.imageShader),this.setUniform("u_texture",e.texture);const{centerX:n,centerY:a,radians:l,aspectRatio:c}=this.calculateRotationParams(t,r,i??e.width,s??e.height);this.setUniform("u_rotation",l),this.setUniform("u_center",[n,a]),this.setUniform("u_aspectRatio",c),this.rect(t,r,i??e.width,s??e.height)}}var m={};m.parse=function(h){var e=function(s,n,a,l){var c=m.T,u={cmap:c.cmap,head:c.head,hhea:c.hhea,maxp:c.maxp,hmtx:c.hmtx,loca:c.loca,glyf:c.glyf},d={_data:s,_index:n,_offset:a};for(var f in u){var g=m.findTable(s,f,a);if(g){var x=g[0],_=l[x];_==null&&(_=u[f].parseTab(s,x,g[1],d)),d[f]=l[x]=_}}return d},t=new Uint8Array(h),r={},i=e(t,0,0,r);return[i]},m.findTable=function(h,e,t){for(var r=m.B,i=r.readUshort(h,t+4),s=t+12,n=0;n<i;n++){var a=r.readASCII(h,s,4);r.readUint(h,s+4);var l=r.readUint(h,s+8),c=r.readUint(h,s+12);if(a==e)return[l,c];s+=16}return null},m.T={},m.B={readShort:function(h,e){var t=m.B.t.uint16;return t[0]=h[e]<<8|h[e+1],m.B.t.int16[0]},readUshort:function(h,e){return h[e]<<8|h[e+1]},readUshorts:function(h,e,t){for(var r=[],i=0;i<t;i++)r.push(m.B.readUshort(h,e+i*2));return r},readUint:function(h,e){var t=m.B.t.uint8;return t[3]=h[e],t[2]=h[e+1],t[1]=h[e+2],t[0]=h[e+3],m.B.t.uint32[0]},readASCII:function(h,e,t){for(var r="",i=0;i<t;i++)r+=String.fromCharCode(h[e+i]);return r},t:function(){var h=new ArrayBuffer(8);return{uint8:new Uint8Array(h),int16:new Int16Array(h),uint16:new Uint16Array(h),uint32:new Uint32Array(h)}}()},m.T.cmap={parseTab:function(h,e,t){var r={tables:[],ids:{},off:e};h=new Uint8Array(h.buffer,e,t),e=0;var i=m.B,s=i.readUshort,n=m.T.cmap;s(h,e),e+=2;var a=s(h,e);e+=2;for(var l=[],c=0;c<a;c++){var u=s(h,e);e+=2;var d=s(h,e);e+=2;var f=i.readUint(h,e);e+=4;var g="p"+u+"e"+d,x=l.indexOf(f);if(x==-1){x=r.tables.length;var _={};l.push(f);var F=_.format=s(h,f);F==4?_=n.parse4(h,f,_):F==12&&(_=n.parse12(h,f,_)),r.tables.push(_)}r.ids[g]!=null&&console.log("multiple tables for one platform+encoding: "+g),r.ids[g]=x}return r},parse4:function(h,e,t){var r=m.B,i=r.readUshort,s=r.readUshorts,n=e;e+=2;var a=i(h,e);e+=2,i(h,e),e+=2;var l=i(h,e);e+=2;var c=l>>>1;t.searchRange=i(h,e),e+=2,t.entrySelector=i(h,e),e+=2,t.rangeShift=i(h,e),e+=2,t.endCount=s(h,e,c),e+=c*2,e+=2,t.startCount=s(h,e,c),e+=c*2,t.idDelta=[];for(var u=0;u<c;u++)t.idDelta.push(r.readShort(h,e)),e+=2;return t.idRangeOffset=s(h,e,c),e+=c*2,t.glyphIdArray=s(h,e,n+a-e>>1),t},parse12:function(h,e,t){var r=m.B,i=r.readUint;e+=4,i(h,e),e+=4,i(h,e),e+=4;var s=i(h,e)*3;e+=4;for(var n=t.groups=new Uint32Array(s),a=0;a<s;a+=3)n[a]=i(h,e+(a<<2)),n[a+1]=i(h,e+(a<<2)+4),n[a+2]=i(h,e+(a<<2)+8);return t}},m.T.head={parseTab:function(h,e,t){var r=m.B,i={};return e+=18,i.unitsPerEm=r.readUshort(h,e),e+=2,e+=16,i.xMin=r.readShort(h,e),e+=2,i.yMin=r.readShort(h,e),e+=2,i.xMax=r.readShort(h,e),e+=2,i.yMax=r.readShort(h,e),e+=2,e+=6,i.indexToLocFormat=r.readShort(h,e),i}},m.T.hhea={parseTab:function(h,e,t){var r=m.B,i={};e+=4;for(var s=["ascender","descender","lineGap","advanceWidthMax","minLeftSideBearing","minRightSideBearing","xMaxExtent","caretSlopeRise","caretSlopeRun","caretOffset","res0","res1","res2","res3","metricDataFormat","numberOfHMetrics"],n=0;n<s.length;n++){var a=s[n],l=a=="advanceWidthMax"||a=="numberOfHMetrics"?r.readUshort:r.readShort;i[a]=l(h,e+n*2)}return i}},m.T.hmtx={parseTab:function(h,e,t,r){for(var i=m.B,s=[],n=[],a=r.maxp.numGlyphs,l=r.hhea.numberOfHMetrics,c=0,u=0,d=0;d<l;)c=i.readUshort(h,e+(d<<2)),u=i.readShort(h,e+(d<<2)+2),s.push(c),n.push(u),d++;for(;d<a;)s.push(c),n.push(u),d++;return{aWidth:s,lsBearing:n}}},m.T.maxp={parseTab:function(h,e,t){var r=m.B,i=r.readUshort,s={};return r.readUint(h,e),e+=4,s.numGlyphs=i(h,e),e+=2,s}},m.T.loca={parseTab:function(h,e,t,r){var i=m.B,s=[],n=r.head.indexToLocFormat,a=r.maxp.numGlyphs+1;if(n==0)for(var l=0;l<a;l++)s.push(i.readUshort(h,e+(l<<1))<<1);if(n==1)for(var l=0;l<a;l++)s.push(i.readUint(h,e+(l<<2)));return s}},m.T.glyf={parseTab:function(h,e,t,r){for(var i=[],s=r.maxp.numGlyphs,n=0;n<s;n++)i.push(null);return i},_parseGlyf:function(h,e){var t=m.B,r=h._data,i=h.loca;if(i[e]==i[e+1])return null;var s=m.findTable(r,"glyf",h._offset)[0]+i[e],n={};if(n.noc=t.readShort(r,s),s+=2,n.xMin=t.readShort(r,s),s+=2,n.yMin=t.readShort(r,s),s+=2,n.xMax=t.readShort(r,s),s+=2,n.yMax=t.readShort(r,s),s+=2,n.xMin>=n.xMax||n.yMin>=n.yMax)return null;if(n.noc>0){n.endPts=[];for(var a=0;a<n.noc;a++)n.endPts.push(t.readUshort(r,s)),s+=2;var l=t.readUshort(r,s);if(s+=2,r.length-s<l)return null;s+=l;var c=n.endPts[n.noc-1]+1;n.flags=[];for(var a=0;a<c;a++){var u=r[s];if(s++,n.flags.push(u),u&8){var d=r[s];s++;for(var f=0;f<d;f++)n.flags.push(u),a++}}n.xs=[];for(var a=0;a<c;a++){var g=(n.flags[a]&2)!=0,x=(n.flags[a]&16)!=0;g?(n.xs.push(x?r[s]:-r[s]),s++):x?n.xs.push(0):(n.xs.push(t.readShort(r,s)),s+=2)}n.ys=[];for(var a=0;a<c;a++){var g=(n.flags[a]&4)!=0,x=(n.flags[a]&32)!=0;g?(n.ys.push(x?r[s]:-r[s]),s++):x?n.ys.push(0):(n.ys.push(t.readShort(r,s)),s+=2)}for(var _=0,F=0,a=0;a<c;a++)_+=n.xs[a],F+=n.ys[a],n.xs[a]=_,n.ys[a]=F}else n.parts=[];return n}},typeof module<"u"&&module.exports?module.exports=m:typeof window<"u"&&(window.Typr=m);class ce{extractCharacters(e){var r;const t=[];return(r=e==null?void 0:e.cmap)!=null&&r.tables?(e.cmap.tables.forEach(i=>{if(i.format===4){const s=this._extractCharactersFromFormat4Table(i);t.push(...s)}else if(i.format===12){const s=this._extractCharactersFromFormat12Table(i);t.push(...s)}}),[...new Set(t)]):[]}_extractCharactersFromFormat4Table(e){const t=[];if(!e.startCount||!e.endCount||!e.idRangeOffset||!e.idDelta)return t;for(let r=0;r<e.startCount.length;r++){const i=e.startCount[r],s=e.endCount[r];if(!(i===65535&&s===65535)){for(let n=i;n<=s;n++)if(this._calculateGlyphIndexFormat4(e,n,r)>0){const l=String.fromCodePoint(n);t.push(l)}}}return t}_extractCharactersFromFormat12Table(e){const t=[];if(!e.groups)return t;for(let r=0;r<e.groups.length;r+=3){const i=e.groups[r],s=e.groups[r+1],n=e.groups[r+2];for(let a=i;a<=s;a++)if(n+(a-i)>0){const c=String.fromCodePoint(a);t.push(c)}}return t}_calculateGlyphIndexFormat4(e,t,r){if(e.idRangeOffset[r]===0)return t+e.idDelta[r]&65535;{const i=e.idRangeOffset[r]/2+(t-e.startCount[r])-(e.startCount.length-r);if(i>=0&&e.glyphIdArray&&i<e.glyphIdArray.length){const s=e.glyphIdArray[i];if(s!==0)return s+e.idDelta[r]&65535}}return 0}filterProblematicCharacters(e){return e.filter(t=>this._isValidCharacter(t))}_isValidCharacter(e){const t=e.codePointAt(0)||0;return!(t>=0&&t<=31&&t!==9&&t!==10&&t!==13||t>=127&&t<=159)}}class ue{constructor(e){o(this,"_textureCanvas");o(this,"_textureContext");o(this,"_renderer");this._renderer=e,this._textureCanvas=document.createElement("canvas"),this._textureContext=this._textureCanvas.getContext("2d",{willReadFrequently:!0,alpha:!1})}createTextureAtlas(e,t,r,i){const s=e.length,n=Math.ceil(Math.sqrt(s)),a=Math.ceil(s/n),l=t.width*n,c=t.height*a;this._setupCanvas(l,c,r,i),this._renderCharactersToCanvas(e,t,n,r),this._applyBlackWhiteThreshold();const u=this._renderer.createFramebuffer(l,c,{filter:"nearest"});return u.update(this._textureCanvas),{framebuffer:u,columns:n,rows:a}}_setupCanvas(e,t,r,i){this._textureCanvas.width=e,this._textureCanvas.height=t,this._textureCanvas.style.width=e+"px",this._textureCanvas.style.height=e+"px",this._textureContext.imageSmoothingEnabled=!1,this._textureCanvas.style.imageRendering="pixelated",this._textureContext.fillStyle="black",this._textureContext.fillRect(0,0,e,t),this._textureContext.font=`${r}px ${i}`,this._textureContext.textBaseline="top",this._textureContext.textAlign="left",this._textureContext.fillStyle="white"}_renderCharactersToCanvas(e,t,r,i){for(let s=0;s<e.length;s++){const n=s%r,a=Math.floor(s/r),l=n*t.width+t.width*.5,c=a*t.height+t.height*.5,u=Math.round(l-t.width*.5),d=Math.round(c-i*.5);this._textureContext.fillText(e[s].character,u,d)}}_applyBlackWhiteThreshold(e=128){const t=this._textureContext.getImageData(0,0,this._textureCanvas.width,this._textureCanvas.height),r=t.data;for(let i=0;i<r.length;i+=4){const s=.299*r[i]+.587*r[i+1]+.114*r[i+2],n=e+32,a=s>n?255:0;r[i]=a,r[i+1]=a,r[i+2]=a}this._textureContext.putImageData(t,0,0)}}class de{constructor(){o(this,"_tempCanvas");o(this,"_tempContext");this._tempCanvas=document.createElement("canvas"),this._tempContext=this._tempCanvas.getContext("2d")}calculateMaxGlyphDimensions(e,t,r){this._tempContext.font=`${t}px ${r}`;let i=0,s=0;for(const n of e){const a=this._tempContext.measureText(n),l=a.width,c=a.actualBoundingBoxAscent+a.actualBoundingBoxDescent;l>0&&(i=Math.max(i,l),s=Math.max(s,c))}return{width:Math.ceil(i),height:Math.ceil(s)}}}class fe{createCharacterObjects(e,t){return e.map((r,i)=>{const s=r.codePointAt(0)||0,n=this._generateCharacterColor(i);let a=0;if(t.hmtx&&t.hmtx.aWidth){const l=this._getGlyphIndex(t,s);l>0&&t.hmtx.aWidth[l]!==void 0&&(a=t.hmtx.aWidth[l])}return{character:r,unicode:s,color:n,advanceWidth:a}})}_getGlyphIndex(e,t){const r=e.cmap;if(!r||!r.tables)return 0;for(const i of r.tables)if(i.format===4){for(let s=0;s<i.startCount.length;s++)if(t>=i.startCount[s]&&t<=i.endCount[s]){if(i.idRangeOffset[s]===0)return t+i.idDelta[s]&65535;{const n=i.idRangeOffset[s]/2+(t-i.startCount[s])-(i.startCount.length-s);if(n>=0&&n<i.glyphIdArray.length){const a=i.glyphIdArray[n];if(a!==0)return a+i.idDelta[s]&65535}}}}return 0}_generateCharacterColor(e){const t=e%256,r=Math.floor(e/256)%256,i=Math.floor(e/65536)%256;return[t,r,i]}getCharacterColor(e,t){if(!b.validate(typeof e=="string"&&e.length===1,"Character must be a single character string.",{method:"getCharacterColor",providedValue:e}))return[0,0,0];const r=t.find(i=>i.character===e);return r?r.color:[0,0,0]}getCharacterColors(e,t){return b.validate(typeof e=="string"&&e.length>0,"Characters must be a string with at least one character.",{method:"getCharacterColors",providedValue:e})?e.split("").map(r=>this.getCharacterColor(r,t)||[0,0,0]):[[0,0,0]]}}class q{constructor(e,t=16){o(this,"_font");o(this,"_characters",[]);o(this,"_fontFramebuffer");o(this,"_fontSize",16);o(this,"_textureColumns",0);o(this,"_textureRows",0);o(this,"_maxGlyphDimensions",{width:0,height:0});o(this,"_fontFace");o(this,"_fontFamilyName","UrsaFont");o(this,"_characterExtractor");o(this,"_textureAtlas");o(this,"_metricsCalculator");o(this,"_characterColorMapper");this._fontSize=t,this._characterExtractor=new ce,this._textureAtlas=new ue(e),this._metricsCalculator=new de,this._characterColorMapper=new fe}async initialize(e){let t;if(e){const r=await fetch(e);if(!r.ok)throw new p(`Failed to load font file: ${r.status} ${r.statusText}`);t=await r.arrayBuffer()}else throw new p("Embedded font not available. This appears to be a minified build - please provide `fontSource`.");await this._loadFontFace(t),this._font=m.parse(t)[0],await this._initializeFont()}setFontSize(e){if(e===void 0)return this._fontSize;this._fontSize=e,this._maxGlyphDimensions=this._metricsCalculator.calculateMaxGlyphDimensions(this._characters.map(r=>r.character),this._fontSize,this._fontFamilyName);const t=this._textureAtlas.createTextureAtlas(this._characters,this._maxGlyphDimensions,this._fontSize,this._fontFamilyName);this._fontFramebuffer=t.framebuffer,this._textureColumns=t.columns,this._textureRows=t.rows}async loadFont(e){try{const t=await fetch(e);if(!t.ok)throw new p(`Failed to load font file: ${t.status} ${t.statusText}`);const r=await t.arrayBuffer();await this._loadFontFace(r);const i=m.parse(r);if(!i||i.length===0)throw new Error("Failed to parse font file");this._font=i[0],await this._initializeFont()}catch(t){throw new p(`Failed to load font: ${t instanceof Error?t.message:"Unknown error"}`,t)}}async _loadFontFace(e){const t=Date.now();this._fontFamilyName=this._fontFamilyName==="UrsaFont"?"UrsaFont":`CustomFont_${t}`,this._fontFace=new FontFace(this._fontFamilyName,e),await this._fontFace.load(),document.fonts.add(this._fontFace)}async _initializeFont(){const e=this._characterExtractor.extractCharacters(this._font),t=this._characterExtractor.filterProblematicCharacters(e);this._characters=this._characterColorMapper.createCharacterObjects(t,this._font),this._maxGlyphDimensions=this._metricsCalculator.calculateMaxGlyphDimensions(t,this._fontSize,this._fontFamilyName);const r=this._textureAtlas.createTextureAtlas(this._characters,this._maxGlyphDimensions,this._fontSize,this._fontFamilyName);this._fontFramebuffer=r.framebuffer,this._textureColumns=r.columns,this._textureRows=r.rows}getCharacterColor(e){return this._characterColorMapper.getCharacterColor(e,this._characters)}getCharacterColors(e){return this._characterColorMapper.getCharacterColors(e,this._characters)}hasAllCharacters(e){if(typeof e!="string"||e.length===0)return!1;const t=new Set(this._characters.map(r=>r.character));for(const r of e)if(!t.has(r))return!1;return!0}get fontFramebuffer(){return this._fontFramebuffer}get characters(){return this._characters}get textureColumns(){return this._textureColumns}get textureRows(){return this._textureRows}get maxGlyphDimensions(){return this._maxGlyphDimensions}dispose(){this._fontFramebuffer&&!this._fontFramebuffer.isDisposed&&this._fontFramebuffer.dispose(),this._fontFace&&document.fonts.has(this._fontFace)&&document.fonts.delete(this._fontFace),this._fontFramebuffer=null,this._fontFace=null,this._font=null,this._characters=[],this._maxGlyphDimensions={width:0,height:0},this._textureColumns=0,this._textureRows=0}get isDisposed(){return this._fontFramebuffer===null||this._font===null}get fontSize(){return this._fontSize}get font(){return this._font}}class Q{constructor(e,t,r){o(this,"_cols");o(this,"_rows");o(this,"_width");o(this,"_height");o(this,"_offsetX");o(this,"_offsetY");o(this,"_fixedDimensions",!1);o(this,"_canvas");o(this,"_cellWidth");o(this,"_cellHeight");this._canvas=e,this._cellWidth=t,this._cellHeight=r,this.reset()}reset(){if(!this._fixedDimensions){const e=this._canvas.getBoundingClientRect();let t=Math.round(e.width),r=Math.round(e.height);[this._cols,this._rows]=[Math.floor(t/this._cellWidth),Math.floor(r/this._cellHeight)]}this._resizeGrid()}_resizeGrid(){const e=this._canvas.getBoundingClientRect();let t=Math.round(e.width),r=Math.round(e.height);this._width=this._cols*this._cellWidth,this._height=this._rows*this._cellHeight,this._offsetX=Math.floor((t-this._width)/2),this._offsetY=Math.floor((r-this._height)/2)}resizeCellPixelDimensions(e,t){[this._cellWidth,this._cellHeight]=[e,t],this.reset()}resizeGridDimensions(e,t){this._fixedDimensions=!0,[this._cols,this._rows]=[e,t],this._resizeGrid()}resetGridDimensions(){this._fixedDimensions=!1,this.reset()}resize(){this._fixedDimensions?this._resizeGrid():this.reset()}fixedDimensions(e){if(e===void 0)return this._fixedDimensions;this._fixedDimensions=e}get cellWidth(){return this._cellWidth}get cellHeight(){return this._cellHeight}dispose(){this._canvas=null,this._cols=0,this._rows=0,this._width=0,this._height=0,this._offsetX=0,this._offsetY=0,this._cellWidth=0,this._cellHeight=0}get isDisposed(){return this._canvas===null}get cols(){return this._cols}get rows(){return this._rows}get width(){return this._width}get height(){return this._height}get offsetX(){return this._offsetX}get offsetY(){return this._offsetY}}class Z{constructor(e,t=!1,r={}){o(this,"_canvas");o(this,"captureSource");o(this,"_isStandalone");this.captureSource=e,this._isStandalone=t,this._canvas=this.createCanvas(r.width,r.height)}createCanvas(e,t){var i;const r=document.createElement("canvas");if(r.className="textmodeCanvas",r.style.imageRendering="pixelated",this._isStandalone)r.width=e||800,r.height=t||600,document.body.appendChild(r);else{const s=this.captureSource.getBoundingClientRect();let n=Math.round(s.width),a=Math.round(s.height);if(this.captureSource instanceof HTMLVideoElement){const u=this.captureSource;(n===0||a===0)&&u.videoWidth>0&&u.videoHeight>0&&(n=u.videoWidth,a=u.videoHeight)}r.width=n,r.height=a,r.style.position="absolute",r.style.pointerEvents="none";const l=window.getComputedStyle(this.captureSource);let c=parseInt(l.zIndex||"0",10);isNaN(c)&&(c=0),r.style.zIndex=(c+1).toString(),this.positionOverlayCanvas(r),(i=this.captureSource.parentNode)==null||i.insertBefore(r,this.captureSource.nextSibling)}return r}positionOverlayCanvas(e){const t=this.captureSource.getBoundingClientRect();let r=this.captureSource.offsetParent;if(r&&r!==document.body){const i=r.getBoundingClientRect();e.style.top=t.top-i.top+"px",e.style.left=t.left-i.left+"px"}else e.style.top=t.top+window.scrollY+"px",e.style.left=t.left+window.scrollX+"px"}resize(e,t){if(this._isStandalone)this._canvas.width=e??this._canvas.width,this._canvas.height=t??this._canvas.height;else{const r=this.captureSource.getBoundingClientRect();let i=Math.round(r.width),s=Math.round(r.height);if(this.captureSource instanceof HTMLVideoElement){const n=this.captureSource;(i===0||s===0)&&n.videoWidth>0&&n.videoHeight>0&&(i=n.videoWidth,s=n.videoHeight)}this._canvas.width=i,this._canvas.height=s,this.positionOverlayCanvas(this._canvas)}}getWebGLContext(){const e={alpha:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!0,antialias:!1,depth:!1,stencil:!1,powerPreference:"high-performance"},t=this._canvas.getContext("webgl2",e)||this._canvas.getContext("webgl",e);if(!t)throw new p("WebGL context could not be created. Ensure your browser supports WebGL.");return t}dispose(){if(this._canvas){const e=this._canvas.getContext("webgl")||this._canvas.getContext("webgl2");if(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}this._canvas.parentNode&&this._canvas.parentNode.removeChild(this._canvas),this._canvas=null}this.captureSource=null}get isDisposed(){return this._canvas===null}get canvas(){return this._canvas}get width(){return this._canvas.width}get height(){return this._canvas.height}}class A{constructor(e,t,r,i={}){o(this,"renderer");o(this,"fontManager");o(this,"grid");o(this,"_characterFramebuffer");o(this,"_primaryColorFramebuffer");o(this,"_secondaryColorFramebuffer");o(this,"_rotationFramebuffer");o(this,"_transformFramebuffer");o(this,"_options");this.renderer=e,this.fontManager=t,this.grid=r,this._options=i,this._characterFramebuffer=this.renderer.createFramebuffer(this.grid.cols,this.grid.rows),this._primaryColorFramebuffer=this.renderer.createFramebuffer(this.grid.cols,this.grid.rows),this._secondaryColorFramebuffer=this.renderer.createFramebuffer(this.grid.cols,this.grid.rows),this._rotationFramebuffer=this.renderer.createFramebuffer(this.grid.cols,this.grid.rows),this._transformFramebuffer=this.renderer.createFramebuffer(this.grid.cols,this.grid.rows)}resize(){this._characterFramebuffer.resize(this.grid.cols,this.grid.rows),this._primaryColorFramebuffer.resize(this.grid.cols,this.grid.rows),this._secondaryColorFramebuffer.resize(this.grid.cols,this.grid.rows),this._rotationFramebuffer.resize(this.grid.cols,this.grid.rows),this._transformFramebuffer.resize(this.grid.cols,this.grid.rows)}enabled(e){this._options.enabled=e}enable(){this.enabled(!0)}disable(){this.enabled(!1)}dispose(){this._characterFramebuffer&&!this._characterFramebuffer.isDisposed&&this._characterFramebuffer.dispose(),this._primaryColorFramebuffer&&!this._primaryColorFramebuffer.isDisposed&&this._primaryColorFramebuffer.dispose(),this._secondaryColorFramebuffer&&!this._secondaryColorFramebuffer.isDisposed&&this._secondaryColorFramebuffer.dispose(),this._rotationFramebuffer&&!this._rotationFramebuffer.isDisposed&&this._rotationFramebuffer.dispose(),this._transformFramebuffer&&!this._transformFramebuffer.isDisposed&&this._transformFramebuffer.dispose(),this._characterFramebuffer=null,this._primaryColorFramebuffer=null,this._secondaryColorFramebuffer=null,this._rotationFramebuffer=null,this._transformFramebuffer=null}get isDisposed(){return this._characterFramebuffer===null}get characterFramebuffer(){return this._characterFramebuffer}get primaryColorFramebuffer(){return this._primaryColorFramebuffer}get secondaryColorFramebuffer(){return this._secondaryColorFramebuffer}get rotationFramebuffer(){return this._rotationFramebuffer}get transformFramebuffer(){return this._transformFramebuffer}get options(){return this._options}}class me{constructor(e,t){o(this,"_framebuffer");o(this,"_renderer");o(this,"_colors");this._renderer=e,this._colors=t;const r=Math.max(this._colors.length,1);this._framebuffer=this._renderer.createFramebuffer(r,1),this._updateFramebuffer()}_updateFramebuffer(){if(!this._framebuffer)return;const e=Math.max(this._colors.length,1),t=1;this._framebuffer.width!==e&&this._framebuffer.resize(e,t);const r=new Uint8Array(e*t*4);for(let i=0;i<e;i++){const s=i<this._colors.length?this._colors[i]:[0,0,0],n=i*4;r[n]=s[0],r[n+1]=s[1],r[n+2]=s[2],r[n+3]=255}this._framebuffer.updatePixels(r,e,t)}setColors(e){this._colors=e,this._updateFramebuffer()}get colors(){return this._colors}get framebuffer(){return this._framebuffer}get texture(){return this._framebuffer.texture}}class k extends A{constructor(t,r,i,s={}){super(t,r,i,s);o(this,"palette");this.palette=new me(this.renderer,this.fontManager.getCharacterColors(" .:-=+*%@#"))}characters(t){b.validate(this.fontManager.hasAllCharacters(t),"One or more characters do not exist in the current font.",{method:"characters",providedValue:t})&&(this._options.characters=t,this.palette.setColors(this.fontManager.getCharacterColors(t)))}characterColor(t,r=t,i=t,s=255){b.validate([t,r,i,s].every(n=>n>=0&&n<=255),"Character color values must be between 0 and 255",{method:"characterColor",providedValues:{r:t,g:r,b:i,a:s}})&&(this._options.characterColor=[t,r,i,s])}characterColorMode(t){b.validate(["sampled","fixed"].includes(t),"Invalid character color mode. Must be 'sampled' or 'fixed'.",{method:"characterColorMode",providedValue:t})&&(this._options.characterColorMode=t)}cellColor(t,r=t,i=t,s=255){b.validate([t,r,i,s].every(n=>n>=0&&n<=255),"Cell color values must be between 0 and 255",{method:"cellColor",providedValues:{r:t,g:r,b:i,a:s}})&&(this._options.cellColor=[t,r,i,s])}cellColorMode(t){b.validate(["sampled","fixed"].includes(t),"Invalid cell color mode. Must be 'sampled' or 'fixed'.",{method:"cellColorMode",providedValue:t})&&(this._options.cellColorMode=t)}invert(t){b.validate(typeof t=="boolean"||typeof t=="number"&&Number.isInteger(t),"Invert must be a boolean value or an integer (0 for false, any other number for true).",{method:"invert",providedValue:t})&&(this._options.invert=!!t)}rotation(t){if(!b.validate(typeof t=="number","Rotation angle must be a number.",{method:"rotation",providedValue:t}))return;t=t%360,t<0&&(t+=360);const r=t*255/360,i=Math.floor(r)/255,s=Math.round(r-i);this._options.rotation=[i,s,0,1]}flipHorizontally(t){b.validate(typeof t=="boolean"||typeof t=="number"&&Number.isInteger(t),"Flip horizontally must be a boolean value or an integer (0 for false, any other number for true).",{method:"flipHorizontally",providedValue:t})&&(this._options.flipHorizontally=!!t)}flipVertically(t){b.validate(typeof t=="boolean"||typeof t=="number"&&Number.isInteger(t),"Flip vertically must be a boolean value or an integer (0 for false, any other number for true).",{method:"flipVertically",providedValue:t})&&(this._options.flipVertically=!!t)}}var ge="precision lowp float;uniform sampler2D u_sketchTexture;uniform vec2 u_gridCellDimensions;uniform vec2 u_brightnessRange;varying vec2 v_uv;void main(){vec2 cellCenter=(floor(v_uv*u_gridCellDimensions)+vec2(0.5))/u_gridCellDimensions;vec4 color=texture2D(u_sketchTexture,cellCenter);float brightness=dot(color.rgb,vec3(0.299,0.587,0.114));float brightnessValue=brightness*255.0;if(brightnessValue>=u_brightnessRange.x&&brightnessValue<=u_brightnessRange.y){gl_FragColor=color;}else{gl_FragColor=vec4(0.0);}}",_e="precision lowp float;uniform sampler2D u_sampleTexture;uniform vec4 u_fillColor;uniform bool u_useFixedColor;varying vec2 v_uv;void main(){vec4 sampleColor=texture2D(u_sampleTexture,v_uv);if(sampleColor.a>0.0){if(u_useFixedColor){gl_FragColor=u_fillColor;}else{gl_FragColor=sampleColor;}}else{gl_FragColor=vec4(0.0);}}",pe="precision lowp float;uniform sampler2D u_sampleTexture;uniform bool u_invert;uniform bool u_flipHorizontally;uniform bool u_flipVertically;varying vec2 v_uv;void main(){vec4 sampleColor=texture2D(u_sampleTexture,v_uv);if(sampleColor.a>0.0){float invertValue=u_invert ? 1.0 : 0.0;float flipHValue=u_flipHorizontally ? 1.0 : 0.0;float flipVValue=u_flipVertically ? 1.0 : 0.0;gl_FragColor=vec4(invertValue,flipHValue,flipVValue,1.0);}else{gl_FragColor=vec4(0.0);}}",xe="precision lowp float;uniform sampler2D u_sampleTexture;uniform vec4 u_rotationColor;varying vec2 v_uv;void main(){vec4 sampleColor=texture2D(u_sampleTexture,v_uv);if(sampleColor.a>0.0){gl_FragColor=u_rotationColor;}else{gl_FragColor=vec4(0.0);}}",ve="precision lowp float;uniform sampler2D u_colorSampleFramebuffer;uniform sampler2D u_charPaletteTexture;uniform vec2 u_charPaletteSize;uniform vec2 u_brightnessRange;varying vec2 v_uv;void main(){vec4 color=texture2D(u_colorSampleFramebuffer,v_uv);if(color.a==0.0){gl_FragColor=vec4(0.0);return;}float brightness=dot(color.rgb,vec3(0.299,0.587,0.114))*255.0;vec2 range=u_brightnessRange;if(brightness<range.x||brightness>range.y){gl_FragColor=vec4(0.0);return;}float t=(brightness-range.x)/(range.y-range.x);float idx=clamp(floor(t*u_charPaletteSize.x),0.0,u_charPaletteSize.x-1.0);vec3 charColor=texture2D(u_charPaletteTexture,vec2((idx+0.5)/u_charPaletteSize.x,0.0)).rgb;gl_FragColor=vec4(charColor,1.0);}";const be={enabled:!0,characters:" .:-=+*%@#",characterColor:[255,255,255,255],characterColorMode:"sampled",cellColor:[0,0,0,255],cellColorMode:"fixed",invert:!1,rotation:[0,0,0,255],flipHorizontally:!1,flipVertically:!1,brightnessRange:[0,255]};class z extends k{constructor(t,r,i){super(t,r,i,{...be});o(this,"sampleShader");o(this,"colorFillShader");o(this,"charMappingShader");o(this,"transformFillShader");o(this,"rotationFillShader");o(this,"sampleFramebuffer");this.sampleShader=new T(t.context,S,ge),this.colorFillShader=new T(t.context,S,_e),this.transformFillShader=new T(t.context,S,pe),this.rotationFillShader=new T(t.context,S,xe),this.charMappingShader=new T(t.context,S,ve),this.sampleFramebuffer=this.renderer.createFramebuffer(this.grid.cols,this.grid.rows)}convert(t){this.sampleFramebuffer.begin(),this.renderer.clear(),this.renderer.shader(this.sampleShader),this.renderer.setUniform("u_sketchTexture",t),this.renderer.setUniform("u_gridCellDimensions",[this.grid.cols,this.grid.rows]),this.renderer.setUniform("u_brightnessRange",this._options.brightnessRange),this.renderer.rect(0,0,this.grid.cols,this.grid.rows),this.sampleFramebuffer.end(),this._primaryColorFramebuffer.begin(),this.renderer.clear(),this.renderer.shader(this.colorFillShader),this.renderer.setUniform("u_sampleTexture",this.sampleFramebuffer.texture),this.renderer.setUniform("u_fillColor",this._options.characterColor),this.renderer.setUniform("u_useFixedColor",this._options.characterColorMode==="fixed"),this.renderer.rect(0,0,this.grid.cols,this.grid.rows),this._primaryColorFramebuffer.end(),this._secondaryColorFramebuffer.begin(),this.renderer.clear(),this.renderer.shader(this.colorFillShader),this.renderer.setUniform("u_sampleTexture",this.sampleFramebuffer.texture),this.renderer.setUniform("u_fillColor",this._options.cellColor),this.renderer.setUniform("u_useFixedColor",this._options.cellColorMode==="fixed"),this.renderer.rect(0,0,this.grid.cols,this.grid.rows),this._secondaryColorFramebuffer.end(),this._transformFramebuffer.begin(),this.renderer.clear(),this.renderer.shader(this.transformFillShader),this.renderer.setUniform("u_sampleTexture",this.sampleFramebuffer.texture),this.renderer.setUniform("u_invert",this._options.invert),this.renderer.setUniform("u_flipHorizontally",this._options.flipHorizontally),this.renderer.setUniform("u_flipVertically",this._options.flipVertically),this.renderer.rect(0,0,this.grid.cols,this.grid.rows),this._transformFramebuffer.end(),this._rotationFramebuffer.begin(),this.renderer.clear(),this.renderer.shader(this.rotationFillShader),this.renderer.setUniform("u_sampleTexture",this.sampleFramebuffer.texture),this.renderer.setUniform("u_rotationColor",this._options.rotation),this.renderer.rect(0,0,this.grid.cols,this.grid.rows),this._rotationFramebuffer.end(),this._characterFramebuffer.begin(),this.renderer.clear(0,0,0,0),this.renderer.shader(this.charMappingShader),this.renderer.setUniform("u_colorSampleFramebuffer",this.sampleFramebuffer.texture),this.renderer.setUniform("u_charPaletteTexture",this.palette.texture),this.renderer.setUniform("u_charPaletteSize",[this.palette.colors.length,1]),this.renderer.setUniform("u_brightnessRange",this._options.brightnessRange),this.renderer.rect(0,0,this.grid.cols,this.grid.rows),this._characterFramebuffer.end()}resize(){super.resize(),this.sampleFramebuffer.resize(this.grid.cols,this.grid.rows)}brightnessRange(t){b.validate(Array.isArray(t)&&t.length===2&&t.every(r=>typeof r=="number"&&r>=0&&r<=255),"Brightness range must be an array of two numbers between 0 and 255.",{method:"brightnessRange",providedValue:t})&&(this._options.brightnessRange=t)}}const Ce=Object.freeze(Object.defineProperty({__proto__:null,TextmodeBrightnessConverter:z,TextmodeConverter:A,TextmodeFeatureConverter:k},Symbol.toStringTag,{value:"Module"}));var Fe="precision mediump float;uniform sampler2D u_characterTexture;uniform vec2 u_charsetDimensions;uniform sampler2D u_primaryColorTexture;uniform sampler2D u_secondaryColorTexture;uniform sampler2D u_transformTexture;uniform sampler2D u_asciiCharacterTexture;uniform sampler2D u_rotationTexture;uniform sampler2D u_captureTexture;uniform vec2 u_captureDimensions;uniform int u_backgroundMode;uniform vec2 u_gridCellDimensions;uniform vec2 u_gridPixelDimensions;mat2 rotate2D(float angle){float s=sin(angle);float c=cos(angle);return mat2(c,-s,s,c);}void main(){vec2 adjustedCoord=gl_FragCoord.xy/u_gridPixelDimensions;vec2 gridCoord=adjustedCoord*u_gridCellDimensions;vec2 cellCoord=floor(gridCoord);vec2 charIndexTexCoord=(cellCoord+0.5)/u_gridCellDimensions;vec4 primaryColor=texture2D(u_primaryColorTexture,charIndexTexCoord);vec4 secondaryColor=texture2D(u_secondaryColorTexture,charIndexTexCoord);vec4 transformColor=texture2D(u_transformTexture,charIndexTexCoord);bool isInverted=transformColor.r>0.5;bool flipHorizontal=transformColor.g>0.5;bool flipVertical=transformColor.b>0.5;vec4 encodedIndexVec=texture2D(u_asciiCharacterTexture,charIndexTexCoord);if(encodedIndexVec.a<0.01){gl_FragColor=(u_backgroundMode==0)? vec4(0.0):texture2D(u_captureTexture,gl_FragCoord.xy/u_captureDimensions);return;}int charIndex=int(encodedIndexVec.r*255.0+0.5)+int(encodedIndexVec.g*255.0+0.5)*256;int charCol=int(mod(float(charIndex),u_charsetDimensions.x));int charRow=charIndex/int(u_charsetDimensions.x);vec2 charCoord=vec2(charCol,charRow)/u_charsetDimensions;vec4 rotationColor=texture2D(u_rotationTexture,charIndexTexCoord);float scaledAngle=rotationColor.r*255.0+rotationColor.g;float rotationAngle=(scaledAngle*360.0/255.0)*0.017453292;vec2 fractionalPart=fract(gridCoord)-0.5;if(flipHorizontal)fractionalPart.x=-fractionalPart.x;if(flipVertical)fractionalPart.y=-fractionalPart.y;fractionalPart=rotate2D(rotationAngle)*fractionalPart+0.5;vec2 cellSize=1.0/u_charsetDimensions;vec2 texCoord=charCoord+fractionalPart*cellSize;vec2 cellMax=charCoord+cellSize;if(any(lessThan(texCoord,charCoord))||any(greaterThan(texCoord,cellMax))){gl_FragColor=isInverted ? primaryColor : secondaryColor;return;}vec4 charTexel=texture2D(u_characterTexture,texCoord);if(isInverted)charTexel.rgb=1.0-charTexel.rgb;gl_FragColor=mix(secondaryColor,primaryColor,charTexel);}";class J{constructor(e,t,r){o(this,"renderer");o(this,"font");o(this,"grid");o(this,"converters");o(this,"_resultFramebuffer");o(this,"_asciiShader");o(this,"_characterFramebuffer");o(this,"_primaryColorFramebuffer");o(this,"_secondaryColorFramebuffer");o(this,"_rotationFramebuffer");o(this,"_transformFramebuffer");this.renderer=e,this.font=t,this.grid=r,this._asciiShader=this.renderer.createShader(S,Fe),this.converters=[{name:"brightness",converter:new z(e,t,r)},{name:"custom",converter:new A(e,t,r)}],this._characterFramebuffer=this.renderer.createFramebuffer(r.cols,r.rows),this._primaryColorFramebuffer=this.renderer.createFramebuffer(r.cols,r.rows),this._secondaryColorFramebuffer=this.renderer.createFramebuffer(r.cols,r.rows),this._rotationFramebuffer=this.renderer.createFramebuffer(r.cols,r.rows),this._transformFramebuffer=this.renderer.createFramebuffer(r.cols,r.rows),this._resultFramebuffer=this.renderer.createFramebuffer(this.grid.width,this.grid.height)}render(e){for(const r of this.converters){const i=r.converter;i.options.enabled&&i instanceof k&&i.convert(e)}const t=(r,i)=>{r.begin(),this.renderer.clear();for(const s of this.converters){const n=s.converter;n.options.enabled&&this.renderer.image(i(n),0,0)}r.end()};t(this._characterFramebuffer,r=>r.characterFramebuffer),t(this._primaryColorFramebuffer,r=>r.primaryColorFramebuffer),t(this._secondaryColorFramebuffer,r=>r.secondaryColorFramebuffer),t(this._rotationFramebuffer,r=>r.rotationFramebuffer),t(this._transformFramebuffer,r=>r.transformFramebuffer),this._resultFramebuffer.begin(),this.renderer.clear(),this.renderer.shader(this._asciiShader),this.renderer.setUniform("u_characterTexture",this.font.fontFramebuffer),this.renderer.setUniform("u_charsetDimensions",[this.font.textureColumns,this.font.textureRows]),this.renderer.setUniform("u_asciiCharacterTexture",this._characterFramebuffer.texture),this.renderer.setUniform("u_primaryColorTexture",this._primaryColorFramebuffer.texture),this.renderer.setUniform("u_secondaryColorTexture",this._secondaryColorFramebuffer.texture),this.renderer.setUniform("u_transformTexture",this._transformFramebuffer.texture),this.renderer.setUniform("u_rotationTexture",this._rotationFramebuffer.texture),this.renderer.setUniform("u_captureTexture",e.texture),this.renderer.setUniform("u_backgroundMode",!1),this.renderer.setUniform("u_captureDimensions",[e.width,e.height]),this.renderer.setUniform("u_gridCellDimensions",[this.grid.cols,this.grid.rows]),this.renderer.setUniform("u_gridPixelDimensions",[this.grid.width,this.grid.height]),this.renderer.rect(0,0,this._resultFramebuffer.width,this._resultFramebuffer.height),this._resultFramebuffer.end()}get(e){if(!b.validate(typeof e=="string"&&e.length>0,"Converter name must be a non-empty string.",{method:"converter",providedValue:e}))return;const t=this.converters.find(i=>i.name===e),r=t==null?void 0:t.converter;if(b.validate(r instanceof A,`Converter "${e}" is not a valid TextmodeConverter.`,{method:"converter",providedValue:e,converterInstance:r}))return r}add(e,t){if(!b.validate(typeof e=="string"&&e.length>0,"Converter name must be a non-empty string.",{method:"add",providedValue:e})||!b.validate(t==="brightness"||t==="custom",`Converter type must be either "brightness" or "custom". Provided: ${t}`,{method:"add",providedValue:t}))return;let r;return t==="brightness"?r=new z(this.renderer,this.font,this.grid):r=new A(this.renderer,this.font,this.grid),this.converters.push({name:e,converter:r}),r}remove(e){if(!b.validate(typeof e=="string"||e instanceof A,"Parameter must be either a string (converter name) or a TextmodeConverter instance.",{method:"remove",providedValue:e}))return;let t=-1;if(typeof e=="string"){if(!b.validate(e.length>0,"Converter name must be a non-empty string.",{method:"remove",providedValue:e}))return;t=this.converters.findIndex(r=>r.name===e)}else t=this.converters.findIndex(r=>r.converter===e);b.validate(t!==-1,typeof e=="string"?`Converter with name "${e}" not found in pipeline.`:"Converter instance not found in pipeline.",{method:"remove",providedValue:e,convertersCount:this.converters.length})&&this.converters.splice(t,1)}get texture(){return this._resultFramebuffer}resize(){this._resultFramebuffer.resize(this.grid.width,this.grid.height),this._characterFramebuffer.resize(this.grid.cols,this.grid.rows),this._primaryColorFramebuffer.resize(this.grid.cols,this.grid.rows),this._secondaryColorFramebuffer.resize(this.grid.cols,this.grid.rows),this._rotationFramebuffer.resize(this.grid.cols,this.grid.rows),this._transformFramebuffer.resize(this.grid.cols,this.grid.rows);for(const e of this.converters)e.converter.resize()}hasEnabledConverters(){return this.converters.some(e=>e.converter.options.enabled)}disable(){for(const e of this.converters)e.converter.disable()}enable(){for(const e of this.converters)e.converter.enable()}dispose(){for(const e of this.converters)e.converter&&!e.converter.isDisposed&&e.converter.dispose();this._characterFramebuffer&&!this._characterFramebuffer.isDisposed&&this._characterFramebuffer.dispose(),this._primaryColorFramebuffer&&!this._primaryColorFramebuffer.isDisposed&&this._primaryColorFramebuffer.dispose(),this._secondaryColorFramebuffer&&!this._secondaryColorFramebuffer.isDisposed&&this._secondaryColorFramebuffer.dispose(),this._rotationFramebuffer&&!this._rotationFramebuffer.isDisposed&&this._rotationFramebuffer.dispose(),this._transformFramebuffer&&!this._transformFramebuffer.isDisposed&&this._transformFramebuffer.dispose(),this._resultFramebuffer&&!this._resultFramebuffer.isDisposed&&this._resultFramebuffer.dispose(),this._asciiShader&&!this._asciiShader.isDisposed&&this._asciiShader.dispose(),this.converters=[],this._characterFramebuffer=null,this._primaryColorFramebuffer=null,this._secondaryColorFramebuffer=null,this._rotationFramebuffer=null,this._transformFramebuffer=null,this._resultFramebuffer=null,this._asciiShader=null}get isDisposed(){return this._resultFramebuffer===null||this._asciiShader===null}get characterFramebuffer(){return this._characterFramebuffer}get primaryColorFramebuffer(){return this._primaryColorFramebuffer}get secondaryColorFramebuffer(){return this._secondaryColorFramebuffer}get rotationFramebuffer(){return this._rotationFramebuffer}get transformFramebuffer(){return this._transformFramebuffer}}class ${extractFramebufferData(e){const t=e.get("brightness"),r=t==null?void 0:t.characterFramebuffer,i=t==null?void 0:t.primaryColorFramebuffer,s=t==null?void 0:t.secondaryColorFramebuffer,n=t==null?void 0:t.transformFramebuffer,a=t==null?void 0:t.rotationFramebuffer;return r==null||r.loadPixels(),i==null||i.loadPixels(),s==null||s.loadPixels(),n==null||n.loadPixels(),a==null||a.loadPixels(),{characterPixels:(r==null?void 0:r.pixels)||new Uint8Array(0),primaryColorPixels:(i==null?void 0:i.pixels)||new Uint8Array(0),secondaryColorPixels:(s==null?void 0:s.pixels)||new Uint8Array(0),transformPixels:(n==null?void 0:n.pixels)||new Uint8Array(0),rotationPixels:(a==null?void 0:a.pixels)||new Uint8Array(0)}}getCharacterIndex(e,t){const r=e[t],i=e[t+1];return r+(i<<8)}pixelsToRGBA(e,t){return{r:e[t],g:e[t+1],b:e[t+2],a:e[t+3]}}}class L{createBlob(e,t){return new Blob([e],{type:t})}downloadFile(e,t,r){try{const i=this.createBlob(e,r),s=URL.createObjectURL(i),n=document.createElement("a");n.href=s,n.download=t,n.style.display="none",n.rel="noopener",document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(s)}catch(i){throw console.error("Failed to download file:",i),new Error(`File download failed: ${i instanceof Error?i.message:"Unknown error"}`)}}generateTimestamp(){return new Date().toISOString().slice(0,19).replace(/:/g,"-")}generateDateTimeString(){const e=new Date,t=e.toISOString().split("T")[0],r=e.toTimeString().split(" ")[0].replace(/:/g,"-");return{date:t,time:r}}sanitizeFilename(e){return e.replace(/[<>:"/\\|?*]/g,"_").replace(/\s+/g,"_").replace(/_{2,}/g,"_").replace(/^_+|_+$/g,"").substring(0,255)}generateDefaultFilename(){return`'textmode-export'-${this.generateTimestamp()}`}}class we extends ${extractTransformData(e,t,r){const i=e[r],s=e[r+1],n=e[r+2],a=i===255,l=s===255,c=n===255,u=t[r],d=t[r+1],f=u+d/255,g=Math.round(f*360/255*100)/100;return{isInverted:a,flipHorizontal:l,flipVertical:c,rotation:g}}calculateCellPosition(e,t,r){return{x:e,y:t,cellX:e*r.cellWidth,cellY:t*r.cellHeight}}extractSVGCellData(e,t){const r=[];let i=0;for(let s=0;s<t.rows;s++)for(let n=0;n<t.cols;n++){const a=i*4,l=this.getCharacterIndex(e.characterPixels,a);let c=this.pixelsToRGBA(e.primaryColorPixels,a),u=this.pixelsToRGBA(e.secondaryColorPixels,a);const d=this.extractTransformData(e.transformPixels,e.rotationPixels,a);if(d.isInverted){const g=c;c=u,u=g}const f=this.calculateCellPosition(n,s,t);r.push({charIndex:l,primaryColor:c,secondaryColor:u,transform:d,position:f}),i++}return r}}class ye{getGlyphIndex(e,t){const r=e.cmap;if(!r||!r.tables)return 0;for(const i of r.tables)if(i.format===4){for(let s=0;s<i.startCount.length;s++)if(t>=i.startCount[s]&&t<=i.endCount[s]){if(i.idRangeOffset[s]===0)return t+i.idDelta[s]&65535;{const n=i.idRangeOffset[s]/2+(t-i.startCount[s])-(i.startCount.length-s);if(n>=0&&n<i.glyphIdArray.length){const a=i.glyphIdArray[n];if(a!==0)return a+i.idDelta[s]&65535}}}}return 0}createEmptyPath(){return{getBoundingBox:()=>({x1:0,y1:0,x2:0,y2:0}),toSVG:()=>""}}createGlyphPath(e,t,r,i,s){if(!t||!t.xs||t.xs.length===0)return this.createEmptyPath();const n=s/e.head.unitsPerEm;return{getBoundingBox:()=>({x1:r+t.xMin*n,y1:i+-t.yMax*n,x2:r+t.xMax*n,y2:i+-t.yMin*n}),toSVG:()=>this.glyphToSVGPath(t,r,i,n)}}glyphToSVGPath(e,t,r,i){if(!e||!e.xs)return"";const{xs:s,ys:n,endPts:a,flags:l}=e;if(!s||!n||!a||!l)return"";let c="",u=0;for(let d=0;d<a.length;d++){const f=a[d];if(!(f<u)){if(f>=u){const g=t+s[u]*i,x=r-n[u]*i;c+=`M${g.toFixed(2)},${x.toFixed(2)}`;let _=u+1;for(;_<=f;)if((l[_]&1)!==0){const w=t+s[_]*i,C=r-n[_]*i;c+=`L${w.toFixed(2)},${C.toFixed(2)}`,_++}else{const w=t+s[_]*i,C=r-n[_]*i;let y=_+1>f?u:_+1;if((l[y]&1)!==0){const D=t+s[y]*i,R=r-n[y]*i;c+=`Q${w.toFixed(2)},${C.toFixed(2)} ${D.toFixed(2)},${R.toFixed(2)}`,_=y+1}else{const D=t+s[y]*i,R=r-n[y]*i,H=(w+D)/2,G=(C+R)/2;c+=`Q${w.toFixed(2)},${C.toFixed(2)} ${H.toFixed(2)},${G.toFixed(2)}`,_=y}}c+="Z"}u=f+1}}return c}generateCharacterPath(e,t,r,i,s){try{const n=e.codePointAt(0)||0,a=this.getGlyphIndex(t,n);if(a===0)return this.createEmptyPath();let l=null;try{t.glyf&&t.glyf[a]!==null?l=t.glyf[a]:m&&m.T&&m.T.glyf&&m.T.glyf._parseGlyf&&(l=m.T.glyf._parseGlyf(t,a),t.glyf&&l&&(t.glyf[a]=l))}catch(c){console.warn(`Failed to parse glyph ${a}:`,c)}return l?this.createGlyphPath(t,l,r,i,s):this.createEmptyPath()}catch(n){return console.warn(`Failed to generate path for character "${e}":`,n),this.createEmptyPath()}}generatePositionedCharacterPath(e,t,r,i,s,n,a,l){try{const c=a/t.head.unitsPerEm,u=l*c,d=r+(s-u)/2,f=i+(n+a*.7)/2;return this.generateCharacterPath(e,t,d,f,a).toSVG()||null}catch(c){return console.warn(`Failed to generate positioned character path for "${e}":`,c),null}}}class Te{constructor(){o(this,"pathGenerator");this.pathGenerator=new ye}generateSVGHeader(e){return`<?xml version="1.0" encoding="UTF-8" standalone="no"?>
7
+ `,i}static formatValue(t){if(t===null)return"null";if(t===void 0)return"undefined";if(typeof t=="string")return`"${t}"`;if(typeof t=="number"||typeof t=="boolean")return String(t);if(Array.isArray(t))return t.length===0?"[]":t.length<=5?`[${t.map(r=>p.formatValue(r)).join(", ")}]`:`[${t.slice(0,3).map(r=>p.formatValue(r)).join(", ")}, ... +${t.length-3} more]`;if(typeof t=="object"){const r=Object.keys(t);return r.length===0?"{}":r.length<=3?`{ ${r.map(n=>`${n}: ${p.formatValue(t[n])}`).join(", ")} }`:`{ ${r.slice(0,2).map(s=>`${s}: ${p.formatValue(t[s])}`).join(", ")}, ... +${r.length-2} more }`}return String(t)}}var E=(h=>(h[h.SILENT=0]="SILENT",h[h.WARNING=1]="WARNING",h[h.ERROR=2]="ERROR",h[h.THROW=3]="THROW",h))(E||{});const U=class U{constructor(){a(this,"_options",{globalLevel:3})}static getInstance(){return U._instance||(U._instance=new U),U._instance}_handle(e,t,r){const i="[textmode.js]";switch(this._options.globalLevel){case 0:return!1;case 1:return console.group(`%c${i} Oops! (╯°□°)╯︵ Something went wrong in your code.`,"color: #f44336; font-weight: bold; background: #ffebee; padding: 2px 6px; border-radius: 3px;"),console.warn(p.createFormattedMessage(e,t)),console.groupEnd(),!1;case 2:return console.group(`%c${i} Oops! (╯°□°)╯︵ Something went wrong in your code.`,"color: #f44336; font-weight: bold; background: #ffebee; padding: 2px 6px; border-radius: 3px;"),console.error(p.createFormattedMessage(e,t)),console.groupEnd(),!1;case 3:default:const s=new p(e,r,t);throw console.group(`%c${i} Oops! (╯°□°)╯︵ Something went wrong in your code.`,"color: #d32f2f; font-weight: bold; background: #ffcdd2; padding: 2px 6px; border-radius: 3px;"),s}}validate(e,t,r){return e?!0:(this._handle(t,r),!1)}setGlobalLevel(e){this._options.globalLevel=e}};a(U,"_instance",null);let V=U;const b=V.getInstance();class ie{constructor(e,t,r=t,i={}){a(this,"gl");a(this,"_framebuffer");a(this,"_texture");a(this,"_width");a(this,"_height");a(this,"options");a(this,"previousState",null);a(this,"_pixels",null);this.gl=e,this._width=t,this._height=r,this.options={filter:"nearest",wrap:"clamp",format:"rgba",type:"unsigned_byte",...i},this._texture=this.createTexture(),this._framebuffer=e.createFramebuffer(),this.attachTexture()}createTexture(){const{gl:e}=this,t=e.createTexture();e.bindTexture(e.TEXTURE_2D,t);const r=this.options.filter==="linear"?e.LINEAR:e.NEAREST,i=this.options.wrap==="repeat"?e.REPEAT:e.CLAMP_TO_EDGE;return e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,r),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,r),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,i),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,i),this.updateTextureSize(),t}updateTextureSize(){const{gl:e}=this,t=e.RGBA,r=e.RGBA,i=this.options.type==="float"?e.FLOAT:e.UNSIGNED_BYTE;e.texImage2D(e.TEXTURE_2D,0,t,this._width,this._height,0,r,i,null)}attachTexture(){const{gl:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this._framebuffer),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this._texture,0),e.bindFramebuffer(e.FRAMEBUFFER,null)}update(e){const{gl:t}=this;e instanceof HTMLVideoElement&&e.readyState<2||(t.bindTexture(t.TEXTURE_2D,this._texture),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),t.bindTexture(t.TEXTURE_2D,null))}updatePixels(e,t,r){const{gl:i}=this;i.bindTexture(i.TEXTURE_2D,this._texture),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,t,r,0,i.RGBA,i.UNSIGNED_BYTE,e),i.bindTexture(i.TEXTURE_2D,null)}resize(e,t){const{gl:r}=this;this._width=e,this._height=t,r.bindTexture(r.TEXTURE_2D,this._texture),this.updateTextureSize(),r.bindTexture(r.TEXTURE_2D,null)}begin(){const{gl:e}=this;this.previousState={framebuffer:e.getParameter(e.FRAMEBUFFER_BINDING),viewport:e.getParameter(e.VIEWPORT)},e.bindFramebuffer(e.FRAMEBUFFER,this._framebuffer),e.viewport(0,0,this._width,this._height)}end(){if(!this.previousState)return;const{gl:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.previousState.framebuffer),e.viewport(...this.previousState.viewport),this.previousState=null}loadPixels(){const{gl:e}=this;this._pixels||(this._pixels=new Uint8Array(this._width*this._height*4));const t=e.getParameter(e.FRAMEBUFFER_BINDING);e.bindFramebuffer(e.FRAMEBUFFER,this._framebuffer),e.readPixels(0,0,this._width,this._height,e.RGBA,e.UNSIGNED_BYTE,this._pixels),e.bindFramebuffer(e.FRAMEBUFFER,t)}get(e,t,r,i){const{gl:s}=this;if(e===void 0&&t===void 0){const n=new Uint8Array(this._width*this._height*4),o=s.getParameter(s.FRAMEBUFFER_BINDING);return s.bindFramebuffer(s.FRAMEBUFFER,this._framebuffer),s.readPixels(0,0,this._width,this._height,s.RGBA,s.UNSIGNED_BYTE,n),s.bindFramebuffer(s.FRAMEBUFFER,o),n}else if(r===void 0&&i===void 0){(e<0||t<0||e>=this._width||t>=this._height)&&(console.warn("The x and y values passed to Framebuffer.get are outside of its range and will be clamped."),e=Math.max(0,Math.min(e,this._width-1)),t=Math.max(0,Math.min(t,this._height-1)));const n=new Uint8Array(4),o=s.getParameter(s.FRAMEBUFFER_BINDING);return s.bindFramebuffer(s.FRAMEBUFFER,this._framebuffer),s.readPixels(e,t,1,1,s.RGBA,s.UNSIGNED_BYTE,n),s.bindFramebuffer(s.FRAMEBUFFER,o),[n[0],n[1],n[2],n[3]]}else{e=Math.max(0,Math.min(e,this._width-1)),t=Math.max(0,Math.min(t,this._height-1)),r=Math.max(1,Math.min(r,this._width-e)),i=Math.max(1,Math.min(i,this._height-t));const n=new Uint8Array(r*i*4),o=s.getParameter(s.FRAMEBUFFER_BINDING);return s.bindFramebuffer(s.FRAMEBUFFER,this._framebuffer),s.readPixels(e,t,r,i,s.RGBA,s.UNSIGNED_BYTE,n),s.bindFramebuffer(s.FRAMEBUFFER,o),n}}dispose(){const{gl:e}=this;this._framebuffer&&(e.deleteFramebuffer(this._framebuffer),this._framebuffer=null),this._texture&&(e.deleteTexture(this._texture),this._texture=null),this._pixels=null}get isDisposed(){return this._framebuffer===null||this._texture===null}get framebuffer(){return this._framebuffer}get texture(){return this._texture}get width(){return this._width}get height(){return this._height}get pixels(){return this._pixels}}class j{constructor(e,t,r){a(this,"gl");a(this,"x");a(this,"y");this.gl=e,this.x=t,this.y=r}}class M{constructor(e,t,r,i,s){a(this,"gl");a(this,"vertexBuffer");a(this,"vertexCount",6);a(this,"bytesPerVertex");this.gl=e,this.bytesPerVertex=16;const n=e.getParameter(e.VIEWPORT),o=n[2],l=n[3],c=e.getParameter(e.FRAMEBUFFER_BINDING)!==null,u=t/o*2-1,d=(t+i)/o*2-1;let f,g;c?(f=r/l*2-1,g=(r+s)/l*2-1):(f=1-r/l*2,g=1-(r+s)/l*2);let x,_,F,w;x=u,F=d,_=f,w=g;const C=this.generateVertices(x,_,F,w);this.vertexBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer),e.bufferData(e.ARRAY_BUFFER,C,e.STATIC_DRAW)}generateVertices(e,t,r,i){return new Float32Array([e,i,0,1,r,i,1,1,e,t,0,0,e,t,0,0,r,i,1,1,r,t,1,0])}render(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer);const e=this.gl.getParameter(this.gl.CURRENT_PROGRAM);let t=this.gl.getAttribLocation(e,"a_position"),r=this.gl.getAttribLocation(e,"a_texCoord");this.gl.enableVertexAttribArray(t),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,this.bytesPerVertex,0),this.gl.enableVertexAttribArray(r),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,this.bytesPerVertex,8),this.gl.drawArrays(this.gl.TRIANGLES,0,this.vertexCount),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r)}}class se extends j{constructor(t,r,i,s,n){super(t,r,i);a(this,"width");a(this,"height");this.width=s,this.height=n}renderFill(){new M(this.gl,this.x,this.y,this.width,this.height).render()}renderStroke(t){if(t<=0)return;const r=new M(this.gl,this.x,this.y,this.width,t),i=new M(this.gl,this.x+this.width-t,this.y,t,this.height),s=new M(this.gl,this.x,this.y+this.height-t,this.width,t),n=new M(this.gl,this.x,this.y,t,this.height);r.render(),i.render(),s.render(),n.render()}}class ne{constructor(e,t,r,i,s,n){a(this,"gl");a(this,"vertexBuffer");a(this,"vertexCount",6);a(this,"bytesPerVertex");this.gl=e,this.bytesPerVertex=16;const o=e.getParameter(e.VIEWPORT),l=o[2],c=o[3],u=e.getParameter(e.FRAMEBUFFER_BINDING)!==null,d=i-t,f=s-r,g=Math.sqrt(d*d+f*f);if(g===0){const Oe=this.generateVertices(0,0,0,0);this.vertexBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer),e.bufferData(e.ARRAY_BUFFER,Oe,e.STATIC_DRAW);return}const x=d/g,F=-(f/g),w=x,C=n/2,y=t+F*C,B=r+w*C,D=t-F*C,R=r-w*C,H=i+F*C,G=s+w*C,ke=i-F*C,re=s-w*C,ze=y/l*2-1,$e=D/l*2-1,Le=H/l*2-1,Xe=ke/l*2-1;let O,N,W,Y;u?(O=B/c*2-1,N=R/c*2-1,W=G/c*2-1,Y=re/c*2-1):(O=1-B/c*2,N=1-R/c*2,W=1-G/c*2,Y=1-re/c*2);const He=this.generateLineVertices(ze,O,$e,N,Le,W,Xe,Y);this.vertexBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer),e.bufferData(e.ARRAY_BUFFER,He,e.STATIC_DRAW)}generateVertices(e,t,r,i){return new Float32Array([e,i,0,1,r,i,1,1,e,t,0,0,e,t,0,0,r,i,1,1,r,t,1,0])}generateLineVertices(e,t,r,i,s,n,o,l){return new Float32Array([e,t,0,0,r,i,0,1,s,n,1,0,r,i,0,1,o,l,1,1,s,n,1,0])}render(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer);const e=this.gl.getParameter(this.gl.CURRENT_PROGRAM);let t=this.gl.getAttribLocation(e,"a_position"),r=this.gl.getAttribLocation(e,"a_texCoord");this.gl.enableVertexAttribArray(t),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,this.bytesPerVertex,0),this.gl.enableVertexAttribArray(r),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,this.bytesPerVertex,8),this.gl.drawArrays(this.gl.TRIANGLES,0,this.vertexCount),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r)}}class oe extends j{constructor(t,r,i,s,n){super(t,r,i);a(this,"x2");a(this,"y2");this.x2=s,this.y2=n}renderFill(){}renderStroke(t){if(t<=0)return;new ne(this.gl,this.x,this.y,this.x2,this.y2,t).render()}}class T{constructor(e,t,r){a(this,"gl");a(this,"program");a(this,"uniformLocations",new Map);a(this,"attributeLocations",new Map);a(this,"textureUnitCounter",0);this.gl=e,this.program=this.createProgram(t,r),this.cacheLocations()}createProgram(e,t){const r=this.createShader(this.gl.VERTEX_SHADER,e),i=this.createShader(this.gl.FRAGMENT_SHADER,t),s=this.gl.createProgram();if(this.gl.attachShader(s,r),this.gl.attachShader(s,i),this.gl.linkProgram(s),!this.gl.getProgramParameter(s,this.gl.LINK_STATUS)){const n=this.gl.getProgramInfoLog(s);throw new Error(`Shader program link error: ${n}`)}return this.gl.deleteShader(r),this.gl.deleteShader(i),s}createShader(e,t){const r=this.gl.createShader(e);if(this.gl.shaderSource(r,t),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS)){const i=this.gl.getShaderInfoLog(r);throw this.gl.deleteShader(r),new Error(`Shader compilation error: ${i}`)}return r}cacheLocations(){const e=this.gl.getProgramParameter(this.program,this.gl.ACTIVE_UNIFORMS);for(let r=0;r<e;r++){const i=this.gl.getActiveUniform(this.program,r);if(i){const s=this.gl.getUniformLocation(this.program,i.name);s&&this.uniformLocations.set(i.name,s)}}const t=this.gl.getProgramParameter(this.program,this.gl.ACTIVE_ATTRIBUTES);for(let r=0;r<t;r++){const i=this.gl.getActiveAttrib(this.program,r);if(i){const s=this.gl.getAttribLocation(this.program,i.name);this.attributeLocations.set(i.name,s)}}}use(){this.gl.useProgram(this.program),this.resetTextureUnits()}setUniform(e,t){const r=this.uniformLocations.get(e);if(!r)return;const i=this.getUniformInfo(e);if(typeof t=="number")i&&i.type===this.gl.INT?this.gl.uniform1i(r,Math.floor(t)):this.gl.uniform1f(r,t);else if(typeof t=="boolean")this.gl.uniform1i(r,t?1:0);else if(Array.isArray(t))if(i&&(i.type===this.gl.INT_VEC2||i.type===this.gl.INT_VEC3||i.type===this.gl.INT_VEC4)){const s=t.map(n=>Math.floor(n));switch(s.length){case 2:this.gl.uniform2iv(r,s);break;case 3:this.gl.uniform3iv(r,s);break;case 4:this.gl.uniform4iv(r,s);break;default:console.warn(`Unsupported array length ${s.length} for uniform '${e}'`)}}else switch(t.length){case 2:this.gl.uniform2f(r,t[0],t[1]);break;case 3:this.gl.uniform3f(r,t[0],t[1],t[2]);break;case 4:this.gl.uniform4f(r,t[0],t[1],t[2],t[3]);break;default:console.warn(`Unsupported array length ${t.length} for uniform '${e}'`)}else if(t instanceof WebGLTexture){const s=this.getNextTextureUnit();this.gl.uniform1i(r,s),this.gl.activeTexture(this.gl.TEXTURE0+s),this.gl.bindTexture(this.gl.TEXTURE_2D,t)}else if(t&&typeof t=="object"&&"texture"in t){const s=this.getNextTextureUnit();this.gl.uniform1i(r,s),this.gl.activeTexture(this.gl.TEXTURE0+s),this.gl.bindTexture(this.gl.TEXTURE_2D,t.texture)}else console.warn(`Unsupported uniform type for '${e}':`,typeof t)}getUniformInfo(e){const t=this.gl.getProgramParameter(this.program,this.gl.ACTIVE_UNIFORMS);for(let r=0;r<t;r++){const i=this.gl.getActiveUniform(this.program,r);if(i&&i.name===e)return i}return null}getNextTextureUnit(){return this.textureUnitCounter++}hasUniform(e){return this.uniformLocations.has(e)}hasAttribute(e){return this.attributeLocations.has(e)}get glProgram(){return this.program}dispose(){this.program&&(this.gl.deleteProgram(this.program),this.program=null),this.uniformLocations.clear(),this.attributeLocations.clear(),this.textureUnitCounter=0}get isDisposed(){return this.program===null}resetTextureUnits(){this.textureUnitCounter=0}}var S="attribute vec2 a_position;attribute vec2 a_texCoord;varying vec2 v_uv;uniform float u_rotation;uniform vec2 u_center;uniform float u_aspectRatio;mat2 rotate2D(float angle){float s=sin(angle);float c=cos(angle);return mat2(c,-s,s,c);}void main(){v_uv=a_texCoord;vec2 pos=a_position;pos-=u_center;pos.x*=u_aspectRatio;pos=rotate2D(-u_rotation)*pos;pos.x/=u_aspectRatio;pos+=u_center;gl_Position=vec4(pos,0.0,1.0);}",ae="precision lowp float;uniform sampler2D u_texture;varying vec2 v_uv;void main(){gl_FragColor=texture2D(u_texture,v_uv);}",he="precision lowp float;uniform vec4 u_color;void main(){gl_FragColor=u_color;}";class le{constructor(e){a(this,"gl");a(this,"imageShader");a(this,"solidColorShader");a(this,"currentShader",null);a(this,"currentFillColor",[1,1,1,1]);a(this,"fillMode",!0);a(this,"currentStrokeColor",[0,0,0,1]);a(this,"currentStrokeWeight",1);a(this,"strokeMode",!0);a(this,"currentRotation",0);a(this,"stateStack",[]);this.gl=e,this.imageShader=new T(this.gl,S,ae),this.solidColorShader=new T(this.gl,S,he),this.gl.enable(this.gl.BLEND),this.gl.blendEquation(this.gl.FUNC_ADD),this.gl.blendFunc(this.gl.ONE,this.gl.ONE_MINUS_SRC_ALPHA)}shader(e){this.currentShader=e,e.use()}fill(e,t,r,i){if(this.fillMode=!0,t===void 0&&r===void 0&&i===void 0){const s=e/255;this.currentFillColor=[s,s,s,1]}else if(r!==void 0&&i===void 0)this.currentFillColor=[e/255,t/255,r/255,1];else if(r!==void 0&&i!==void 0)this.currentFillColor=[e/255,t/255,r/255,i/255];else throw new Error("Invalid fill parameters. Use fill(gray), fill(r,g,b), or fill(r,g,b,a)")}stroke(e,t,r,i){if(this.strokeMode=!0,t===void 0&&r===void 0&&i===void 0){const s=e/255;this.currentStrokeColor=[s,s,s,1]}else if(r!==void 0&&i===void 0)this.currentStrokeColor=[e/255,t/255,r/255,1];else if(r!==void 0&&i!==void 0)this.currentStrokeColor=[e/255,t/255,r/255,i/255];else throw new Error("Invalid stroke parameters. Use stroke(gray), stroke(r,g,b), or stroke(r,g,b,a)")}strokeWeight(e){if(e<0)throw new Error("Stroke weight must be non-negative");this.currentStrokeWeight=e}noStroke(){this.strokeMode=!1}noFill(){this.fillMode=!1}rotate(e){this.currentRotation=e}push(){this.stateStack.push({fillColor:[...this.currentFillColor],fillMode:this.fillMode,strokeColor:[...this.currentStrokeColor],strokeWeight:this.currentStrokeWeight,strokeMode:this.strokeMode,rotation:this.currentRotation})}pop(){const e=this.stateStack.pop();e?(this.currentFillColor=e.fillColor,this.fillMode=e.fillMode,this.currentStrokeColor=e.strokeColor,this.currentStrokeWeight=e.strokeWeight,this.strokeMode=e.strokeMode,this.currentRotation=e.rotation):console.warn("pop() called without matching push()")}reset(){this.currentShader=null,this.stateStack=[],this.currentRotation=0,this.fillMode=!0,this.strokeMode=!0,this.currentFillColor=[1,1,1,1],this.currentStrokeColor=[0,0,0,1],this.currentStrokeWeight=1}createShader(e,t){return new T(this.gl,e,t)}setUniform(e,t){this.currentShader.setUniform(e,t)}rect(e,t,r,i){const s=new se(this.gl,e,t,r,i);if(this.currentShader!==null){if(this.currentRotation!==0){const{centerX:d,centerY:f,radians:g,aspectRatio:x}=this.calculateRotationParams(e,t,r,i);this.setUniform("u_rotation",g),this.setUniform("u_center",[d,f]),this.setUniform("u_aspectRatio",x)}else this.setUniform("u_rotation",0),this.setUniform("u_center",[0,0]),this.setUniform("u_aspectRatio",1);s.renderFill(),this.currentShader=null;return}const n=this.solidColorShader,{centerX:o,centerY:l,radians:c,aspectRatio:u}=this.calculateRotationParams(e,t,r,i);this.fillMode&&(this.shader(n),this.setUniform("u_color",this.currentFillColor),this.setUniform("u_rotation",c),this.setUniform("u_center",[o,l]),this.setUniform("u_aspectRatio",u),s.renderFill()),this.strokeMode&&(this.shader(n),this.setUniform("u_color",this.currentStrokeColor),this.setUniform("u_rotation",c),this.setUniform("u_center",[o,l]),this.setUniform("u_aspectRatio",u),s.renderStroke(this.currentStrokeWeight)),this.currentShader=null}line(e,t,r,i){if(!this.strokeMode)return;const s=new oe(this.gl,e,t,r,i);if(this.currentShader!==null){if(this.currentRotation!==0){const _=(e+r)/2,F=(t+i)/2,w=Math.abs(r-e),C=Math.abs(i-t),{centerX:y,centerY:B,radians:D,aspectRatio:R}=this.calculateRotationParams(_-w/2,F-C/2,w,C);this.setUniform("u_rotation",D),this.setUniform("u_center",[y,B]),this.setUniform("u_aspectRatio",R)}else this.setUniform("u_rotation",0),this.setUniform("u_center",[0,0]),this.setUniform("u_aspectRatio",1);s.renderStroke(this.currentStrokeWeight),this.currentShader=null;return}const n=this.solidColorShader,o=(e+r)/2,l=(t+i)/2,c=Math.abs(r-e),u=Math.abs(i-t),{centerX:d,centerY:f,radians:g,aspectRatio:x}=this.calculateRotationParams(o-c/2,l-u/2,c,u);this.shader(n),this.setUniform("u_color",this.currentStrokeColor),this.setUniform("u_rotation",g),this.setUniform("u_center",[d,f]),this.setUniform("u_aspectRatio",x),s.renderStroke(this.currentStrokeWeight),this.currentShader=null}calculateRotationParams(e,t,r,i){const s=this.gl.getParameter(this.gl.VIEWPORT),n=s[2],o=s[3],l=n/o,c=this.gl.getParameter(this.gl.FRAMEBUFFER_BINDING)!==null,u=e+r/2,d=t+i/2,f=u/n*2-1;let g;c?g=d/o*2-1:g=1-d/o*2;const x=this.currentRotation*Math.PI/180;return{centerX:f,centerY:g,radians:x,aspectRatio:l}}createFramebuffer(e,t,r={}){return new ie(this.gl,e,t,r)}background(e,t=e,r=e,i=255){this.clear(e/255,t/255,r/255,i/255)}clear(e=0,t=0,r=0,i=0){this.gl.clearColor(e,t,r,i),this.gl.clear(this.gl.COLOR_BUFFER_BIT)}resetViewport(){this.gl.viewport(0,0,this.gl.canvas.width,this.gl.canvas.height)}get context(){return this.gl}dispose(){this.imageShader&&!this.imageShader.isDisposed&&this.imageShader.dispose(),this.solidColorShader&&!this.solidColorShader.isDisposed&&this.solidColorShader.dispose(),this.imageShader=null,this.solidColorShader=null,this.currentShader=null,this.stateStack=[]}get isDisposed(){return this.imageShader===null||this.solidColorShader===null}image(e,t,r,i,s){this.shader(this.imageShader),this.setUniform("u_texture",e.texture);const{centerX:n,centerY:o,radians:l,aspectRatio:c}=this.calculateRotationParams(t,r,i??e.width,s??e.height);this.setUniform("u_rotation",l),this.setUniform("u_center",[n,o]),this.setUniform("u_aspectRatio",c),this.rect(t,r,i??e.width,s??e.height)}}var m={};m.parse=function(h){var e=function(s,n,o,l){var c=m.T,u={cmap:c.cmap,head:c.head,hhea:c.hhea,maxp:c.maxp,hmtx:c.hmtx,loca:c.loca,glyf:c.glyf},d={_data:s,_index:n,_offset:o};for(var f in u){var g=m.findTable(s,f,o);if(g){var x=g[0],_=l[x];_==null&&(_=u[f].parseTab(s,x,g[1],d)),d[f]=l[x]=_}}return d},t=new Uint8Array(h),r={},i=e(t,0,0,r);return[i]},m.findTable=function(h,e,t){for(var r=m.B,i=r.readUshort(h,t+4),s=t+12,n=0;n<i;n++){var o=r.readASCII(h,s,4);r.readUint(h,s+4);var l=r.readUint(h,s+8),c=r.readUint(h,s+12);if(o==e)return[l,c];s+=16}return null},m.T={},m.B={readShort:function(h,e){var t=m.B.t.uint16;return t[0]=h[e]<<8|h[e+1],m.B.t.int16[0]},readUshort:function(h,e){return h[e]<<8|h[e+1]},readUshorts:function(h,e,t){for(var r=[],i=0;i<t;i++)r.push(m.B.readUshort(h,e+i*2));return r},readUint:function(h,e){var t=m.B.t.uint8;return t[3]=h[e],t[2]=h[e+1],t[1]=h[e+2],t[0]=h[e+3],m.B.t.uint32[0]},readASCII:function(h,e,t){for(var r="",i=0;i<t;i++)r+=String.fromCharCode(h[e+i]);return r},t:function(){var h=new ArrayBuffer(8);return{uint8:new Uint8Array(h),int16:new Int16Array(h),uint16:new Uint16Array(h),uint32:new Uint32Array(h)}}()},m.T.cmap={parseTab:function(h,e,t){var r={tables:[],ids:{},off:e};h=new Uint8Array(h.buffer,e,t),e=0;var i=m.B,s=i.readUshort,n=m.T.cmap;s(h,e),e+=2;var o=s(h,e);e+=2;for(var l=[],c=0;c<o;c++){var u=s(h,e);e+=2;var d=s(h,e);e+=2;var f=i.readUint(h,e);e+=4;var g="p"+u+"e"+d,x=l.indexOf(f);if(x==-1){x=r.tables.length;var _={};l.push(f);var F=_.format=s(h,f);F==4?_=n.parse4(h,f,_):F==12&&(_=n.parse12(h,f,_)),r.tables.push(_)}r.ids[g]!=null&&console.log("multiple tables for one platform+encoding: "+g),r.ids[g]=x}return r},parse4:function(h,e,t){var r=m.B,i=r.readUshort,s=r.readUshorts,n=e;e+=2;var o=i(h,e);e+=2,i(h,e),e+=2;var l=i(h,e);e+=2;var c=l>>>1;t.searchRange=i(h,e),e+=2,t.entrySelector=i(h,e),e+=2,t.rangeShift=i(h,e),e+=2,t.endCount=s(h,e,c),e+=c*2,e+=2,t.startCount=s(h,e,c),e+=c*2,t.idDelta=[];for(var u=0;u<c;u++)t.idDelta.push(r.readShort(h,e)),e+=2;return t.idRangeOffset=s(h,e,c),e+=c*2,t.glyphIdArray=s(h,e,n+o-e>>1),t},parse12:function(h,e,t){var r=m.B,i=r.readUint;e+=4,i(h,e),e+=4,i(h,e),e+=4;var s=i(h,e)*3;e+=4;for(var n=t.groups=new Uint32Array(s),o=0;o<s;o+=3)n[o]=i(h,e+(o<<2)),n[o+1]=i(h,e+(o<<2)+4),n[o+2]=i(h,e+(o<<2)+8);return t}},m.T.head={parseTab:function(h,e,t){var r=m.B,i={};return e+=18,i.unitsPerEm=r.readUshort(h,e),e+=2,e+=16,i.xMin=r.readShort(h,e),e+=2,i.yMin=r.readShort(h,e),e+=2,i.xMax=r.readShort(h,e),e+=2,i.yMax=r.readShort(h,e),e+=2,e+=6,i.indexToLocFormat=r.readShort(h,e),i}},m.T.hhea={parseTab:function(h,e,t){var r=m.B,i={};e+=4;for(var s=["ascender","descender","lineGap","advanceWidthMax","minLeftSideBearing","minRightSideBearing","xMaxExtent","caretSlopeRise","caretSlopeRun","caretOffset","res0","res1","res2","res3","metricDataFormat","numberOfHMetrics"],n=0;n<s.length;n++){var o=s[n],l=o=="advanceWidthMax"||o=="numberOfHMetrics"?r.readUshort:r.readShort;i[o]=l(h,e+n*2)}return i}},m.T.hmtx={parseTab:function(h,e,t,r){for(var i=m.B,s=[],n=[],o=r.maxp.numGlyphs,l=r.hhea.numberOfHMetrics,c=0,u=0,d=0;d<l;)c=i.readUshort(h,e+(d<<2)),u=i.readShort(h,e+(d<<2)+2),s.push(c),n.push(u),d++;for(;d<o;)s.push(c),n.push(u),d++;return{aWidth:s,lsBearing:n}}},m.T.maxp={parseTab:function(h,e,t){var r=m.B,i=r.readUshort,s={};return r.readUint(h,e),e+=4,s.numGlyphs=i(h,e),e+=2,s}},m.T.loca={parseTab:function(h,e,t,r){var i=m.B,s=[],n=r.head.indexToLocFormat,o=r.maxp.numGlyphs+1;if(n==0)for(var l=0;l<o;l++)s.push(i.readUshort(h,e+(l<<1))<<1);if(n==1)for(var l=0;l<o;l++)s.push(i.readUint(h,e+(l<<2)));return s}},m.T.glyf={parseTab:function(h,e,t,r){for(var i=[],s=r.maxp.numGlyphs,n=0;n<s;n++)i.push(null);return i},_parseGlyf:function(h,e){var t=m.B,r=h._data,i=h.loca;if(i[e]==i[e+1])return null;var s=m.findTable(r,"glyf",h._offset)[0]+i[e],n={};if(n.noc=t.readShort(r,s),s+=2,n.xMin=t.readShort(r,s),s+=2,n.yMin=t.readShort(r,s),s+=2,n.xMax=t.readShort(r,s),s+=2,n.yMax=t.readShort(r,s),s+=2,n.xMin>=n.xMax||n.yMin>=n.yMax)return null;if(n.noc>0){n.endPts=[];for(var o=0;o<n.noc;o++)n.endPts.push(t.readUshort(r,s)),s+=2;var l=t.readUshort(r,s);if(s+=2,r.length-s<l)return null;s+=l;var c=n.endPts[n.noc-1]+1;n.flags=[];for(var o=0;o<c;o++){var u=r[s];if(s++,n.flags.push(u),u&8){var d=r[s];s++;for(var f=0;f<d;f++)n.flags.push(u),o++}}n.xs=[];for(var o=0;o<c;o++){var g=(n.flags[o]&2)!=0,x=(n.flags[o]&16)!=0;g?(n.xs.push(x?r[s]:-r[s]),s++):x?n.xs.push(0):(n.xs.push(t.readShort(r,s)),s+=2)}n.ys=[];for(var o=0;o<c;o++){var g=(n.flags[o]&4)!=0,x=(n.flags[o]&32)!=0;g?(n.ys.push(x?r[s]:-r[s]),s++):x?n.ys.push(0):(n.ys.push(t.readShort(r,s)),s+=2)}for(var _=0,F=0,o=0;o<c;o++)_+=n.xs[o],F+=n.ys[o],n.xs[o]=_,n.ys[o]=F}else n.parts=[];return n}},typeof module<"u"&&module.exports?module.exports=m:typeof window<"u"&&(window.Typr=m);class ce{extractCharacters(e){var r;const t=[];return(r=e==null?void 0:e.cmap)!=null&&r.tables?(e.cmap.tables.forEach(i=>{if(i.format===4){const s=this._extractCharactersFromFormat4Table(i);t.push(...s)}else if(i.format===12){const s=this._extractCharactersFromFormat12Table(i);t.push(...s)}}),[...new Set(t)]):[]}_extractCharactersFromFormat4Table(e){const t=[];if(!e.startCount||!e.endCount||!e.idRangeOffset||!e.idDelta)return t;for(let r=0;r<e.startCount.length;r++){const i=e.startCount[r],s=e.endCount[r];if(!(i===65535&&s===65535)){for(let n=i;n<=s;n++)if(this._calculateGlyphIndexFormat4(e,n,r)>0){const l=String.fromCodePoint(n);t.push(l)}}}return t}_extractCharactersFromFormat12Table(e){const t=[];if(!e.groups)return t;for(let r=0;r<e.groups.length;r+=3){const i=e.groups[r],s=e.groups[r+1],n=e.groups[r+2];for(let o=i;o<=s;o++)if(n+(o-i)>0){const c=String.fromCodePoint(o);t.push(c)}}return t}_calculateGlyphIndexFormat4(e,t,r){if(e.idRangeOffset[r]===0)return t+e.idDelta[r]&65535;{const i=e.idRangeOffset[r]/2+(t-e.startCount[r])-(e.startCount.length-r);if(i>=0&&e.glyphIdArray&&i<e.glyphIdArray.length){const s=e.glyphIdArray[i];if(s!==0)return s+e.idDelta[r]&65535}}return 0}filterProblematicCharacters(e){return e.filter(t=>this._isValidCharacter(t))}_isValidCharacter(e){const t=e.codePointAt(0)||0;return!(t>=0&&t<=31&&t!==9&&t!==10&&t!==13||t>=127&&t<=159)}}class ue{constructor(e){a(this,"_textureCanvas");a(this,"_textureContext");a(this,"_renderer");this._renderer=e,this._textureCanvas=document.createElement("canvas"),this._textureContext=this._textureCanvas.getContext("2d",{willReadFrequently:!0,alpha:!1})}createTextureAtlas(e,t,r,i){const s=e.length,n=Math.ceil(Math.sqrt(s)),o=Math.ceil(s/n),l=t.width*n,c=t.height*o;this._setupCanvas(l,c,r,i),this._renderCharactersToCanvas(e,t,n,r),this._applyBlackWhiteThreshold();const u=this._renderer.createFramebuffer(l,c,{filter:"nearest"});return u.update(this._textureCanvas),{framebuffer:u,columns:n,rows:o}}_setupCanvas(e,t,r,i){this._textureCanvas.width=e,this._textureCanvas.height=t,this._textureCanvas.style.width=e+"px",this._textureCanvas.style.height=e+"px",this._textureContext.imageSmoothingEnabled=!1,this._textureCanvas.style.imageRendering="pixelated",this._textureContext.fillStyle="black",this._textureContext.fillRect(0,0,e,t),this._textureContext.font=`${r}px ${i}`,this._textureContext.textBaseline="top",this._textureContext.textAlign="left",this._textureContext.fillStyle="white"}_renderCharactersToCanvas(e,t,r,i){for(let s=0;s<e.length;s++){const n=s%r,o=Math.floor(s/r),l=n*t.width+t.width*.5,c=o*t.height+t.height*.5,u=Math.round(l-t.width*.5),d=Math.round(c-i*.5);this._textureContext.fillText(e[s].character,u,d)}}_applyBlackWhiteThreshold(e=128){const t=this._textureContext.getImageData(0,0,this._textureCanvas.width,this._textureCanvas.height),r=t.data;for(let i=0;i<r.length;i+=4){const s=.299*r[i]+.587*r[i+1]+.114*r[i+2],n=e+32,o=s>n?255:0;r[i]=o,r[i+1]=o,r[i+2]=o}this._textureContext.putImageData(t,0,0)}}class de{constructor(){a(this,"_tempCanvas");a(this,"_tempContext");this._tempCanvas=document.createElement("canvas"),this._tempContext=this._tempCanvas.getContext("2d")}calculateMaxGlyphDimensions(e,t,r){this._tempContext.font=`${t}px ${r}`;let i=0,s=0;for(const n of e){const o=this._tempContext.measureText(n),l=o.width,c=o.actualBoundingBoxAscent+o.actualBoundingBoxDescent;l>0&&(i=Math.max(i,l),s=Math.max(s,c))}return{width:Math.ceil(i),height:Math.ceil(s)}}}class fe{createCharacterObjects(e,t){return e.map((r,i)=>{const s=r.codePointAt(0)||0,n=this._generateCharacterColor(i);let o=0;if(t.hmtx&&t.hmtx.aWidth){const l=this._getGlyphIndex(t,s);l>0&&t.hmtx.aWidth[l]!==void 0&&(o=t.hmtx.aWidth[l])}return{character:r,unicode:s,color:n,advanceWidth:o}})}_getGlyphIndex(e,t){const r=e.cmap;if(!r||!r.tables)return 0;for(const i of r.tables)if(i.format===4){for(let s=0;s<i.startCount.length;s++)if(t>=i.startCount[s]&&t<=i.endCount[s]){if(i.idRangeOffset[s]===0)return t+i.idDelta[s]&65535;{const n=i.idRangeOffset[s]/2+(t-i.startCount[s])-(i.startCount.length-s);if(n>=0&&n<i.glyphIdArray.length){const o=i.glyphIdArray[n];if(o!==0)return o+i.idDelta[s]&65535}}}}return 0}_generateCharacterColor(e){const t=e%256,r=Math.floor(e/256)%256,i=Math.floor(e/65536)%256;return[t,r,i]}getCharacterColor(e,t){if(!b.validate(typeof e=="string"&&e.length===1,"Character must be a single character string.",{method:"getCharacterColor",providedValue:e}))return[0,0,0];const r=t.find(i=>i.character===e);return r?r.color:[0,0,0]}getCharacterColors(e,t){return b.validate(typeof e=="string"&&e.length>0,"Characters must be a string with at least one character.",{method:"getCharacterColors",providedValue:e})?e.split("").map(r=>this.getCharacterColor(r,t)||[0,0,0]):[[0,0,0]]}}class q{constructor(e,t=16){a(this,"_font");a(this,"_characters",[]);a(this,"_fontFramebuffer");a(this,"_fontSize",16);a(this,"_textureColumns",0);a(this,"_textureRows",0);a(this,"_maxGlyphDimensions",{width:0,height:0});a(this,"_fontFace");a(this,"_fontFamilyName","UrsaFont");a(this,"_characterExtractor");a(this,"_textureAtlas");a(this,"_metricsCalculator");a(this,"_characterColorMapper");this._fontSize=t,this._characterExtractor=new ce,this._textureAtlas=new ue(e),this._metricsCalculator=new de,this._characterColorMapper=new fe}async initialize(e){let t;if(e){const r=await fetch(e);if(!r.ok)throw new p(`Failed to load font file: ${r.status} ${r.statusText}`);t=await r.arrayBuffer()}else throw new p("Embedded font not available. This appears to be a minified build - please provide `fontSource`.");await this._loadFontFace(t),this._font=m.parse(t)[0],await this._initializeFont()}setFontSize(e){if(e===void 0)return this._fontSize;this._fontSize=e,this._maxGlyphDimensions=this._metricsCalculator.calculateMaxGlyphDimensions(this._characters.map(r=>r.character),this._fontSize,this._fontFamilyName);const t=this._textureAtlas.createTextureAtlas(this._characters,this._maxGlyphDimensions,this._fontSize,this._fontFamilyName);this._fontFramebuffer=t.framebuffer,this._textureColumns=t.columns,this._textureRows=t.rows}async loadFont(e){try{const t=await fetch(e);if(!t.ok)throw new p(`Failed to load font file: ${t.status} ${t.statusText}`);const r=await t.arrayBuffer();await this._loadFontFace(r);const i=m.parse(r);if(!i||i.length===0)throw new Error("Failed to parse font file");this._font=i[0],await this._initializeFont()}catch(t){throw new p(`Failed to load font: ${t instanceof Error?t.message:"Unknown error"}`,t)}}async _loadFontFace(e){const t=Date.now();this._fontFamilyName=this._fontFamilyName==="UrsaFont"?"UrsaFont":`CustomFont_${t}`,this._fontFace=new FontFace(this._fontFamilyName,e),await this._fontFace.load(),document.fonts.add(this._fontFace)}async _initializeFont(){const e=this._characterExtractor.extractCharacters(this._font),t=this._characterExtractor.filterProblematicCharacters(e);this._characters=this._characterColorMapper.createCharacterObjects(t,this._font),this._maxGlyphDimensions=this._metricsCalculator.calculateMaxGlyphDimensions(t,this._fontSize,this._fontFamilyName);const r=this._textureAtlas.createTextureAtlas(this._characters,this._maxGlyphDimensions,this._fontSize,this._fontFamilyName);this._fontFramebuffer=r.framebuffer,this._textureColumns=r.columns,this._textureRows=r.rows}getCharacterColor(e){return this._characterColorMapper.getCharacterColor(e,this._characters)}getCharacterColors(e){return this._characterColorMapper.getCharacterColors(e,this._characters)}hasAllCharacters(e){if(typeof e!="string"||e.length===0)return!1;const t=new Set(this._characters.map(r=>r.character));for(const r of e)if(!t.has(r))return!1;return!0}get fontFramebuffer(){return this._fontFramebuffer}get characters(){return this._characters}get textureColumns(){return this._textureColumns}get textureRows(){return this._textureRows}get maxGlyphDimensions(){return this._maxGlyphDimensions}dispose(){this._fontFramebuffer&&!this._fontFramebuffer.isDisposed&&this._fontFramebuffer.dispose(),this._fontFace&&document.fonts.has(this._fontFace)&&document.fonts.delete(this._fontFace),this._fontFramebuffer=null,this._fontFace=null,this._font=null,this._characters=[],this._maxGlyphDimensions={width:0,height:0},this._textureColumns=0,this._textureRows=0}get isDisposed(){return this._fontFramebuffer===null||this._font===null}get fontSize(){return this._fontSize}get font(){return this._font}}class Q{constructor(e,t,r){a(this,"_cols");a(this,"_rows");a(this,"_width");a(this,"_height");a(this,"_offsetX");a(this,"_offsetY");a(this,"_fixedDimensions",!1);a(this,"_canvas");a(this,"_cellWidth");a(this,"_cellHeight");this._canvas=e,this._cellWidth=t,this._cellHeight=r,this.reset()}reset(){if(!this._fixedDimensions){const e=this._canvas.getBoundingClientRect();let t=Math.round(e.width),r=Math.round(e.height);[this._cols,this._rows]=[Math.floor(t/this._cellWidth),Math.floor(r/this._cellHeight)]}this._resizeGrid()}_resizeGrid(){const e=this._canvas.getBoundingClientRect();let t=Math.round(e.width),r=Math.round(e.height);this._width=this._cols*this._cellWidth,this._height=this._rows*this._cellHeight,this._offsetX=Math.floor((t-this._width)/2),this._offsetY=Math.floor((r-this._height)/2)}resizeCellPixelDimensions(e,t){[this._cellWidth,this._cellHeight]=[e,t],this.reset()}resizeGridDimensions(e,t){this._fixedDimensions=!0,[this._cols,this._rows]=[e,t],this._resizeGrid()}resetGridDimensions(){this._fixedDimensions=!1,this.reset()}resize(){this._fixedDimensions?this._resizeGrid():this.reset()}fixedDimensions(e){if(e===void 0)return this._fixedDimensions;this._fixedDimensions=e}get cellWidth(){return this._cellWidth}get cellHeight(){return this._cellHeight}dispose(){this._canvas=null,this._cols=0,this._rows=0,this._width=0,this._height=0,this._offsetX=0,this._offsetY=0,this._cellWidth=0,this._cellHeight=0}get isDisposed(){return this._canvas===null}get cols(){return this._cols}get rows(){return this._rows}get width(){return this._width}get height(){return this._height}get offsetX(){return this._offsetX}get offsetY(){return this._offsetY}}class Z{constructor(e,t=!1,r={}){a(this,"_canvas");a(this,"captureSource");a(this,"_isStandalone");this.captureSource=e,this._isStandalone=t,this._canvas=this.createCanvas(r.width,r.height)}createCanvas(e,t){var i;const r=document.createElement("canvas");if(r.className="textmodeCanvas",r.style.imageRendering="pixelated",this._isStandalone)r.width=e||800,r.height=t||600,document.body.appendChild(r);else{const s=this.captureSource.getBoundingClientRect();let n=Math.round(s.width),o=Math.round(s.height);if(this.captureSource instanceof HTMLVideoElement){const u=this.captureSource;(n===0||o===0)&&u.videoWidth>0&&u.videoHeight>0&&(n=u.videoWidth,o=u.videoHeight)}r.width=n,r.height=o,r.style.position="absolute",r.style.pointerEvents="none";const l=window.getComputedStyle(this.captureSource);let c=parseInt(l.zIndex||"0",10);isNaN(c)&&(c=0),r.style.zIndex=(c+1).toString(),this.positionOverlayCanvas(r),(i=this.captureSource.parentNode)==null||i.insertBefore(r,this.captureSource.nextSibling)}return r}positionOverlayCanvas(e){const t=this.captureSource.getBoundingClientRect();let r=this.captureSource.offsetParent;if(r&&r!==document.body){const i=r.getBoundingClientRect();e.style.top=t.top-i.top+"px",e.style.left=t.left-i.left+"px"}else e.style.top=t.top+window.scrollY+"px",e.style.left=t.left+window.scrollX+"px"}resize(e,t){if(this._isStandalone)this._canvas.width=e??this._canvas.width,this._canvas.height=t??this._canvas.height;else{const r=this.captureSource.getBoundingClientRect();let i=Math.round(r.width),s=Math.round(r.height);if(this.captureSource instanceof HTMLVideoElement){const n=this.captureSource;(i===0||s===0)&&n.videoWidth>0&&n.videoHeight>0&&(i=n.videoWidth,s=n.videoHeight)}this._canvas.width=i,this._canvas.height=s,this.positionOverlayCanvas(this._canvas)}}getWebGLContext(){const e={alpha:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!0,antialias:!1,depth:!1,stencil:!1,powerPreference:"high-performance"},t=this._canvas.getContext("webgl2",e)||this._canvas.getContext("webgl",e);if(!t)throw new p("WebGL context could not be created. Ensure your browser supports WebGL.");return t}dispose(){if(this._canvas){const e=this._canvas.getContext("webgl")||this._canvas.getContext("webgl2");if(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}this._canvas.parentNode&&this._canvas.parentNode.removeChild(this._canvas),this._canvas=null}this.captureSource=null}get isDisposed(){return this._canvas===null}get canvas(){return this._canvas}get width(){return this._canvas.width}get height(){return this._canvas.height}}class A{constructor(e,t,r,i={}){a(this,"renderer");a(this,"fontManager");a(this,"grid");a(this,"_characterFramebuffer");a(this,"_primaryColorFramebuffer");a(this,"_secondaryColorFramebuffer");a(this,"_rotationFramebuffer");a(this,"_transformFramebuffer");a(this,"_options");this.renderer=e,this.fontManager=t,this.grid=r,this._options=i,this._characterFramebuffer=this.renderer.createFramebuffer(this.grid.cols,this.grid.rows),this._primaryColorFramebuffer=this.renderer.createFramebuffer(this.grid.cols,this.grid.rows),this._secondaryColorFramebuffer=this.renderer.createFramebuffer(this.grid.cols,this.grid.rows),this._rotationFramebuffer=this.renderer.createFramebuffer(this.grid.cols,this.grid.rows),this._transformFramebuffer=this.renderer.createFramebuffer(this.grid.cols,this.grid.rows)}resize(){this._characterFramebuffer.resize(this.grid.cols,this.grid.rows),this._primaryColorFramebuffer.resize(this.grid.cols,this.grid.rows),this._secondaryColorFramebuffer.resize(this.grid.cols,this.grid.rows),this._rotationFramebuffer.resize(this.grid.cols,this.grid.rows),this._transformFramebuffer.resize(this.grid.cols,this.grid.rows)}enabled(e){this._options.enabled=e}enable(){this.enabled(!0)}disable(){this.enabled(!1)}dispose(){this._characterFramebuffer&&!this._characterFramebuffer.isDisposed&&this._characterFramebuffer.dispose(),this._primaryColorFramebuffer&&!this._primaryColorFramebuffer.isDisposed&&this._primaryColorFramebuffer.dispose(),this._secondaryColorFramebuffer&&!this._secondaryColorFramebuffer.isDisposed&&this._secondaryColorFramebuffer.dispose(),this._rotationFramebuffer&&!this._rotationFramebuffer.isDisposed&&this._rotationFramebuffer.dispose(),this._transformFramebuffer&&!this._transformFramebuffer.isDisposed&&this._transformFramebuffer.dispose(),this._characterFramebuffer=null,this._primaryColorFramebuffer=null,this._secondaryColorFramebuffer=null,this._rotationFramebuffer=null,this._transformFramebuffer=null}get isDisposed(){return this._characterFramebuffer===null}get characterFramebuffer(){return this._characterFramebuffer}get primaryColorFramebuffer(){return this._primaryColorFramebuffer}get secondaryColorFramebuffer(){return this._secondaryColorFramebuffer}get rotationFramebuffer(){return this._rotationFramebuffer}get transformFramebuffer(){return this._transformFramebuffer}get options(){return this._options}}class me{constructor(e,t){a(this,"_framebuffer");a(this,"_renderer");a(this,"_colors");this._renderer=e,this._colors=t;const r=Math.max(this._colors.length,1);this._framebuffer=this._renderer.createFramebuffer(r,1),this._updateFramebuffer()}_updateFramebuffer(){if(!this._framebuffer)return;const e=Math.max(this._colors.length,1),t=1;this._framebuffer.width!==e&&this._framebuffer.resize(e,t);const r=new Uint8Array(e*t*4);for(let i=0;i<e;i++){const s=i<this._colors.length?this._colors[i]:[0,0,0],n=i*4;r[n]=s[0],r[n+1]=s[1],r[n+2]=s[2],r[n+3]=255}this._framebuffer.updatePixels(r,e,t)}setColors(e){this._colors=e,this._updateFramebuffer()}get colors(){return this._colors}get framebuffer(){return this._framebuffer}get texture(){return this._framebuffer.texture}}class k extends A{constructor(t,r,i,s={}){super(t,r,i,s);a(this,"palette");this.palette=new me(this.renderer,this.fontManager.getCharacterColors(" .:-=+*%@#"))}characters(t){b.validate(this.fontManager.hasAllCharacters(t),"One or more characters do not exist in the current font.",{method:"characters",providedValue:t})&&(this._options.characters=t,this.palette.setColors(this.fontManager.getCharacterColors(t)))}characterColor(t,r=t,i=t,s=255){b.validate([t,r,i,s].every(n=>n>=0&&n<=255),"Character color values must be between 0 and 255",{method:"characterColor",providedValues:{r:t,g:r,b:i,a:s}})&&(this._options.characterColor=[t,r,i,s])}characterColorMode(t){b.validate(["sampled","fixed"].includes(t),"Invalid character color mode. Must be 'sampled' or 'fixed'.",{method:"characterColorMode",providedValue:t})&&(this._options.characterColorMode=t)}cellColor(t,r=t,i=t,s=255){b.validate([t,r,i,s].every(n=>n>=0&&n<=255),"Cell color values must be between 0 and 255",{method:"cellColor",providedValues:{r:t,g:r,b:i,a:s}})&&(this._options.cellColor=[t,r,i,s])}cellColorMode(t){b.validate(["sampled","fixed"].includes(t),"Invalid cell color mode. Must be 'sampled' or 'fixed'.",{method:"cellColorMode",providedValue:t})&&(this._options.cellColorMode=t)}invert(t){b.validate(typeof t=="boolean"||typeof t=="number"&&Number.isInteger(t),"Invert must be a boolean value or an integer (0 for false, any other number for true).",{method:"invert",providedValue:t})&&(this._options.invert=!!t)}rotation(t){if(!b.validate(typeof t=="number","Rotation angle must be a number.",{method:"rotation",providedValue:t}))return;t=t%360,t<0&&(t+=360);const r=t*255/360,i=Math.floor(r)/255,s=Math.round(r-i);this._options.rotation=[i,s,0,1]}flipHorizontally(t){b.validate(typeof t=="boolean"||typeof t=="number"&&Number.isInteger(t),"Flip horizontally must be a boolean value or an integer (0 for false, any other number for true).",{method:"flipHorizontally",providedValue:t})&&(this._options.flipHorizontally=!!t)}flipVertically(t){b.validate(typeof t=="boolean"||typeof t=="number"&&Number.isInteger(t),"Flip vertically must be a boolean value or an integer (0 for false, any other number for true).",{method:"flipVertically",providedValue:t})&&(this._options.flipVertically=!!t)}}var ge="precision lowp float;uniform sampler2D u_sketchTexture;uniform vec2 u_gridCellDimensions;uniform vec2 u_brightnessRange;varying vec2 v_uv;void main(){vec2 cellCenter=(floor(v_uv*u_gridCellDimensions)+vec2(0.5))/u_gridCellDimensions;vec4 color=texture2D(u_sketchTexture,cellCenter);float brightness=dot(color.rgb,vec3(0.299,0.587,0.114));float brightnessValue=brightness*255.0;if(brightnessValue>=u_brightnessRange.x&&brightnessValue<=u_brightnessRange.y){gl_FragColor=color;}else{gl_FragColor=vec4(0.0);}}",_e="precision lowp float;uniform sampler2D u_sampleTexture;uniform vec4 u_fillColor;uniform bool u_useFixedColor;varying vec2 v_uv;void main(){vec4 sampleColor=texture2D(u_sampleTexture,v_uv);if(sampleColor.a>0.0){if(u_useFixedColor){gl_FragColor=u_fillColor;}else{gl_FragColor=sampleColor;}}else{gl_FragColor=vec4(0.0);}}",pe="precision lowp float;uniform sampler2D u_sampleTexture;uniform bool u_invert;uniform bool u_flipHorizontally;uniform bool u_flipVertically;varying vec2 v_uv;void main(){vec4 sampleColor=texture2D(u_sampleTexture,v_uv);if(sampleColor.a>0.0){float invertValue=u_invert ? 1.0 : 0.0;float flipHValue=u_flipHorizontally ? 1.0 : 0.0;float flipVValue=u_flipVertically ? 1.0 : 0.0;gl_FragColor=vec4(invertValue,flipHValue,flipVValue,1.0);}else{gl_FragColor=vec4(0.0);}}",xe="precision lowp float;uniform sampler2D u_sampleTexture;uniform vec4 u_rotationColor;varying vec2 v_uv;void main(){vec4 sampleColor=texture2D(u_sampleTexture,v_uv);if(sampleColor.a>0.0){gl_FragColor=u_rotationColor;}else{gl_FragColor=vec4(0.0);}}",ve="precision lowp float;uniform sampler2D u_colorSampleFramebuffer;uniform sampler2D u_charPaletteTexture;uniform vec2 u_charPaletteSize;uniform vec2 u_brightnessRange;varying vec2 v_uv;void main(){vec4 color=texture2D(u_colorSampleFramebuffer,v_uv);if(color.a==0.0){gl_FragColor=vec4(0.0);return;}float brightness=dot(color.rgb,vec3(0.299,0.587,0.114))*255.0;vec2 range=u_brightnessRange;if(brightness<range.x||brightness>range.y){gl_FragColor=vec4(0.0);return;}float t=(brightness-range.x)/(range.y-range.x);float idx=clamp(floor(t*u_charPaletteSize.x),0.0,u_charPaletteSize.x-1.0);vec3 charColor=texture2D(u_charPaletteTexture,vec2((idx+0.5)/u_charPaletteSize.x,0.0)).rgb;gl_FragColor=vec4(charColor,1.0);}";const be={enabled:!0,characters:" .:-=+*%@#",characterColor:[255,255,255,255],characterColorMode:"sampled",cellColor:[0,0,0,255],cellColorMode:"fixed",invert:!1,rotation:[0,0,0,255],flipHorizontally:!1,flipVertically:!1,brightnessRange:[0,255]};class z extends k{constructor(t,r,i){super(t,r,i,{...be});a(this,"sampleShader");a(this,"colorFillShader");a(this,"charMappingShader");a(this,"transformFillShader");a(this,"rotationFillShader");a(this,"sampleFramebuffer");this.sampleShader=new T(t.context,S,ge),this.colorFillShader=new T(t.context,S,_e),this.transformFillShader=new T(t.context,S,pe),this.rotationFillShader=new T(t.context,S,xe),this.charMappingShader=new T(t.context,S,ve),this.sampleFramebuffer=this.renderer.createFramebuffer(this.grid.cols,this.grid.rows)}convert(t){this.sampleFramebuffer.begin(),this.renderer.clear(),this.renderer.shader(this.sampleShader),this.renderer.setUniform("u_sketchTexture",t),this.renderer.setUniform("u_gridCellDimensions",[this.grid.cols,this.grid.rows]),this.renderer.setUniform("u_brightnessRange",this._options.brightnessRange),this.renderer.rect(0,0,this.grid.cols,this.grid.rows),this.sampleFramebuffer.end(),this._primaryColorFramebuffer.begin(),this.renderer.clear(),this.renderer.shader(this.colorFillShader),this.renderer.setUniform("u_sampleTexture",this.sampleFramebuffer.texture),this.renderer.setUniform("u_fillColor",this._options.characterColor),this.renderer.setUniform("u_useFixedColor",this._options.characterColorMode==="fixed"),this.renderer.rect(0,0,this.grid.cols,this.grid.rows),this._primaryColorFramebuffer.end(),this._secondaryColorFramebuffer.begin(),this.renderer.clear(),this.renderer.shader(this.colorFillShader),this.renderer.setUniform("u_sampleTexture",this.sampleFramebuffer.texture),this.renderer.setUniform("u_fillColor",this._options.cellColor),this.renderer.setUniform("u_useFixedColor",this._options.cellColorMode==="fixed"),this.renderer.rect(0,0,this.grid.cols,this.grid.rows),this._secondaryColorFramebuffer.end(),this._transformFramebuffer.begin(),this.renderer.clear(),this.renderer.shader(this.transformFillShader),this.renderer.setUniform("u_sampleTexture",this.sampleFramebuffer.texture),this.renderer.setUniform("u_invert",this._options.invert),this.renderer.setUniform("u_flipHorizontally",this._options.flipHorizontally),this.renderer.setUniform("u_flipVertically",this._options.flipVertically),this.renderer.rect(0,0,this.grid.cols,this.grid.rows),this._transformFramebuffer.end(),this._rotationFramebuffer.begin(),this.renderer.clear(),this.renderer.shader(this.rotationFillShader),this.renderer.setUniform("u_sampleTexture",this.sampleFramebuffer.texture),this.renderer.setUniform("u_rotationColor",this._options.rotation),this.renderer.rect(0,0,this.grid.cols,this.grid.rows),this._rotationFramebuffer.end(),this._characterFramebuffer.begin(),this.renderer.clear(0,0,0,0),this.renderer.shader(this.charMappingShader),this.renderer.setUniform("u_colorSampleFramebuffer",this.sampleFramebuffer.texture),this.renderer.setUniform("u_charPaletteTexture",this.palette.texture),this.renderer.setUniform("u_charPaletteSize",[this.palette.colors.length,1]),this.renderer.setUniform("u_brightnessRange",this._options.brightnessRange),this.renderer.rect(0,0,this.grid.cols,this.grid.rows),this._characterFramebuffer.end()}resize(){super.resize(),this.sampleFramebuffer.resize(this.grid.cols,this.grid.rows)}brightnessRange(t){b.validate(Array.isArray(t)&&t.length===2&&t.every(r=>typeof r=="number"&&r>=0&&r<=255),"Brightness range must be an array of two numbers between 0 and 255.",{method:"brightnessRange",providedValue:t})&&(this._options.brightnessRange=t)}}const Ce=Object.freeze(Object.defineProperty({__proto__:null,TextmodeBrightnessConverter:z,TextmodeConverter:A,TextmodeFeatureConverter:k},Symbol.toStringTag,{value:"Module"}));var Fe="precision mediump float;uniform sampler2D u_characterTexture;uniform vec2 u_charsetDimensions;uniform sampler2D u_primaryColorTexture;uniform sampler2D u_secondaryColorTexture;uniform sampler2D u_transformTexture;uniform sampler2D u_asciiCharacterTexture;uniform sampler2D u_rotationTexture;uniform sampler2D u_captureTexture;uniform vec2 u_captureDimensions;uniform int u_backgroundMode;uniform vec2 u_gridCellDimensions;uniform vec2 u_gridPixelDimensions;mat2 rotate2D(float angle){float s=sin(angle);float c=cos(angle);return mat2(c,-s,s,c);}void main(){vec2 adjustedCoord=gl_FragCoord.xy/u_gridPixelDimensions;vec2 gridCoord=adjustedCoord*u_gridCellDimensions;vec2 cellCoord=floor(gridCoord);vec2 charIndexTexCoord=(cellCoord+0.5)/u_gridCellDimensions;vec4 primaryColor=texture2D(u_primaryColorTexture,charIndexTexCoord);vec4 secondaryColor=texture2D(u_secondaryColorTexture,charIndexTexCoord);vec4 transformColor=texture2D(u_transformTexture,charIndexTexCoord);bool isInverted=transformColor.r>0.5;bool flipHorizontal=transformColor.g>0.5;bool flipVertical=transformColor.b>0.5;vec4 encodedIndexVec=texture2D(u_asciiCharacterTexture,charIndexTexCoord);if(encodedIndexVec.a<0.01){gl_FragColor=(u_backgroundMode==0)? vec4(0.0):texture2D(u_captureTexture,gl_FragCoord.xy/u_captureDimensions);return;}int charIndex=int(encodedIndexVec.r*255.0+0.5)+int(encodedIndexVec.g*255.0+0.5)*256;int charCol=int(mod(float(charIndex),u_charsetDimensions.x));int charRow=charIndex/int(u_charsetDimensions.x);vec2 charCoord=vec2(charCol,charRow)/u_charsetDimensions;vec4 rotationColor=texture2D(u_rotationTexture,charIndexTexCoord);float scaledAngle=rotationColor.r*255.0+rotationColor.g;float rotationAngle=(scaledAngle*360.0/255.0)*0.017453292;vec2 fractionalPart=fract(gridCoord)-0.5;if(flipHorizontal)fractionalPart.x=-fractionalPart.x;if(flipVertical)fractionalPart.y=-fractionalPart.y;fractionalPart=rotate2D(rotationAngle)*fractionalPart+0.5;vec2 cellSize=1.0/u_charsetDimensions;vec2 texCoord=charCoord+fractionalPart*cellSize;vec2 cellMax=charCoord+cellSize;if(any(lessThan(texCoord,charCoord))||any(greaterThan(texCoord,cellMax))){gl_FragColor=isInverted ? primaryColor : secondaryColor;return;}vec4 charTexel=texture2D(u_characterTexture,texCoord);if(isInverted)charTexel.rgb=1.0-charTexel.rgb;gl_FragColor=mix(secondaryColor,primaryColor,charTexel);}";class J{constructor(e,t,r){a(this,"renderer");a(this,"font");a(this,"grid");a(this,"converters");a(this,"_resultFramebuffer");a(this,"_asciiShader");a(this,"_characterFramebuffer");a(this,"_primaryColorFramebuffer");a(this,"_secondaryColorFramebuffer");a(this,"_rotationFramebuffer");a(this,"_transformFramebuffer");this.renderer=e,this.font=t,this.grid=r,this._asciiShader=this.renderer.createShader(S,Fe),this.converters=[{name:"brightness",converter:new z(e,t,r)},{name:"custom",converter:new A(e,t,r)}],this._characterFramebuffer=this.renderer.createFramebuffer(r.cols,r.rows),this._primaryColorFramebuffer=this.renderer.createFramebuffer(r.cols,r.rows),this._secondaryColorFramebuffer=this.renderer.createFramebuffer(r.cols,r.rows),this._rotationFramebuffer=this.renderer.createFramebuffer(r.cols,r.rows),this._transformFramebuffer=this.renderer.createFramebuffer(r.cols,r.rows),this._resultFramebuffer=this.renderer.createFramebuffer(this.grid.width,this.grid.height)}render(e){for(const r of this.converters){const i=r.converter;i.options.enabled&&i instanceof k&&i.convert(e)}const t=(r,i)=>{r.begin(),this.renderer.clear();for(const s of this.converters){const n=s.converter;n.options.enabled&&this.renderer.image(i(n),0,0)}r.end()};t(this._characterFramebuffer,r=>r.characterFramebuffer),t(this._primaryColorFramebuffer,r=>r.primaryColorFramebuffer),t(this._secondaryColorFramebuffer,r=>r.secondaryColorFramebuffer),t(this._rotationFramebuffer,r=>r.rotationFramebuffer),t(this._transformFramebuffer,r=>r.transformFramebuffer),this._resultFramebuffer.begin(),this.renderer.clear(),this.renderer.shader(this._asciiShader),this.renderer.setUniform("u_characterTexture",this.font.fontFramebuffer),this.renderer.setUniform("u_charsetDimensions",[this.font.textureColumns,this.font.textureRows]),this.renderer.setUniform("u_asciiCharacterTexture",this._characterFramebuffer.texture),this.renderer.setUniform("u_primaryColorTexture",this._primaryColorFramebuffer.texture),this.renderer.setUniform("u_secondaryColorTexture",this._secondaryColorFramebuffer.texture),this.renderer.setUniform("u_transformTexture",this._transformFramebuffer.texture),this.renderer.setUniform("u_rotationTexture",this._rotationFramebuffer.texture),this.renderer.setUniform("u_captureTexture",e.texture),this.renderer.setUniform("u_backgroundMode",!1),this.renderer.setUniform("u_captureDimensions",[e.width,e.height]),this.renderer.setUniform("u_gridCellDimensions",[this.grid.cols,this.grid.rows]),this.renderer.setUniform("u_gridPixelDimensions",[this.grid.width,this.grid.height]),this.renderer.rect(0,0,this._resultFramebuffer.width,this._resultFramebuffer.height),this._resultFramebuffer.end()}get(e){if(!b.validate(typeof e=="string"&&e.length>0,"Converter name must be a non-empty string.",{method:"converter",providedValue:e}))return;const t=this.converters.find(i=>i.name===e),r=t==null?void 0:t.converter;if(b.validate(r instanceof A,`Converter "${e}" is not a valid TextmodeConverter.`,{method:"converter",providedValue:e,converterInstance:r}))return r}add(e,t){if(!b.validate(typeof e=="string"&&e.length>0,"Converter name must be a non-empty string.",{method:"add",providedValue:e})||!b.validate(t==="brightness"||t==="custom",`Converter type must be either "brightness" or "custom". Provided: ${t}`,{method:"add",providedValue:t}))return;let r;return t==="brightness"?r=new z(this.renderer,this.font,this.grid):r=new A(this.renderer,this.font,this.grid),this.converters.push({name:e,converter:r}),r}remove(e){if(!b.validate(typeof e=="string"||e instanceof A,"Parameter must be either a string (converter name) or a TextmodeConverter instance.",{method:"remove",providedValue:e}))return;let t=-1;if(typeof e=="string"){if(!b.validate(e.length>0,"Converter name must be a non-empty string.",{method:"remove",providedValue:e}))return;t=this.converters.findIndex(r=>r.name===e)}else t=this.converters.findIndex(r=>r.converter===e);b.validate(t!==-1,typeof e=="string"?`Converter with name "${e}" not found in pipeline.`:"Converter instance not found in pipeline.",{method:"remove",providedValue:e,convertersCount:this.converters.length})&&this.converters.splice(t,1)}get texture(){return this._resultFramebuffer}resize(){this._resultFramebuffer.resize(this.grid.width,this.grid.height),this._characterFramebuffer.resize(this.grid.cols,this.grid.rows),this._primaryColorFramebuffer.resize(this.grid.cols,this.grid.rows),this._secondaryColorFramebuffer.resize(this.grid.cols,this.grid.rows),this._rotationFramebuffer.resize(this.grid.cols,this.grid.rows),this._transformFramebuffer.resize(this.grid.cols,this.grid.rows);for(const e of this.converters)e.converter.resize()}hasEnabledConverters(){return this.converters.some(e=>e.converter.options.enabled)}disable(){for(const e of this.converters)e.converter.disable()}enable(){for(const e of this.converters)e.converter.enable()}dispose(){for(const e of this.converters)e.converter&&!e.converter.isDisposed&&e.converter.dispose();this._characterFramebuffer&&!this._characterFramebuffer.isDisposed&&this._characterFramebuffer.dispose(),this._primaryColorFramebuffer&&!this._primaryColorFramebuffer.isDisposed&&this._primaryColorFramebuffer.dispose(),this._secondaryColorFramebuffer&&!this._secondaryColorFramebuffer.isDisposed&&this._secondaryColorFramebuffer.dispose(),this._rotationFramebuffer&&!this._rotationFramebuffer.isDisposed&&this._rotationFramebuffer.dispose(),this._transformFramebuffer&&!this._transformFramebuffer.isDisposed&&this._transformFramebuffer.dispose(),this._resultFramebuffer&&!this._resultFramebuffer.isDisposed&&this._resultFramebuffer.dispose(),this._asciiShader&&!this._asciiShader.isDisposed&&this._asciiShader.dispose(),this.converters=[],this._characterFramebuffer=null,this._primaryColorFramebuffer=null,this._secondaryColorFramebuffer=null,this._rotationFramebuffer=null,this._transformFramebuffer=null,this._resultFramebuffer=null,this._asciiShader=null}get isDisposed(){return this._resultFramebuffer===null||this._asciiShader===null}get characterFramebuffer(){return this._characterFramebuffer}get primaryColorFramebuffer(){return this._primaryColorFramebuffer}get secondaryColorFramebuffer(){return this._secondaryColorFramebuffer}get rotationFramebuffer(){return this._rotationFramebuffer}get transformFramebuffer(){return this._transformFramebuffer}}class ${extractFramebufferData(e){const t=e.get("brightness"),r=t==null?void 0:t.characterFramebuffer,i=t==null?void 0:t.primaryColorFramebuffer,s=t==null?void 0:t.secondaryColorFramebuffer,n=t==null?void 0:t.transformFramebuffer,o=t==null?void 0:t.rotationFramebuffer;return r==null||r.loadPixels(),i==null||i.loadPixels(),s==null||s.loadPixels(),n==null||n.loadPixels(),o==null||o.loadPixels(),{characterPixels:(r==null?void 0:r.pixels)||new Uint8Array(0),primaryColorPixels:(i==null?void 0:i.pixels)||new Uint8Array(0),secondaryColorPixels:(s==null?void 0:s.pixels)||new Uint8Array(0),transformPixels:(n==null?void 0:n.pixels)||new Uint8Array(0),rotationPixels:(o==null?void 0:o.pixels)||new Uint8Array(0)}}getCharacterIndex(e,t){const r=e[t],i=e[t+1];return r+(i<<8)}pixelsToRGBA(e,t){return{r:e[t],g:e[t+1],b:e[t+2],a:e[t+3]}}}class L{createBlob(e,t){return new Blob([e],{type:t})}downloadFile(e,t,r){try{const i=this.createBlob(e,r),s=URL.createObjectURL(i),n=document.createElement("a");n.href=s,n.download=t,n.style.display="none",n.rel="noopener",document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(s)}catch(i){throw console.error("Failed to download file:",i),new Error(`File download failed: ${i instanceof Error?i.message:"Unknown error"}`)}}generateTimestamp(){return new Date().toISOString().slice(0,19).replace(/:/g,"-")}generateDateTimeString(){const e=new Date,t=e.toISOString().split("T")[0],r=e.toTimeString().split(" ")[0].replace(/:/g,"-");return{date:t,time:r}}sanitizeFilename(e){return e.replace(/[<>:"/\\|?*]/g,"_").replace(/\s+/g,"_").replace(/_{2,}/g,"_").replace(/^_+|_+$/g,"").substring(0,255)}generateDefaultFilename(){return`'textmode-export'-${this.generateTimestamp()}`}}class we extends ${extractTransformData(e,t,r){const i=e[r],s=e[r+1],n=e[r+2],o=i===255,l=s===255,c=n===255,u=t[r],d=t[r+1],f=u+d/255,g=Math.round(f*360/255*100)/100;return{isInverted:o,flipHorizontal:l,flipVertical:c,rotation:g}}calculateCellPosition(e,t,r){return{x:e,y:t,cellX:e*r.cellWidth,cellY:t*r.cellHeight}}extractSVGCellData(e,t){const r=[];let i=0;for(let s=0;s<t.rows;s++)for(let n=0;n<t.cols;n++){const o=i*4,l=this.getCharacterIndex(e.characterPixels,o);let c=this.pixelsToRGBA(e.primaryColorPixels,o),u=this.pixelsToRGBA(e.secondaryColorPixels,o);const d=this.extractTransformData(e.transformPixels,e.rotationPixels,o);if(d.isInverted){const g=c;c=u,u=g}const f=this.calculateCellPosition(n,s,t);r.push({charIndex:l,primaryColor:c,secondaryColor:u,transform:d,position:f}),i++}return r}}class ye{getGlyphIndex(e,t){const r=e.cmap;if(!r||!r.tables)return 0;for(const i of r.tables)if(i.format===4){for(let s=0;s<i.startCount.length;s++)if(t>=i.startCount[s]&&t<=i.endCount[s]){if(i.idRangeOffset[s]===0)return t+i.idDelta[s]&65535;{const n=i.idRangeOffset[s]/2+(t-i.startCount[s])-(i.startCount.length-s);if(n>=0&&n<i.glyphIdArray.length){const o=i.glyphIdArray[n];if(o!==0)return o+i.idDelta[s]&65535}}}}return 0}createEmptyPath(){return{getBoundingBox:()=>({x1:0,y1:0,x2:0,y2:0}),toSVG:()=>""}}createGlyphPath(e,t,r,i,s){if(!t||!t.xs||t.xs.length===0)return this.createEmptyPath();const n=s/e.head.unitsPerEm;return{getBoundingBox:()=>({x1:r+t.xMin*n,y1:i+-t.yMax*n,x2:r+t.xMax*n,y2:i+-t.yMin*n}),toSVG:()=>this.glyphToSVGPath(t,r,i,n)}}glyphToSVGPath(e,t,r,i){if(!e||!e.xs)return"";const{xs:s,ys:n,endPts:o,flags:l}=e;if(!s||!n||!o||!l)return"";let c="",u=0;for(let d=0;d<o.length;d++){const f=o[d];if(!(f<u)){if(f>=u){const g=t+s[u]*i,x=r-n[u]*i;c+=`M${g.toFixed(2)},${x.toFixed(2)}`;let _=u+1;for(;_<=f;)if((l[_]&1)!==0){const w=t+s[_]*i,C=r-n[_]*i;c+=`L${w.toFixed(2)},${C.toFixed(2)}`,_++}else{const w=t+s[_]*i,C=r-n[_]*i;let y=_+1>f?u:_+1;if((l[y]&1)!==0){const D=t+s[y]*i,R=r-n[y]*i;c+=`Q${w.toFixed(2)},${C.toFixed(2)} ${D.toFixed(2)},${R.toFixed(2)}`,_=y+1}else{const D=t+s[y]*i,R=r-n[y]*i,H=(w+D)/2,G=(C+R)/2;c+=`Q${w.toFixed(2)},${C.toFixed(2)} ${H.toFixed(2)},${G.toFixed(2)}`,_=y}}c+="Z"}u=f+1}}return c}generateCharacterPath(e,t,r,i,s){try{const n=e.codePointAt(0)||0,o=this.getGlyphIndex(t,n);if(o===0)return this.createEmptyPath();let l=null;try{t.glyf&&t.glyf[o]!==null?l=t.glyf[o]:m&&m.T&&m.T.glyf&&m.T.glyf._parseGlyf&&(l=m.T.glyf._parseGlyf(t,o),t.glyf&&l&&(t.glyf[o]=l))}catch(c){console.warn(`Failed to parse glyph ${o}:`,c)}return l?this.createGlyphPath(t,l,r,i,s):this.createEmptyPath()}catch(n){return console.warn(`Failed to generate path for character "${e}":`,n),this.createEmptyPath()}}generatePositionedCharacterPath(e,t,r,i,s,n,o,l){try{const c=o/t.head.unitsPerEm,u=l*c,d=r+(s-u)/2,f=i+(n+o*.7)/2;return this.generateCharacterPath(e,t,d,f,o).toSVG()||null}catch(c){return console.warn(`Failed to generate positioned character path for "${e}":`,c),null}}}class Te{constructor(){a(this,"pathGenerator");this.pathGenerator=new ye}generateSVGHeader(e){return`<?xml version="1.0" encoding="UTF-8" standalone="no"?>
8
8
  <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
9
9
  <svg width="${e.width}" height="${e.height}" viewBox="0 0 ${e.width} ${e.height}"
10
10
  xmlns="http://www.w3.org/2000/svg" version="1.1">
@@ -12,14 +12,14 @@
12
12
  <desc>textmode art visualization generated by textmode.js library</desc>`}generateSVGFooter(){return`
13
13
  </g>
14
14
  </svg>`}generateBackground(e,t){if(!t.includeBackgroundRectangles)return"";const r=t.backgroundColor,i=`rgba(${r[0]},${r[1]},${r[2]},${r[3]/255})`;return`
15
- <rect width="${e.width}" height="${e.height}" fill="${i}" />`}rgbaToColorString(e){return`rgba(${e.r},${e.g},${e.b},${e.a/255})`}generateTransformAttribute(e,t){const{transform:r,position:i}=e,s=i.cellX+t.cellWidth/2,n=i.cellY+t.cellHeight/2,a=[];if(r.flipHorizontal||r.flipVertical){const l=r.flipHorizontal?-1:1,c=r.flipVertical?-1:1;a.push(`translate(${s} ${n})`),a.push(`scale(${l} ${c})`),a.push(`translate(${-s} ${-n})`)}return r.rotation&&a.push(`rotate(${r.rotation} ${s} ${n})`),a.length?` transform="${a.join(" ")}"`:""}generateCellBackground(e,t,r){if(!r.includeBackgroundRectangles||e.secondaryColor.a===0)return"";const{position:i}=e,s=this.rgbaToColorString(e.secondaryColor);return r.drawMode==="stroke"?`
15
+ <rect width="${e.width}" height="${e.height}" fill="${i}" />`}rgbaToColorString(e){return`rgba(${e.r},${e.g},${e.b},${e.a/255})`}generateTransformAttribute(e,t){const{transform:r,position:i}=e,s=i.cellX+t.cellWidth/2,n=i.cellY+t.cellHeight/2,o=[];if(r.flipHorizontal||r.flipVertical){const l=r.flipHorizontal?-1:1,c=r.flipVertical?-1:1;o.push(`translate(${s} ${n})`),o.push(`scale(${l} ${c})`),o.push(`translate(${-s} ${-n})`)}return r.rotation&&o.push(`rotate(${r.rotation} ${s} ${n})`),o.length?` transform="${o.join(" ")}"`:""}generateCellBackground(e,t,r){if(!r.includeBackgroundRectangles||e.secondaryColor.a===0)return"";const{position:i}=e,s=this.rgbaToColorString(e.secondaryColor);return r.drawMode==="stroke"?`
16
16
  <rect x="${i.cellX}" y="${i.cellY}" width="${t.cellWidth}" height="${t.cellHeight}" stroke="${s}" fill="none" stroke-width="${r.strokeWidth}" />`:`
17
- <rect x="${i.cellX}" y="${i.cellY}" width="${t.cellWidth}" height="${t.cellHeight}" fill="${s}" />`}generateCharacterPath(e,t,r,i){const s=r.characters[e.charIndex];if(!s)return"";const n=this.pathGenerator.generatePositionedCharacterPath(s.character,r.font,e.position.cellX,e.position.cellY,t.cellWidth,t.cellHeight,r.fontSize,s.advanceWidth);if(!n)return"";const a=this.rgbaToColorString(e.primaryColor);return i.drawMode==="stroke"?`
18
- <path id="${`path-${e.charIndex}-${e.position.cellX}-${e.position.cellY}`.replace(/\./g,"-")}" d="${n}" stroke="${a}" stroke-width="${i.strokeWidth}" fill="none" />`:`
19
- <path d="${n}" fill="${a}" />`}generateCellContent(e,t,r,i){let s="";s+=this.generateCellBackground(e,t,i);const n=this.generateTransformAttribute(e,t),a=this.generateCharacterPath(e,t,r,i);return a&&(n?(s+=`
20
- <g${n}>`,s+=a,s+=`
21
- </g>`):s+=a),s}generateSVGContent(e,t,r,i){let s=this.generateSVGHeader(t);s+=this.generateBackground(t,i),s+=`
17
+ <rect x="${i.cellX}" y="${i.cellY}" width="${t.cellWidth}" height="${t.cellHeight}" fill="${s}" />`}generateCharacterPath(e,t,r,i){const s=r.characters[e.charIndex];if(!s)return"";const n=this.pathGenerator.generatePositionedCharacterPath(s.character,r.font,e.position.cellX,e.position.cellY,t.cellWidth,t.cellHeight,r.fontSize,s.advanceWidth);if(!n)return"";const o=this.rgbaToColorString(e.primaryColor);return i.drawMode==="stroke"?`
18
+ <path id="${`path-${e.charIndex}-${e.position.cellX}-${e.position.cellY}`.replace(/\./g,"-")}" d="${n}" stroke="${o}" stroke-width="${i.strokeWidth}" fill="none" />`:`
19
+ <path d="${n}" fill="${o}" />`}generateCellContent(e,t,r,i){let s="";s+=this.generateCellBackground(e,t,i);const n=this.generateTransformAttribute(e,t),o=this.generateCharacterPath(e,t,r,i);return o&&(n?(s+=`
20
+ <g${n}>`,s+=o,s+=`
21
+ </g>`):s+=o),s}generateSVGContent(e,t,r,i){let s=this.generateSVGHeader(t);s+=this.generateBackground(t,i),s+=`
22
22
  <g id="ascii-cells">`;for(const n of e)s+=this.generateCellContent(n,t,r,i);return s+=this.generateSVGFooter(),s}optimizeSVGContent(e){return e.replace(/<path[^>]*d=""[^>]*\/>/g,"").replace(/\n\s*\n/g,`
23
- `).replace(/[ \t]+$/gm,"")}}class Se extends L{createSVGBlob(e){return this.createBlob(e,"image/svg+xml;charset=utf-8")}downloadSVG(e,t){try{this.downloadFile(e,this.sanitizeFilename(t)+".svg","image/svg+xml;charset=utf-8")}catch(r){throw console.error("Failed to download SVG file:",r),new Error(`SVG download failed: ${r instanceof Error?r.message:"Unknown error"}`)}}saveSVG(e,t){this.downloadSVG(e,t||this.generateDefaultFilename())}}class K{constructor(){o(this,"dataExtractor");o(this,"contentGenerator");o(this,"fileHandler");this.dataExtractor=new we,this.contentGenerator=new Te,this.fileHandler=new Se}applyDefaultOptions(e){return{includeBackgroundRectangles:e.includeBackgroundRectangles??!0,drawMode:e.drawMode??"fill",strokeWidth:e.strokeWidth??1,backgroundColor:e.backgroundColor??[0,0,0,0]}}generateSVG(e,t={}){const r=this.applyDefaultOptions(t),i=this.dataExtractor.extractFramebufferData(e.pipeline),s=this.dataExtractor.extractSVGCellData(i,e.grid),n=this.contentGenerator.generateSVGContent(s,e.grid,e.font,r);return this.contentGenerator.optimizeSVGContent(n)}saveSVG(e,t={}){try{const r=this.generateSVG(e,t),i=t.filename||this.fileHandler.generateDefaultFilename();this.fileHandler.saveSVG(r,i)}catch(r){throw console.error("Failed to save SVG:",r),new Error(`SVG save failed: ${r instanceof Error?r.message:"Unknown error"}`)}}}class Re extends ${extractCharacterGrid(e,t,r,i=" "){var a;const s=[];let n=0;for(let l=0;l<t.rows;l++){const c=[];for(let u=0;u<t.cols;u++){const d=n*4,f=this.getCharacterIndex(e.characterPixels,d),g=((a=r.characters[f])==null?void 0:a.character)||i;c.push(g),n++}s.push(c)}return s}}class Ee{generateTXTContent(e,t){const r=[];for(const s of e){let n=s.join("");t.preserveTrailingSpaces||(n=n.replace(/\s+$/,"")),r.push(n)}const i=t.lineEnding==="crlf"?`\r
23
+ `).replace(/[ \t]+$/gm,"")}}class Se extends L{createSVGBlob(e){return this.createBlob(e,"image/svg+xml;charset=utf-8")}downloadSVG(e,t){try{this.downloadFile(e,this.sanitizeFilename(t)+".svg","image/svg+xml;charset=utf-8")}catch(r){throw console.error("Failed to download SVG file:",r),new Error(`SVG download failed: ${r instanceof Error?r.message:"Unknown error"}`)}}saveSVG(e,t){this.downloadSVG(e,t||this.generateDefaultFilename())}}class K{constructor(){a(this,"dataExtractor");a(this,"contentGenerator");a(this,"fileHandler");this.dataExtractor=new we,this.contentGenerator=new Te,this.fileHandler=new Se}applyDefaultOptions(e){return{includeBackgroundRectangles:e.includeBackgroundRectangles??!0,drawMode:e.drawMode??"fill",strokeWidth:e.strokeWidth??1,backgroundColor:e.backgroundColor??[0,0,0,0]}}generateSVG(e,t={}){const r=this.applyDefaultOptions(t),i=this.dataExtractor.extractFramebufferData(e.pipeline),s=this.dataExtractor.extractSVGCellData(i,e.grid),n=this.contentGenerator.generateSVGContent(s,e.grid,e.font,r);return this.contentGenerator.optimizeSVGContent(n)}saveSVG(e,t={}){try{const r=this.generateSVG(e,t),i=t.filename||this.fileHandler.generateDefaultFilename();this.fileHandler.saveSVG(r,i)}catch(r){throw console.error("Failed to save SVG:",r),new Error(`SVG save failed: ${r instanceof Error?r.message:"Unknown error"}`)}}}class Re extends ${extractCharacterGrid(e,t,r,i=" "){var o;const s=[];let n=0;for(let l=0;l<t.rows;l++){const c=[];for(let u=0;u<t.cols;u++){const d=n*4,f=this.getCharacterIndex(e.characterPixels,d),g=((o=r.characters[f])==null?void 0:o.character)||i;c.push(g),n++}s.push(c)}return s}}class Ee{generateTXTContent(e,t){const r=[];for(const s of e){let n=s.join("");t.preserveTrailingSpaces||(n=n.replace(/\s+$/,"")),r.push(n)}const i=t.lineEnding==="crlf"?`\r
24
24
  `:`
25
- `;return r.join(i)}}class Ue extends L{saveTXT(e,t){try{const r=this.ensureValidFilename(t);this.downloadFile(e,r,"text/plain;charset=utf-8")}catch(r){throw console.error("Failed to save TXT file:",r),new Error(`TXT file save failed: ${r instanceof Error?r.message:"Unknown error"}`)}}ensureValidFilename(e){let t=this.sanitizeFilename(e);return t===".txt"||t.length<=4?this.generateDefaultFilename():t}}class ee{constructor(){o(this,"dataExtractor");o(this,"contentGenerator");o(this,"fileHandler");this.dataExtractor=new Re,this.contentGenerator=new Ee,this.fileHandler=new Ue}applyDefaultOptions(e){return{preserveTrailingSpaces:e.preserveTrailingSpaces??!1,lineEnding:e.lineEnding??"lf",emptyCharacter:e.emptyCharacter??" "}}generateTXT(e,t={}){const r=this.applyDefaultOptions(t),i=this.dataExtractor.extractFramebufferData(e.pipeline),s=this.dataExtractor.extractCharacterGrid(i,e.grid,e.font,r.emptyCharacter);return this.contentGenerator.generateTXTContent(s,r)}saveTXT(e,t={}){try{const r=this.generateTXT(e,t),i=t.filename||this.fileHandler.generateDefaultFilename();this.fileHandler.saveTXT(r,i)}catch(r){throw console.error("Failed to save TXT:",r),new Error(`TXT save failed: ${r instanceof Error?r.message:"Unknown error"}`)}}}class De extends ${captureCanvasData(e,t=1,r="transparent"){const i=e.canvas;if(t===1&&r==="transparent")return i;const s=document.createElement("canvas"),n=s.getContext("2d"),a=Math.round(i.width*t),l=Math.round(i.height*t);return s.width=a,s.height=l,r!=="transparent"&&(n.fillStyle=r,n.fillRect(0,0,a,l)),n.imageSmoothingEnabled=!1,n.drawImage(i,0,0,i.width,i.height,0,0,a,l),s}}class Ae{generateImageData(e,t){const r=this.getMimeType(t.format);return t.format==="png"?e.toDataURL(r):e.toDataURL(r,t.quality)}async generateImageBlob(e,t){return new Promise((r,i)=>{const s=this.getMimeType(t.format),n=a=>{a?r(a):i(new Error(`Failed to generate ${t.format.toUpperCase()} blob`))};t.format==="png"?e.toBlob(n,s):e.toBlob(n,s,t.quality)})}getMimeType(e){switch(e){case"png":return"image/png";case"jpg":return"image/jpeg";case"webp":return"image/webp";default:throw new Error(`Unsupported image format: ${e}`)}}}const te={png:"image/png",jpg:"image/jpeg",webp:"image/webp"},X={png:".png",jpg:".jpg",webp:".webp"};class Me extends L{saveImage(e,t,r){try{const i=X[r];typeof e=="string"?this.saveImageFromDataURL(e,this.sanitizeFilename(t)+i):this.saveImageFromBlob(e,this.sanitizeFilename(t)+i)}catch(i){throw console.error(`Failed to save ${r.toUpperCase()} image:`,i),new Error(`Image save failed: ${i instanceof Error?i.message:"Unknown error"}`)}}saveImageFromDataURL(e,t){const r=document.createElement("a");r.href=e,r.download=t,r.style.display="none",r.rel="noopener",document.body.appendChild(r),r.click(),document.body.removeChild(r)}saveImageFromBlob(e,t){const r=URL.createObjectURL(e);try{const i=document.createElement("a");i.href=r,i.download=t,i.style.display="none",i.rel="noopener",document.body.appendChild(i),i.click(),document.body.removeChild(i)}finally{URL.revokeObjectURL(r)}}validateSaveSupport(e){return e in te&&e in X}getMimeType(e){return te[e]}getFileExtension(e){return X[e]}}class Pe{constructor(){o(this,"dataExtractor");o(this,"contentGenerator");o(this,"fileHandler");this.dataExtractor=new De,this.contentGenerator=new Ae,this.fileHandler=new Me}applyDefaultOptions(e){return{format:e.format??"png",quality:e.quality??1,scale:e.scale??1,backgroundColor:e.backgroundColor??"transparent"}}validateOptions(e){if(console.log("Validating image export options:",e),!this.fileHandler.validateSaveSupport(e.format))throw new Error(`Saving '${e.format}' files is not supported`);if(e.quality<0||e.quality>1)throw new Error("Image quality must be between 0.0 and 1.0");if(e.scale<=0)throw new Error("Scale factor must be greater than 0");e.scale>10&&console.warn("Large scale factors may result in very large files and slow performance"),e.format==="jpg"&&e.backgroundColor==="transparent"&&(e.backgroundColor="black")}generateImage(e,t={}){const r=this.applyDefaultOptions(t);if(this.validateOptions(r),r.scale===1&&r.backgroundColor==="transparent")return this.contentGenerator.generateImageData(e.canvas,r);const i=this.dataExtractor.captureCanvasData(e,r.scale,r.backgroundColor);return this.contentGenerator.generateImageData(i,r)}async generateImageBlob(e,t={}){const r=this.applyDefaultOptions(t);if(this.validateOptions(r),r.scale===1&&r.backgroundColor==="transparent")return await this.contentGenerator.generateImageBlob(e.canvas,r);const i=this.dataExtractor.captureCanvasData(e,r.scale,r.backgroundColor);return await this.contentGenerator.generateImageBlob(i,r)}async saveImage(e,t={}){try{const r=await this.generateImageBlob(e,t),i=t.format??"png",s=t.filename||this.fileHandler.generateDefaultFilename();this.fileHandler.saveImage(r,s,i)}catch(r){throw console.error("Failed to save image:",r),new Error(`Image save failed: ${r instanceof Error?r.message:"Unknown error"}`)}}}class P{constructor(e=null,t={}){o(this,"captureSource");o(this,"textmodeCanvas");o(this,"_renderer");o(this,"_canvasFramebuffer");o(this,"_font");o(this,"_grid");o(this,"resizeObserver");o(this,"_mode");o(this,"_frameRateLimit");o(this,"animationFrameId",null);o(this,"lastFrameTime",0);o(this,"frameInterval");o(this,"_frameRate",0);o(this,"lastRenderTime",0);o(this,"_frameCount",0);o(this,"frameTimeHistory",[]);o(this,"frameTimeHistorySize",10);o(this,"_pipeline");o(this,"_standalone",!1);o(this,"_drawCallback",()=>{});o(this,"_resizedCallback",()=>{});o(this,"_isDestroyed",!1);o(this,"_windowResizeListener",null);this.captureSource=e,this._standalone=e===null,this._mode=t.renderMode??"auto",this._frameRateLimit=t.frameRate??60,this.frameInterval=1e3/this._frameRateLimit}static async create(e=null,t={}){const r=new P(e,t),i=r._standalone?t:void 0;r.textmodeCanvas=new Z(r.captureSource,r._standalone,i),r._renderer=new le(r.textmodeCanvas.getWebGLContext());let s,n;r._standalone?(s=t.width||800,n=t.height||600):(s=r.textmodeCanvas.width||800,n=r.textmodeCanvas.height||600),r._canvasFramebuffer=r._renderer.createFramebuffer(s,n),r._font=new q(r._renderer,t.fontSize??16),await r._font.initialize(t.fontSource);const a=r._font.maxGlyphDimensions;return r._grid=new Q(r.textmodeCanvas.canvas,a.width,a.height),r._pipeline=new J(r._renderer,r._font,r._grid),r.setupEventListeners(),r.startAutoRendering(),r}setupEventListeners(){this._windowResizeListener=()=>{this._standalone?this._resizedCallback():this.resize()},window.addEventListener("resize",this._windowResizeListener),window.ResizeObserver&&this.captureSource&&!this._standalone&&(this.resizeObserver=new ResizeObserver(()=>{this.resize()}),this.resizeObserver.observe(this.captureSource))}toString(e={}){return new ee().generateTXT(this,e)}saveStrings(e={}){new ee().saveTXT(this,e)}toSVG(e={}){return new K().generateSVG(this,e)}saveSVG(e={}){new K().saveSVG(this,e)}async saveCanvas(e,t="png",r={}){await new Pe().saveImage(this.textmodeCanvas,{...r,filename:e,format:t})}async loadFont(e){return this._font.loadFont(e).then(()=>{const t=this._font.maxGlyphDimensions;this._grid.resizeCellPixelDimensions(t.width,t.height),this._pipeline.resize()})}render(){if(this._isDestroyed){console.warn("Cannot render: Textmodifier instance has been destroyed");return}if(this.measureFrameRate(),this._frameCount++,!this._canvasFramebuffer||!this._renderer||!this._pipeline){console.warn("Cannot render: Required resources have been disposed");return}if(this._standalone?this._canvasFramebuffer&&(this._canvasFramebuffer.begin(),this._drawCallback(),this._renderer&&this._renderer.reset(),this._canvasFramebuffer&&this._canvasFramebuffer.end()):this.captureSource&&this._canvasFramebuffer&&this._canvasFramebuffer.update(this.captureSource),!this._pipeline||!this._renderer){console.warn("Cannot complete render: Pipeline or renderer has been disposed");return}this._pipeline.render(this._canvasFramebuffer),this._pipeline.hasEnabledConverters()?this._renderer&&this._pipeline.texture&&this._grid&&(this._renderer.background(0),this._renderer.image(this._pipeline.texture,this._grid.offsetX,this._grid.offsetY,this._pipeline.texture.width,this._pipeline.texture.height)):this._renderer&&this._canvasFramebuffer&&this._grid&&(this._renderer.clear(),this._renderer.image(this._canvasFramebuffer,this._grid.offsetX,this._grid.offsetY,this._canvasFramebuffer.width,this._canvasFramebuffer.height))}resize(){this.textmodeCanvas.resize(),this._canvasFramebuffer.resize(this.textmodeCanvas.width,this.textmodeCanvas.height),this._grid.resize(),this._pipeline.resize(),this._renderer.resetViewport(),this._mode!=="manual"&&this.render()}startAutoRendering(){if(this._mode!=="auto"||this._isDestroyed)return;this.lastFrameTime=performance.now();const e=t=>{if(this._isDestroyed)return;const r=t-this.lastFrameTime;r>=this.frameInterval&&(this.render(),this.lastFrameTime=t-r%this.frameInterval),this._isDestroyed||(this.animationFrameId=requestAnimationFrame(e))};this.animationFrameId=requestAnimationFrame(e)}measureFrameRate(){if(this._isDestroyed)return;const e=performance.now();if(this.lastRenderTime>0){const t=e-this.lastRenderTime;this.frameTimeHistory.push(t),this.frameTimeHistory.length>this.frameTimeHistorySize&&this.frameTimeHistory.shift();const r=this.frameTimeHistory.reduce((i,s)=>i+s,0)/this.frameTimeHistory.length;this._frameRate=1e3/r}this.lastRenderTime=e}stopAutoRendering(){this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}renderMode(e){if(this._isDestroyed){console.warn("Cannot change render mode: Textmodifier instance has been destroyed");return}this._mode!==e&&(this.stopAutoRendering(),this._mode=e,e==="auto"&&this.startAutoRendering())}frameRate(e){if(e===void 0)return this._frameRate;this._frameRateLimit=e,this.frameInterval=1e3/e,this._mode==="auto"&&(this.stopAutoRendering(),this.startAutoRendering())}fontSize(e){b.validate(typeof e=="number"&&e>0,"Font size must be a positive number greater than 0.",{method:"fontSize",providedValue:e})&&this._font.fontSize!==e&&(this._font.setFontSize(e),this._grid.resizeCellPixelDimensions(this._font.maxGlyphDimensions.width,this._font.maxGlyphDimensions.height),this._pipeline.resize(),this._renderer.resetViewport())}draw(e){this._drawCallback=e}windowResized(e){this._resizedCallback=e}resizeCanvas(e,t){this.textmodeCanvas.resize(e,t),this._canvasFramebuffer.resize(this.textmodeCanvas.width,this.textmodeCanvas.height),this._grid.resize(),this._pipeline.resize(),this._renderer.resetViewport(),this._mode!=="manual"&&this.render()}converter(e){return this._pipeline.get(e)}fill(e,t,r,i){this._renderer.fill(e,t,r,i)}stroke(e,t,r,i){this._renderer.stroke(e,t,r,i)}strokeWeight(e){this._renderer.strokeWeight(e)}noStroke(){this._renderer.noStroke()}noFill(){this._renderer.noFill()}rotate(e){this._renderer.rotate(e)}push(){this._renderer.push()}pop(){this._renderer.pop()}rect(e,t,r=1,i=1){this._renderer.rect(e,t,r,i)}line(e,t,r,i){this._renderer.line(e,t,r,i)}background(e,t=e,r=e,i=255){this._renderer.background(e,t,r,i)}createShader(e,t){return this._renderer.createShader(e,t)}shader(e){this._renderer.shader(e)}setUniform(e,t){this._renderer.setUniform(e,t)}destroy(){this._isDestroyed||(this._isDestroyed=!0,this.stopAutoRendering(),this._windowResizeListener&&(window.removeEventListener("resize",this._windowResizeListener),this._windowResizeListener=null),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this._pipeline&&!this._pipeline.isDisposed&&this._pipeline.dispose(),this._font&&!this._font.isDisposed&&this._font.dispose(),this._grid&&!this._grid.isDisposed&&this._grid.dispose(),this._canvasFramebuffer&&!this._canvasFramebuffer.isDisposed&&this._canvasFramebuffer.dispose(),this._renderer&&!this._renderer.isDisposed&&this._renderer.dispose(),this.textmodeCanvas&&!this.textmodeCanvas.isDisposed&&this.textmodeCanvas.dispose(),this.captureSource=null,this.textmodeCanvas=null,this._renderer=null,this._canvasFramebuffer=null,this._font=null,this._grid=null,this._pipeline=null,this.resizeObserver=null,this._drawCallback=()=>{},this._resizedCallback=()=>{},this.animationFrameId=null,this.lastFrameTime=0,this.lastRenderTime=0,this._frameCount=0,this._frameRate=0,this.frameTimeHistory=[])}get grid(){if(this._isDestroyed)throw new Error("Cannot access grid: Textmodifier instance has been destroyed");return this._grid}get font(){if(this._isDestroyed)throw new Error("Cannot access font: Textmodifier instance has been destroyed");return this._font}get mode(){if(this._isDestroyed)throw new Error("Cannot access mode: Textmodifier instance has been destroyed");return this._mode}get pipeline(){if(this._isDestroyed)throw new Error("Cannot access pipeline: Textmodifier instance has been destroyed");return this._pipeline}get frameCount(){return this._isDestroyed?0:this._frameCount}get width(){return this._isDestroyed?0:this.textmodeCanvas.width}get height(){return this._isDestroyed?0:this.textmodeCanvas.height}get isDestroyed(){return this._isDestroyed}}class I{static async create(e,t={}){if(e instanceof HTMLCanvasElement||e instanceof HTMLVideoElement)return P.create(e,t);{const r=e||{};return P.create(null,r)}}static setErrorLevel(e){b.setGlobalLevel(e)}static get version(){return"0.1.4-beta.1"}constructor(){throw new Error("Textmode is a static class and cannot be instantiated.")}}const Ie=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),Be=I.create,Ge=I.setErrorLevel,Ve=I.version;v.TextmodeCanvas=Z,v.TextmodeConversionPipeline=J,v.TextmodeErrorLevel=E,v.TextmodeFont=q,v.TextmodeGrid=Q,v.Textmodifier=P,v.converters=Ce,v.create=Be,v.default=I,v.export=Ie,v.setErrorLevel=Ge,v.textmode=I,v.version=Ve,Object.defineProperties(v,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
25
+ `;return r.join(i)}}class Ue extends L{saveTXT(e,t){try{const r=this.ensureValidFilename(t);this.downloadFile(e,r,"text/plain;charset=utf-8")}catch(r){throw console.error("Failed to save TXT file:",r),new Error(`TXT file save failed: ${r instanceof Error?r.message:"Unknown error"}`)}}ensureValidFilename(e){let t=this.sanitizeFilename(e);return t===".txt"||t.length<=4?this.generateDefaultFilename():t}}class ee{constructor(){a(this,"dataExtractor");a(this,"contentGenerator");a(this,"fileHandler");this.dataExtractor=new Re,this.contentGenerator=new Ee,this.fileHandler=new Ue}applyDefaultOptions(e){return{preserveTrailingSpaces:e.preserveTrailingSpaces??!1,lineEnding:e.lineEnding??"lf",emptyCharacter:e.emptyCharacter??" "}}generateTXT(e,t={}){const r=this.applyDefaultOptions(t),i=this.dataExtractor.extractFramebufferData(e.pipeline),s=this.dataExtractor.extractCharacterGrid(i,e.grid,e.font,r.emptyCharacter);return this.contentGenerator.generateTXTContent(s,r)}saveTXT(e,t={}){try{const r=this.generateTXT(e,t),i=t.filename||this.fileHandler.generateDefaultFilename();this.fileHandler.saveTXT(r,i)}catch(r){throw console.error("Failed to save TXT:",r),new Error(`TXT save failed: ${r instanceof Error?r.message:"Unknown error"}`)}}}class De extends ${captureCanvasData(e,t=1,r="transparent"){const i=e.canvas;if(t===1&&r==="transparent")return i;const s=document.createElement("canvas"),n=s.getContext("2d"),o=Math.round(i.width*t),l=Math.round(i.height*t);return s.width=o,s.height=l,r!=="transparent"&&(n.fillStyle=r,n.fillRect(0,0,o,l)),n.imageSmoothingEnabled=!1,n.drawImage(i,0,0,i.width,i.height,0,0,o,l),s}}class Ae{generateImageData(e,t){const r=this.getMimeType(t.format);return t.format==="png"?e.toDataURL(r):e.toDataURL(r,t.quality)}async generateImageBlob(e,t){return new Promise((r,i)=>{const s=this.getMimeType(t.format),n=o=>{o?r(o):i(new Error(`Failed to generate ${t.format.toUpperCase()} blob`))};t.format==="png"?e.toBlob(n,s):e.toBlob(n,s,t.quality)})}getMimeType(e){switch(e){case"png":return"image/png";case"jpg":return"image/jpeg";case"webp":return"image/webp";default:throw new Error(`Unsupported image format: ${e}`)}}}const te={png:"image/png",jpg:"image/jpeg",webp:"image/webp"},X={png:".png",jpg:".jpg",webp:".webp"};class Me extends L{saveImage(e,t,r){try{const i=X[r];typeof e=="string"?this.saveImageFromDataURL(e,this.sanitizeFilename(t)+i):this.saveImageFromBlob(e,this.sanitizeFilename(t)+i)}catch(i){throw console.error(`Failed to save ${r.toUpperCase()} image:`,i),new Error(`Image save failed: ${i instanceof Error?i.message:"Unknown error"}`)}}saveImageFromDataURL(e,t){const r=document.createElement("a");r.href=e,r.download=t,r.style.display="none",r.rel="noopener",document.body.appendChild(r),r.click(),document.body.removeChild(r)}saveImageFromBlob(e,t){const r=URL.createObjectURL(e);try{const i=document.createElement("a");i.href=r,i.download=t,i.style.display="none",i.rel="noopener",document.body.appendChild(i),i.click(),document.body.removeChild(i)}finally{URL.revokeObjectURL(r)}}validateSaveSupport(e){return e in te&&e in X}getMimeType(e){return te[e]}getFileExtension(e){return X[e]}}class Ie{constructor(){a(this,"dataExtractor");a(this,"contentGenerator");a(this,"fileHandler");this.dataExtractor=new De,this.contentGenerator=new Ae,this.fileHandler=new Me}applyDefaultOptions(e){return{format:e.format??"png",quality:e.quality??1,scale:e.scale??1,backgroundColor:e.backgroundColor??"transparent"}}validateOptions(e){if(console.log("Validating image export options:",e),!this.fileHandler.validateSaveSupport(e.format))throw new Error(`Saving '${e.format}' files is not supported`);if(e.quality<0||e.quality>1)throw new Error("Image quality must be between 0.0 and 1.0");if(e.scale<=0)throw new Error("Scale factor must be greater than 0");e.scale>10&&console.warn("Large scale factors may result in very large files and slow performance"),e.format==="jpg"&&e.backgroundColor==="transparent"&&(e.backgroundColor="black")}generateImage(e,t={}){const r=this.applyDefaultOptions(t);if(this.validateOptions(r),r.scale===1&&r.backgroundColor==="transparent")return this.contentGenerator.generateImageData(e.canvas,r);const i=this.dataExtractor.captureCanvasData(e,r.scale,r.backgroundColor);return this.contentGenerator.generateImageData(i,r)}async generateImageBlob(e,t={}){const r=this.applyDefaultOptions(t);if(this.validateOptions(r),r.scale===1&&r.backgroundColor==="transparent")return await this.contentGenerator.generateImageBlob(e.canvas,r);const i=this.dataExtractor.captureCanvasData(e,r.scale,r.backgroundColor);return await this.contentGenerator.generateImageBlob(i,r)}async saveImage(e,t={}){try{const r=await this.generateImageBlob(e,t),i=t.format??"png",s=t.filename||this.fileHandler.generateDefaultFilename();this.fileHandler.saveImage(r,s,i)}catch(r){throw console.error("Failed to save image:",r),new Error(`Image save failed: ${r instanceof Error?r.message:"Unknown error"}`)}}}class I{constructor(e=null,t={}){a(this,"captureSource");a(this,"textmodeCanvas");a(this,"_renderer");a(this,"_canvasFramebuffer");a(this,"_font");a(this,"_grid");a(this,"resizeObserver");a(this,"_mode");a(this,"_frameRateLimit");a(this,"animationFrameId",null);a(this,"lastFrameTime",0);a(this,"frameInterval");a(this,"_isLooping",!0);a(this,"_frameRate",0);a(this,"lastRenderTime",0);a(this,"_frameCount",0);a(this,"frameTimeHistory",[]);a(this,"frameTimeHistorySize",10);a(this,"_pipeline");a(this,"_standalone",!1);a(this,"_drawCallback",()=>{});a(this,"_resizedCallback",()=>{});a(this,"_isDestroyed",!1);a(this,"_windowResizeListener",null);this.captureSource=e,this._standalone=e===null,this._mode=t.renderMode??"auto",this._frameRateLimit=t.frameRate??60,this.frameInterval=1e3/this._frameRateLimit}static async create(e=null,t={}){const r=new I(e,t),i=r._standalone?t:void 0;r.textmodeCanvas=new Z(r.captureSource,r._standalone,i),r._renderer=new le(r.textmodeCanvas.getWebGLContext());let s,n;r._standalone?(s=t.width||800,n=t.height||600):(s=r.textmodeCanvas.width||800,n=r.textmodeCanvas.height||600),r._canvasFramebuffer=r._renderer.createFramebuffer(s,n),r._font=new q(r._renderer,t.fontSize??16),await r._font.initialize(t.fontSource);const o=r._font.maxGlyphDimensions;return r._grid=new Q(r.textmodeCanvas.canvas,o.width,o.height),r._pipeline=new J(r._renderer,r._font,r._grid),r.setupEventListeners(),r.startAutoRendering(),r}setupEventListeners(){this._windowResizeListener=()=>{this._standalone?this._resizedCallback():this.resize()},window.addEventListener("resize",this._windowResizeListener),window.ResizeObserver&&this.captureSource&&!this._standalone&&(this.resizeObserver=new ResizeObserver(()=>{this.resize()}),this.resizeObserver.observe(this.captureSource))}toString(e={}){return new ee().generateTXT(this,e)}saveStrings(e={}){new ee().saveTXT(this,e)}toSVG(e={}){return new K().generateSVG(this,e)}saveSVG(e={}){new K().saveSVG(this,e)}async saveCanvas(e,t="png",r={}){await new Ie().saveImage(this.textmodeCanvas,{...r,filename:e,format:t})}async loadFont(e){return this._font.loadFont(e).then(()=>{const t=this._font.maxGlyphDimensions;this._grid.resizeCellPixelDimensions(t.width,t.height),this._pipeline.resize()})}render(){if(this._isDestroyed){console.warn("Cannot render: Textmodifier instance has been destroyed");return}if(this.measureFrameRate(),this._frameCount++,!this._canvasFramebuffer||!this._renderer||!this._pipeline){console.warn("Cannot render: Required resources have been disposed");return}if(this._standalone?this._canvasFramebuffer&&(this._canvasFramebuffer.begin(),this._drawCallback(),this._renderer&&this._renderer.reset(),this._canvasFramebuffer&&this._canvasFramebuffer.end()):this.captureSource&&this._canvasFramebuffer&&this._canvasFramebuffer.update(this.captureSource),!this._pipeline||!this._renderer){console.warn("Cannot complete render: Pipeline or renderer has been disposed");return}this._pipeline.render(this._canvasFramebuffer),this._pipeline.hasEnabledConverters()?this._renderer&&this._pipeline.texture&&this._grid&&(this._renderer.background(0),this._renderer.image(this._pipeline.texture,this._grid.offsetX,this._grid.offsetY,this._pipeline.texture.width,this._pipeline.texture.height)):this._renderer&&this._canvasFramebuffer&&this._grid&&(this._renderer.clear(),this._renderer.image(this._canvasFramebuffer,this._grid.offsetX,this._grid.offsetY,this._canvasFramebuffer.width,this._canvasFramebuffer.height))}resize(){this.textmodeCanvas.resize(),this._canvasFramebuffer.resize(this.textmodeCanvas.width,this.textmodeCanvas.height),this._grid.resize(),this._pipeline.resize(),this._renderer.resetViewport(),this._mode!=="manual"&&this.render()}startAutoRendering(){if(this._mode!=="auto"||this._isDestroyed||!this._isLooping)return;this.lastFrameTime=performance.now();const e=t=>{if(this._isDestroyed)return;if(!this._isLooping){this.animationFrameId=null;return}const r=t-this.lastFrameTime;r>=this.frameInterval&&(this.render(),this.lastFrameTime=t-r%this.frameInterval),!this._isDestroyed&&this._isLooping&&(this.animationFrameId=requestAnimationFrame(e))};this.animationFrameId=requestAnimationFrame(e)}measureFrameRate(){if(this._isDestroyed)return;const e=performance.now();if(this.lastRenderTime>0){const t=e-this.lastRenderTime;this.frameTimeHistory.push(t),this.frameTimeHistory.length>this.frameTimeHistorySize&&this.frameTimeHistory.shift();const r=this.frameTimeHistory.reduce((i,s)=>i+s,0)/this.frameTimeHistory.length;this._frameRate=1e3/r}this.lastRenderTime=e}stopAutoRendering(){this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}renderMode(e){if(this._isDestroyed){console.warn("Cannot change render mode: Textmodifier instance has been destroyed");return}this._mode!==e&&(this.stopAutoRendering(),this._mode=e,e==="auto"&&this._isLooping&&this.startAutoRendering())}frameRate(e){if(e===void 0)return this._frameRate;this._frameRateLimit=e,this.frameInterval=1e3/e,this._mode==="auto"&&this._isLooping&&(this.stopAutoRendering(),this.startAutoRendering())}noLoop(){if(this._isDestroyed){console.warn("Cannot stop loop: Textmodifier instance has been destroyed");return}this._isLooping&&(this._isLooping=!1,this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null))}loop(){if(this._isDestroyed){console.warn("Cannot start loop: Textmodifier instance has been destroyed");return}this._isLooping||(this._isLooping=!0,this._mode==="auto"&&this.startAutoRendering())}isLooping(){return this._isDestroyed?!1:this._mode==="auto"&&this._isLooping}fontSize(e){b.validate(typeof e=="number"&&e>0,"Font size must be a positive number greater than 0.",{method:"fontSize",providedValue:e})&&this._font.fontSize!==e&&(this._font.setFontSize(e),this._grid.resizeCellPixelDimensions(this._font.maxGlyphDimensions.width,this._font.maxGlyphDimensions.height),this._pipeline.resize(),this._renderer.resetViewport())}draw(e){this._drawCallback=e}windowResized(e){this._resizedCallback=e}resizeCanvas(e,t){this.textmodeCanvas.resize(e,t),this._canvasFramebuffer.resize(this.textmodeCanvas.width,this.textmodeCanvas.height),this._grid.resize(),this._pipeline.resize(),this._renderer.resetViewport(),this._mode!=="manual"&&this.render()}converter(e){return this._pipeline.get(e)}fill(e,t,r,i){this._renderer.fill(e,t,r,i)}stroke(e,t,r,i){this._renderer.stroke(e,t,r,i)}strokeWeight(e){this._renderer.strokeWeight(e)}noStroke(){this._renderer.noStroke()}noFill(){this._renderer.noFill()}rotate(e){this._renderer.rotate(e)}push(){this._renderer.push()}pop(){this._renderer.pop()}rect(e,t,r=1,i=1){this._renderer.rect(e,t,r,i)}line(e,t,r,i){this._renderer.line(e,t,r,i)}background(e,t=e,r=e,i=255){this._renderer.background(e,t,r,i)}createShader(e,t){return this._renderer.createShader(e,t)}shader(e){this._renderer.shader(e)}setUniform(e,t){this._renderer.setUniform(e,t)}destroy(){this._isDestroyed||(this._isDestroyed=!0,this.stopAutoRendering(),this._windowResizeListener&&(window.removeEventListener("resize",this._windowResizeListener),this._windowResizeListener=null),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this._pipeline&&!this._pipeline.isDisposed&&this._pipeline.dispose(),this._font&&!this._font.isDisposed&&this._font.dispose(),this._grid&&!this._grid.isDisposed&&this._grid.dispose(),this._canvasFramebuffer&&!this._canvasFramebuffer.isDisposed&&this._canvasFramebuffer.dispose(),this._renderer&&!this._renderer.isDisposed&&this._renderer.dispose(),this.textmodeCanvas&&!this.textmodeCanvas.isDisposed&&this.textmodeCanvas.dispose(),this.captureSource=null,this.textmodeCanvas=null,this._renderer=null,this._canvasFramebuffer=null,this._font=null,this._grid=null,this._pipeline=null,this.resizeObserver=null,this._drawCallback=()=>{},this._resizedCallback=()=>{},this.animationFrameId=null,this.lastFrameTime=0,this.lastRenderTime=0,this._frameCount=0,this._frameRate=0,this.frameTimeHistory=[],this._isLooping=!1)}get grid(){if(this._isDestroyed)throw new Error("Cannot access grid: Textmodifier instance has been destroyed");return this._grid}get font(){if(this._isDestroyed)throw new Error("Cannot access font: Textmodifier instance has been destroyed");return this._font}get mode(){if(this._isDestroyed)throw new Error("Cannot access mode: Textmodifier instance has been destroyed");return this._mode}get pipeline(){if(this._isDestroyed)throw new Error("Cannot access pipeline: Textmodifier instance has been destroyed");return this._pipeline}get frameCount(){return this._isDestroyed?0:this._frameCount}get width(){return this._isDestroyed?0:this.textmodeCanvas.width}get height(){return this._isDestroyed?0:this.textmodeCanvas.height}get isDestroyed(){return this._isDestroyed}}class P{static async create(e,t={}){if(e instanceof HTMLCanvasElement||e instanceof HTMLVideoElement)return I.create(e,t);{const r=e||{};return I.create(null,r)}}static setErrorLevel(e){b.setGlobalLevel(e)}static get version(){return"0.1.4-beta.2"}constructor(){throw new Error("Textmode is a static class and cannot be instantiated.")}}const Pe=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),Be=P.create,Ge=P.setErrorLevel,Ve=P.version;v.TextmodeCanvas=Z,v.TextmodeConversionPipeline=J,v.TextmodeErrorLevel=E,v.TextmodeFont=q,v.TextmodeGrid=Q,v.Textmodifier=I,v.converters=Ce,v.create=Be,v.default=P,v.export=Pe,v.setErrorLevel=Ge,v.textmode=P,v.version=Ve,Object.defineProperties(v,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
@@ -57,6 +57,7 @@ export declare class Textmodifier {
57
57
  private animationFrameId;
58
58
  private lastFrameTime;
59
59
  private frameInterval;
60
+ private _isLooping;
60
61
  private _frameRate;
61
62
  private lastRenderTime;
62
63
  private _frameCount;
@@ -332,6 +333,90 @@ export declare class Textmodifier {
332
333
  * ```
333
334
  */
334
335
  frameRate(fps?: number): number | void;
336
+ /**
337
+ * Stop the automatic rendering loop while keeping the render mode as 'auto'.
338
+ *
339
+ * This method pauses the render loop without changing the render mode, allowing
340
+ * it to be resumed later with {@link loop}. This is useful for temporarily pausing
341
+ * animation while maintaining the ability to restart it.
342
+ *
343
+ * **Note:** This only affects rendering when in `'auto'` mode. In `'manual'` mode,
344
+ * this method has no effect since rendering is already controlled manually.
345
+ *
346
+ * @example
347
+ * ```javascript
348
+ * // Create a textmodifier instance in auto mode
349
+ * const textmodifier = await textmode.create(canvas);
350
+ *
351
+ * // The render loop is running automatically
352
+ * console.log(textmodifier.isLooping()); // true
353
+ *
354
+ * // Stop the automatic rendering loop
355
+ * textmodifier.noLoop();
356
+ * console.log(textmodifier.isLooping()); // false
357
+ *
358
+ * // Resume the automatic rendering loop
359
+ * textmodifier.loop();
360
+ * console.log(textmodifier.isLooping()); // true
361
+ * ```
362
+ */
363
+ noLoop(): void;
364
+ /**
365
+ * Resume the automatic rendering loop if it was stopped by {@link noLoop}.
366
+ *
367
+ * This method restarts the render loop when in `'auto'` mode. If the render mode
368
+ * is `'manual'`, the loop state will be set but automatic rendering will not start
369
+ * until the mode is changed back to `'auto'`.
370
+ *
371
+ * @example
372
+ * ```javascript
373
+ * // Create a textmodifier instance
374
+ * const textmodifier = await textmode.create(canvas);
375
+ *
376
+ * // Stop the loop
377
+ * textmodifier.noLoop();
378
+ *
379
+ * // Resume the loop
380
+ * textmodifier.loop();
381
+ *
382
+ * // You can also use this pattern for conditional animation
383
+ * if (someCondition) {
384
+ * textmodifier.loop();
385
+ * } else {
386
+ * textmodifier.noLoop();
387
+ * }
388
+ * ```
389
+ */
390
+ loop(): void;
391
+ /**
392
+ * Check whether the textmodifier is currently running the automatic render loop.
393
+ *
394
+ * Returns `true` when both the render mode is `'auto'` AND the loop is active.
395
+ * Returns `false` when in `'manual'` mode or when {@link noLoop} has been called.
396
+ *
397
+ * @returns True if the automatic render loop is currently active, false otherwise.
398
+ *
399
+ * @example
400
+ * ```javascript
401
+ * const textmodifier = await textmode.create(canvas);
402
+ *
403
+ * // Check loop status in different states
404
+ * console.log(textmodifier.isLooping()); // true (auto mode, looping)
405
+ *
406
+ * textmodifier.noLoop();
407
+ * console.log(textmodifier.isLooping()); // false (auto mode, not looping)
408
+ *
409
+ * textmodifier.renderMode('manual');
410
+ * console.log(textmodifier.isLooping()); // false (manual mode)
411
+ *
412
+ * textmodifier.renderMode('auto');
413
+ * console.log(textmodifier.isLooping()); // false (auto mode, but loop was stopped)
414
+ *
415
+ * textmodifier.loop();
416
+ * console.log(textmodifier.isLooping()); // true (auto mode, looping)
417
+ * ```
418
+ */
419
+ isLooping(): boolean;
335
420
  /**
336
421
  * Set the font size used for rendering.
337
422
  * @param size The font size to set.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "textmode.js",
3
- "version": "0.1.4-beta.2",
3
+ "version": "0.1.4-beta.3",
4
4
  "description": "Apply real-time ASCII conversion to any HTML canvas.",
5
5
  "type": "module",
6
6
  "types": "./dist/types/index.d.ts",
@@ -19,7 +19,7 @@
19
19
  }
20
20
  },
21
21
  "scripts": {
22
- "dev": "vite",
22
+ "dev": "vite --port 5177 --host",
23
23
  "build": "vite build && vite build --mode min && tsc",
24
24
  "build:full": "vite build && tsc",
25
25
  "build:min": "vite build --mode min && tsc",