@utsp/core 0.7.0 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +7 -0
- package/dist/index.mjs +1 -1
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -5,6 +5,6 @@
|
|
|
5
5
|
`,this.axes.forEach(t=>{e+=` [${t.bindingId}] ${t.name}: `,e+=`${t.min} to ${t.max} (default: ${t.defaultValue})
|
|
6
6
|
`}),e+=`Buttons (${this.buttons.size}):
|
|
7
7
|
`,this.buttons.forEach(t=>{e+=` [${t.bindingId}] ${t.name}: `,e+=`(default: ${t.defaultValue})
|
|
8
|
-
`}),e}};g(Ct,"InputBindingRegistry");var ee=Ct;function Re(m=0n){return{tick:m,axes:new Map,buttons:new Map,displayId:0,mouseX:0,mouseY:0,mouseOverDisplay:!1,textInputs:[],macroEvents:[]}}g(Re,"createEmptyCompressedInputPacket");function ke(m){let e=Math.max(-1,Math.min(1,m));return Math.round(e*127)}g(ke,"encodeAxisToInt8");function Pe(m){return m/127}g(Pe,"decodeInt8ToAxis");function V(m){return m===0?0:Math.ceil(m/8)}g(V,"getButtonByteCount");function Be(m,e){let r=m,n=V(e);return 8+r+n+4}g(Be,"getCompressedPacketSize");var ft=class ft{decode(e,t=0){let r=e.readUInt8(t);switch(r){case 1:return this.decodeClick(e,t);case 2:return this.decodeChange(e,t);case 3:return this.decodeSubmit(e,t);case 4:return this.decodeSelect(e,t);default:throw new Error(`Unknown macro event type: 0x${r.toString(16)}`)}}decodeAll(e,t,r){let n=[],o=0;for(let i=0;i<r;i++){let{event:s,bytesRead:a}=this.decode(e,t+o);n.push(s),o+=a}return{events:n,bytesRead:o}}decodeClick(e,t){let r=e.readUInt8(t),n=e.readUInt8(t+1);return{event:{type:r,instanceId:n},bytesRead:2}}decodeChange(e,t){let r=e.readUInt8(t),n=e.readUInt8(t+1),o=e.readUInt8(t+2),i,s;return o===1?(i=e.readUInt8(t+3)===1,s=4):(i=e.readFloatBE(t+3),s=7),{event:{type:r,instanceId:n,value:i},bytesRead:s}}decodeSubmit(e,t){let r=t,n=e.readUInt8(t++),o=e.readUInt8(t++),i=e.readUInt16BE(t);t+=2;let s=e.toUint8Array().subarray(t,t+i);t+=i;let a=new TextDecoder().decode(s);return{event:{type:n,instanceId:o,text:a},bytesRead:t-r}}decodeSelect(e,t){let r=e.readUInt8(t),n=e.readUInt8(t+1),o=e.readUInt16BE(t+2);return{event:{type:r,instanceId:n,index:o},bytesRead:4}}};g(ft,"MacroEventDecoder");var Te=ft;F();function ze(m,e){let t=e.getAllAxes().length,r=e.getAllButtons().length,n=V(r),o=8+t+n+4;if(m.length<o)throw new Error(`Invalid compressed input packet: expected at least ${o} bytes (${t} axes + ${r} buttons), got ${m.length}`);let i=new DataView(m.buffer,m.byteOffset,m.byteLength),s=0,a=Re();a.tick=i.getBigUint64(s,!0),s+=8;for(let c=0;c<t;c++){let l=m[s],u=l>127?l-256:l,p=Pe(u);a.axes.set(c,p),s+=1}for(let c=0;c<n;c++){let l=m[s];for(let u=0;u<8;u++){let p=c*8+u;if(p<r){let h=(l&1<<u)!==0;a.buttons.set(p,h)}}s+=1}a.displayId=m[s],s+=1,a.mouseX=m[s],s+=1,a.mouseY=m[s],s+=1;let d=m[s];if(a.mouseOverDisplay=(d&1)!==0,s+=1,s<m.length){let c=m[s];s+=1;let l=new TextDecoder;a.textInputs=[];for(let u=0;u<c&&s<m.length;u++){let p=m[s];if(s+=1,s+p<=m.length){let h=m.slice(s,s+p),y=l.decode(h);a.textInputs.push(y),s+=p}}}if(s<m.length){let c=m[s];s+=1;let l=new Te,u=[],p=C.from(m);for(let h=0;h<c&&s<m.length;h++){let y=l.decode(p,s);u.push(y.event),s+=y.bytesRead}a.macroEvents=u}return a}g(ze,"decodeCompressedInput");var R=require("@utsp/types");var St=class St{constructor(e,t){b(this,"enabled",!1);b(this,"currentStats",null);b(this,"_userId");b(this,"_userName");this._userId=e,this._userName=t}setEnabled(e){this.enabled=e,e||(this.currentStats=null)}isEnabled(){return this.enabled}get userId(){return this.currentStats?.userId??this._userId}get userName(){return this.currentStats?.userName??this._userName}get tick(){return this.currentStats?.tick??0}get timestamp(){return this.currentStats?.timestamp??0}get displayCount(){return this.currentStats?.displayCount??0}get totalDisplayArea(){return this.currentStats?.totalDisplayArea??0}get totalLayers(){return this.currentStats?.totalLayers??0}get visibleLayers(){return this.currentStats?.visibleLayers??0}get staticLayers(){return this.currentStats?.staticLayers??0}get dynamicLayers(){return this.currentStats?.dynamicLayers??0}get totalOrders(){return this.currentStats?.totalOrders??0}get ordersByLayer(){return this.currentStats?.ordersByLayer??new Map}get staticPacketSize(){return this.currentStats?.staticPacketSize??0}get dynamicPacketSize(){return this.currentStats?.dynamicPacketSize??0}get totalPacketSize(){return this.currentStats?.totalPacketSize??0}get compressedPacketSize(){return Math.round(this.totalPacketSize*.25)}get hasInput(){return this.currentStats?.hasInput??!1}get axisCount(){return this.currentStats?.axisCount??0}get buttonCount(){return this.currentStats?.buttonCount??0}startTick(e){this.enabled&&(this.currentStats={userId:this._userId,userName:this._userName,tick:e,timestamp:Date.now(),displayCount:0,totalDisplayArea:0,totalLayers:0,visibleLayers:0,staticLayers:0,dynamicLayers:0,totalOrders:0,ordersByLayer:new Map,staticPacketSize:0,dynamicPacketSize:0,totalPacketSize:0,hasInput:!1,axisCount:0,buttonCount:0})}recordDisplays(e,t){!this.enabled||!this.currentStats||(this.currentStats.displayCount=e,this.currentStats.totalDisplayArea=t)}recordLayers(e,t,r,n){!this.enabled||!this.currentStats||(this.currentStats.totalLayers=e,this.currentStats.visibleLayers=t,this.currentStats.staticLayers=r,this.currentStats.dynamicLayers=n)}recordLayerOrders(e,t){!this.enabled||!this.currentStats||(this.currentStats.totalOrders+=t,this.currentStats.ordersByLayer.set(e,t))}recordPacketSizes(e,t){!this.enabled||!this.currentStats||(this.currentStats.staticPacketSize=e,this.currentStats.dynamicPacketSize=t,this.currentStats.totalPacketSize=e+t)}recordInput(e,t,r){!this.enabled||!this.currentStats||(this.currentStats.hasInput=e,this.currentStats.axisCount=t,this.currentStats.buttonCount=r)}endTick(){}reset(){this.currentStats=null}};g(St,"UserStats");var te=St;var vt=class vt{constructor(e,t,r){this.id=e;this.name=t;b(this,"displays",[]);b(this,"layers",[]);b(this,"spriteRegistry");b(this,"mode");b(this,"axes",new Map);b(this,"buttons",new Map);b(this,"textInputs",[]);b(this,"mouseX",0);b(this,"mouseY",0);b(this,"mouseOver",!1);b(this,"mouseDisplayId",0);b(this,"touchPositions",new Map);b(this,"activeTouchId",null);b(this,"inputBindings",new ee);b(this,"stats");b(this,"soundCommands",[]);b(this,"nextSoundInstanceId",1);b(this,"audioConfigCommands",[]);b(this,"lastListenerX",-1);b(this,"lastListenerY",-1);b(this,"pendingSendSounds",!1);b(this,"audioProcessor");b(this,"loadedSounds",new Map);b(this,"soundLoadErrors",new Map);b(this,"playingSounds",new Map);b(this,"macroRegistry",new q);b(this,"macroEngine",new Q);b(this,"macroEventHandlers",new Map);b(this,"postProcessCommands",[]);b(this,"currentPostProcessConfig",null);b(this,"data");b(this,"currentScalingMode",null);b(this,"currentGridConfig",null);this.mode=r,this.stats=new te(e,t),this.data={}}setSpriteRegistry(e){this.spriteRegistry=e;for(let t of this.layers)t.setSpriteRegistry(e);this.macroEngine.setSpriteRegistry(e)}getDisplays(){return this.displays}addDisplay(e){this.displays.push(e)}removeDisplay(e){let t=this.displays.indexOf(e);return t!==-1?(this.displays.splice(t,1),!0):!1}clearDisplays(){this.displays=[]}getLayers(){return this.layers}getLayerById(e){return this.layers.find(t=>t.getId()===e)}addLayer(e,t){e.setMode(this.mode);let r=this.layers.length+1;e.setId(r),this.layers.push(e),this.spriteRegistry&&e.setSpriteRegistry(this.spriteRegistry),t&&this.macroRegistry.setLayerMapping(t,e.getId())}removeLayer(e){let t=this.layers.indexOf(e);return t!==-1?(this.layers.splice(t,1),!0):!1}clearLayers(){this.layers=[]}setMousePosition(e,t,r=!0){this.mouseX=Math.max(0,Math.min(255,e)),this.mouseY=Math.max(0,Math.min(255,t)),this.mouseOver=r}setTouchPosition(e,t,r,n=!0,o=0){if(e<0||e>9){console.warn(`Invalid touchId ${e}, must be 0-9`);return}n?(this.touchPositions.set(e,{x:Math.max(0,Math.min(255,t)),y:Math.max(0,Math.min(255,r)),over:!0,displayId:o}),this.activeTouchId=e):(this.touchPositions.delete(e),this.activeTouchId===e&&(this.activeTouchId=null))}setAxis(e,t){let r=Math.max(-1,Math.min(1,t));this.axes.set(e,r)}getAxis(e){return this.axes.get(e)??0}setButton(e,t){this.buttons.set(e,t)}getButton(e){return this.buttons.get(e)??!1}getButtonJustPressed(e){let t=`${e}_justPressed`;return this.buttons.get(t)??!1}getButtonJustReleased(e){let t=`${e}_justReleased`;return this.buttons.get(t)??!1}setTextInputs(e){this.textInputs=e}getTextInputs(){return this.textInputs}clearTextInputs(){this.textInputs=[]}getAxisNames(){return Array.from(this.axes.keys())}getButtonNames(){return Array.from(this.buttons.keys())}clearAxes(){this.axes.clear()}clearButtons(){this.buttons.clear()}getMouseDisplayInfo(){if(!this.mouseOver||this.displays.length===0)return null;let e=this.displays[0],t=0,r=this.mouseX,n=this.mouseY,o=e.getOrigin(),i=o.x+r,s=o.y+n;return{displayId:t,localX:r,localY:n,worldX:i,worldY:s}}getTouchDisplayInfo(e=0){if(e<0||e>9)return console.warn(`Invalid touchId ${e}, must be 0-9`),null;let t=this.touchPositions.get(e);if(!t||!t.over||this.displays.length===0)return null;let r=this.displays[0],n=t.displayId,o=t.x,i=t.y,s=r.getOrigin(),a=s.x+o,d=s.y+i;return{displayId:n,localX:o,localY:i,worldX:a,worldY:d}}getIsMouseOnADisplay(){return this.mouseOver}getMouseDisplayHover(){let e=this.getMouseDisplayInfo();return e?e.displayId:null}findLayerById(e){return this.layers.find(t=>t.getId()===e)??null}applyUpdate(e){if(this.updateDisplaysFromPacket(e.displays),this.updateLayersFromPacket(e.layers),e.macroOrders&&e.macroOrders.length>0)for(let t of e.macroOrders)this.macroEngine.applyOrder(t)}updateDisplaysFromPacket(e){for(let t of e){let r=this.displays[t.id];if(!r){for(r=new Z(t.id,t.sizeX,t.sizeY);this.displays.length<=t.id;)this.displays.push(null);this.displays[t.id]=r}r.setOrigin(new R.Vector2(t.originX,t.originY)),r.setSize(new R.Vector2(t.sizeX,t.sizeY))}}updateLayersFromPacket(e){for(let t of e){let r=this.findLayerById(t.id);r||(r=new J(new R.Vector2(t.originX,t.originY),t.zIndex,t.width,t.height,!1),r.setId(t.id),r.setMode(this.mode),this.spriteRegistry&&r.setSpriteRegistry(this.spriteRegistry),this.addLayer(r)),t.updateFlags&1&&r.setOrigin(new R.Vector2(t.originX,t.originY)),t.updateFlags&2&&r.setZOrder(t.zIndex),t.updateFlags&4&&r.setOrders(t.orders)}}defineAxisBinding(e,t,r=[],n=-1,o=1,i=0){this.inputBindings.defineAxis(e,t,r,n,o,i)}defineButtonBinding(e,t,r=[],n=!1){this.inputBindings.defineButton(e,t,r,n)}defineAxisBindings(e){e.forEach(({bindingId:t,name:r,sources:n,min:o,max:i,defaultValue:s})=>{this.defineAxisBinding(t,r,n??[],o,i,s)})}defineButtonBindings(e){e.forEach(({bindingId:t,name:r,sources:n,defaultValue:o})=>{this.defineButtonBinding(t,r,n??[],o)})}getInputBindingsLoadPacket(){return this.inputBindings.toLoadPacket()}applyInputBindingsLoadPacket(e){try{let t=JSON.parse(e);if(t.type!=="input-binding")throw new Error(`Invalid packet type: ${t.type}`);for(let r of t.axes)this.defineAxisBinding(r.bindingId,r.name,r.sources||[],r.min,r.max,r.defaultValue);for(let r of t.buttons)this.defineButtonBinding(r.bindingId,r.name,r.sources||[],r.defaultValue)}catch(t){throw console.error("[User] Failed to apply input bindings:",t),t}}getInputBindingRegistry(){return this.inputBindings}getStats(){return this.stats}getAxisBindingId(e){return this.inputBindings.getAxisBindingId(e)}getButtonBindingId(e){return this.inputBindings.getButtonBindingId(e)}decodeAndApplyCompressedInput(e){let t=ze(e,this.inputBindings),r=this.inputBindings.getAllAxes(),n=this.inputBindings.getAllButtons(),o=r.sort((s,a)=>s.bindingId-a.bindingId),i=n.sort((s,a)=>s.bindingId-a.bindingId);for(let[s,a]of t.axes)if(s<o.length){let d=o[s];this.setAxis(d.name,a)}for(let[s,a]of t.buttons)if(s<i.length){let d=i[s];this.setButton(d.name,a)}this.mouseX=t.mouseX,this.mouseY=t.mouseY,this.mouseOver=t.mouseOverDisplay,this.mouseDisplayId=t.displayId}playSound(e,t){let r=this.nextSoundInstanceId++,n={sound:e,instanceId:r,volume:t?.volume,pitch:t?.pitch,loop:t?.loop,fadeIn:t?.fadeIn,x:t?.x,y:t?.y,lowpass:t?.lowpass,highpass:t?.highpass,reverb:t?.reverb};return this.soundCommands.push(n),r}stopSound(e){let t={sound:e};this.soundCommands.push(t)}fadeOutSound(e,t){let r={fadeOut:!0,sound:e,duration:t};this.soundCommands.push(r)}fadeOutAllSounds(e){let t={fadeOut:!0,sound:"all",duration:e};this.soundCommands.push(t)}stopAllSounds(){let e={sound:"all"};this.soundCommands.push(e)}pauseSound(e){let t={pause:!0,sound:e};this.soundCommands.push(t)}pauseAllSounds(){let e={pause:!0,sound:"all"};this.soundCommands.push(e)}resumeSound(e){let t={resume:!0,sound:e};this.soundCommands.push(t)}resumeAllSounds(){let e={resume:!0,sound:"all"};this.soundCommands.push(e)}setSoundEffects(e,t){let r={setEffects:!0,instanceId:e,lowpass:t.lowpass,highpass:t.highpass,reverb:t.reverb};this.soundCommands.push(r)}setListenerPosition(e,t){e===this.lastListenerX&&t===this.lastListenerY||(this.lastListenerX=e,this.lastListenerY=t,this.audioConfigCommands.push({type:"set-listener-position",x:e,y:t}))}configureSpatialAudio(e){this.audioConfigCommands.push({type:"configure-spatial",...e})}flushAudioConfigCommands(){let e=this.audioConfigCommands;return this.audioConfigCommands=[],e}hasAudioConfigCommands(){return this.audioConfigCommands.length>0}flushSoundCommands(){let e=this.soundCommands;return this.soundCommands=[],e}hasSoundCommands(){return this.soundCommands.length>0}sendSounds(){this.pendingSendSounds=!0}needsSendSounds(){return this.pendingSendSounds}clearSendSounds(){this.pendingSendSounds=!1}setAudioProcessor(e){this.audioProcessor=e,this.macroEngine.setAudioCallback(t=>{e.play(t)})}getAudioProcessor(){return this.audioProcessor}applyAudioCommands(e){if(this.audioProcessor&&this.mode!=="server")for(let t of e){if("setEffects"in t&&t.setEffects===!0){let n=t;this.audioProcessor.setEffects(n.instanceId,n.lowpass,n.highpass,n.reverb);continue}if("fadeOut"in t&&t.fadeOut===!0){let n=t;this.audioProcessor.fadeOut(n.sound,n.duration);continue}if("pause"in t&&t.pause===!0){let n=t;this.audioProcessor.pause(n.sound);continue}if("resume"in t&&t.resume===!0){let n=t;this.audioProcessor.resume(n.sound);continue}if("instanceId"in t||"volume"in t||"pitch"in t||"loop"in t||"fadeIn"in t||"x"in t||"y"in t||"lowpass"in t||"highpass"in t||"reverb"in t){let n=t,o=n.x!==void 0&&n.y!==void 0?{x:n.x,y:n.y}:void 0;this.audioProcessor.play(n.sound,{volume:n.volume,pitch:n.pitch,loop:n.loop,fadeIn:n.fadeIn,position:o,instanceId:n.instanceId,lowpass:n.lowpass,highpass:n.highpass,reverb:n.reverb})}else{let n=t;n.sound==="all"?this.audioProcessor.stopAll():this.audioProcessor.stop(n.sound)}}}applyAudioConfigCommands(e){if(this.audioProcessor&&this.mode!=="server")for(let t of e)t.type==="set-listener-position"?this.audioProcessor.setListenerPosition(t.x,t.y):t.type==="configure-spatial"&&this.audioProcessor.configureSpatial({maxDistance:t.maxDistance,referenceDistance:t.referenceDistance,rolloffFactor:t.rolloffFactor,panSpread:t.panSpread})}applyAudioOrders(e){if(!this.audioProcessor||this.mode==="server")return;let{AudioOrderType:t,AudioTargetType:r}=(Ut(),T(Mr)),{PlaySoundFlags:n}=(wt(),T(Er));for(let o of e)switch(o.type){case t.PlaySound:case t.PlayGlobalSound:{let i=o,s=i.volume!==void 0?i.volume/255:void 0,a=i.pitch!==void 0?.25*Math.pow(2,i.pitch/64):void 0,d=i.fadeIn!==void 0?i.fadeIn/10:void 0,c=(i.flags&n.Loop)!==0,l=i.posX!==void 0&&i.posY!==void 0?{x:i.posX,y:i.posY}:void 0;this.audioProcessor.play(i.soundId,{volume:s,pitch:a,loop:c,fadeIn:d,position:l,instanceId:i.instanceId,lowpass:i.lowpass,highpass:i.highpass,reverb:i.reverb});break}case t.StopSound:{let i=o;i.targetType===r.All?this.audioProcessor.stopAll():i.targetType===r.InstanceId?this.audioProcessor.stop(i.target):this.audioProcessor.stop(i.target);break}case t.FadeOutSound:{let i=o,s=i.duration/10;i.targetType===r.All?this.audioProcessor.fadeOut("all",s):this.audioProcessor.fadeOut(i.target,s);break}case t.PauseSound:{let i=o;i.targetType===r.All?this.audioProcessor.pause("all"):this.audioProcessor.pause(i.target);break}case t.ResumeSound:{let i=o;i.targetType===r.All?this.audioProcessor.resume("all"):this.audioProcessor.resume(i.target);break}case t.SetListenerPosition:{let i=o;this.audioProcessor.setListenerPosition(i.x,i.y);break}case t.ConfigureSpatial:{let i=o;this.audioProcessor.configureSpatial({maxDistance:i.maxDistance*100,referenceDistance:i.referenceDistance*100,rolloffFactor:i.rolloffFactor/100,panSpread:i.panSpread/255});break}case t.SetSoundEffects:{let i=o;this.audioProcessor.setEffects(i.instanceId,i.lowpass,i.highpass,i.reverb);break}}}handleAudioAck(e){switch(e.type){case"sound-loaded":this.loadedSounds.set(e.soundId,{name:e.name,loadedAt:Date.now()}),this.soundLoadErrors.delete(e.soundId);break;case"sound-error":this.soundLoadErrors.set(e.soundId,{name:e.name,error:e.error,at:Date.now()});break;case"playback-started":this.playingSounds.set(e.instanceId,{soundId:e.soundId,startedAt:Date.now()});break;case"playback-ended":this.playingSounds.delete(e.instanceId);break;case"playback-error":e.instanceId!==void 0&&this.playingSounds.delete(e.instanceId);break}}isSoundLoaded(e){return this.loadedSounds.has(e)}getSoundLoadError(e){return this.soundLoadErrors.get(e)?.error}getLoadedSounds(){return this.loadedSounds}getSoundLoadErrors(){return this.soundLoadErrors}isSoundPlaying(e){return this.playingSounds.has(e)}getPlayingSounds(){return this.playingSounds}getPlayingSoundCount(){return this.playingSounds.size}loadMacro(e,t){let r={...t,id:e},n=this.macroRegistry.registerMacro(r);return this.mode==="client"&&this.macroEngine.loadTemplate(n,r),n}createInstance(e){return this.updateLayerMappings(),this.macroRegistry.createInstance(e)}updateInstance(e,t){return this.macroRegistry.updateInstance(e,t)}removeInstance(e){return this.macroEventHandlers.delete(e),this.macroRegistry.removeInstance(e)}onMacroEvent(e,t,r){this.macroEventHandlers.has(e)||this.macroEventHandlers.set(e,new Map),this.macroEventHandlers.get(e).set(t,r)}offMacroEvent(e,t){t?this.macroEventHandlers.get(e)?.delete(t):this.macroEventHandlers.delete(e)}handleMacroEvent(e){let t=this.macroRegistry.getInstanceName(e.instanceId);if(!t){console.warn(`MacroEvent: Unknown instance ID ${e.instanceId}`);return}let r=this.macroEventHandlers.get(t);if(!r)return;let n,o;switch(e.type){case 1:n="click",o=void 0;break;case 2:n="change",o=e.value;break;case 3:n="submit",o=e.text;break;case 4:n="select",o=e.index;break;default:return}let i=r.get(n);i&&i(o)}flushMacroOrders(){return this.macroRegistry.flushPendingOrders()}hasPendingMacroOrders(){return this.macroRegistry.hasPendingOrders()}applyMacroOrders(e){for(let t of e)this.macroEngine.applyOrder(t)}getMacroRegistry(){return this.macroRegistry}getMacroLoads(){return this.macroRegistry.toAllMacroLoads()}updateLayerMappings(){for(let e of this.layers){let t=e.getId()}}registerLayerName(e,t){this.macroRegistry.setLayerMapping(e,t.getId())}loadMacroTemplate(e,t){this.macroEngine.loadTemplate(e,t)}updateMacros(){return this.macroEngine.update()}updateMacroMouse(e,t,r){let n=this.displays.find(o=>o.getId()===this.mouseDisplayId);if(!n&&this.displays.length>0&&(n=this.displays[0]),n){let o=n.getOrigin(),i=e+o.x,s=t+o.y;this.macroEngine.updateMouse(i,s,r)}else this.macroEngine.updateMouse(e,t,r)}getMacroRenderOrders(){let e=this.macroEngine.getOrdersByLayer(),t=this.displays[0];if(!t)return e;let r=t.getOrigin();if(r.x===0&&r.y===0)return e;let n=new Map;for(let[o,i]of e){let s=i.map(a=>{let d={...a};return"posX"in d&&typeof d.posX=="number"&&(d.posX=d.posX-r.x),"posY"in d&&typeof d.posY=="number"&&(d.posY=d.posY-r.y),d});n.set(o,s)}return n}getMacroEffectOffset(){return this.macroEngine.getEffectOffset()}getMacroEngine(){return this.macroEngine}macroFocusNext(){this.macroEngine.focusNext()}macroFocusPrevious(){this.macroEngine.focusPrevious()}macroActivateFocused(){this.macroEngine.activateFocused()}setPostProcess(e){let t=JSON.stringify(e),r=JSON.stringify(this.currentPostProcessConfig);t!==r&&(this.currentPostProcessConfig=e,this.postProcessCommands.push({type:"set-config",config:e??void 0}))}setScanlinesEnabled(e){if(e){let t=this.currentPostProcessConfig?.scanlines;this.setPostProcess({scanlines:{enabled:!0,opacity:t?.opacity??R.POST_PROCESS_DEFAULTS.scanlines.opacity,pattern:t?.pattern??R.POST_PROCESS_DEFAULTS.scanlines.pattern,color:t?.color??R.POST_PROCESS_DEFAULTS.scanlines.color}})}else this.setPostProcess({scanlines:{enabled:!1}})}setScanlinesOpacity(e){let t=Math.max(0,Math.min(1,e)),r=this.currentPostProcessConfig?.scanlines;this.setPostProcess({scanlines:{enabled:!0,opacity:t,pattern:r?.pattern??"horizontal",color:r?.color??{r:0,g:0,b:0}}})}setScanlinesPattern(e){let t=this.currentPostProcessConfig?.scanlines;this.setPostProcess({scanlines:{enabled:t?.enabled??!0,opacity:t?.opacity??R.POST_PROCESS_DEFAULTS.scanlines.opacity,pattern:e,color:t?.color??{r:0,g:0,b:0}}})}setAmbientEffect(e){let t=this.currentPostProcessConfig?.ambientEffect;typeof e=="boolean"?this.setPostProcess({...this.currentPostProcessConfig,ambientEffect:{enabled:e,blur:t?.blur??R.POST_PROCESS_DEFAULTS.ambientEffect.blur,scale:t?.scale??R.POST_PROCESS_DEFAULTS.ambientEffect.scale}}):this.setPostProcess({...this.currentPostProcessConfig,ambientEffect:{enabled:!0,blur:e.blur??t?.blur??R.POST_PROCESS_DEFAULTS.ambientEffect.blur,scale:e.scale??t?.scale??R.POST_PROCESS_DEFAULTS.ambientEffect.scale}})}setAmbientEffectEnabled(e){this.setAmbientEffect(e)}setAmbientEffectBlur(e){let t=this.currentPostProcessConfig?.ambientEffect;this.setPostProcess({...this.currentPostProcessConfig,ambientEffect:{enabled:t?.enabled??!0,blur:Math.max(0,e),scale:t?.scale??R.POST_PROCESS_DEFAULTS.ambientEffect.scale}})}setAmbientEffectScale(e){let t=this.currentPostProcessConfig?.ambientEffect;this.setPostProcess({...this.currentPostProcessConfig,ambientEffect:{enabled:t?.enabled??!0,blur:t?.blur??R.POST_PROCESS_DEFAULTS.ambientEffect.blur,scale:Math.max(1,e)}})}isAmbientEffectEnabled(){return this.currentPostProcessConfig?.ambientEffect?.enabled??!1}getAmbientEffectConfig(){let e=this.currentPostProcessConfig?.ambientEffect;return e?{enabled:e.enabled,blur:e.blur??R.POST_PROCESS_DEFAULTS.ambientEffect.blur,scale:e.scale??R.POST_PROCESS_DEFAULTS.ambientEffect.scale}:null}getPostProcessConfig(){return this.currentPostProcessConfig}hasPostProcessCommands(){return this.postProcessCommands.length>0}flushPostProcessCommands(){let e=this.postProcessCommands;return this.postProcessCommands=[],e}setScalingMode(e){this.currentScalingMode!==e&&(this.currentScalingMode=e,this.postProcessCommands.push({type:"set-scaling-mode",scalingMode:e}))}getScalingMode(){return this.currentScalingMode}setGrid(e){let t;typeof e=="boolean"?t={enabled:e,color:R.GRID_DEFAULTS.color,lineWidth:R.GRID_DEFAULTS.lineWidth}:t={enabled:e.enabled,color:e.color??R.GRID_DEFAULTS.color,lineWidth:e.lineWidth??R.GRID_DEFAULTS.lineWidth},this.currentGridConfig=t,this.postProcessCommands.push({type:"set-grid",gridConfig:t})}setGridEnabled(e){this.setGrid(e)}isGridEnabled(){return this.currentGridConfig?.enabled??!1}getGridConfig(){return this.currentGridConfig}};g(vt,"User");var re=vt;F();var Mt=class Mt{encode(e){switch(e.type){case 1:return this.encodeCharOrder(e);case 2:return this.encodeTextOrder(e);case 23:return this.encodeTextMultilineOrder(e);case 3:return this.encodeSubFrameOrder(e);case 4:return this.encodeSubFrameMultiColorOrder(e);case 5:return this.encodeFullFrameOrder(e);case 6:return this.encodeFullFrameMultiColorOrder(e);case 7:return this.encodeSpriteOrder(e);case 8:return this.encodeSpriteMultiColorOrder(e);case 9:return this.encodeColorMapOrder(e);case 10:return this.encodeShapeOrder(e);case 11:return this.encodeDotCloudOrder(e);case 12:return this.encodeDotCloudMultiColorOrder(e);case 17:return this.encodeBitmaskOrder(e);case 18:return this.encodeBitmask4Order(e);case 24:return this.encodeBitmask16Order(e);case 25:return this.encodePolylineOrder(e);case 13:return this.encodeSpriteCloudOrder(e);case 14:return this.encodeSpriteCloudMultiColorOrder(e);case 15:return this.encodeSpriteCloudVariedOrder(e);case 16:return this.encodeSpriteCloudVariedMultiColorOrder(e);case 19:return this.encodeClearOrder(e);case 20:return this.encodeFillCharOrder(e);case 21:return this.encodeFillSpriteOrder(e);case 22:return this.encodeFillSpriteMultiColorOrder(e);case 32:return this.encodeTriggerSoundOrder(e);case 33:return this.encodeTriggerGlobalSoundOrder(e);default:throw new Error(`Unknown order type: ${e.type}`)}}encodeCharOrder(e){let t=C.allocUnsafe(6),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.posX,r++),t.writeUInt8(e.posY,r++),t.writeUInt8(e.charCode,r++),t.writeUInt8(e.bgColorCode,r++),t.writeUInt8(e.fgColorCode,r++),t.toUint8Array()}encodeTextOrder(e){let t=new TextEncoder().encode(e.text),r=C.allocUnsafe(6+t.length),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(t.length,n++);for(let o=0;o<t.length;o++)r.writeUInt8(t[o],n++);return r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.toUint8Array()}encodeTextMultilineOrder(e){let t=new TextEncoder().encode(e.text),r=C.allocUnsafe(6+t.length),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(t.length,n++);for(let o=0;o<t.length;o++)r.writeUInt8(t[o],n++);return r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.toUint8Array()}encodeSubFrameOrder(e){let t=e.sizeX*e.sizeY,r=C.allocUnsafe(7+t),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(e.sizeX,n++),r.writeUInt8(e.sizeY,n++),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++);for(let o of e.frame)r.writeUInt8(o,n++);return r.toUint8Array()}encodeSubFrameMultiColorOrder(e){let t=e.sizeX*e.sizeY,r=C.allocUnsafe(5+t*3),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(e.sizeX,n++),r.writeUInt8(e.sizeY,n++);for(let o of e.frame)r.writeUInt8(o.charCode,n++),r.writeUInt8(o.bgColorCode,n++),r.writeUInt8(o.fgColorCode,n++);return r.toUint8Array()}encodeFullFrameOrder(e){let t=e.frame.length,r=C.allocUnsafe(3+t),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++);for(let o of e.frame)r.writeUInt8(o,n++);return r.toUint8Array()}encodeFullFrameMultiColorOrder(e){let t=e.frame.length,r=C.allocUnsafe(1+t*3),n=0;r.writeUInt8(e.type,n++);for(let o of e.frame)r.writeUInt8(o.charCode,n++),r.writeUInt8(o.bgColorCode,n++),r.writeUInt8(o.fgColorCode,n++);return r.toUint8Array()}encodeSpriteOrder(e){let t=C.allocUnsafe(6),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.posX,r++),t.writeUInt8(e.posY,r++),t.writeUInt8(e.spriteIndex,r++),t.writeUInt8(e.bgColorCode,r++),t.writeUInt8(e.fgColorCode,r++),t.toUint8Array()}encodeSpriteMultiColorOrder(e){let t=C.allocUnsafe(4),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.posX,r++),t.writeUInt8(e.posY,r++),t.writeUInt8(e.spriteIndex,r++),t.toUint8Array()}encodeColorMapOrder(e){let t=e.sizeX*e.sizeY,r=C.allocUnsafe(5+t*2),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(e.sizeX,n++),r.writeUInt8(e.sizeY,n++);for(let o of e.colorData)r.writeUInt8(o.bgColorCode,n++),r.writeUInt8(o.fgColorCode,n++);return r.toUint8Array()}encodeShapeOrder(e){let t=this.encodeShapeData(e.shapeType,e.shapeData),r=C.allocUnsafe(2+t.length),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.shapeType,n++);for(let o=0;o<t.length;o++)r.writeUInt8(t[o],n++);return r.toUint8Array()}encodeShapeData(e,t){switch(e){case 1:{let r=C.allocUnsafe(8),n=0;return r.writeUInt8(t.posX,n++),r.writeUInt8(t.posY,n++),r.writeUInt8(t.width,n++),r.writeUInt8(t.height,n++),r.writeUInt8(t.filled?1:0,n++),r.writeUInt8(t.charCode,n++),r.writeUInt8(t.bgColorCode,n++),r.writeUInt8(t.fgColorCode,n++),r.toUint8Array()}case 2:{let r=C.allocUnsafe(7),n=0;return r.writeUInt8(t.centerX,n++),r.writeUInt8(t.centerY,n++),r.writeUInt8(t.radius,n++),r.writeUInt8(t.filled?1:0,n++),r.writeUInt8(t.charCode,n++),r.writeUInt8(t.bgColorCode,n++),r.writeUInt8(t.fgColorCode,n++),r.toUint8Array()}case 3:{let r=C.allocUnsafe(7),n=0;return r.writeUInt8(t.x1,n++),r.writeUInt8(t.y1,n++),r.writeUInt8(t.x2,n++),r.writeUInt8(t.y2,n++),r.writeUInt8(t.charCode,n++),r.writeUInt8(t.bgColorCode,n++),r.writeUInt8(t.fgColorCode,n++),r.toUint8Array()}case 4:{let r=C.allocUnsafe(8),n=0;return r.writeUInt8(t.centerX,n++),r.writeUInt8(t.centerY,n++),r.writeUInt8(t.radiusX,n++),r.writeUInt8(t.radiusY,n++),r.writeUInt8(t.filled?1:0,n++),r.writeUInt8(t.charCode,n++),r.writeUInt8(t.bgColorCode,n++),r.writeUInt8(t.fgColorCode,n++),r.toUint8Array()}case 5:{let r=C.allocUnsafe(10),n=0;return r.writeUInt8(t.x1,n++),r.writeUInt8(t.y1,n++),r.writeUInt8(t.x2,n++),r.writeUInt8(t.y2,n++),r.writeUInt8(t.x3,n++),r.writeUInt8(t.y3,n++),r.writeUInt8(t.filled?1:0,n++),r.writeUInt8(t.charCode,n++),r.writeUInt8(t.bgColorCode,n++),r.writeUInt8(t.fgColorCode,n++),r.toUint8Array()}default:throw new Error(`Unknown shape type: ${e}`)}}encodeDotCloudOrder(e){let t=e.positions.length,r=C.allocUnsafe(6+t*2),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.charCode,n++),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.positions)r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeDotCloudMultiColorOrder(e){let t=e.dots.length,r=C.allocUnsafe(5+t*5),n=0;r.writeUInt8(e.type,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.dots)r.writeUInt8(o.charCode,n++),r.writeUInt8(o.bgColorCode,n++),r.writeUInt8(o.fgColorCode,n++),r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeBitmaskOrder(e){let t=e.mask.length,r=C.allocUnsafe(9+t),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(e.sizeX,n++),r.writeUInt8(e.sizeY,n++),r.writeUInt8(e.charCode,n++),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.writeUInt8(e.override?1:0,n++);for(let o=0;o<t;o++)r.writeUInt8(e.mask[o],n++);return r.toUint8Array()}encodeBitmask4Order(e){let t=e.mask.length,r=C.allocUnsafe(15+t),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(e.sizeX,n++),r.writeUInt8(e.sizeY,n++),r.writeUInt8(e.override?1:0,n++);for(let o of e.variants)r.writeUInt8(o.charCode,n++),r.writeUInt8(o.bgColorCode,n++),r.writeUInt8(o.fgColorCode,n++);for(let o=0;o<t;o++)r.writeUInt8(e.mask[o],n++);return r.toUint8Array()}encodeBitmask16Order(e){let t=e.mask.length,r=C.allocUnsafe(51+t),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(e.sizeX,n++),r.writeUInt8(e.sizeY,n++),r.writeUInt8(e.override?1:0,n++);for(let o of e.variants)r.writeUInt8(o.charCode,n++),r.writeUInt8(o.bgColorCode,n++),r.writeUInt8(o.fgColorCode,n++);for(let o=0;o<t;o++)r.writeUInt8(e.mask[o],n++);return r.toUint8Array()}encodePolylineOrder(e){let t=e.points.length,r=C.allocUnsafe(5+t*2),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.charCode,n++),r.writeUInt8(e.fgColorCode,n++),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(t,n++);for(let o of e.points)r.writeUInt8(o.x,n++),r.writeUInt8(o.y,n++);return r.toUint8Array()}encodeSpriteCloudOrder(e){let t=e.positions.length,r=C.allocUnsafe(8+t*2),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.spriteIndex,n++),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.positions)r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeSpriteCloudMultiColorOrder(e){let t=e.positions.length,r=C.allocUnsafe(6+t*2),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.spriteIndex,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.positions)r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeSpriteCloudVariedOrder(e){let t=e.sprites.length,r=C.allocUnsafe(3+t*5),n=0;r.writeUInt8(e.type,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.sprites)r.writeUInt8(o.spriteIndex,n++),r.writeUInt8(o.bgColorCode,n++),r.writeUInt8(o.fgColorCode,n++),r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeSpriteCloudVariedMultiColorOrder(e){let t=e.sprites.length,r=C.allocUnsafe(3+t*3),n=0;r.writeUInt8(e.type,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.sprites)r.writeUInt8(o.spriteIndex,n++),r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeClearOrder(e){let t=C.allocUnsafe(4),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.charCode,r++),t.writeUInt8(e.bgColorCode,r++),t.writeUInt8(e.fgColorCode,r++),t.toUint8Array()}encodeFillCharOrder(e){let t=e.patternWidth*e.patternHeight,r=C.allocUnsafe(5+t),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.patternWidth,n++),r.writeUInt8(e.patternHeight,n++),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++);for(let o of e.pattern)r.writeUInt8(o,n++);return r.toUint8Array()}encodeFillSpriteOrder(e){let t=C.allocUnsafe(4),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.spriteIndex,r++),t.writeUInt8(e.bgColorCode,r++),t.writeUInt8(e.fgColorCode,r++),t.toUint8Array()}encodeFillSpriteMultiColorOrder(e){let t=C.allocUnsafe(2),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.spriteIndex,r++),t.toUint8Array()}encodeTriggerSoundOrder(e){let t=C.allocUnsafe(5),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.posX,r++),t.writeUInt8(e.posY,r++),t.writeUInt8(e.soundId,r++),t.writeUInt8(e.loop?1:0,r++),t.toUint8Array()}encodeTriggerGlobalSoundOrder(e){let t=C.allocUnsafe(3),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.soundId,r++),t.writeUInt8(e.loop?1:0,r++),t.toUint8Array()}};g(Mt,"OrderEncoder");var Ye=Mt;F();var At=class At{constructor(){b(this,"orderEncoder");this.orderEncoder=new Ye}encode(e){let t=e.orders.map(a=>this.orderEncoder.encode(a)),r=13,n=t.reduce((a,d)=>a+d.length,0),o=r+n,i=C.allocUnsafe(o),s=0;i.writeUInt16BE(e.id,s),s+=2,i.writeUInt8(e.updateFlags,s++),i.writeUInt8(e.zIndex,s++),i.writeUInt16BE(e.originX,s),s+=2,i.writeUInt16BE(e.originY,s),s+=2,i.writeUInt16BE(e.width,s),s+=2,i.writeUInt16BE(e.height,s),s+=2,i.writeUInt8(e.orders.length,s++);for(let a of t)C.from(a).copy(i,s),s+=a.length;return i.toUint8Array()}calculateSize(e){return 13+e.orders.reduce((n,o)=>n+this.orderEncoder.encode(o).length,0)}};g(At,"LayerEncoder");var Xe=At;F();var Et=class Et{encode(e){switch(e.type){case 1:return this.encodePlaySoundOrder(e);case 2:return this.encodePlayGlobalSoundOrder(e);case 3:return this.encodeStopSoundOrder(e);case 4:return this.encodeFadeOutSoundOrder(e);case 5:return this.encodePauseSoundOrder(e);case 6:return this.encodeResumeSoundOrder(e);case 7:return this.encodeSetListenerPositionOrder(e);case 8:return this.encodeConfigureSpatialOrder(e);case 9:return this.encodeSetSoundEffectsOrder(e);default:throw new Error(`Unknown audio order type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return this.calculatePlaySoundSize(e);case 2:return this.calculatePlayGlobalSoundSize(e);case 3:case 5:case 6:return this.calculateTargetOrderSize(e);case 4:return this.calculateFadeOutSize(e);case 7:return 5;case 8:return 5;case 9:return this.calculateSetSoundEffectsSize(e);default:throw new Error(`Unknown audio order type: ${e.type}`)}}encodePlaySoundOrder(e){let t=this.calculatePlaySoundSize(e),r=C.allocUnsafe(t),n=0;return r.writeUInt8(e.type,n++),r.writeUInt8(e.soundId,n++),r.writeUInt16BE(e.instanceId,n),n+=2,r.writeUInt8(e.flags,n++),e.flags&2&&r.writeUInt8(e.volume??255,n++),e.flags&4&&r.writeUInt8(e.pitch??128,n++),e.flags&8&&r.writeUInt8(e.fadeIn??0,n++),e.flags&16&&(r.writeUInt16BE(e.posX??0,n),n+=2,r.writeUInt16BE(e.posY??0,n),n+=2),e.flags&32&&r.writeUInt8(e.lowpass??0,n++),e.flags&64&&r.writeUInt8(e.highpass??0,n++),e.flags&128&&r.writeUInt8(e.reverb??0,n++),r.toUint8Array()}encodePlayGlobalSoundOrder(e){let t=this.calculatePlayGlobalSoundSize(e),r=C.allocUnsafe(t),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.soundId,n++),r.writeUInt16BE(e.instanceId,n),n+=2;let o=e.flags&-17;return r.writeUInt8(o,n++),o&2&&r.writeUInt8(e.volume??255,n++),o&4&&r.writeUInt8(e.pitch??128,n++),o&8&&r.writeUInt8(e.fadeIn??0,n++),o&32&&r.writeUInt8(e.lowpass??0,n++),o&64&&r.writeUInt8(e.highpass??0,n++),o&128&&r.writeUInt8(e.reverb??0,n++),r.toUint8Array()}calculatePlaySoundSize(e){let t=5;return e.flags&2&&(t+=1),e.flags&4&&(t+=1),e.flags&8&&(t+=1),e.flags&16&&(t+=4),e.flags&32&&(t+=1),e.flags&64&&(t+=1),e.flags&128&&(t+=1),t}calculatePlayGlobalSoundSize(e){let t=5,r=e.flags&-17;return r&2&&(t+=1),r&4&&(t+=1),r&8&&(t+=1),r&32&&(t+=1),r&64&&(t+=1),r&128&&(t+=1),t}encodeStopSoundOrder(e){return this.encodeTargetOrder(e.type,e.targetType,e.target)}encodePauseSoundOrder(e){return this.encodeTargetOrder(e.type,e.targetType,e.target)}encodeResumeSoundOrder(e){return this.encodeTargetOrder(e.type,e.targetType,e.target)}encodeFadeOutSoundOrder(e){let t=this.calculateFadeOutSize(e),r=C.allocUnsafe(t),n=0;return r.writeUInt8(e.type,n++),r.writeUInt8(e.targetType,n++),r.writeUInt8(e.duration,n++),e.targetType===0?r.writeUInt16BE(e.target??0,n):e.targetType===1&&r.writeUInt8(e.target??0,n),r.toUint8Array()}encodeTargetOrder(e,t,r){let n=2;t===0?n+=2:t===1&&(n+=1);let o=C.allocUnsafe(n),i=0;return o.writeUInt8(e,i++),o.writeUInt8(t,i++),t===0?o.writeUInt16BE(r??0,i):t===1&&o.writeUInt8(r??0,i),o.toUint8Array()}calculateTargetOrderSize(e){let t=2;return e.targetType===0?t+=2:e.targetType===1&&(t+=1),t}calculateFadeOutSize(e){let t=3;return e.targetType===0?t+=2:e.targetType===1&&(t+=1),t}encodeSetListenerPositionOrder(e){let t=C.allocUnsafe(5),r=0;return t.writeUInt8(e.type,r++),t.writeUInt16BE(e.x,r),r+=2,t.writeUInt16BE(e.y,r),t.toUint8Array()}encodeConfigureSpatialOrder(e){let t=C.allocUnsafe(5),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.maxDistance,r++),t.writeUInt8(e.referenceDistance,r++),t.writeUInt8(e.rolloffFactor,r++),t.writeUInt8(e.panSpread,r++),t.toUint8Array()}encodeSetSoundEffectsOrder(e){let t=this.calculateSetSoundEffectsSize(e),r=C.allocUnsafe(t),n=0;return r.writeUInt8(e.type,n++),r.writeUInt16BE(e.instanceId,n),n+=2,r.writeUInt8(e.flags,n++),e.flags&1&&r.writeUInt8(e.lowpass??0,n++),e.flags&2&&r.writeUInt8(e.highpass??0,n++),e.flags&4&&r.writeUInt8(e.reverb??0,n++),r.toUint8Array()}calculateSetSoundEffectsSize(e){let t=4;return e.flags&1&&(t+=1),e.flags&2&&(t+=1),e.flags&4&&(t+=1),t}};g(Et,"AudioOrderEncoder");var Ne=Et;F();var Rt=class Rt{encode(e){switch(e.type){case 1:return this.encodeCreateInstance(e);case 2:return this.encodeUpdateInstance(e);case 3:return this.encodeRemoveInstance(e);default:throw new Error(`Unknown macro order type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return this.calculateCreateInstanceSize(e);case 2:return this.calculateUpdateInstanceSize(e);case 3:return 2;default:throw new Error(`Unknown macro order type: ${e.type}`)}}encodeCreateInstance(e){let t=JSON.stringify(e.params),r=new TextEncoder().encode(t);if(r.length>65535)throw new Error(`Params JSON too large: ${r.length} bytes (max 65535)`);let n=11+r.length,o=C.allocUnsafe(n),i=0;return o.writeUInt8(e.type,i++),o.writeUInt8(e.instanceId,i++),o.writeUInt8(e.macroId,i++),o.writeUInt8(e.layerId,i++),o.writeInt16BE(e.x,i),i+=2,o.writeInt16BE(e.y,i),i+=2,o.writeUInt8(e.tabIndex,i++),o.writeUInt16BE(r.length,i),i+=2,o.toUint8Array().set(r,i),o.toUint8Array()}calculateCreateInstanceSize(e){let t=JSON.stringify(e.params);return 11+new TextEncoder().encode(t).length}encodeUpdateInstance(e){let t=JSON.stringify(e.params),r=new TextEncoder().encode(t);if(r.length>65535)throw new Error(`Params JSON too large: ${r.length} bytes (max 65535)`);let n=4+r.length,o=C.allocUnsafe(n),i=0;return o.writeUInt8(e.type,i++),o.writeUInt8(e.instanceId,i++),o.writeUInt16BE(r.length,i),i+=2,o.toUint8Array().set(r,i),o.toUint8Array()}calculateUpdateInstanceSize(e){let t=JSON.stringify(e.params);return 4+new TextEncoder().encode(t).length}encodeRemoveInstance(e){let t=C.allocUnsafe(2);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.toUint8Array()}};g(Rt,"MacroOrderEncoder");var _e=Rt;F();var Bt=class Bt{encode(e){switch(e.type){case 1:return this.encodeSetConfigOrder(e);case 2:return this.encodeSetScanlinesOrder(e);case 3:return this.encodeSetAmbientEffectOrder(e);case 4:return this.encodeSetScalingModeOrder(e);case 5:return this.encodeSetGridOrder(e);default:throw new Error(`Unknown post-process order type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return this.calculateSetConfigSize(e);case 2:return 7;case 3:return 5;case 4:return 2;case 5:return 7;default:throw new Error(`Unknown post-process order type: ${e.type}`)}}encodeSetConfigOrder(e){let t=this.calculateSetConfigSize(e),r=C.allocUnsafe(t),n=0;return r.writeUInt8(e.type,n++),r.writeUInt8(e.flags,n++),e.flags&1&&e.scanlines&&(r.writeUInt8(e.scanlines.enabled?1:0,n++),r.writeUInt8(Math.round(e.scanlines.opacity*255),n++),r.writeUInt8(e.scanlines.pattern,n++),r.writeUInt8(e.scanlines.colorR,n++),r.writeUInt8(e.scanlines.colorG,n++),r.writeUInt8(e.scanlines.colorB,n++)),e.flags&2&&e.ambientEffect&&(r.writeUInt8(e.ambientEffect.enabled?1:0,n++),r.writeUInt8(Math.min(255,Math.round(e.ambientEffect.blur)),n++),r.writeUInt8(Math.min(255,Math.max(100,Math.round(e.ambientEffect.scale*100))),n++),r.writeUInt8(Math.round(e.ambientEffect.opacity*255),n++)),r.toUint8Array()}calculateSetConfigSize(e){let t=2;return e.flags&1&&(t+=6),e.flags&2&&(t+=4),t}encodeSetScanlinesOrder(e){let t=C.allocUnsafe(7),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.enabled?1:0,r++),t.writeUInt8(Math.round(e.opacity*255),r++),t.writeUInt8(e.pattern,r++),t.writeUInt8(e.colorR,r++),t.writeUInt8(e.colorG,r++),t.writeUInt8(e.colorB,r++),t.toUint8Array()}encodeSetAmbientEffectOrder(e){let t=C.allocUnsafe(5),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.enabled?1:0,r++),t.writeUInt8(Math.min(255,Math.round(e.blur)),r++),t.writeUInt8(Math.min(255,Math.max(100,Math.round(e.scale*100))),r++),t.writeUInt8(Math.round(e.opacity*255),r++),t.toUint8Array()}encodeSetScalingModeOrder(e){let t=C.allocUnsafe(2),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.mode,r++),t.toUint8Array()}encodeSetGridOrder(e){let t=C.allocUnsafe(7),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.enabled?1:0,r++),t.writeUInt8(e.colorR,r++),t.writeUInt8(e.colorG,r++),t.writeUInt8(e.colorB,r++),t.writeUInt8(e.colorA,r++),t.writeUInt8(Math.min(10,Math.max(1,e.lineWidth)),r++),t.toUint8Array()}};g(Bt,"PostProcessOrderEncoder");var He=Bt;F();var Tt=class Tt{constructor(){b(this,"layerEncoder");b(this,"audioOrderEncoder");b(this,"macroOrderEncoder");b(this,"postProcessOrderEncoder");this.layerEncoder=new Xe,this.audioOrderEncoder=new Ne,this.macroOrderEncoder=new _e,this.postProcessOrderEncoder=new He}encode(e){let t=e.layers.map(f=>this.layerEncoder.encode(f)),r=e.audioOrders||[],n=r.map(f=>this.audioOrderEncoder.encode(f)),o=e.macroOrders||[],i=o.map(f=>this.macroOrderEncoder.encode(f)),s=e.postProcessOrders||[],a=s.map(f=>this.postProcessOrderEncoder.encode(f)),d=9,c=e.displays.length*7,l=2,u=t.reduce((f,k)=>f+k.length,0),p=1,h=n.reduce((f,k)=>f+k.length,0),y=1,x=i.reduce((f,k)=>f+k.length,0),v=1,U=a.reduce((f,k)=>f+k.length,0),S=d+c+l+u+p+h+y+x+v+U,w=C.allocUnsafe(S),I=0,M=typeof e.tick=="bigint"?e.tick:BigInt(e.tick);w.writeBigUInt64BE(M,I),I+=8,w.writeUInt8(e.displays.length,I),I+=1;for(let f of e.displays)w.writeUInt8(f.id,I++),w.writeUInt16BE(f.originX,I),I+=2,w.writeUInt16BE(f.originY,I),I+=2,w.writeUInt8(Math.max(1,Math.min(256,f.sizeX))-1,I++),w.writeUInt8(Math.max(1,Math.min(256,f.sizeY))-1,I++);w.writeUInt16BE(e.layers.length,I),I+=2;for(let f of t)C.from(f).copy(w,I),I+=f.length;w.writeUInt8(r.length,I),I+=1;for(let f of n)C.from(f).copy(w,I),I+=f.length;w.writeUInt8(o.length,I),I+=1;for(let f of i)C.from(f).copy(w,I),I+=f.length;w.writeUInt8(s.length,I),I+=1;for(let f of a)C.from(f).copy(w,I),I+=f.length;return w.toUint8Array()}calculateSize(e){let r=e.displays.length*7,n=2,o=e.layers.reduce((y,x)=>y+this.layerEncoder.calculateSize(x),0),i=1,a=(e.audioOrders||[]).reduce((y,x)=>y+this.audioOrderEncoder.calculateSize(x),0),d=1,l=(e.macroOrders||[]).reduce((y,x)=>y+this.macroOrderEncoder.calculateSize(x),0),u=1,h=(e.postProcessOrders||[]).reduce((y,x)=>y+this.postProcessOrderEncoder.calculateSize(x),0);return 9+r+n+o+i+a+d+l+u+h}static createEmptyPacket(e){return{tick:typeof e=="bigint"?Number(e):e,displayCount:0,displays:[],layerCount:0,layers:[],audioOrderCount:0,audioOrders:[],macroOrderCount:0,macroOrders:[],postProcessOrderCount:0,postProcessOrders:[]}}encodeEmpty(e){let t=C.allocUnsafe(14),r=typeof e=="bigint"?e:BigInt(e);return t.writeBigUInt64BE(r,0),t.writeUInt8(0,8),t.writeUInt16BE(0,9),t.writeUInt8(0,11),t.writeUInt8(0,12),t.writeUInt8(0,13),t.toUint8Array()}};g(Tt,"UpdatePacketEncoder");var We=Tt;F();var zt=class zt{encode(e){let t=JSON.stringify(e.template),r=new TextEncoder().encode(t);if(r.length>65535)throw new Error(`Macro template JSON too large: ${r.length} bytes (max 65535)`);let n=4+r.length,o=C.allocUnsafe(n),i=0;return o.writeUInt8(7,i++),o.writeUInt8(e.macroId,i++),o.writeUInt16BE(r.length,i),i+=2,o.toUint8Array().set(r,i),o.toUint8Array()}calculateSize(e){let t=JSON.stringify(e.template);return 4+new TextEncoder().encode(t).length}};g(zt,"MacroLoadEncoder");var $e=zt;var ne=class ne{constructor(e){this.engine=e;b(this,"colorCache",new Array(256));b(this,"cellsBuffer",[]);b(this,"opacityBuffer",new Uint8Array(0));b(this,"visibleLayersBuffer",[]);this.rebuildColorCache()}rebuildColorCache(){for(let e=0;e<256;e++){let t=this.engine.getColor(e);t?this.colorCache[e]={r:t.r,g:t.g,b:t.b,a:t.a}:this.colorCache[e]={r:0,g:0,b:0,a:0}}}getColorRGB(e){return this.colorCache[e]??this.colorCache[255]}getColorEmission(e){let t=this.engine.getColor(e);return t?t.e:0}isLayerVisible(e,t){let r=e.x,n=e.x+e.width,o=e.y,i=e.y+e.height,s=t.x,a=t.x+256,d=t.y,c=t.y+256;return!(n<=s||r>=a||i<=d||o>=c)}rasterize(e,t){let r=e.width*e.height,n=this.cellsBuffer;n.length=r;for(let s=0;s<r;s++)n[s]?(n[s].char=" ",n[s].fgColorIndex=255,n[s].bgColorIndex=255,n[s].fgEmission=0,n[s].bgEmission=0):n[s]={char:" ",fgColorIndex:255,bgColorIndex:255,fgEmission:0,bgEmission:0};this.opacityBuffer.length<r?this.opacityBuffer=new Uint8Array(r):this.opacityBuffer.fill(0,0,r);let o=this.opacityBuffer,i=this.visibleLayersBuffer;i.length=0;for(let s=0;s<t.length;s++){let a=t[s];a.isEnabled()&&this.isLayerVisible(e,a.getOrigin())&&i.push(a)}i.sort((s,a)=>a.getZOrder()-s.getZOrder());for(let s=0;s<e.height;s++)for(let a=0;a<e.width;a++){let d=s*e.width+a;if(o[d])continue;let c=e.x+a,l=e.y+s;for(let u=0;u<i.length;u++){let p=i[u],h=c-p.getOrigin().x,y=l-p.getOrigin().y,x=p.getWidth(),v=p.getHeight();if(h<0||h>=x||y<0||y>=v)continue;let U=y*x+h,S=p.getData(),w=S.getCharCode(U),I=S.getFgColorCode(U),M=S.getBgColorCode(U),f=n[d];if(w!==0&&w<256&&f.char===" "&&(f.char=ne.charCache[w]),I!==255&&f.fgColorIndex===255&&(f.fgColorIndex=I,f.fgEmission=this.getColorEmission(I)),M!==255){f.bgColorIndex===255&&(f.bgColorIndex=M,f.bgEmission=this.getColorEmission(M)),o[d]=1;break}}}return{width:e.width,height:e.height,cells:n,palette:this.colorCache}}rasterizeWithSortedLayers(e,t){let r=e.width*e.height,n=this.cellsBuffer;n.length=r;for(let s=0;s<r;s++)n[s]?(n[s].char=" ",n[s].fgColorIndex=255,n[s].bgColorIndex=255,n[s].fgEmission=0,n[s].bgEmission=0):n[s]={char:" ",fgColorIndex:255,bgColorIndex:255,fgEmission:0,bgEmission:0};this.opacityBuffer.length<r?this.opacityBuffer=new Uint8Array(r):this.opacityBuffer.fill(0,0,r);let o=this.opacityBuffer,i=this.visibleLayersBuffer;i.length=0;for(let s=0;s<t.length;s++){let a=t[s];this.isLayerVisible(e,a.getOrigin())&&i.push(a)}for(let s=0;s<e.height;s++)for(let a=0;a<e.width;a++){let d=s*e.width+a;if(o[d])continue;let c=e.x+a,l=e.y+s;for(let u=0;u<i.length;u++){let p=i[u],h=c-p.getOrigin().x,y=l-p.getOrigin().y,x=p.getWidth(),v=p.getHeight();if(h<0||h>=x||y<0||y>=v)continue;let U=y*x+h,S=p.getData(),w=S.getCharCode(U),I=S.getFgColorCode(U),M=S.getBgColorCode(U),f=n[d];if(w!==0&&w<256&&f.char===" "&&(f.char=ne.charCache[w]),I!==255&&f.fgColorIndex===255&&(f.fgColorIndex=I,f.fgEmission=this.getColorEmission(I)),M!==255){f.bgColorIndex===255&&(f.bgColorIndex=M,f.bgEmission=this.getColorEmission(M)),o[d]=1;break}}}return{width:e.width,height:e.height,cells:n,palette:this.colorCache}}calculateIntersection(e,t){let r=e.x,n=e.x+e.width,o=e.y,i=e.y+e.height,s=t.x,a=t.x+256,d=t.y,c=t.y+256,l=Math.max(r,s),u=Math.min(n,a),p=Math.max(o,d),h=Math.min(i,c);return{visible:l<u&&p<h,originStart:{x:l-e.x,y:p-e.y},originEnd:{x:u-e.x,y:h-e.y},layerStart:{x:l-t.x,y:p-t.y},layerEnd:{x:u-t.x,y:h-t.y}}}};g(ne,"DisplayRasterizer"),b(ne,"charCache",(()=>{let e=new Array(256);for(let t=0;t<256;t++)e[t]=String.fromCharCode(t);return e})());var Ge=ne;var Ft=class Ft{constructor(){b(this,"enabled",!1);b(this,"currentStats",null)}setEnabled(e){this.enabled=e,e||(this.currentStats=null)}isEnabled(){return this.enabled}get tick(){return this.currentStats?.tick??0}get timestamp(){return this.currentStats?.timestamp??0}get totalOrders(){return this.currentStats?.totalOrders??0}get ordersByLayer(){return this.currentStats?.ordersByLayer??new Map}get ordersByType(){return this.currentStats?.ordersByType??new Map}get totalLayers(){return this.currentStats?.totalLayers??0}get visibleLayers(){return this.currentStats?.visibleLayers??0}get layersPerDisplay(){return this.currentStats?.layersPerDisplay??new Map}get updatePacketSize(){return this.currentStats?.updatePacketSize??0}get displayHeaderSize(){return this.currentStats?.displayHeaderSize??0}get layerHeaderSize(){return this.currentStats?.layerHeaderSize??0}get orderDataSize(){return this.currentStats?.orderDataSize??0}get compressionRatio(){return this.currentStats?.compressionRatio??0}get compressedPacketSize(){return Math.round(this.updatePacketSize*this.compressionRatio)}get totalCells(){return this.currentStats?.totalCells??0}get nonEmptyCells(){return this.currentStats?.nonEmptyCells??0}get cellsWithBackground(){return this.currentStats?.cellsWithBackground??0}get rasterizationTimeMs(){return this.currentStats?.rasterizationTimeMs??0}get encodingTimeMs(){return this.currentStats?.encodingTimeMs??0}get packetSplit(){return this.currentStats?.packetSplit}get layerDetails(){return this.currentStats?.layerDetails}startTick(e){this.enabled&&(this.currentStats={tick:e,timestamp:Date.now(),totalOrders:0,ordersByLayer:new Map,ordersByType:new Map,totalLayers:0,visibleLayers:0,layersPerDisplay:new Map,updatePacketSize:0,displayHeaderSize:0,layerHeaderSize:0,orderDataSize:0,compressionRatio:0,totalCells:0,nonEmptyCells:0,cellsWithBackground:0,rasterizationTimeMs:0,encodingTimeMs:0})}recordLayerOrders(e,t){if(!(!this.enabled||!this.currentStats)){this.currentStats.totalOrders+=t.length,this.currentStats.ordersByLayer.set(e,t.length);for(let r of t){let n=this.currentStats.ordersByType.get(r.type)||0;this.currentStats.ordersByType.set(r.type,n+1)}}}recordLayers(e,t){!this.enabled||!this.currentStats||(this.currentStats.totalLayers=e,this.currentStats.visibleLayers=t)}recordDisplayLayers(e,t){!this.enabled||!this.currentStats||this.currentStats.layersPerDisplay.set(e,t)}recordUpdatePacketSize(e,t,r,n){!this.enabled||!this.currentStats||(this.currentStats.updatePacketSize=e,this.currentStats.displayHeaderSize=t,this.currentStats.layerHeaderSize=r,this.currentStats.orderDataSize=n,this.currentStats.compressionRatio=.25)}recordPacketSplit(e,t,r,n){!this.enabled||!this.currentStats||(this.currentStats.packetSplit={userId:e,displayCount:t,staticLayerCount:r,dynamicLayerCount:n})}recordLayerInfo(e,t,r,n){!this.enabled||!this.currentStats||(this.currentStats.layerDetails||(this.currentStats.layerDetails=[]),this.currentStats.layerDetails.push({layerId:e,isStatic:t,orderCount:r,updateFlags:n}))}recordRenderStats(e,t,r){!this.enabled||!this.currentStats||(this.currentStats.totalCells=e,this.currentStats.nonEmptyCells=t,this.currentStats.cellsWithBackground=r)}recordRasterizationTime(e){!this.enabled||!this.currentStats||(this.currentStats.rasterizationTimeMs=e)}recordEncodingTime(e){!this.enabled||!this.currentStats||(this.currentStats.encodingTimeMs=e)}endTick(){}reset(){this.currentStats=null}};g(Ft,"CoreStats");var oe=Ft;var Lt=class Lt{constructor(){b(this,"unicolorSprites",new Map);b(this,"multicolorSprites",new Map)}loadUnicolorSprites(e){for(let t of e.sprites){let r=new j(t.sizeX*t.sizeY);for(let o=0;o<t.data.length;o++)r.set(o,t.data[o]);let n={id:t.spriteId,sizeX:t.sizeX,sizeY:t.sizeY,data:r};this.unicolorSprites.set(n.id,n)}}loadMulticolorSprites(e){for(let t of e.sprites){let r=new Y(t.sizeX*t.sizeY);for(let o=0;o<t.data.length;o++){let i=t.data[o];r.set(o,i.charCode,i.fgColorId,i.bgColorId)}let n={id:t.spriteId,sizeX:t.sizeX,sizeY:t.sizeY,data:r};this.multicolorSprites.set(n.id,n)}}getUnicolorSprite(e){return this.unicolorSprites.get(e)}getMulticolorSprite(e){return this.multicolorSprites.get(e)}hasUnicolorSprite(e){return this.unicolorSprites.has(e)}hasMulticolorSprite(e){return this.multicolorSprites.has(e)}unloadUnicolorSprite(e){return this.unicolorSprites.delete(e)}unloadMulticolorSprite(e){return this.multicolorSprites.delete(e)}clearUnicolorSprites(){this.unicolorSprites.clear()}clearMulticolorSprites(){this.multicolorSprites.clear()}clearAll(){this.unicolorSprites.clear(),this.multicolorSprites.clear()}getUnicolorSpriteCount(){return this.unicolorSprites.size}getMulticolorSpriteCount(){return this.multicolorSprites.size}getTotalSpriteCount(){return this.unicolorSprites.size+this.multicolorSprites.size}};g(Lt,"SpriteRegistry");var ie=Lt;var Dt=(t=>(t.Web="web",t.Bitmap="bitmap",t))(Dt||{}),Yt=class Yt{constructor(e,t){this.fontId=e;this.config=t}getFontId(){return this.fontId}getConfig(){return{...this.config}}getFontFamily(){return this.config.fontFamily}getFontSize(){return this.config.fontSize}getOffsetX(){return this.config.offsetX??0}getOffsetY(){return this.config.offsetY??0}getCharSpacing(){return this.config.charSpacing??0}getLineHeight(){return this.config.lineHeight??1.2}getFontWeight(){return this.config.fontWeight??"normal"}getFontStyle(){return this.config.fontStyle??"normal"}toCSS(){let e=[];e.push(`font-family: ${this.config.fontFamily}`),e.push(`font-size: ${this.config.fontSize}px`);let t=this.config.fontWeight??"normal";t!=="normal"&&e.push(`font-weight: ${t}`);let r=this.config.fontStyle??"normal";return r!=="normal"&&e.push(`font-style: ${r}`),e.join("; ")+";"}};g(Yt,"WebFont");var _=Yt,Xt=class Xt{constructor(e,t){this.fontId=e;this.config=t}getFontId(){return this.fontId}getConfig(){return{charWidth:this.config.charWidth,charHeight:this.config.charHeight,cellWidth:this.config.cellWidth,cellHeight:this.config.cellHeight,glyphs:new Map(this.config.glyphs)}}getCharWidth(){return this.config.charWidth}getCharHeight(){return this.config.charHeight}getCellWidth(){return this.config.cellWidth??this.config.charWidth}getCellHeight(){return this.config.cellHeight??this.config.charHeight}getGlyph(e){return this.config.glyphs.get(e)}hasGlyph(e){return this.config.glyphs.has(e)}getGlyphCount(){return this.config.glyphs.size}getCharCodes(){return Array.from(this.config.glyphs.keys())}};g(Xt,"BitmapFont");var se=Xt;var Nt=class Nt{constructor(){b(this,"fonts",new Map)}loadFont(e,t){if(this.fonts.has(e))throw new Error(`WebFont with ID ${e} already exists`);let r=new _(e,t);this.fonts.set(e,r)}getFont(e){return this.fonts.get(e)}hasFont(e){return this.fonts.has(e)}unloadFont(e){return this.fonts.delete(e)}clearFonts(){this.fonts.clear()}getFontIds(){return Array.from(this.fonts.keys()).sort((e,t)=>e-t)}getAllFonts(){return Array.from(this.fonts.entries()).sort((e,t)=>e[0]-t[0]).map(e=>e[1])}getFontCount(){return this.fonts.size}};g(Nt,"WebFontRegistry");var ae=Nt;var _t=class _t{constructor(){b(this,"fonts",new Map)}loadFont(e,t){if(this.fonts.has(e))throw new Error(`BitmapFont with ID ${e} already exists`);let r=new se(e,t);this.fonts.set(e,r)}getFont(e){return this.fonts.get(e)}hasFont(e){return this.fonts.has(e)}unloadFont(e){return this.fonts.delete(e)}clearFonts(){this.fonts.clear()}getFontIds(){return Array.from(this.fonts.keys()).sort((e,t)=>e-t)}getAllFonts(){return Array.from(this.fonts.entries()).sort((e,t)=>e[0]-t[0]).map(e=>e[1])}getFontCount(){return this.fonts.size}};g(_t,"BitmapFontRegistry");var de=_t;var Ht=class Ht{constructor(){b(this,"sounds",new Map);b(this,"nameToId",new Map);b(this,"nextId",0)}registerFile(e,t,r){let n=this.allocateId(e),o={soundId:n,name:e,loadType:"file",format:t,data:r};return this.sounds.set(n,o),this.nameToId.set(e,n),n}registerFileWithId(e,t,r,n){this.validateId(e),this.checkIdAvailable(e,t);let o={soundId:e,name:t,loadType:"file",format:r,data:n};this.sounds.set(e,o),this.nameToId.set(t,e)}registerExternal(e,t,r,n,o){let i=this.allocateId(e),s={soundId:i,name:e,loadType:"external",format:t,url:r,size:n,checksum:o};return this.sounds.set(i,s),this.nameToId.set(e,i),i}registerExternalWithId(e,t,r,n,o,i){this.validateId(e),this.checkIdAvailable(e,t);let s={soundId:e,name:t,loadType:"external",format:r,url:n,size:o,checksum:i};this.sounds.set(e,s),this.nameToId.set(t,e)}get(e){if(typeof e=="number")return this.sounds.get(e);let t=this.nameToId.get(e);return t!==void 0?this.sounds.get(t):void 0}has(e){return this.get(e)!==void 0}getAll(){return Array.from(this.sounds.values())}getFileSounds(){return this.getAll().filter(e=>e.loadType==="file")}getExternalSounds(){return this.getAll().filter(e=>e.loadType==="external")}getNames(){return Array.from(this.nameToId.keys())}getId(e){return this.nameToId.get(e)}toLoadPackets(){let e=[],t=this.getFileSounds();if(t.length>0){let n=t.map(o=>({soundId:o.soundId,name:o.name,format:o.format,data:o.data}));e.push({type:"sound",mode:"file",sounds:n})}let r=this.getExternalSounds();if(r.length>0){let n=r.map(o=>({soundId:o.soundId,name:o.name,format:o.format,url:o.url,size:o.size,checksum:o.checksum}));e.push({type:"sound",mode:"external",sounds:n})}return e}toLoadPacket(e){let t=this.get(e);return t?t.loadType==="file"?{type:"sound",mode:"file",sounds:[{soundId:t.soundId,name:t.name,format:t.format,data:t.data}]}:{type:"sound",mode:"external",sounds:[{soundId:t.soundId,name:t.name,format:t.format,url:t.url,size:t.size,checksum:t.checksum}]}:null}unregister(e){let t=this.get(e);return t?(this.sounds.delete(t.soundId),this.nameToId.delete(t.name),!0):!1}clear(){this.sounds.clear(),this.nameToId.clear(),this.nextId=0}get size(){return this.sounds.size}getStats(){let e=this.getAll(),t=e.filter(n=>n.loadType==="file"),r=t.reduce((n,o)=>n+(o.data?.length??0),0);return{total:e.length,file:t.length,external:e.length-t.length,totalFileSize:r}}allocateId(e){if(this.nameToId.has(e))throw new Error(`Sound with name "${e}" already exists`);for(;this.sounds.has(this.nextId);)if(this.nextId++,this.nextId>255)throw new Error("Maximum number of sounds (256) reached");return this.nextId++}validateId(e){if(!Number.isInteger(e)||e<0||e>255)throw new Error(`Invalid sound ID: ${e}. Must be an integer between 0 and 255.`)}checkIdAvailable(e,t){if(this.sounds.has(e)){let r=this.sounds.get(e);throw new Error(`Sound ID ${e} is already used by "${r.name}". Cannot register "${t}".`)}if(this.nameToId.has(t))throw new Error(`Sound with name "${t}" already exists`)}};g(Ht,"SoundRegistry");var ce=Ht;var Wt=class Wt{constructor(e){this.soundRegistry=e}collectFromUser(e){let t=[],r=e.flushSoundCommands();for(let o of r){let i=this.convertSoundCommand(o);i&&t.push(i)}let n=e.flushAudioConfigCommands();for(let o of n){let i=this.convertConfigCommand(o);i&&t.push(i)}return t}convertSoundCommand(e){return"setEffects"in e&&e.setEffects===!0?this.convertSetEffectsCommand(e):"fadeOut"in e&&e.fadeOut===!0?this.convertFadeOutCommand(e):"pause"in e&&e.pause===!0?this.convertPauseCommand(e):"resume"in e&&e.resume===!0?this.convertResumeCommand(e):"instanceId"in e||"volume"in e||"pitch"in e||"loop"in e||"fadeIn"in e||"x"in e||"y"in e||"lowpass"in e||"highpass"in e||"reverb"in e?this.convertPlayCommand(e):this.convertStopCommand(e)}convertPlayCommand(e){let t=this.resolveSoundId(e.sound);if(t===null)return console.warn(`[AudioOrderCollector] Unknown sound: ${e.sound}`),null;let r=0;e.loop&&(r|=1),e.volume!==void 0&&(r|=2),e.pitch!==void 0&&(r|=4),e.fadeIn!==void 0&&(r|=8),e.lowpass!==void 0&&e.lowpass>0&&(r|=32),e.highpass!==void 0&&e.highpass>0&&(r|=64),e.reverb!==void 0&&e.reverb>0&&(r|=128);let n=e.x!==void 0&&e.y!==void 0;return n&&(r|=16),n?{type:1,soundId:t,instanceId:e.instanceId??0,flags:r,volume:e.volume!==void 0?this.encodeVolume(e.volume):void 0,pitch:e.pitch!==void 0?this.encodePitch(e.pitch):void 0,fadeIn:e.fadeIn!==void 0?this.encodeFadeTime(e.fadeIn):void 0,posX:this.encodePosition(e.x),posY:this.encodePosition(e.y),lowpass:e.lowpass!==void 0&&e.lowpass>0?this.encodeFilterFreq(e.lowpass):void 0,highpass:e.highpass!==void 0&&e.highpass>0?this.encodeFilterFreq(e.highpass):void 0,reverb:e.reverb!==void 0&&e.reverb>0?this.encodeReverb(e.reverb):void 0}:{type:2,soundId:t,instanceId:e.instanceId??0,flags:r&-17,volume:e.volume!==void 0?this.encodeVolume(e.volume):void 0,pitch:e.pitch!==void 0?this.encodePitch(e.pitch):void 0,fadeIn:e.fadeIn!==void 0?this.encodeFadeTime(e.fadeIn):void 0,lowpass:e.lowpass!==void 0&&e.lowpass>0?this.encodeFilterFreq(e.lowpass):void 0,highpass:e.highpass!==void 0&&e.highpass>0?this.encodeFilterFreq(e.highpass):void 0,reverb:e.reverb!==void 0&&e.reverb>0?this.encodeReverb(e.reverb):void 0}}convertStopCommand(e){let{targetType:t,target:r}=this.resolveTarget(e.sound);return{type:3,targetType:t,target:r}}convertFadeOutCommand(e){let{targetType:t,target:r}=this.resolveTarget(e.sound);return{type:4,targetType:t,duration:this.encodeFadeTime(e.duration),target:r}}convertPauseCommand(e){let{targetType:t,target:r}=this.resolveTarget(e.sound);return{type:5,targetType:t,target:r}}convertResumeCommand(e){let{targetType:t,target:r}=this.resolveTarget(e.sound);return{type:6,targetType:t,target:r}}convertSetEffectsCommand(e){let t=0;return e.lowpass!==void 0&&(t|=1),e.highpass!==void 0&&(t|=2),e.reverb!==void 0&&(t|=4),{type:9,instanceId:e.instanceId,flags:t,lowpass:e.lowpass!==void 0?this.encodeFilterFreq(e.lowpass):void 0,highpass:e.highpass!==void 0?this.encodeFilterFreq(e.highpass):void 0,reverb:e.reverb!==void 0?this.encodeReverb(e.reverb):void 0}}convertConfigCommand(e){return e.type==="set-listener-position"?{type:7,x:this.encodePosition(e.x),y:this.encodePosition(e.y)}:e.type==="configure-spatial"?{type:8,maxDistance:this.encodeDistance(e.maxDistance??1e3),referenceDistance:this.encodeDistance(e.referenceDistance??100),rolloffFactor:this.encodeRolloff(e.rolloffFactor??1),panSpread:this.encodePanSpread(e.panSpread??.5)}:null}resolveSoundId(e){if(typeof e=="number")return e>=0&&e<=255?e:null;let t=this.soundRegistry.getId(e);return t!==void 0?t:null}resolveTarget(e){if(e==="all")return{targetType:2,target:void 0};if(typeof e=="number")return{targetType:0,target:e};let t=this.soundRegistry.getId(e);return t!==void 0?{targetType:1,target:t}:(console.warn(`[AudioOrderCollector] Unknown sound name: ${e}, treating as 'all'`),{targetType:2,target:void 0})}encodeVolume(e){return Math.round(Math.max(0,Math.min(1,e))*255)}encodePitch(e){let t=Math.max(.25,Math.min(4,e)),r=64*Math.log2(t/.25);return Math.round(Math.max(0,Math.min(255,r)))}encodeFadeTime(e){return Math.round(Math.max(0,Math.min(25.5,e))*10)}encodeDistance(e){return Math.round(Math.max(0,Math.min(25500,e))/100)}encodeRolloff(e){return Math.round(Math.max(0,Math.min(2.55,e))*100)}encodePanSpread(e){return Math.round(Math.max(0,Math.min(1,e))*255)}encodePosition(e){return Math.round(Math.max(0,Math.min(65535,e)))}encodeFilterFreq(e){return e<=0?0:Math.round(Math.max(1,Math.min(255,e/100)))}encodeReverb(e){return Math.round(Math.max(0,Math.min(1,e))*255)}};g(Wt,"AudioOrderCollector");var le=Wt;var z=require("@utsp/types");var Vt=class Vt{collectFromUser(e){let t=e.flushPostProcessCommands();return this.convertCommands(t)}convertCommands(e){let t=[];for(let r of e){let n=this.convertCommand(r);n&&t.push(n)}return t}convertCommand(e){switch(e.type){case"set-config":return this.convertSetConfig(e);case"set-scanlines-enabled":return this.createSetScanlinesOrder(e.enabled??!1,e.opacity);case"set-scanlines-opacity":return this.createSetScanlinesOrder(!0,e.opacity??z.POST_PROCESS_DEFAULTS.scanlines.opacity);case"set-ambient-effect-enabled":return this.createSetAmbientEffectOrder(e.enabled??!1);case"set-ambient-effect-blur":return this.createSetAmbientEffectOrder(!0,e.blur);case"set-ambient-effect-scale":return this.createSetAmbientEffectOrder(!0,void 0,e.scale);case"set-scaling-mode":return this.createSetScalingModeOrder(e.scalingMode);case"set-grid":return this.createSetGridOrder(e.gridConfig);default:return console.warn(`[PostProcessOrderCollector] Unknown command type: ${e.type}`),null}}convertSetConfig(e){if(!e.config)return{type:1,flags:3,scanlines:{enabled:!1,opacity:0,pattern:0,colorR:0,colorG:0,colorB:0},ambientEffect:{enabled:!1,blur:0,scale:1,opacity:0}};let t=0,r={type:1,flags:0};if(e.config.scanlines){t|=1;let n=e.config.scanlines;r.scanlines={enabled:n.enabled,opacity:n.opacity??z.POST_PROCESS_DEFAULTS.scanlines.opacity,pattern:this.patternToType(n.pattern??"horizontal"),colorR:n.color?.r??0,colorG:n.color?.g??0,colorB:n.color?.b??0}}if(e.config.ambientEffect){t|=2;let n=e.config.ambientEffect;r.ambientEffect={enabled:n.enabled,blur:n.blur??z.POST_PROCESS_DEFAULTS.ambientEffect.blur,scale:n.scale??z.POST_PROCESS_DEFAULTS.ambientEffect.scale,opacity:n.opacity??z.POST_PROCESS_DEFAULTS.ambientEffect.opacity}}return r.flags=t,r}createSetScanlinesOrder(e,t){return{type:2,enabled:e,opacity:t??z.POST_PROCESS_DEFAULTS.scanlines.opacity,pattern:0,colorR:0,colorG:0,colorB:0}}createSetAmbientEffectOrder(e,t,r){return{type:3,enabled:e,blur:t??z.POST_PROCESS_DEFAULTS.ambientEffect.blur,scale:r??z.POST_PROCESS_DEFAULTS.ambientEffect.scale,opacity:z.POST_PROCESS_DEFAULTS.ambientEffect.opacity}}patternToType(e){switch(e){case"horizontal":return 0;case"vertical":return 1;case"grid":return 2;default:return 0}}createSetScalingModeOrder(e){return{type:4,mode:(0,z.scalingModeToValue)(e)}}createSetGridOrder(e){let{r:t,g:r,b:n,a:o}=this.parseColor(e.color??z.GRID_DEFAULTS.color);return{type:5,enabled:e.enabled,colorR:t,colorG:r,colorB:n,colorA:o,lineWidth:e.lineWidth??z.GRID_DEFAULTS.lineWidth}}parseColor(e){let t=e.match(/rgba?\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+))?\s*\)/);if(t)return{r:parseInt(t[1],10),g:parseInt(t[2],10),b:parseInt(t[3],10),a:t[4]?Math.round(parseFloat(t[4])*255):255};let r=e.match(/^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$/);if(r){let n=r[1];return n.length===3?{r:parseInt(n[0]+n[0],16),g:parseInt(n[1]+n[1],16),b:parseInt(n[2]+n[2],16),a:255}:{r:parseInt(n.slice(0,2),16),g:parseInt(n.slice(2,4),16),b:parseInt(n.slice(4,6),16),a:255}}return{r:144,g:24,b:24,a:255}}};g(Vt,"PostProcessOrderCollector");var ue=Vt;var ge=class ge{constructor(e={}){b(this,"users",new Map);b(this,"mode");b(this,"maxUsers");b(this,"strictMode");b(this,"currentTick",0);b(this,"encoder");b(this,"displayRasterizer");b(this,"colorPalette",new Map);b(this,"stats",new oe);b(this,"spriteRegistry",new ie);b(this,"webFontRegistry",new ae);b(this,"bitmapFontRegistry",new de);b(this,"soundRegistry",new ce);b(this,"audioOrderCollector");b(this,"postProcessOrderCollector");b(this,"activeWebFontId",0);b(this,"_renderCallCount",0);b(this,"onPaletteChangedCallback");b(this,"onBitmapFontChangedCallback");this.mode=e.mode??"server",this.maxUsers=e.maxUsers??64,this.strictMode=e.strictMode??!1,this.encoder=new We,this.displayRasterizer=new Ge(this),this.audioOrderCollector=new le(this.soundRegistry),this.postProcessOrderCollector=new ue,this.initializeDefaultPalette(),this.displayRasterizer.rebuildColorCache(),this.loadDefaultWebFont()}initializeDefaultPalette(){ge.ANSI_VGA_COLORS.forEach(e=>{this.colorPalette.set(e.colorId,{r:e.r,g:e.g,b:e.b,a:e.a,e:e.e})}),this.colorPalette.set(255,{r:0,g:0,b:0,a:0,e:0})}getMode(){return this.mode}getMaxUsers(){return this.maxUsers}isStrictMode(){return this.strictMode}isServer(){return this.mode==="server"}isClient(){return this.mode==="client"}isStandalone(){return this.mode==="standalone"}createUser(e,t){if(this.users.has(e))throw new Error(`User with ID ${e} already exists`);if(this.mode==="server"&&this.users.size>=this.maxUsers)throw new Error(`Maximum number of users reached (${this.maxUsers}). Cannot create user ${e}`);if(this.mode==="client"&&this.users.size>=1)throw new Error(`Client mode only allows one user. Cannot create user ${e}`);let r=new re(e,t,this.mode);return r.setSpriteRegistry(this.spriteRegistry),this.users.set(e,r),r}getUser(e){return this.users.get(e)??null}getUsers(){return Array.from(this.users.values())}hasUser(e){return this.users.has(e)}removeUser(e){return this.users.delete(e)}getUserCount(){return this.users.size}clearAllUsers(){this.users.clear()}setColor(e,t,r,n,o=255,i=0){if(e<0||e>255)throw new Error(`Color ID must be between 0 and 255, got ${e}`);if(e>=240)throw new Error("Color IDs 240-255 are reserved (240-254: UI palette, 255: skip color). Use IDs 0-239 for custom colors.");if(t<0||t>255||r<0||r>255||n<0||n>255||o<0||o>255||i<0||i>255)throw new Error("Color components must be between 0 and 255");this.colorPalette.set(e,{r:t,g:r,b:n,a:o,e:i}),this.onPaletteChangedCallback&&this.onPaletteChangedCallback(this.colorPalette)}onPaletteChanged(e){this.onPaletteChangedCallback=e}onBitmapFontChanged(e){this.onBitmapFontChangedCallback=e}getColor(e){return this.colorPalette.get(e)??null}loadPalette(e){for(let t of e)t.colorId<0||t.colorId>255||this.colorPalette.set(t.colorId,{r:t.r,g:t.g,b:t.b,a:t.a,e:t.e??0});ge.ANSI_VGA_COLORS.forEach(t=>{this.colorPalette.set(t.colorId,{r:t.r,g:t.g,b:t.b,a:t.a,e:t.e})}),this.colorPalette.set(255,{r:0,g:0,b:0,a:0,e:0}),this.displayRasterizer.rebuildColorCache(),this.onPaletteChangedCallback&&this.onPaletteChangedCallback(this.colorPalette)}getPalette(){return new Map(this.colorPalette)}resetPalette(){this.colorPalette.clear(),this.initializeDefaultPalette(),this.onPaletteChangedCallback&&this.onPaletteChangedCallback(this.colorPalette)}getColorCSS(e){let t=this.getColor(e);if(!t)return null;let r=t.a/255;return`rgba(${t.r}, ${t.g}, ${t.b}, ${r})`}getUserIds(){return Array.from(this.users.keys())}forEachUser(e){this.users.forEach(e)}filterUsers(e){return this.getUsers().filter(e)}findUser(e){return this.getUsers().find(e)}getCurrentTick(){return this.currentTick}getStats(){return this.stats}endTick(){this.stats.isEnabled()&&this.stats.startTick(this.currentTick);let e=new Map,t=0,r=0;return this.users.forEach((n,o)=>{let i=n.getLayers(),s=n.getDisplays();t+=i.length,n.getStats().isEnabled()&&n.getStats().startTick(this.currentTick);let a=s.map(x=>{let v=x.getOrigin(),U=x.getSize();return{id:x.getId(),originX:v.x,originY:v.y,sizeX:U.x,sizeY:U.y}});s.forEach(x=>x.resetChangeTracking());let d=[],c=[];i.forEach((x,v)=>{let U=x.getOrigin(),S=x.getOrders(),w=x.getStatic(),I=x.calculateUpdateFlags();x.resetChangeTracking(),x.getId()===0&&x.setId(v);let M={id:x.getId(),updateFlags:I,zIndex:x.getZOrder(),originX:U.x,originY:U.y,width:x.getWidth(),height:x.getHeight(),orderCount:S.length,orders:S};w?d.push(M):c.push(M)}),r+=d.length+c.length;let l=this.audioOrderCollector.collectFromUser(n),u=n.flushMacroOrders(),p=this.postProcessOrderCollector.collectFromUser(n),h=[...d,...c],y=this.encoder.encode({tick:this.currentTick,displayCount:a.length,displays:a,layerCount:h.length,layers:h,audioOrderCount:l.length,audioOrders:l,macroOrderCount:u.length,macroOrders:u,postProcessOrderCount:p.length,postProcessOrders:p});if(e.set(o,y),this.stats.isEnabled()){h.forEach((S,w)=>{this.stats.recordLayerOrders(w,S.orders)}),s.forEach((S,w)=>{this.stats.recordDisplayLayers(w,h.length)});let x=s.length*12,v=h.length*20,U=y.length-x-v;this.stats.recordUpdatePacketSize(y.length,x,v,U>0?U:0)}}),this.stats.isEnabled()&&(this.stats.recordLayers(t,r),this.stats.endTick()),this.currentTick++,e}endTickSplit(){this.stats.isEnabled()&&this.stats.startTick(this.currentTick);let e=new Map,t=0,r=0;return this.users.forEach((n,o)=>{let i=n.getLayers(),s=n.getDisplays();t+=i.length,n.getStats().isEnabled()&&n.getStats().startTick(this.currentTick);let a=s.map(x=>{let v=x.getOrigin(),U=x.getSize();return{id:x.getId(),originX:v.x,originY:v.y,sizeX:U.x,sizeY:U.y}});s.forEach(x=>x.resetChangeTracking());let d=[],c=[];i.forEach((x,v)=>{if(!x.getNeedsCommit())return;let U=x.getOrigin(),S=x.getOrders(),w=x.getStatic(),I=x.calculateUpdateFlags();x.resetChangeTracking(),x.resetCommit(),x.getId()===0&&x.setId(v);let M={id:x.getId(),updateFlags:I,zIndex:x.getZOrder(),originX:U.x,originY:U.y,width:x.getWidth(),height:x.getHeight(),orderCount:S.length,orders:S};S.length>0&&this.stats.isEnabled()&&this.stats.recordLayerInfo(x.getId(),w,S.length,I),w?d.push(M):c.push(M)}),r+=d.length+c.length;let l=this.audioOrderCollector.collectFromUser(n),u=this.postProcessOrderCollector.collectFromUser(n),p=n.flushMacroOrders(),h=null,y=null;if(this.stats.isEnabled()&&this.stats.recordPacketSplit(o,a.length,d.length,c.length),d.length>0&&(h=this.encoder.encode({tick:this.currentTick,displayCount:a.length,displays:a,layerCount:d.length,layers:d,audioOrderCount:0,audioOrders:[],macroOrderCount:0,macroOrders:[],postProcessOrderCount:0,postProcessOrders:[]})),y=this.encoder.encode({tick:this.currentTick,displayCount:a.length,displays:a,layerCount:c.length,layers:c,audioOrderCount:l.length,audioOrders:l,macroOrderCount:p.length,macroOrders:p,postProcessOrderCount:u.length,postProcessOrders:u}),e.set(o,{static:h,dynamic:y}),n.getStats().isEnabled()){let x=s.reduce((w,I)=>{let M=I.getSize();return w+M.x*M.y},0);n.getStats().recordDisplays(s.length,x),n.getStats().recordLayers(i.length,d.length+c.length,d.length,c.length),[...d,...c].forEach(w=>{n.getStats().recordLayerOrders(w.id,w.orders.length)});let v=h?.length||0,U=y?.length||0;n.getStats().recordPacketSizes(v,U);let S=n.getInputBindingRegistry();n.getStats().recordInput(!1,S.getAxisCount(),S.getButtonCount()),n.getStats().endTick()}if(this.stats.isEnabled()){let x=[...d,...c];x.forEach((I,M)=>{this.stats.recordLayerOrders(M,I.orders)}),s.forEach((I,M)=>{this.stats.recordDisplayLayers(M,x.length)});let v=(h?.length||0)+(y?.length||0),U=s.length*12,S=x.length*20,w=v-U-S;this.stats.recordUpdatePacketSize(v,U,S,w>0?w:0)}}),this.stats.isEnabled()&&(this.stats.recordLayers(t,r),this.stats.endTick()),this.currentTick++,e}getSnapshot(e){let t=this.getUser(e);if(!t)return null;let r=t.getDisplays(),n=t.getLayers(),o=r.map((s,a)=>{let d=s.getOrigin(),c=s.getSize();return{id:a,originX:d.x,originY:d.y,sizeX:c.x,sizeY:c.y}}),i=n.map((s,a)=>{let d=s.getOrigin(),c=s.getOrders(),l=7;return s.getId()===0&&s.setId(a),{id:s.getId(),updateFlags:l,zIndex:s.getZOrder(),originX:d.x,originY:d.y,width:s.getWidth(),height:s.getHeight(),orderCount:c.length,orders:c}});return this.encoder.encode({tick:this.currentTick,displayCount:o.length,displays:o,layerCount:i.length,layers:i,audioOrderCount:0,audioOrders:[],macroOrderCount:0,macroOrders:[],postProcessOrderCount:0,postProcessOrders:[]})}resetTick(){this.currentTick=0}applyUpdatePacket(e,t){let r=this.getUser(e);if(!r){if(this.strictMode)throw new Error(`Cannot apply update packet: user ${e} does not exist`);return!1}return r.applyUpdate(t),t.audioOrders&&t.audioOrders.length>0&&r.applyAudioOrders(t.audioOrders),!0}applyUpdatePacketBuffer(e,t){let{UpdatePacketDecoder:r}=(tr(),T(Fr)),o=new r().decode(t);return this.applyUpdatePacket(e,o)?o:null}applyLoadPacket(e){try{let{LoadDecoder:t}=(Yr(),T(Dr)),{LoadType:r}=(N(),T($)),i=new t().decode(e).load;switch(i.loadType){case r.ColorPalette:this.loadPalette(i.colors);break;case r.Sprite:this.loadUnicolorSprites(i);break;case r.MulticolorSprite:this.loadMulticolorSprites(i);break;case r.BitmapFont:{let s=this.getBitmapFontRegistry();s.hasFont(i.fontId)&&s.unloadFont(i.fontId),s.loadFont(i.fontId,{charWidth:i.width,charHeight:i.height,cellWidth:i.cellWidth,cellHeight:i.cellHeight,glyphs:new Map(i.characters.map(a=>[a.charCode,a.bitmap]))});break}case r.WebFont:{let s=this.getWebFontRegistry();s.hasFont(i.fontId)&&s.unloadFont(i.fontId),this.loadWebFontById(i.fontId,{fontFamily:i.fontFamily,fontSize:i.fontSize,offsetX:i.offsetX,offsetY:i.offsetY,charSpacing:i.charSpacing,lineHeight:i.lineHeight,fontWeight:i.fontWeight,fontStyle:i.fontStyle});break}case r.Sound:console.warn("[Core] Sound loading not yet implemented");break;case r.Macro:{for(let s of this.users.values())s.loadMacroTemplate(i.macroId,i.template);break}default:return console.error(`[Core] Unknown LoadType: ${i.loadType}`),!1}return!0}catch(t){return console.error("[Core] Failed to apply LoadPacket:",t),!1}}generatePaletteLoadPacket(){let e=this.getPalette();if(e.size===0)return null;let{LoadEncoder:t}=(be(),T(he)),{LoadType:r}=(N(),T($)),n=new t,o=[];return e.forEach((i,s)=>{s!==255&&o.push({colorId:s,r:i.r,g:i.g,b:i.b,a:i.a,e:i.e})}),n.encode({loadType:r.ColorPalette,colors:o})}generateUnicolorSpritesLoadPacket(){let e=this.getSpriteRegistry(),t=[];for(let i=0;i<=255;i++){let s=e.getUnicolorSprite(i);if(s){let a=[];for(let d=0;d<s.sizeX*s.sizeY;d++)a.push(s.data.get(d));t.push({spriteId:s.id,sizeX:s.sizeX,sizeY:s.sizeY,data:a})}}if(t.length===0)return null;let{LoadEncoder:r}=(be(),T(he)),{LoadType:n}=(N(),T($));return new r().encode({loadType:n.Sprite,sprites:t})}generateMulticolorSpritesLoadPacket(){let e=this.getSpriteRegistry(),t=[];for(let i=0;i<=255;i++){let s=e.getMulticolorSprite(i);if(s){let a=[];for(let d=0;d<s.sizeX*s.sizeY;d++){let c=s.data.get(d);a.push({charCode:c.charCode,fgColorId:c.fgColorCode,bgColorId:c.bgColorCode})}t.push({spriteId:s.id,sizeX:s.sizeX,sizeY:s.sizeY,data:a})}}if(t.length===0)return null;let{LoadEncoder:r}=(be(),T(he)),{LoadType:n}=(N(),T($));return new r().encode({loadType:n.MulticolorSprite,sprites:t})}generateWebFontsLoadPackets(){let e=this.getWebFontRegistry(),t=e.getFontIds(),r=[],{LoadEncoder:n}=(be(),T(he)),{LoadType:o}=(N(),T($)),i=new n;for(let s of t){let a=e.getFont(s);if(a){let d=a.getConfig(),c=i.encode({loadType:o.WebFont,fontId:s,fontFamily:d.fontFamily,fontSize:d.fontSize,offsetX:d.offsetX,offsetY:d.offsetY,charSpacing:d.charSpacing,lineHeight:d.lineHeight,fontWeight:d.fontWeight,fontStyle:d.fontStyle});r.push(c)}}return r}generateBitmapFontsLoadPackets(){let e=this.getBitmapFontRegistry(),t=e.getFontIds(),r=[],{LoadEncoder:n}=(be(),T(he)),{LoadType:o}=(N(),T($)),i=new n;for(let s of t){let a=e.getFont(s);if(a){let d=[];for(let c=0;c<256;c++){let l=a.getGlyph(c);l&&d.push({charCode:c,bitmap:l})}if(d.length>0){let c=i.encode({loadType:o.BitmapFont,fontId:s,width:a.getCharWidth(),height:a.getCharHeight(),cellWidth:a.getCellWidth(),cellHeight:a.getCellHeight(),characters:d});r.push(c)}}}return r}generateAllLoadPackets(){let e=[],t=this.generatePaletteLoadPacket();t&&e.push(t);let r=this.generateUnicolorSpritesLoadPacket();r&&e.push(r);let n=this.generateMulticolorSpritesLoadPacket();n&&e.push(n);let o=this.generateWebFontsLoadPackets();e.push(...o);let i=this.generateBitmapFontsLoadPackets();return e.push(...i),e}generateMacroLoadPackets(e){let t=this.getUser(e);if(!t)return[];let r=t.getMacroLoads();if(r.length===0)return[];let n=new $e;return r.map(o=>n.encode(o))}applyInputBindingsLoadPacket(e,t){let r=this.getUser(e);if(!r){if(this.strictMode)throw new Error(`Cannot apply input bindings: user ${e} does not exist`);return!1}try{return r.applyInputBindingsLoadPacket(t),!0}catch(n){return console.error(`[Core] Failed to apply input bindings for user ${e}:`,n),!1}}getRenderState(e){let t=this.getUser(e);if(!t)return null;let r=t.getDisplays(),n=t.getLayers(),o=performance.now(),i=new Array(r.length);for(let a=0;a<r.length;a++){let d=r[a],c=d.getOrigin(),l=d.getSize();i[a]=this.displayRasterizer.rasterize({x:c.x,y:c.y,width:l.x,height:l.y},n)}let s=performance.now()-o;return this._renderCallCount||(this._renderCallCount=0),this._renderCallCount++,{userId:t.id,userName:t.name,tick:this.currentTick,displays:i}}getAllRenderStates(){let e=new Map;return this.users.forEach((t,r)=>{let n=this.getRenderState(r);n&&e.set(r,n)}),e}enableStats(e){this.stats.setEnabled(e)}getStatsInstance(){return this.stats}resetStats(){this.stats.reset()}loadUnicolorSprites(e){this.spriteRegistry.loadUnicolorSprites(e)}loadMulticolorSprites(e){this.spriteRegistry.loadMulticolorSprites(e)}unloadUnicolorSprite(e){return this.spriteRegistry.unloadUnicolorSprite(e)}unloadMulticolorSprite(e){return this.spriteRegistry.unloadMulticolorSprite(e)}clearUnicolorSprites(){this.spriteRegistry.clearUnicolorSprites()}clearMulticolorSprites(){this.spriteRegistry.clearMulticolorSprites()}clearAllSprites(){this.spriteRegistry.clearAll()}getUnicolorSpriteCount(){return this.spriteRegistry.getUnicolorSpriteCount()}getMulticolorSpriteCount(){return this.spriteRegistry.getMulticolorSpriteCount()}getTotalSpriteCount(){return this.spriteRegistry.getTotalSpriteCount()}hasUnicolorSprite(e){return this.spriteRegistry.hasUnicolorSprite(e)}hasMulticolorSprite(e){return this.spriteRegistry.hasMulticolorSprite(e)}getSpriteRegistry(){return this.spriteRegistry}getSoundRegistry(){return this.soundRegistry}async loadSound(e,t){let r=this.detectSoundFormat(t),n=await this.loadSoundData(t);return this.soundRegistry.registerFile(e,r,n)}async loadSounds(e){let t={},n=Object.entries(e).map(async([o,i])=>{let s=await this.loadSound(o,i);t[o]=s});return await Promise.all(n),t}detectSoundFormat(e){let t=e.split(".").pop()?.toLowerCase()??"",r={mp3:"mp3",wav:"wav",ogg:"ogg",webm:"webm",aac:"aac",m4a:"aac"},n=r[t];if(!n)throw new Error(`Unsupported audio format: .${t}. Supported: ${Object.keys(r).join(", ")}`);return n}async loadSoundData(e){let t=globalThis;if(typeof t.document<"u"||typeof t.window<"u"||typeof t.fetch=="function")try{let n=await fetch(e);if(!n.ok)throw new Error(`HTTP ${n.status}: ${n.statusText}`);let o=await n.arrayBuffer();return new Uint8Array(o)}catch(n){let o=n instanceof Error?n.message:String(n);throw new Error(`Failed to load sound "${e}": ${o}`)}else{let n=typeof require<"u"?require:null;if(!n)throw new Error("Node.js require is not available");let s=n("fs").readFileSync(e);return new Uint8Array(s)}}registerSound(e,t,r){return this.soundRegistry.registerFile(e,t,r)}registerExternalSound(e,t,r,n){return this.soundRegistry.registerExternal(e,t,r,n)}hasSound(e){return this.soundRegistry.has(e)}generateSoundLoadPackets(){return this.soundRegistry.toLoadPackets()}loadDefaultWebFont(){this.webFontRegistry.loadFont(0,{fontFamily:"Courier New",fontSize:16,offsetX:0,offsetY:0,charSpacing:0,lineHeight:1,fontWeight:"normal",fontStyle:"normal"}),this.activeWebFontId=0}loadWebFont(e){let t=e.getFontId(),r=e.getConfig();this.webFontRegistry.loadFont(t,r)}getWebFont(e){return this.webFontRegistry.getFont(e)??null}hasWebFont(e){return this.webFontRegistry.hasFont(e)}unloadWebFont(e){if(e===0)throw new Error("Cannot unload default font (fontId 0)");return this.webFontRegistry.unloadFont(e)}clearWebFonts(){this.webFontRegistry.clearFonts(),this.loadDefaultWebFont()}setActiveWebFont(e){if(!this.webFontRegistry.hasFont(e))throw new Error(`WebFont with ID ${e} does not exist`);this.activeWebFontId=e}getActiveWebFontId(){return this.activeWebFontId}getActiveWebFont(){let e=this.webFontRegistry.getFont(this.activeWebFontId);if(!e)throw new Error(`Active WebFont ${this.activeWebFontId} not found. This should not happen.`);return e}getWebFontCount(){return this.webFontRegistry.getFontCount()}getWebFontIds(){return this.webFontRegistry.getFontIds()}getWebFontRegistry(){return this.webFontRegistry}getBitmapFontRegistry(){return this.bitmapFontRegistry}loadWebFontById(e,t){let r=new _(e,t);this.loadWebFont(r)}loadBitmapFontById(e,t){this.bitmapFontRegistry.loadFont(e,t),this.onBitmapFontChangedCallback&&this.onBitmapFontChangedCallback(e)}getBitmapFont(e){return this.bitmapFontRegistry.getFont(e)??null}hasBitmapFont(e){return this.bitmapFontRegistry.hasFont(e)}unloadBitmapFont(e){return this.bitmapFontRegistry.unloadFont(e)}clearBitmapFonts(){this.bitmapFontRegistry.clearFonts()}getBitmapFontCount(){return this.bitmapFontRegistry.getFontCount()}getBitmapFontIds(){return this.bitmapFontRegistry.getFontIds()}};g(ge,"Core"),b(ge,"ANSI_VGA_COLORS",[{colorId:240,r:16,g:16,b:16,a:255,e:0},{colorId:241,r:128,g:128,b:128,a:255,e:0},{colorId:242,r:192,g:192,b:192,a:255,e:0},{colorId:243,r:240,g:240,b:240,a:255,e:0},{colorId:244,r:200,g:50,b:50,a:255,e:0},{colorId:245,r:50,g:200,b:50,a:255,e:0},{colorId:246,r:220,g:180,b:50,a:255,e:0},{colorId:247,r:50,g:100,b:220,a:255,e:0},{colorId:248,r:50,g:200,b:200,a:255,e:0},{colorId:249,r:200,g:50,b:200,a:255,e:0},{colorId:250,r:220,g:120,b:50,a:255,e:0},{colorId:251,r:120,g:220,b:120,a:255,e:0},{colorId:252,r:120,g:180,b:220,a:255,e:0},{colorId:253,r:220,g:150,b:200,a:255,e:0},{colorId:254,r:250,g:220,b:150,a:255,e:0}]);var Qe=ge;var $r=require("@utsp/types");var G=new Map([[24,new Uint8Array([0,24,60,126,255,255,0,0])],[25,new Uint8Array([0,0,255,255,126,60,24,0])],[26,new Uint8Array([0,48,120,252,252,120,48,0])],[27,new Uint8Array([0,12,30,63,63,30,12,0])],[32,new Uint8Array([0,0,0,0,0,0,0,0])],[33,new Uint8Array([24,24,24,24,24,0,24,0])],[34,new Uint8Array([108,108,108,0,0,0,0,0])],[35,new Uint8Array([54,54,127,54,127,54,54,0])],[36,new Uint8Array([12,63,104,62,11,126,24,0])],[37,new Uint8Array([96,102,12,24,48,102,6,0])],[38,new Uint8Array([56,108,108,56,109,102,59,0])],[39,new Uint8Array([24,24,24,0,0,0,0,0])],[40,new Uint8Array([12,24,48,48,48,24,12,0])],[41,new Uint8Array([48,24,12,12,12,24,48,0])],[42,new Uint8Array([0,102,60,255,60,102,0,0])],[43,new Uint8Array([0,24,24,126,24,24,0,0])],[44,new Uint8Array([0,0,0,0,0,24,24,48])],[45,new Uint8Array([0,0,0,126,0,0,0,0])],[46,new Uint8Array([0,0,0,0,0,24,24,0])],[47,new Uint8Array([0,6,12,24,48,96,0,0])],[48,new Uint8Array([60,102,110,126,118,102,60,0])],[49,new Uint8Array([24,56,24,24,24,24,126,0])],[50,new Uint8Array([60,102,6,12,24,48,126,0])],[51,new Uint8Array([60,102,6,28,6,102,60,0])],[52,new Uint8Array([12,28,60,108,126,12,12,0])],[53,new Uint8Array([126,96,124,6,6,102,60,0])],[54,new Uint8Array([28,48,96,124,102,102,60,0])],[55,new Uint8Array([126,6,12,24,48,48,48,0])],[56,new Uint8Array([60,102,102,60,102,102,60,0])],[57,new Uint8Array([60,102,102,62,6,12,56,0])],[58,new Uint8Array([0,0,24,24,0,24,24,0])],[59,new Uint8Array([0,0,24,24,0,24,24,48])],[60,new Uint8Array([12,24,48,96,48,24,12,0])],[61,new Uint8Array([0,0,126,0,126,0,0,0])],[62,new Uint8Array([48,24,12,6,12,24,48,0])],[63,new Uint8Array([60,102,12,24,24,0,24,0])],[64,new Uint8Array([60,102,110,106,110,96,60,0])],[65,new Uint8Array([60,102,102,126,102,102,102,0])],[66,new Uint8Array([124,102,102,124,102,102,124,0])],[67,new Uint8Array([60,102,96,96,96,102,60,0])],[68,new Uint8Array([120,108,102,102,102,108,120,0])],[69,new Uint8Array([126,96,96,124,96,96,126,0])],[70,new Uint8Array([126,96,96,124,96,96,96,0])],[71,new Uint8Array([60,102,96,110,102,102,60,0])],[72,new Uint8Array([102,102,102,126,102,102,102,0])],[73,new Uint8Array([126,24,24,24,24,24,126,0])],[74,new Uint8Array([62,12,12,12,12,108,56,0])],[75,new Uint8Array([102,108,120,112,120,108,102,0])],[76,new Uint8Array([96,96,96,96,96,96,126,0])],[77,new Uint8Array([99,119,127,107,99,99,99,0])],[78,new Uint8Array([102,102,118,126,110,102,102,0])],[79,new Uint8Array([60,102,102,102,102,102,60,0])],[80,new Uint8Array([124,102,102,124,96,96,96,0])],[81,new Uint8Array([60,102,102,102,106,108,54,0])],[82,new Uint8Array([124,102,102,124,108,102,102,0])],[83,new Uint8Array([60,102,96,60,6,102,60,0])],[84,new Uint8Array([126,24,24,24,24,24,24,0])],[85,new Uint8Array([102,102,102,102,102,102,60,0])],[86,new Uint8Array([102,102,102,102,102,60,24,0])],[87,new Uint8Array([99,99,99,107,127,119,99,0])],[88,new Uint8Array([102,102,60,24,60,102,102,0])],[89,new Uint8Array([102,102,102,60,24,24,24,0])],[90,new Uint8Array([126,6,12,24,48,96,126,0])],[91,new Uint8Array([60,48,48,48,48,48,60,0])],[92,new Uint8Array([0,96,48,24,12,6,0,0])],[93,new Uint8Array([60,12,12,12,12,12,60,0])],[94,new Uint8Array([24,60,102,0,0,0,0,0])],[95,new Uint8Array([0,0,0,0,0,0,255,0])],[96,new Uint8Array([48,24,12,0,0,0,0,0])],[97,new Uint8Array([0,0,60,6,62,102,62,0])],[98,new Uint8Array([96,96,124,102,102,102,124,0])],[99,new Uint8Array([0,0,60,102,96,102,60,0])],[100,new Uint8Array([6,6,62,102,102,102,62,0])],[101,new Uint8Array([0,0,60,102,126,96,60,0])],[102,new Uint8Array([28,54,48,124,48,48,48,0])],[103,new Uint8Array([0,0,62,102,102,62,6,60])],[104,new Uint8Array([96,96,124,102,102,102,102,0])],[105,new Uint8Array([24,0,56,24,24,24,60,0])],[106,new Uint8Array([12,0,28,12,12,12,108,56])],[107,new Uint8Array([96,96,102,108,120,108,102,0])],[108,new Uint8Array([56,24,24,24,24,24,60,0])],[109,new Uint8Array([0,0,102,127,107,107,99,0])],[110,new Uint8Array([0,0,124,102,102,102,102,0])],[111,new Uint8Array([0,0,60,102,102,102,60,0])],[112,new Uint8Array([0,0,124,102,102,124,96,96])],[113,new Uint8Array([0,0,62,102,102,62,6,6])],[114,new Uint8Array([0,0,108,118,96,96,96,0])],[115,new Uint8Array([0,0,62,96,60,6,124,0])],[116,new Uint8Array([48,48,124,48,48,54,28,0])],[117,new Uint8Array([0,0,102,102,102,102,62,0])],[118,new Uint8Array([0,0,102,102,102,60,24,0])],[119,new Uint8Array([0,0,99,107,107,127,54,0])],[120,new Uint8Array([0,0,102,60,24,60,102,0])],[121,new Uint8Array([0,0,102,102,102,62,6,60])],[122,new Uint8Array([0,0,126,12,24,48,126,0])],[123,new Uint8Array([14,24,24,112,24,24,14,0])],[124,new Uint8Array([24,24,24,24,24,24,24,0])],[125,new Uint8Array([112,24,24,14,24,24,112,0])],[126,new Uint8Array([49,107,70,0,0,0,0,0])],[179,new Uint8Array([24,24,24,24,24,24,24,24])],[196,new Uint8Array([0,0,0,255,0,0,0,0])],[218,new Uint8Array([0,0,0,31,24,24,24,24])],[191,new Uint8Array([0,0,0,248,24,24,24,24])],[192,new Uint8Array([24,24,24,31,0,0,0,0])],[217,new Uint8Array([24,24,24,248,0,0,0,0])],[195,new Uint8Array([24,24,24,31,24,24,24,24])],[180,new Uint8Array([24,24,24,248,24,24,24,24])],[194,new Uint8Array([0,0,0,255,24,24,24,24])],[193,new Uint8Array([24,24,24,255,0,0,0,0])],[197,new Uint8Array([24,24,24,255,24,24,24,24])],[186,new Uint8Array([54,54,54,54,54,54,54,54])],[205,new Uint8Array([0,0,0,255,0,255,0,0])],[201,new Uint8Array([0,0,0,63,54,54,54,54])],[187,new Uint8Array([0,0,0,252,54,54,54,54])],[200,new Uint8Array([54,54,54,63,0,0,0,0])],[188,new Uint8Array([54,54,54,252,0,0,0,0])],[204,new Uint8Array([54,54,54,63,54,54,54,54])],[185,new Uint8Array([54,54,54,252,54,54,54,54])],[203,new Uint8Array([0,0,0,255,54,54,54,54])],[202,new Uint8Array([54,54,54,255,0,0,0,0])],[206,new Uint8Array([54,54,54,255,54,54,54,54])],[219,new Uint8Array([255,255,255,255,255,255,255,255])],[178,new Uint8Array([170,85,170,85,170,85,170,85])],[177,new Uint8Array([136,34,136,34,136,34,136,34])],[176,new Uint8Array([34,136,34,136,34,136,34,136])],[223,new Uint8Array([255,255,255,255,0,0,0,0])],[220,new Uint8Array([0,0,0,0,255,255,255,255])],[221,new Uint8Array([240,240,240,240,240,240,240,240])],[222,new Uint8Array([15,15,15,15,15,15,15,15])]]);function Xr(m){return G.get(m)}g(Xr,"getCharBitmap");function Nr(m){return G.has(m)}g(Nr,"hasChar");function _r(){return Array.from(G.keys()).sort((m,e)=>m-e)}g(_r,"getAllCharCodes");function Hr(m){let e=Array.from(G.entries()).map(([t,r])=>({charCode:t,bitmap:r}));return{loadType:4,fontId:m,width:8,height:8,cellWidth:8,cellHeight:8,characters:e}}g(Hr,"createASCII8x8FontLoad");function Wr(){return{charWidth:8,charHeight:8,glyphs:new Map(G)}}g(Wr,"getASCII8x8FontConfig");F();var ar=class ar{encode(e){switch(e.type){case 1:return this.encodeClick(e);case 2:return this.encodeChange(e);case 3:return this.encodeSubmit(e);case 4:return this.encodeSelect(e);default:throw new Error(`Unknown macro event type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return 2;case 2:return this.calculateChangeSize(e);case 3:return this.calculateSubmitSize(e);case 4:return 4;default:throw new Error(`Unknown macro event type: ${e.type}`)}}encodeClick(e){let t=C.allocUnsafe(2);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.toUint8Array()}encodeChange(e){if(typeof e.value=="boolean"){let r=C.allocUnsafe(4);return r.writeUInt8(e.type,0),r.writeUInt8(e.instanceId,1),r.writeUInt8(1,2),r.writeUInt8(e.value?1:0,3),r.toUint8Array()}else{let r=C.allocUnsafe(7);return r.writeUInt8(e.type,0),r.writeUInt8(e.instanceId,1),r.writeUInt8(0,2),r.writeFloatBE(e.value,3),r.toUint8Array()}}calculateChangeSize(e){return typeof e.value=="boolean"?4:7}encodeSubmit(e){let t=new TextEncoder().encode(e.text);if(t.length>65535)throw new Error(`Submit text too large: ${t.length} bytes (max 65535)`);let r=4+t.length,n=C.allocUnsafe(r),o=0;return n.writeUInt8(e.type,o++),n.writeUInt8(e.instanceId,o++),n.writeUInt16BE(t.length,o),o+=2,n.toUint8Array().set(t,o),n.toUint8Array()}calculateSubmitSize(e){return 4+new TextEncoder().encode(e.text).length}encodeSelect(e){let t=C.allocUnsafe(4);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.writeUInt16BE(e.index,2),t.toUint8Array()}};g(ar,"MacroEventEncoder");var et=ar;function Vr(m,e,t,r,n,o,i,s=[],a=[]){let d=Array.from(e.entries()).sort((A,O)=>A[0]-O[0]),c=Array.from(t.entries()).sort((A,O)=>A[0]-O[0]),l=d.length,u=c.length,p=Be(l,u),h=new TextEncoder,y=s.map(A=>h.encode(A)),x=1+y.reduce((A,O)=>A+1+O.length,0),v=new et,U=a.map(A=>v.encode(A)),S=1+U.reduce((A,O)=>A+O.length,0),w=p+x+S,I=new Uint8Array(w),M=new DataView(I.buffer),f=0;M.setBigUint64(f,m,!0),f+=8;for(let[,A]of d){let O=ke(A);I[f]=O+256&255,f+=1}let k=V(u);for(let A=0;A<k;A++){let O=0;for(let Oe=0;Oe<8;Oe++){let cr=A*8+Oe;if(cr<u){let[,Gr]=c[cr];Gr&&(O|=1<<Oe)}}I[f]=O,f+=1}I[f]=r&255,f+=1,I[f]=n&255,f+=1,I[f]=o&255,f+=1;let H=0;i&&(H|=1),I[f]=H,f+=1,I[f]=Math.min(s.length,255),f+=1;for(let A of y)I[f]=Math.min(A.length,255),f+=1,I.set(A.slice(0,255),f),f+=A.length;I[f]=Math.min(a.length,255),f+=1;for(let A of U)I.set(A,f),f+=A.length;return I}g(Vr,"encodeCompressedInput");var E=class E{static toCharCode(e){if(typeof e=="number")return e&255;let t=e.charCodeAt(0);return Ce(t)}static dedent(e){let t=e.split(`
|
|
8
|
+
`}),e}};g(Ct,"InputBindingRegistry");var ee=Ct;function Re(m=0n){return{tick:m,axes:new Map,buttons:new Map,displayId:0,mouseX:0,mouseY:0,mouseOverDisplay:!1,textInputs:[],macroEvents:[]}}g(Re,"createEmptyCompressedInputPacket");function ke(m){let e=Math.max(-1,Math.min(1,m));return Math.round(e*127)}g(ke,"encodeAxisToInt8");function Pe(m){return m/127}g(Pe,"decodeInt8ToAxis");function V(m){return m===0?0:Math.ceil(m/8)}g(V,"getButtonByteCount");function Be(m,e){let r=m,n=V(e);return 8+r+n+4}g(Be,"getCompressedPacketSize");var ft=class ft{decode(e,t=0){let r=e.readUInt8(t);switch(r){case 1:return this.decodeClick(e,t);case 2:return this.decodeChange(e,t);case 3:return this.decodeSubmit(e,t);case 4:return this.decodeSelect(e,t);default:throw new Error(`Unknown macro event type: 0x${r.toString(16)}`)}}decodeAll(e,t,r){let n=[],o=0;for(let i=0;i<r;i++){let{event:s,bytesRead:a}=this.decode(e,t+o);n.push(s),o+=a}return{events:n,bytesRead:o}}decodeClick(e,t){let r=e.readUInt8(t),n=e.readUInt8(t+1);return{event:{type:r,instanceId:n},bytesRead:2}}decodeChange(e,t){let r=e.readUInt8(t),n=e.readUInt8(t+1),o=e.readUInt8(t+2),i,s;return o===1?(i=e.readUInt8(t+3)===1,s=4):(i=e.readFloatBE(t+3),s=7),{event:{type:r,instanceId:n,value:i},bytesRead:s}}decodeSubmit(e,t){let r=t,n=e.readUInt8(t++),o=e.readUInt8(t++),i=e.readUInt16BE(t);t+=2;let s=e.toUint8Array().subarray(t,t+i);t+=i;let a=new TextDecoder().decode(s);return{event:{type:n,instanceId:o,text:a},bytesRead:t-r}}decodeSelect(e,t){let r=e.readUInt8(t),n=e.readUInt8(t+1),o=e.readUInt16BE(t+2);return{event:{type:r,instanceId:n,index:o},bytesRead:4}}};g(ft,"MacroEventDecoder");var Te=ft;F();function ze(m,e){let t=e.getAllAxes().length,r=e.getAllButtons().length,n=V(r),o=8+t+n+4;if(m.length<o)throw new Error(`Invalid compressed input packet: expected at least ${o} bytes (${t} axes + ${r} buttons), got ${m.length}`);let i=new DataView(m.buffer,m.byteOffset,m.byteLength),s=0,a=Re();a.tick=i.getBigUint64(s,!0),s+=8;for(let c=0;c<t;c++){let l=m[s],u=l>127?l-256:l,p=Pe(u);a.axes.set(c,p),s+=1}for(let c=0;c<n;c++){let l=m[s];for(let u=0;u<8;u++){let p=c*8+u;if(p<r){let h=(l&1<<u)!==0;a.buttons.set(p,h)}}s+=1}a.displayId=m[s],s+=1,a.mouseX=m[s],s+=1,a.mouseY=m[s],s+=1;let d=m[s];if(a.mouseOverDisplay=(d&1)!==0,s+=1,s<m.length){let c=m[s];s+=1;let l=new TextDecoder;a.textInputs=[];for(let u=0;u<c&&s<m.length;u++){let p=m[s];if(s+=1,s+p<=m.length){let h=m.slice(s,s+p),y=l.decode(h);a.textInputs.push(y),s+=p}}}if(s<m.length){let c=m[s];s+=1;let l=new Te,u=[],p=C.from(m);for(let h=0;h<c&&s<m.length;h++){let y=l.decode(p,s);u.push(y.event),s+=y.bytesRead}a.macroEvents=u}return a}g(ze,"decodeCompressedInput");var R=require("@utsp/types");var St=class St{constructor(e,t){b(this,"enabled",!1);b(this,"currentStats",null);b(this,"_userId");b(this,"_userName");this._userId=e,this._userName=t}setEnabled(e){this.enabled=e,e||(this.currentStats=null)}isEnabled(){return this.enabled}get userId(){return this.currentStats?.userId??this._userId}get userName(){return this.currentStats?.userName??this._userName}get tick(){return this.currentStats?.tick??0}get timestamp(){return this.currentStats?.timestamp??0}get displayCount(){return this.currentStats?.displayCount??0}get totalDisplayArea(){return this.currentStats?.totalDisplayArea??0}get totalLayers(){return this.currentStats?.totalLayers??0}get visibleLayers(){return this.currentStats?.visibleLayers??0}get staticLayers(){return this.currentStats?.staticLayers??0}get dynamicLayers(){return this.currentStats?.dynamicLayers??0}get totalOrders(){return this.currentStats?.totalOrders??0}get ordersByLayer(){return this.currentStats?.ordersByLayer??new Map}get staticPacketSize(){return this.currentStats?.staticPacketSize??0}get dynamicPacketSize(){return this.currentStats?.dynamicPacketSize??0}get totalPacketSize(){return this.currentStats?.totalPacketSize??0}get compressedPacketSize(){return Math.round(this.totalPacketSize*.25)}get hasInput(){return this.currentStats?.hasInput??!1}get axisCount(){return this.currentStats?.axisCount??0}get buttonCount(){return this.currentStats?.buttonCount??0}startTick(e){this.enabled&&(this.currentStats={userId:this._userId,userName:this._userName,tick:e,timestamp:Date.now(),displayCount:0,totalDisplayArea:0,totalLayers:0,visibleLayers:0,staticLayers:0,dynamicLayers:0,totalOrders:0,ordersByLayer:new Map,staticPacketSize:0,dynamicPacketSize:0,totalPacketSize:0,hasInput:!1,axisCount:0,buttonCount:0})}recordDisplays(e,t){!this.enabled||!this.currentStats||(this.currentStats.displayCount=e,this.currentStats.totalDisplayArea=t)}recordLayers(e,t,r,n){!this.enabled||!this.currentStats||(this.currentStats.totalLayers=e,this.currentStats.visibleLayers=t,this.currentStats.staticLayers=r,this.currentStats.dynamicLayers=n)}recordLayerOrders(e,t){!this.enabled||!this.currentStats||(this.currentStats.totalOrders+=t,this.currentStats.ordersByLayer.set(e,t))}recordPacketSizes(e,t){!this.enabled||!this.currentStats||(this.currentStats.staticPacketSize=e,this.currentStats.dynamicPacketSize=t,this.currentStats.totalPacketSize=e+t)}recordInput(e,t,r){!this.enabled||!this.currentStats||(this.currentStats.hasInput=e,this.currentStats.axisCount=t,this.currentStats.buttonCount=r)}endTick(){}reset(){this.currentStats=null}};g(St,"UserStats");var te=St;var vt=class vt{constructor(e,t,r){this.id=e;this.name=t;b(this,"displays",[]);b(this,"layers",[]);b(this,"spriteRegistry");b(this,"mode");b(this,"axes",new Map);b(this,"buttons",new Map);b(this,"textInputs",[]);b(this,"mouseX",0);b(this,"mouseY",0);b(this,"mouseOver",!1);b(this,"mouseDisplayId",0);b(this,"touchPositions",new Map);b(this,"activeTouchId",null);b(this,"inputBindings",new ee);b(this,"stats");b(this,"soundCommands",[]);b(this,"nextSoundInstanceId",1);b(this,"audioConfigCommands",[]);b(this,"lastListenerX",-1);b(this,"lastListenerY",-1);b(this,"pendingSendSounds",!1);b(this,"audioProcessor");b(this,"loadedSounds",new Map);b(this,"soundLoadErrors",new Map);b(this,"playingSounds",new Map);b(this,"macroRegistry",new q);b(this,"macroEngine",new Q);b(this,"macroEventHandlers",new Map);b(this,"postProcessCommands",[]);b(this,"currentPostProcessConfig",null);b(this,"data");b(this,"currentScalingMode",null);b(this,"currentGridConfig",null);this.mode=r,this.stats=new te(e,t),this.data={}}setSpriteRegistry(e){this.spriteRegistry=e;for(let t of this.layers)t.setSpriteRegistry(e);this.macroEngine.setSpriteRegistry(e)}getDisplays(){return this.displays}addDisplay(e){this.displays.push(e)}removeDisplay(e){let t=this.displays.indexOf(e);return t!==-1?(this.displays.splice(t,1),!0):!1}clearDisplays(){this.displays=[]}getLayers(){return this.layers}getLayerById(e){return this.layers.find(t=>t.getId()===e)}addLayer(e,t){e.setMode(this.mode);let r=this.layers.length+1;e.setId(r),this.layers.push(e),this.spriteRegistry&&e.setSpriteRegistry(this.spriteRegistry),t&&this.macroRegistry.setLayerMapping(t,e.getId())}removeLayer(e){let t=this.layers.indexOf(e);return t!==-1?(this.layers.splice(t,1),!0):!1}clearLayers(){this.layers=[]}setMousePosition(e,t,r=!0){this.mouseX=Math.max(0,Math.min(255,e)),this.mouseY=Math.max(0,Math.min(255,t)),this.mouseOver=r}setTouchPosition(e,t,r,n=!0,o=0){if(e<0||e>9){console.warn(`Invalid touchId ${e}, must be 0-9`);return}n?(this.touchPositions.set(e,{x:Math.max(0,Math.min(255,t)),y:Math.max(0,Math.min(255,r)),over:!0,displayId:o}),this.activeTouchId=e):(this.touchPositions.delete(e),this.activeTouchId===e&&(this.activeTouchId=null))}setAxis(e,t){let r=Math.max(-1,Math.min(1,t));this.axes.set(e,r)}getAxis(e){return this.axes.get(e)??0}setButton(e,t){this.buttons.set(e,t)}getButton(e){return this.buttons.get(e)??!1}getButtonJustPressed(e){let t=`${e}_justPressed`;return this.buttons.get(t)??!1}getButtonJustReleased(e){let t=`${e}_justReleased`;return this.buttons.get(t)??!1}setTextInputs(e){this.textInputs=e}getTextInputs(){return this.textInputs}clearTextInputs(){this.textInputs=[]}getAxisNames(){return Array.from(this.axes.keys())}getButtonNames(){return Array.from(this.buttons.keys())}clearAxes(){this.axes.clear()}clearButtons(){this.buttons.clear()}getMouseDisplayInfo(){if(!this.mouseOver||this.displays.length===0)return null;let e=this.displays[0],t=0,r=this.mouseX,n=this.mouseY,o=e.getOrigin(),i=o.x+r,s=o.y+n;return{displayId:t,localX:r,localY:n,worldX:i,worldY:s}}getTouchDisplayInfo(e=0){if(e<0||e>9)return console.warn(`Invalid touchId ${e}, must be 0-9`),null;let t=this.touchPositions.get(e);if(!t||!t.over||this.displays.length===0)return null;let r=this.displays[0],n=t.displayId,o=t.x,i=t.y,s=r.getOrigin(),a=s.x+o,d=s.y+i;return{displayId:n,localX:o,localY:i,worldX:a,worldY:d}}getIsMouseOnADisplay(){return this.mouseOver}getMouseDisplayHover(){let e=this.getMouseDisplayInfo();return e?e.displayId:null}findLayerById(e){return this.layers.find(t=>t.getId()===e)??null}applyUpdate(e){if(this.updateDisplaysFromPacket(e.displays),this.updateLayersFromPacket(e.layers),e.macroOrders&&e.macroOrders.length>0)for(let t of e.macroOrders)this.macroEngine.applyOrder(t)}updateDisplaysFromPacket(e){for(let t of e){let r=this.displays[t.id];if(!r){for(r=new Z(t.id,t.sizeX,t.sizeY);this.displays.length<=t.id;)this.displays.push(null);this.displays[t.id]=r}r.setOrigin(new R.Vector2(t.originX,t.originY)),r.setSize(new R.Vector2(t.sizeX,t.sizeY))}}updateLayersFromPacket(e){for(let t of e){let r=this.findLayerById(t.id);r||(r=new J(new R.Vector2(t.originX,t.originY),t.zIndex,t.width,t.height,!1),r.setId(t.id),r.setMode(this.mode),this.spriteRegistry&&r.setSpriteRegistry(this.spriteRegistry),this.addLayer(r)),t.updateFlags&1&&r.setOrigin(new R.Vector2(t.originX,t.originY)),t.updateFlags&2&&r.setZOrder(t.zIndex),t.updateFlags&4&&r.setOrders(t.orders)}}defineAxisBinding(e,t,r=[],n=-1,o=1,i=0){this.inputBindings.defineAxis(e,t,r,n,o,i)}defineButtonBinding(e,t,r=[],n=!1){this.inputBindings.defineButton(e,t,r,n)}defineAxisBindings(e){e.forEach(({bindingId:t,name:r,sources:n,min:o,max:i,defaultValue:s})=>{this.defineAxisBinding(t,r,n??[],o,i,s)})}defineButtonBindings(e){e.forEach(({bindingId:t,name:r,sources:n,defaultValue:o})=>{this.defineButtonBinding(t,r,n??[],o)})}getInputBindingsLoadPacket(){return this.inputBindings.toLoadPacket()}applyInputBindingsLoadPacket(e){try{let t=JSON.parse(e);if(t.type!=="input-binding")throw new Error(`Invalid packet type: ${t.type}`);for(let r of t.axes)this.defineAxisBinding(r.bindingId,r.name,r.sources||[],r.min,r.max,r.defaultValue);for(let r of t.buttons)this.defineButtonBinding(r.bindingId,r.name,r.sources||[],r.defaultValue)}catch(t){throw console.error("[User] Failed to apply input bindings:",t),t}}getInputBindingRegistry(){return this.inputBindings}getStats(){return this.stats}getAxisBindingId(e){return this.inputBindings.getAxisBindingId(e)}getButtonBindingId(e){return this.inputBindings.getButtonBindingId(e)}decodeAndApplyCompressedInput(e){let t=ze(e,this.inputBindings),r=this.inputBindings.getAllAxes(),n=this.inputBindings.getAllButtons(),o=r.sort((s,a)=>s.bindingId-a.bindingId),i=n.sort((s,a)=>s.bindingId-a.bindingId);for(let[s,a]of t.axes)if(s<o.length){let d=o[s];this.setAxis(d.name,a)}for(let[s,a]of t.buttons)if(s<i.length){let d=i[s];this.setButton(d.name,a)}this.mouseX=t.mouseX,this.mouseY=t.mouseY,this.mouseOver=t.mouseOverDisplay,this.mouseDisplayId=t.displayId}playSound(e,t){let r=this.nextSoundInstanceId++,n={sound:e,instanceId:r,volume:t?.volume,pitch:t?.pitch,loop:t?.loop,fadeIn:t?.fadeIn,x:t?.x,y:t?.y,lowpass:t?.lowpass,highpass:t?.highpass,reverb:t?.reverb};return this.soundCommands.push(n),r}stopSound(e){let t={sound:e};this.soundCommands.push(t)}fadeOutSound(e,t){let r={fadeOut:!0,sound:e,duration:t};this.soundCommands.push(r)}fadeOutAllSounds(e){let t={fadeOut:!0,sound:"all",duration:e};this.soundCommands.push(t)}stopAllSounds(){let e={sound:"all"};this.soundCommands.push(e)}pauseSound(e){let t={pause:!0,sound:e};this.soundCommands.push(t)}pauseAllSounds(){let e={pause:!0,sound:"all"};this.soundCommands.push(e)}resumeSound(e){let t={resume:!0,sound:e};this.soundCommands.push(t)}resumeAllSounds(){let e={resume:!0,sound:"all"};this.soundCommands.push(e)}setSoundEffects(e,t){let r={setEffects:!0,instanceId:e,lowpass:t.lowpass,highpass:t.highpass,reverb:t.reverb};this.soundCommands.push(r)}setListenerPosition(e,t){e===this.lastListenerX&&t===this.lastListenerY||(this.lastListenerX=e,this.lastListenerY=t,this.audioConfigCommands.push({type:"set-listener-position",x:e,y:t}))}configureSpatialAudio(e){this.audioConfigCommands.push({type:"configure-spatial",...e})}flushAudioConfigCommands(){let e=this.audioConfigCommands;return this.audioConfigCommands=[],e}hasAudioConfigCommands(){return this.audioConfigCommands.length>0}flushSoundCommands(){let e=this.soundCommands;return this.soundCommands=[],e}hasSoundCommands(){return this.soundCommands.length>0}sendSounds(){this.pendingSendSounds=!0}needsSendSounds(){return this.pendingSendSounds}clearSendSounds(){this.pendingSendSounds=!1}setAudioProcessor(e){this.audioProcessor=e,this.macroEngine.setAudioCallback(t=>{e.play(t)})}getAudioProcessor(){return this.audioProcessor}applyAudioCommands(e){if(this.audioProcessor&&this.mode!=="server")for(let t of e){if("setEffects"in t&&t.setEffects===!0){let n=t;this.audioProcessor.setEffects(n.instanceId,n.lowpass,n.highpass,n.reverb);continue}if("fadeOut"in t&&t.fadeOut===!0){let n=t;this.audioProcessor.fadeOut(n.sound,n.duration);continue}if("pause"in t&&t.pause===!0){let n=t;this.audioProcessor.pause(n.sound);continue}if("resume"in t&&t.resume===!0){let n=t;this.audioProcessor.resume(n.sound);continue}if("instanceId"in t||"volume"in t||"pitch"in t||"loop"in t||"fadeIn"in t||"x"in t||"y"in t||"lowpass"in t||"highpass"in t||"reverb"in t){let n=t,o=n.x!==void 0&&n.y!==void 0?{x:n.x,y:n.y}:void 0;this.audioProcessor.play(n.sound,{volume:n.volume,pitch:n.pitch,loop:n.loop,fadeIn:n.fadeIn,position:o,instanceId:n.instanceId,lowpass:n.lowpass,highpass:n.highpass,reverb:n.reverb})}else{let n=t;n.sound==="all"?this.audioProcessor.stopAll():this.audioProcessor.stop(n.sound)}}}applyAudioConfigCommands(e){if(this.audioProcessor&&this.mode!=="server")for(let t of e)t.type==="set-listener-position"?this.audioProcessor.setListenerPosition(t.x,t.y):t.type==="configure-spatial"&&this.audioProcessor.configureSpatial({maxDistance:t.maxDistance,referenceDistance:t.referenceDistance,rolloffFactor:t.rolloffFactor,panSpread:t.panSpread})}applyAudioOrders(e){if(!this.audioProcessor||this.mode==="server")return;let{AudioOrderType:t,AudioTargetType:r}=(Ut(),T(Mr)),{PlaySoundFlags:n}=(wt(),T(Er));for(let o of e)switch(o.type){case t.PlaySound:case t.PlayGlobalSound:{let i=o,s=i.volume!==void 0?i.volume/255:void 0,a=i.pitch!==void 0?.25*Math.pow(2,i.pitch/64):void 0,d=i.fadeIn!==void 0?i.fadeIn/10:void 0,c=(i.flags&n.Loop)!==0,l=i.posX!==void 0&&i.posY!==void 0?{x:i.posX,y:i.posY}:void 0;this.audioProcessor.play(i.soundId,{volume:s,pitch:a,loop:c,fadeIn:d,position:l,instanceId:i.instanceId,lowpass:i.lowpass,highpass:i.highpass,reverb:i.reverb});break}case t.StopSound:{let i=o;i.targetType===r.All?this.audioProcessor.stopAll():i.targetType===r.InstanceId?this.audioProcessor.stop(i.target):this.audioProcessor.stop(i.target);break}case t.FadeOutSound:{let i=o,s=i.duration/10;i.targetType===r.All?this.audioProcessor.fadeOut("all",s):this.audioProcessor.fadeOut(i.target,s);break}case t.PauseSound:{let i=o;i.targetType===r.All?this.audioProcessor.pause("all"):this.audioProcessor.pause(i.target);break}case t.ResumeSound:{let i=o;i.targetType===r.All?this.audioProcessor.resume("all"):this.audioProcessor.resume(i.target);break}case t.SetListenerPosition:{let i=o;this.audioProcessor.setListenerPosition(i.x,i.y);break}case t.ConfigureSpatial:{let i=o;this.audioProcessor.configureSpatial({maxDistance:i.maxDistance*100,referenceDistance:i.referenceDistance*100,rolloffFactor:i.rolloffFactor/100,panSpread:i.panSpread/255});break}case t.SetSoundEffects:{let i=o;this.audioProcessor.setEffects(i.instanceId,i.lowpass,i.highpass,i.reverb);break}}}handleAudioAck(e){switch(e.type){case"sound-loaded":this.loadedSounds.set(e.soundId,{name:e.name,loadedAt:Date.now()}),this.soundLoadErrors.delete(e.soundId);break;case"sound-error":this.soundLoadErrors.set(e.soundId,{name:e.name,error:e.error,at:Date.now()});break;case"playback-started":this.playingSounds.set(e.instanceId,{soundId:e.soundId,startedAt:Date.now()});break;case"playback-ended":this.playingSounds.delete(e.instanceId);break;case"playback-error":e.instanceId!==void 0&&this.playingSounds.delete(e.instanceId);break}}isSoundLoaded(e){return this.loadedSounds.has(e)}getSoundLoadError(e){return this.soundLoadErrors.get(e)?.error}getLoadedSounds(){return this.loadedSounds}getSoundLoadErrors(){return this.soundLoadErrors}isSoundPlaying(e){return this.playingSounds.has(e)}getPlayingSounds(){return this.playingSounds}getPlayingSoundCount(){return this.playingSounds.size}loadMacro(e,t){let r={...t,id:e},n=this.macroRegistry.registerMacro(r);return this.mode==="client"&&this.macroEngine.loadTemplate(n,r),n}createInstance(e){return this.updateLayerMappings(),this.macroRegistry.createInstance(e)}updateInstance(e,t){return this.macroRegistry.updateInstance(e,t)}removeInstance(e){return this.macroEventHandlers.delete(e),this.macroRegistry.removeInstance(e)}onMacroEvent(e,t,r){this.macroEventHandlers.has(e)||this.macroEventHandlers.set(e,new Map),this.macroEventHandlers.get(e).set(t,r)}offMacroEvent(e,t){t?this.macroEventHandlers.get(e)?.delete(t):this.macroEventHandlers.delete(e)}handleMacroEvent(e){let t=this.macroRegistry.getInstanceName(e.instanceId);if(!t){console.warn(`MacroEvent: Unknown instance ID ${e.instanceId}`);return}let r=this.macroEventHandlers.get(t);if(!r)return;let n,o;switch(e.type){case 1:n="click",o=void 0;break;case 2:n="change",o=e.value;break;case 3:n="submit",o=e.text;break;case 4:n="select",o=e.index;break;default:return}let i=r.get(n);i&&i(o)}flushMacroOrders(){return this.macroRegistry.flushPendingOrders()}hasPendingMacroOrders(){return this.macroRegistry.hasPendingOrders()}applyMacroOrders(e){for(let t of e)this.macroEngine.applyOrder(t)}getMacroRegistry(){return this.macroRegistry}getMacroLoads(){return this.macroRegistry.toAllMacroLoads()}updateLayerMappings(){for(let e of this.layers){let t=e.getId()}}registerLayerName(e,t){this.macroRegistry.setLayerMapping(e,t.getId())}loadMacroTemplate(e,t){this.macroEngine.loadTemplate(e,t)}updateMacros(){return this.macroEngine.update()}processMacroEvents(e){for(let t of e.events){let r=this.macroRegistry.getInstanceName(t.instanceId);if(!r)continue;let n=this.macroEventHandlers.get(r);if(!n)continue;let o=n.get(t.event);o&&o(t.data)}}updateMacroMouse(e,t,r){let n=this.displays.find(o=>o.getId()===this.mouseDisplayId);if(!n&&this.displays.length>0&&(n=this.displays[0]),n){let o=n.getOrigin(),i=e+o.x,s=t+o.y;this.macroEngine.updateMouse(i,s,r)}else this.macroEngine.updateMouse(e,t,r)}getMacroRenderOrders(){let e=this.macroEngine.getOrdersByLayer(),t=this.displays[0];if(!t)return e;let r=t.getOrigin();if(r.x===0&&r.y===0)return e;let n=new Map;for(let[o,i]of e){let s=i.map(a=>{let d={...a};return"posX"in d&&typeof d.posX=="number"&&(d.posX=d.posX-r.x),"posY"in d&&typeof d.posY=="number"&&(d.posY=d.posY-r.y),d});n.set(o,s)}return n}getMacroEffectOffset(){return this.macroEngine.getEffectOffset()}getMacroEngine(){return this.macroEngine}macroFocusNext(){this.macroEngine.focusNext()}macroFocusPrevious(){this.macroEngine.focusPrevious()}macroActivateFocused(){this.macroEngine.activateFocused()}setPostProcess(e){let t=JSON.stringify(e),r=JSON.stringify(this.currentPostProcessConfig);t!==r&&(this.currentPostProcessConfig=e,this.postProcessCommands.push({type:"set-config",config:e??void 0}))}setScanlinesEnabled(e){if(e){let t=this.currentPostProcessConfig?.scanlines;this.setPostProcess({scanlines:{enabled:!0,opacity:t?.opacity??R.POST_PROCESS_DEFAULTS.scanlines.opacity,pattern:t?.pattern??R.POST_PROCESS_DEFAULTS.scanlines.pattern,color:t?.color??R.POST_PROCESS_DEFAULTS.scanlines.color}})}else this.setPostProcess({scanlines:{enabled:!1}})}setScanlinesOpacity(e){let t=Math.max(0,Math.min(1,e)),r=this.currentPostProcessConfig?.scanlines;this.setPostProcess({scanlines:{enabled:!0,opacity:t,pattern:r?.pattern??"horizontal",color:r?.color??{r:0,g:0,b:0}}})}setScanlinesPattern(e){let t=this.currentPostProcessConfig?.scanlines;this.setPostProcess({scanlines:{enabled:t?.enabled??!0,opacity:t?.opacity??R.POST_PROCESS_DEFAULTS.scanlines.opacity,pattern:e,color:t?.color??{r:0,g:0,b:0}}})}setAmbientEffect(e){let t=this.currentPostProcessConfig?.ambientEffect;typeof e=="boolean"?this.setPostProcess({...this.currentPostProcessConfig,ambientEffect:{enabled:e,blur:t?.blur??R.POST_PROCESS_DEFAULTS.ambientEffect.blur,scale:t?.scale??R.POST_PROCESS_DEFAULTS.ambientEffect.scale}}):this.setPostProcess({...this.currentPostProcessConfig,ambientEffect:{enabled:!0,blur:e.blur??t?.blur??R.POST_PROCESS_DEFAULTS.ambientEffect.blur,scale:e.scale??t?.scale??R.POST_PROCESS_DEFAULTS.ambientEffect.scale}})}setAmbientEffectEnabled(e){this.setAmbientEffect(e)}setAmbientEffectBlur(e){let t=this.currentPostProcessConfig?.ambientEffect;this.setPostProcess({...this.currentPostProcessConfig,ambientEffect:{enabled:t?.enabled??!0,blur:Math.max(0,e),scale:t?.scale??R.POST_PROCESS_DEFAULTS.ambientEffect.scale}})}setAmbientEffectScale(e){let t=this.currentPostProcessConfig?.ambientEffect;this.setPostProcess({...this.currentPostProcessConfig,ambientEffect:{enabled:t?.enabled??!0,blur:t?.blur??R.POST_PROCESS_DEFAULTS.ambientEffect.blur,scale:Math.max(1,e)}})}isAmbientEffectEnabled(){return this.currentPostProcessConfig?.ambientEffect?.enabled??!1}getAmbientEffectConfig(){let e=this.currentPostProcessConfig?.ambientEffect;return e?{enabled:e.enabled,blur:e.blur??R.POST_PROCESS_DEFAULTS.ambientEffect.blur,scale:e.scale??R.POST_PROCESS_DEFAULTS.ambientEffect.scale}:null}getPostProcessConfig(){return this.currentPostProcessConfig}hasPostProcessCommands(){return this.postProcessCommands.length>0}flushPostProcessCommands(){let e=this.postProcessCommands;return this.postProcessCommands=[],e}setScalingMode(e){this.currentScalingMode!==e&&(this.currentScalingMode=e,this.postProcessCommands.push({type:"set-scaling-mode",scalingMode:e}))}getScalingMode(){return this.currentScalingMode}setGrid(e){let t;typeof e=="boolean"?t={enabled:e,color:R.GRID_DEFAULTS.color,lineWidth:R.GRID_DEFAULTS.lineWidth}:t={enabled:e.enabled,color:e.color??R.GRID_DEFAULTS.color,lineWidth:e.lineWidth??R.GRID_DEFAULTS.lineWidth},this.currentGridConfig=t,this.postProcessCommands.push({type:"set-grid",gridConfig:t})}setGridEnabled(e){this.setGrid(e)}isGridEnabled(){return this.currentGridConfig?.enabled??!1}getGridConfig(){return this.currentGridConfig}};g(vt,"User");var re=vt;F();var Mt=class Mt{encode(e){switch(e.type){case 1:return this.encodeCharOrder(e);case 2:return this.encodeTextOrder(e);case 23:return this.encodeTextMultilineOrder(e);case 3:return this.encodeSubFrameOrder(e);case 4:return this.encodeSubFrameMultiColorOrder(e);case 5:return this.encodeFullFrameOrder(e);case 6:return this.encodeFullFrameMultiColorOrder(e);case 7:return this.encodeSpriteOrder(e);case 8:return this.encodeSpriteMultiColorOrder(e);case 9:return this.encodeColorMapOrder(e);case 10:return this.encodeShapeOrder(e);case 11:return this.encodeDotCloudOrder(e);case 12:return this.encodeDotCloudMultiColorOrder(e);case 17:return this.encodeBitmaskOrder(e);case 18:return this.encodeBitmask4Order(e);case 24:return this.encodeBitmask16Order(e);case 25:return this.encodePolylineOrder(e);case 13:return this.encodeSpriteCloudOrder(e);case 14:return this.encodeSpriteCloudMultiColorOrder(e);case 15:return this.encodeSpriteCloudVariedOrder(e);case 16:return this.encodeSpriteCloudVariedMultiColorOrder(e);case 19:return this.encodeClearOrder(e);case 20:return this.encodeFillCharOrder(e);case 21:return this.encodeFillSpriteOrder(e);case 22:return this.encodeFillSpriteMultiColorOrder(e);case 32:return this.encodeTriggerSoundOrder(e);case 33:return this.encodeTriggerGlobalSoundOrder(e);default:throw new Error(`Unknown order type: ${e.type}`)}}encodeCharOrder(e){let t=C.allocUnsafe(6),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.posX,r++),t.writeUInt8(e.posY,r++),t.writeUInt8(e.charCode,r++),t.writeUInt8(e.bgColorCode,r++),t.writeUInt8(e.fgColorCode,r++),t.toUint8Array()}encodeTextOrder(e){let t=new TextEncoder().encode(e.text),r=C.allocUnsafe(6+t.length),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(t.length,n++);for(let o=0;o<t.length;o++)r.writeUInt8(t[o],n++);return r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.toUint8Array()}encodeTextMultilineOrder(e){let t=new TextEncoder().encode(e.text),r=C.allocUnsafe(6+t.length),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(t.length,n++);for(let o=0;o<t.length;o++)r.writeUInt8(t[o],n++);return r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.toUint8Array()}encodeSubFrameOrder(e){let t=e.sizeX*e.sizeY,r=C.allocUnsafe(7+t),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(e.sizeX,n++),r.writeUInt8(e.sizeY,n++),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++);for(let o of e.frame)r.writeUInt8(o,n++);return r.toUint8Array()}encodeSubFrameMultiColorOrder(e){let t=e.sizeX*e.sizeY,r=C.allocUnsafe(5+t*3),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(e.sizeX,n++),r.writeUInt8(e.sizeY,n++);for(let o of e.frame)r.writeUInt8(o.charCode,n++),r.writeUInt8(o.bgColorCode,n++),r.writeUInt8(o.fgColorCode,n++);return r.toUint8Array()}encodeFullFrameOrder(e){let t=e.frame.length,r=C.allocUnsafe(3+t),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++);for(let o of e.frame)r.writeUInt8(o,n++);return r.toUint8Array()}encodeFullFrameMultiColorOrder(e){let t=e.frame.length,r=C.allocUnsafe(1+t*3),n=0;r.writeUInt8(e.type,n++);for(let o of e.frame)r.writeUInt8(o.charCode,n++),r.writeUInt8(o.bgColorCode,n++),r.writeUInt8(o.fgColorCode,n++);return r.toUint8Array()}encodeSpriteOrder(e){let t=C.allocUnsafe(6),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.posX,r++),t.writeUInt8(e.posY,r++),t.writeUInt8(e.spriteIndex,r++),t.writeUInt8(e.bgColorCode,r++),t.writeUInt8(e.fgColorCode,r++),t.toUint8Array()}encodeSpriteMultiColorOrder(e){let t=C.allocUnsafe(4),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.posX,r++),t.writeUInt8(e.posY,r++),t.writeUInt8(e.spriteIndex,r++),t.toUint8Array()}encodeColorMapOrder(e){let t=e.sizeX*e.sizeY,r=C.allocUnsafe(5+t*2),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(e.sizeX,n++),r.writeUInt8(e.sizeY,n++);for(let o of e.colorData)r.writeUInt8(o.bgColorCode,n++),r.writeUInt8(o.fgColorCode,n++);return r.toUint8Array()}encodeShapeOrder(e){let t=this.encodeShapeData(e.shapeType,e.shapeData),r=C.allocUnsafe(2+t.length),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.shapeType,n++);for(let o=0;o<t.length;o++)r.writeUInt8(t[o],n++);return r.toUint8Array()}encodeShapeData(e,t){switch(e){case 1:{let r=C.allocUnsafe(8),n=0;return r.writeUInt8(t.posX,n++),r.writeUInt8(t.posY,n++),r.writeUInt8(t.width,n++),r.writeUInt8(t.height,n++),r.writeUInt8(t.filled?1:0,n++),r.writeUInt8(t.charCode,n++),r.writeUInt8(t.bgColorCode,n++),r.writeUInt8(t.fgColorCode,n++),r.toUint8Array()}case 2:{let r=C.allocUnsafe(7),n=0;return r.writeUInt8(t.centerX,n++),r.writeUInt8(t.centerY,n++),r.writeUInt8(t.radius,n++),r.writeUInt8(t.filled?1:0,n++),r.writeUInt8(t.charCode,n++),r.writeUInt8(t.bgColorCode,n++),r.writeUInt8(t.fgColorCode,n++),r.toUint8Array()}case 3:{let r=C.allocUnsafe(7),n=0;return r.writeUInt8(t.x1,n++),r.writeUInt8(t.y1,n++),r.writeUInt8(t.x2,n++),r.writeUInt8(t.y2,n++),r.writeUInt8(t.charCode,n++),r.writeUInt8(t.bgColorCode,n++),r.writeUInt8(t.fgColorCode,n++),r.toUint8Array()}case 4:{let r=C.allocUnsafe(8),n=0;return r.writeUInt8(t.centerX,n++),r.writeUInt8(t.centerY,n++),r.writeUInt8(t.radiusX,n++),r.writeUInt8(t.radiusY,n++),r.writeUInt8(t.filled?1:0,n++),r.writeUInt8(t.charCode,n++),r.writeUInt8(t.bgColorCode,n++),r.writeUInt8(t.fgColorCode,n++),r.toUint8Array()}case 5:{let r=C.allocUnsafe(10),n=0;return r.writeUInt8(t.x1,n++),r.writeUInt8(t.y1,n++),r.writeUInt8(t.x2,n++),r.writeUInt8(t.y2,n++),r.writeUInt8(t.x3,n++),r.writeUInt8(t.y3,n++),r.writeUInt8(t.filled?1:0,n++),r.writeUInt8(t.charCode,n++),r.writeUInt8(t.bgColorCode,n++),r.writeUInt8(t.fgColorCode,n++),r.toUint8Array()}default:throw new Error(`Unknown shape type: ${e}`)}}encodeDotCloudOrder(e){let t=e.positions.length,r=C.allocUnsafe(6+t*2),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.charCode,n++),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.positions)r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeDotCloudMultiColorOrder(e){let t=e.dots.length,r=C.allocUnsafe(5+t*5),n=0;r.writeUInt8(e.type,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.dots)r.writeUInt8(o.charCode,n++),r.writeUInt8(o.bgColorCode,n++),r.writeUInt8(o.fgColorCode,n++),r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeBitmaskOrder(e){let t=e.mask.length,r=C.allocUnsafe(9+t),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(e.sizeX,n++),r.writeUInt8(e.sizeY,n++),r.writeUInt8(e.charCode,n++),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.writeUInt8(e.override?1:0,n++);for(let o=0;o<t;o++)r.writeUInt8(e.mask[o],n++);return r.toUint8Array()}encodeBitmask4Order(e){let t=e.mask.length,r=C.allocUnsafe(15+t),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(e.sizeX,n++),r.writeUInt8(e.sizeY,n++),r.writeUInt8(e.override?1:0,n++);for(let o of e.variants)r.writeUInt8(o.charCode,n++),r.writeUInt8(o.bgColorCode,n++),r.writeUInt8(o.fgColorCode,n++);for(let o=0;o<t;o++)r.writeUInt8(e.mask[o],n++);return r.toUint8Array()}encodeBitmask16Order(e){let t=e.mask.length,r=C.allocUnsafe(51+t),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(e.sizeX,n++),r.writeUInt8(e.sizeY,n++),r.writeUInt8(e.override?1:0,n++);for(let o of e.variants)r.writeUInt8(o.charCode,n++),r.writeUInt8(o.bgColorCode,n++),r.writeUInt8(o.fgColorCode,n++);for(let o=0;o<t;o++)r.writeUInt8(e.mask[o],n++);return r.toUint8Array()}encodePolylineOrder(e){let t=e.points.length,r=C.allocUnsafe(5+t*2),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.charCode,n++),r.writeUInt8(e.fgColorCode,n++),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(t,n++);for(let o of e.points)r.writeUInt8(o.x,n++),r.writeUInt8(o.y,n++);return r.toUint8Array()}encodeSpriteCloudOrder(e){let t=e.positions.length,r=C.allocUnsafe(8+t*2),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.spriteIndex,n++),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.positions)r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeSpriteCloudMultiColorOrder(e){let t=e.positions.length,r=C.allocUnsafe(6+t*2),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.spriteIndex,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.positions)r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeSpriteCloudVariedOrder(e){let t=e.sprites.length,r=C.allocUnsafe(3+t*5),n=0;r.writeUInt8(e.type,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.sprites)r.writeUInt8(o.spriteIndex,n++),r.writeUInt8(o.bgColorCode,n++),r.writeUInt8(o.fgColorCode,n++),r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeSpriteCloudVariedMultiColorOrder(e){let t=e.sprites.length,r=C.allocUnsafe(3+t*3),n=0;r.writeUInt8(e.type,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.sprites)r.writeUInt8(o.spriteIndex,n++),r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeClearOrder(e){let t=C.allocUnsafe(4),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.charCode,r++),t.writeUInt8(e.bgColorCode,r++),t.writeUInt8(e.fgColorCode,r++),t.toUint8Array()}encodeFillCharOrder(e){let t=e.patternWidth*e.patternHeight,r=C.allocUnsafe(5+t),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.patternWidth,n++),r.writeUInt8(e.patternHeight,n++),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++);for(let o of e.pattern)r.writeUInt8(o,n++);return r.toUint8Array()}encodeFillSpriteOrder(e){let t=C.allocUnsafe(4),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.spriteIndex,r++),t.writeUInt8(e.bgColorCode,r++),t.writeUInt8(e.fgColorCode,r++),t.toUint8Array()}encodeFillSpriteMultiColorOrder(e){let t=C.allocUnsafe(2),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.spriteIndex,r++),t.toUint8Array()}encodeTriggerSoundOrder(e){let t=C.allocUnsafe(5),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.posX,r++),t.writeUInt8(e.posY,r++),t.writeUInt8(e.soundId,r++),t.writeUInt8(e.loop?1:0,r++),t.toUint8Array()}encodeTriggerGlobalSoundOrder(e){let t=C.allocUnsafe(3),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.soundId,r++),t.writeUInt8(e.loop?1:0,r++),t.toUint8Array()}};g(Mt,"OrderEncoder");var Ye=Mt;F();var At=class At{constructor(){b(this,"orderEncoder");this.orderEncoder=new Ye}encode(e){let t=e.orders.map(a=>this.orderEncoder.encode(a)),r=13,n=t.reduce((a,d)=>a+d.length,0),o=r+n,i=C.allocUnsafe(o),s=0;i.writeUInt16BE(e.id,s),s+=2,i.writeUInt8(e.updateFlags,s++),i.writeUInt8(e.zIndex,s++),i.writeUInt16BE(e.originX,s),s+=2,i.writeUInt16BE(e.originY,s),s+=2,i.writeUInt16BE(e.width,s),s+=2,i.writeUInt16BE(e.height,s),s+=2,i.writeUInt8(e.orders.length,s++);for(let a of t)C.from(a).copy(i,s),s+=a.length;return i.toUint8Array()}calculateSize(e){return 13+e.orders.reduce((n,o)=>n+this.orderEncoder.encode(o).length,0)}};g(At,"LayerEncoder");var Xe=At;F();var Et=class Et{encode(e){switch(e.type){case 1:return this.encodePlaySoundOrder(e);case 2:return this.encodePlayGlobalSoundOrder(e);case 3:return this.encodeStopSoundOrder(e);case 4:return this.encodeFadeOutSoundOrder(e);case 5:return this.encodePauseSoundOrder(e);case 6:return this.encodeResumeSoundOrder(e);case 7:return this.encodeSetListenerPositionOrder(e);case 8:return this.encodeConfigureSpatialOrder(e);case 9:return this.encodeSetSoundEffectsOrder(e);default:throw new Error(`Unknown audio order type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return this.calculatePlaySoundSize(e);case 2:return this.calculatePlayGlobalSoundSize(e);case 3:case 5:case 6:return this.calculateTargetOrderSize(e);case 4:return this.calculateFadeOutSize(e);case 7:return 5;case 8:return 5;case 9:return this.calculateSetSoundEffectsSize(e);default:throw new Error(`Unknown audio order type: ${e.type}`)}}encodePlaySoundOrder(e){let t=this.calculatePlaySoundSize(e),r=C.allocUnsafe(t),n=0;return r.writeUInt8(e.type,n++),r.writeUInt8(e.soundId,n++),r.writeUInt16BE(e.instanceId,n),n+=2,r.writeUInt8(e.flags,n++),e.flags&2&&r.writeUInt8(e.volume??255,n++),e.flags&4&&r.writeUInt8(e.pitch??128,n++),e.flags&8&&r.writeUInt8(e.fadeIn??0,n++),e.flags&16&&(r.writeUInt16BE(e.posX??0,n),n+=2,r.writeUInt16BE(e.posY??0,n),n+=2),e.flags&32&&r.writeUInt8(e.lowpass??0,n++),e.flags&64&&r.writeUInt8(e.highpass??0,n++),e.flags&128&&r.writeUInt8(e.reverb??0,n++),r.toUint8Array()}encodePlayGlobalSoundOrder(e){let t=this.calculatePlayGlobalSoundSize(e),r=C.allocUnsafe(t),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.soundId,n++),r.writeUInt16BE(e.instanceId,n),n+=2;let o=e.flags&-17;return r.writeUInt8(o,n++),o&2&&r.writeUInt8(e.volume??255,n++),o&4&&r.writeUInt8(e.pitch??128,n++),o&8&&r.writeUInt8(e.fadeIn??0,n++),o&32&&r.writeUInt8(e.lowpass??0,n++),o&64&&r.writeUInt8(e.highpass??0,n++),o&128&&r.writeUInt8(e.reverb??0,n++),r.toUint8Array()}calculatePlaySoundSize(e){let t=5;return e.flags&2&&(t+=1),e.flags&4&&(t+=1),e.flags&8&&(t+=1),e.flags&16&&(t+=4),e.flags&32&&(t+=1),e.flags&64&&(t+=1),e.flags&128&&(t+=1),t}calculatePlayGlobalSoundSize(e){let t=5,r=e.flags&-17;return r&2&&(t+=1),r&4&&(t+=1),r&8&&(t+=1),r&32&&(t+=1),r&64&&(t+=1),r&128&&(t+=1),t}encodeStopSoundOrder(e){return this.encodeTargetOrder(e.type,e.targetType,e.target)}encodePauseSoundOrder(e){return this.encodeTargetOrder(e.type,e.targetType,e.target)}encodeResumeSoundOrder(e){return this.encodeTargetOrder(e.type,e.targetType,e.target)}encodeFadeOutSoundOrder(e){let t=this.calculateFadeOutSize(e),r=C.allocUnsafe(t),n=0;return r.writeUInt8(e.type,n++),r.writeUInt8(e.targetType,n++),r.writeUInt8(e.duration,n++),e.targetType===0?r.writeUInt16BE(e.target??0,n):e.targetType===1&&r.writeUInt8(e.target??0,n),r.toUint8Array()}encodeTargetOrder(e,t,r){let n=2;t===0?n+=2:t===1&&(n+=1);let o=C.allocUnsafe(n),i=0;return o.writeUInt8(e,i++),o.writeUInt8(t,i++),t===0?o.writeUInt16BE(r??0,i):t===1&&o.writeUInt8(r??0,i),o.toUint8Array()}calculateTargetOrderSize(e){let t=2;return e.targetType===0?t+=2:e.targetType===1&&(t+=1),t}calculateFadeOutSize(e){let t=3;return e.targetType===0?t+=2:e.targetType===1&&(t+=1),t}encodeSetListenerPositionOrder(e){let t=C.allocUnsafe(5),r=0;return t.writeUInt8(e.type,r++),t.writeUInt16BE(e.x,r),r+=2,t.writeUInt16BE(e.y,r),t.toUint8Array()}encodeConfigureSpatialOrder(e){let t=C.allocUnsafe(5),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.maxDistance,r++),t.writeUInt8(e.referenceDistance,r++),t.writeUInt8(e.rolloffFactor,r++),t.writeUInt8(e.panSpread,r++),t.toUint8Array()}encodeSetSoundEffectsOrder(e){let t=this.calculateSetSoundEffectsSize(e),r=C.allocUnsafe(t),n=0;return r.writeUInt8(e.type,n++),r.writeUInt16BE(e.instanceId,n),n+=2,r.writeUInt8(e.flags,n++),e.flags&1&&r.writeUInt8(e.lowpass??0,n++),e.flags&2&&r.writeUInt8(e.highpass??0,n++),e.flags&4&&r.writeUInt8(e.reverb??0,n++),r.toUint8Array()}calculateSetSoundEffectsSize(e){let t=4;return e.flags&1&&(t+=1),e.flags&2&&(t+=1),e.flags&4&&(t+=1),t}};g(Et,"AudioOrderEncoder");var Ne=Et;F();var Rt=class Rt{encode(e){switch(e.type){case 1:return this.encodeCreateInstance(e);case 2:return this.encodeUpdateInstance(e);case 3:return this.encodeRemoveInstance(e);default:throw new Error(`Unknown macro order type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return this.calculateCreateInstanceSize(e);case 2:return this.calculateUpdateInstanceSize(e);case 3:return 2;default:throw new Error(`Unknown macro order type: ${e.type}`)}}encodeCreateInstance(e){let t=JSON.stringify(e.params),r=new TextEncoder().encode(t);if(r.length>65535)throw new Error(`Params JSON too large: ${r.length} bytes (max 65535)`);let n=11+r.length,o=C.allocUnsafe(n),i=0;return o.writeUInt8(e.type,i++),o.writeUInt8(e.instanceId,i++),o.writeUInt8(e.macroId,i++),o.writeUInt8(e.layerId,i++),o.writeInt16BE(e.x,i),i+=2,o.writeInt16BE(e.y,i),i+=2,o.writeUInt8(e.tabIndex,i++),o.writeUInt16BE(r.length,i),i+=2,o.toUint8Array().set(r,i),o.toUint8Array()}calculateCreateInstanceSize(e){let t=JSON.stringify(e.params);return 11+new TextEncoder().encode(t).length}encodeUpdateInstance(e){let t=JSON.stringify(e.params),r=new TextEncoder().encode(t);if(r.length>65535)throw new Error(`Params JSON too large: ${r.length} bytes (max 65535)`);let n=4+r.length,o=C.allocUnsafe(n),i=0;return o.writeUInt8(e.type,i++),o.writeUInt8(e.instanceId,i++),o.writeUInt16BE(r.length,i),i+=2,o.toUint8Array().set(r,i),o.toUint8Array()}calculateUpdateInstanceSize(e){let t=JSON.stringify(e.params);return 4+new TextEncoder().encode(t).length}encodeRemoveInstance(e){let t=C.allocUnsafe(2);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.toUint8Array()}};g(Rt,"MacroOrderEncoder");var _e=Rt;F();var Bt=class Bt{encode(e){switch(e.type){case 1:return this.encodeSetConfigOrder(e);case 2:return this.encodeSetScanlinesOrder(e);case 3:return this.encodeSetAmbientEffectOrder(e);case 4:return this.encodeSetScalingModeOrder(e);case 5:return this.encodeSetGridOrder(e);default:throw new Error(`Unknown post-process order type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return this.calculateSetConfigSize(e);case 2:return 7;case 3:return 5;case 4:return 2;case 5:return 7;default:throw new Error(`Unknown post-process order type: ${e.type}`)}}encodeSetConfigOrder(e){let t=this.calculateSetConfigSize(e),r=C.allocUnsafe(t),n=0;return r.writeUInt8(e.type,n++),r.writeUInt8(e.flags,n++),e.flags&1&&e.scanlines&&(r.writeUInt8(e.scanlines.enabled?1:0,n++),r.writeUInt8(Math.round(e.scanlines.opacity*255),n++),r.writeUInt8(e.scanlines.pattern,n++),r.writeUInt8(e.scanlines.colorR,n++),r.writeUInt8(e.scanlines.colorG,n++),r.writeUInt8(e.scanlines.colorB,n++)),e.flags&2&&e.ambientEffect&&(r.writeUInt8(e.ambientEffect.enabled?1:0,n++),r.writeUInt8(Math.min(255,Math.round(e.ambientEffect.blur)),n++),r.writeUInt8(Math.min(255,Math.max(100,Math.round(e.ambientEffect.scale*100))),n++),r.writeUInt8(Math.round(e.ambientEffect.opacity*255),n++)),r.toUint8Array()}calculateSetConfigSize(e){let t=2;return e.flags&1&&(t+=6),e.flags&2&&(t+=4),t}encodeSetScanlinesOrder(e){let t=C.allocUnsafe(7),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.enabled?1:0,r++),t.writeUInt8(Math.round(e.opacity*255),r++),t.writeUInt8(e.pattern,r++),t.writeUInt8(e.colorR,r++),t.writeUInt8(e.colorG,r++),t.writeUInt8(e.colorB,r++),t.toUint8Array()}encodeSetAmbientEffectOrder(e){let t=C.allocUnsafe(5),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.enabled?1:0,r++),t.writeUInt8(Math.min(255,Math.round(e.blur)),r++),t.writeUInt8(Math.min(255,Math.max(100,Math.round(e.scale*100))),r++),t.writeUInt8(Math.round(e.opacity*255),r++),t.toUint8Array()}encodeSetScalingModeOrder(e){let t=C.allocUnsafe(2),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.mode,r++),t.toUint8Array()}encodeSetGridOrder(e){let t=C.allocUnsafe(7),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.enabled?1:0,r++),t.writeUInt8(e.colorR,r++),t.writeUInt8(e.colorG,r++),t.writeUInt8(e.colorB,r++),t.writeUInt8(e.colorA,r++),t.writeUInt8(Math.min(10,Math.max(1,e.lineWidth)),r++),t.toUint8Array()}};g(Bt,"PostProcessOrderEncoder");var He=Bt;F();var Tt=class Tt{constructor(){b(this,"layerEncoder");b(this,"audioOrderEncoder");b(this,"macroOrderEncoder");b(this,"postProcessOrderEncoder");this.layerEncoder=new Xe,this.audioOrderEncoder=new Ne,this.macroOrderEncoder=new _e,this.postProcessOrderEncoder=new He}encode(e){let t=e.layers.map(f=>this.layerEncoder.encode(f)),r=e.audioOrders||[],n=r.map(f=>this.audioOrderEncoder.encode(f)),o=e.macroOrders||[],i=o.map(f=>this.macroOrderEncoder.encode(f)),s=e.postProcessOrders||[],a=s.map(f=>this.postProcessOrderEncoder.encode(f)),d=9,c=e.displays.length*7,l=2,u=t.reduce((f,k)=>f+k.length,0),p=1,h=n.reduce((f,k)=>f+k.length,0),y=1,x=i.reduce((f,k)=>f+k.length,0),v=1,U=a.reduce((f,k)=>f+k.length,0),S=d+c+l+u+p+h+y+x+v+U,w=C.allocUnsafe(S),I=0,M=typeof e.tick=="bigint"?e.tick:BigInt(e.tick);w.writeBigUInt64BE(M,I),I+=8,w.writeUInt8(e.displays.length,I),I+=1;for(let f of e.displays)w.writeUInt8(f.id,I++),w.writeUInt16BE(f.originX,I),I+=2,w.writeUInt16BE(f.originY,I),I+=2,w.writeUInt8(Math.max(1,Math.min(256,f.sizeX))-1,I++),w.writeUInt8(Math.max(1,Math.min(256,f.sizeY))-1,I++);w.writeUInt16BE(e.layers.length,I),I+=2;for(let f of t)C.from(f).copy(w,I),I+=f.length;w.writeUInt8(r.length,I),I+=1;for(let f of n)C.from(f).copy(w,I),I+=f.length;w.writeUInt8(o.length,I),I+=1;for(let f of i)C.from(f).copy(w,I),I+=f.length;w.writeUInt8(s.length,I),I+=1;for(let f of a)C.from(f).copy(w,I),I+=f.length;return w.toUint8Array()}calculateSize(e){let r=e.displays.length*7,n=2,o=e.layers.reduce((y,x)=>y+this.layerEncoder.calculateSize(x),0),i=1,a=(e.audioOrders||[]).reduce((y,x)=>y+this.audioOrderEncoder.calculateSize(x),0),d=1,l=(e.macroOrders||[]).reduce((y,x)=>y+this.macroOrderEncoder.calculateSize(x),0),u=1,h=(e.postProcessOrders||[]).reduce((y,x)=>y+this.postProcessOrderEncoder.calculateSize(x),0);return 9+r+n+o+i+a+d+l+u+h}static createEmptyPacket(e){return{tick:typeof e=="bigint"?Number(e):e,displayCount:0,displays:[],layerCount:0,layers:[],audioOrderCount:0,audioOrders:[],macroOrderCount:0,macroOrders:[],postProcessOrderCount:0,postProcessOrders:[]}}encodeEmpty(e){let t=C.allocUnsafe(14),r=typeof e=="bigint"?e:BigInt(e);return t.writeBigUInt64BE(r,0),t.writeUInt8(0,8),t.writeUInt16BE(0,9),t.writeUInt8(0,11),t.writeUInt8(0,12),t.writeUInt8(0,13),t.toUint8Array()}};g(Tt,"UpdatePacketEncoder");var We=Tt;F();var zt=class zt{encode(e){let t=JSON.stringify(e.template),r=new TextEncoder().encode(t);if(r.length>65535)throw new Error(`Macro template JSON too large: ${r.length} bytes (max 65535)`);let n=4+r.length,o=C.allocUnsafe(n),i=0;return o.writeUInt8(7,i++),o.writeUInt8(e.macroId,i++),o.writeUInt16BE(r.length,i),i+=2,o.toUint8Array().set(r,i),o.toUint8Array()}calculateSize(e){let t=JSON.stringify(e.template);return 4+new TextEncoder().encode(t).length}};g(zt,"MacroLoadEncoder");var $e=zt;var ne=class ne{constructor(e){this.engine=e;b(this,"colorCache",new Array(256));b(this,"cellsBuffer",[]);b(this,"opacityBuffer",new Uint8Array(0));b(this,"visibleLayersBuffer",[]);this.rebuildColorCache()}rebuildColorCache(){for(let e=0;e<256;e++){let t=this.engine.getColor(e);t?this.colorCache[e]={r:t.r,g:t.g,b:t.b,a:t.a}:this.colorCache[e]={r:0,g:0,b:0,a:0}}}getColorRGB(e){return this.colorCache[e]??this.colorCache[255]}getColorEmission(e){let t=this.engine.getColor(e);return t?t.e:0}isLayerVisible(e,t){let r=e.x,n=e.x+e.width,o=e.y,i=e.y+e.height,s=t.x,a=t.x+256,d=t.y,c=t.y+256;return!(n<=s||r>=a||i<=d||o>=c)}rasterize(e,t){let r=e.width*e.height,n=this.cellsBuffer;n.length=r;for(let s=0;s<r;s++)n[s]?(n[s].char=" ",n[s].fgColorIndex=255,n[s].bgColorIndex=255,n[s].fgEmission=0,n[s].bgEmission=0):n[s]={char:" ",fgColorIndex:255,bgColorIndex:255,fgEmission:0,bgEmission:0};this.opacityBuffer.length<r?this.opacityBuffer=new Uint8Array(r):this.opacityBuffer.fill(0,0,r);let o=this.opacityBuffer,i=this.visibleLayersBuffer;i.length=0;for(let s=0;s<t.length;s++){let a=t[s];a.isEnabled()&&this.isLayerVisible(e,a.getOrigin())&&i.push(a)}i.sort((s,a)=>a.getZOrder()-s.getZOrder());for(let s=0;s<e.height;s++)for(let a=0;a<e.width;a++){let d=s*e.width+a;if(o[d])continue;let c=e.x+a,l=e.y+s;for(let u=0;u<i.length;u++){let p=i[u],h=c-p.getOrigin().x,y=l-p.getOrigin().y,x=p.getWidth(),v=p.getHeight();if(h<0||h>=x||y<0||y>=v)continue;let U=y*x+h,S=p.getData(),w=S.getCharCode(U),I=S.getFgColorCode(U),M=S.getBgColorCode(U),f=n[d];if(w!==0&&w<256&&f.char===" "&&(f.char=ne.charCache[w]),I!==255&&f.fgColorIndex===255&&(f.fgColorIndex=I,f.fgEmission=this.getColorEmission(I)),M!==255){f.bgColorIndex===255&&(f.bgColorIndex=M,f.bgEmission=this.getColorEmission(M)),o[d]=1;break}}}return{width:e.width,height:e.height,cells:n,palette:this.colorCache}}rasterizeWithSortedLayers(e,t){let r=e.width*e.height,n=this.cellsBuffer;n.length=r;for(let s=0;s<r;s++)n[s]?(n[s].char=" ",n[s].fgColorIndex=255,n[s].bgColorIndex=255,n[s].fgEmission=0,n[s].bgEmission=0):n[s]={char:" ",fgColorIndex:255,bgColorIndex:255,fgEmission:0,bgEmission:0};this.opacityBuffer.length<r?this.opacityBuffer=new Uint8Array(r):this.opacityBuffer.fill(0,0,r);let o=this.opacityBuffer,i=this.visibleLayersBuffer;i.length=0;for(let s=0;s<t.length;s++){let a=t[s];this.isLayerVisible(e,a.getOrigin())&&i.push(a)}for(let s=0;s<e.height;s++)for(let a=0;a<e.width;a++){let d=s*e.width+a;if(o[d])continue;let c=e.x+a,l=e.y+s;for(let u=0;u<i.length;u++){let p=i[u],h=c-p.getOrigin().x,y=l-p.getOrigin().y,x=p.getWidth(),v=p.getHeight();if(h<0||h>=x||y<0||y>=v)continue;let U=y*x+h,S=p.getData(),w=S.getCharCode(U),I=S.getFgColorCode(U),M=S.getBgColorCode(U),f=n[d];if(w!==0&&w<256&&f.char===" "&&(f.char=ne.charCache[w]),I!==255&&f.fgColorIndex===255&&(f.fgColorIndex=I,f.fgEmission=this.getColorEmission(I)),M!==255){f.bgColorIndex===255&&(f.bgColorIndex=M,f.bgEmission=this.getColorEmission(M)),o[d]=1;break}}}return{width:e.width,height:e.height,cells:n,palette:this.colorCache}}calculateIntersection(e,t){let r=e.x,n=e.x+e.width,o=e.y,i=e.y+e.height,s=t.x,a=t.x+256,d=t.y,c=t.y+256,l=Math.max(r,s),u=Math.min(n,a),p=Math.max(o,d),h=Math.min(i,c);return{visible:l<u&&p<h,originStart:{x:l-e.x,y:p-e.y},originEnd:{x:u-e.x,y:h-e.y},layerStart:{x:l-t.x,y:p-t.y},layerEnd:{x:u-t.x,y:h-t.y}}}};g(ne,"DisplayRasterizer"),b(ne,"charCache",(()=>{let e=new Array(256);for(let t=0;t<256;t++)e[t]=String.fromCharCode(t);return e})());var Ge=ne;var Ft=class Ft{constructor(){b(this,"enabled",!1);b(this,"currentStats",null)}setEnabled(e){this.enabled=e,e||(this.currentStats=null)}isEnabled(){return this.enabled}get tick(){return this.currentStats?.tick??0}get timestamp(){return this.currentStats?.timestamp??0}get totalOrders(){return this.currentStats?.totalOrders??0}get ordersByLayer(){return this.currentStats?.ordersByLayer??new Map}get ordersByType(){return this.currentStats?.ordersByType??new Map}get totalLayers(){return this.currentStats?.totalLayers??0}get visibleLayers(){return this.currentStats?.visibleLayers??0}get layersPerDisplay(){return this.currentStats?.layersPerDisplay??new Map}get updatePacketSize(){return this.currentStats?.updatePacketSize??0}get displayHeaderSize(){return this.currentStats?.displayHeaderSize??0}get layerHeaderSize(){return this.currentStats?.layerHeaderSize??0}get orderDataSize(){return this.currentStats?.orderDataSize??0}get compressionRatio(){return this.currentStats?.compressionRatio??0}get compressedPacketSize(){return Math.round(this.updatePacketSize*this.compressionRatio)}get totalCells(){return this.currentStats?.totalCells??0}get nonEmptyCells(){return this.currentStats?.nonEmptyCells??0}get cellsWithBackground(){return this.currentStats?.cellsWithBackground??0}get rasterizationTimeMs(){return this.currentStats?.rasterizationTimeMs??0}get encodingTimeMs(){return this.currentStats?.encodingTimeMs??0}get packetSplit(){return this.currentStats?.packetSplit}get layerDetails(){return this.currentStats?.layerDetails}startTick(e){this.enabled&&(this.currentStats={tick:e,timestamp:Date.now(),totalOrders:0,ordersByLayer:new Map,ordersByType:new Map,totalLayers:0,visibleLayers:0,layersPerDisplay:new Map,updatePacketSize:0,displayHeaderSize:0,layerHeaderSize:0,orderDataSize:0,compressionRatio:0,totalCells:0,nonEmptyCells:0,cellsWithBackground:0,rasterizationTimeMs:0,encodingTimeMs:0})}recordLayerOrders(e,t){if(!(!this.enabled||!this.currentStats)){this.currentStats.totalOrders+=t.length,this.currentStats.ordersByLayer.set(e,t.length);for(let r of t){let n=this.currentStats.ordersByType.get(r.type)||0;this.currentStats.ordersByType.set(r.type,n+1)}}}recordLayers(e,t){!this.enabled||!this.currentStats||(this.currentStats.totalLayers=e,this.currentStats.visibleLayers=t)}recordDisplayLayers(e,t){!this.enabled||!this.currentStats||this.currentStats.layersPerDisplay.set(e,t)}recordUpdatePacketSize(e,t,r,n){!this.enabled||!this.currentStats||(this.currentStats.updatePacketSize=e,this.currentStats.displayHeaderSize=t,this.currentStats.layerHeaderSize=r,this.currentStats.orderDataSize=n,this.currentStats.compressionRatio=.25)}recordPacketSplit(e,t,r,n){!this.enabled||!this.currentStats||(this.currentStats.packetSplit={userId:e,displayCount:t,staticLayerCount:r,dynamicLayerCount:n})}recordLayerInfo(e,t,r,n){!this.enabled||!this.currentStats||(this.currentStats.layerDetails||(this.currentStats.layerDetails=[]),this.currentStats.layerDetails.push({layerId:e,isStatic:t,orderCount:r,updateFlags:n}))}recordRenderStats(e,t,r){!this.enabled||!this.currentStats||(this.currentStats.totalCells=e,this.currentStats.nonEmptyCells=t,this.currentStats.cellsWithBackground=r)}recordRasterizationTime(e){!this.enabled||!this.currentStats||(this.currentStats.rasterizationTimeMs=e)}recordEncodingTime(e){!this.enabled||!this.currentStats||(this.currentStats.encodingTimeMs=e)}endTick(){}reset(){this.currentStats=null}};g(Ft,"CoreStats");var oe=Ft;var Lt=class Lt{constructor(){b(this,"unicolorSprites",new Map);b(this,"multicolorSprites",new Map)}loadUnicolorSprites(e){for(let t of e.sprites){let r=new j(t.sizeX*t.sizeY);for(let o=0;o<t.data.length;o++)r.set(o,t.data[o]);let n={id:t.spriteId,sizeX:t.sizeX,sizeY:t.sizeY,data:r};this.unicolorSprites.set(n.id,n)}}loadMulticolorSprites(e){for(let t of e.sprites){let r=new Y(t.sizeX*t.sizeY);for(let o=0;o<t.data.length;o++){let i=t.data[o];r.set(o,i.charCode,i.fgColorId,i.bgColorId)}let n={id:t.spriteId,sizeX:t.sizeX,sizeY:t.sizeY,data:r};this.multicolorSprites.set(n.id,n)}}getUnicolorSprite(e){return this.unicolorSprites.get(e)}getMulticolorSprite(e){return this.multicolorSprites.get(e)}hasUnicolorSprite(e){return this.unicolorSprites.has(e)}hasMulticolorSprite(e){return this.multicolorSprites.has(e)}unloadUnicolorSprite(e){return this.unicolorSprites.delete(e)}unloadMulticolorSprite(e){return this.multicolorSprites.delete(e)}clearUnicolorSprites(){this.unicolorSprites.clear()}clearMulticolorSprites(){this.multicolorSprites.clear()}clearAll(){this.unicolorSprites.clear(),this.multicolorSprites.clear()}getUnicolorSpriteCount(){return this.unicolorSprites.size}getMulticolorSpriteCount(){return this.multicolorSprites.size}getTotalSpriteCount(){return this.unicolorSprites.size+this.multicolorSprites.size}};g(Lt,"SpriteRegistry");var ie=Lt;var Dt=(t=>(t.Web="web",t.Bitmap="bitmap",t))(Dt||{}),Yt=class Yt{constructor(e,t){this.fontId=e;this.config=t}getFontId(){return this.fontId}getConfig(){return{...this.config}}getFontFamily(){return this.config.fontFamily}getFontSize(){return this.config.fontSize}getOffsetX(){return this.config.offsetX??0}getOffsetY(){return this.config.offsetY??0}getCharSpacing(){return this.config.charSpacing??0}getLineHeight(){return this.config.lineHeight??1.2}getFontWeight(){return this.config.fontWeight??"normal"}getFontStyle(){return this.config.fontStyle??"normal"}toCSS(){let e=[];e.push(`font-family: ${this.config.fontFamily}`),e.push(`font-size: ${this.config.fontSize}px`);let t=this.config.fontWeight??"normal";t!=="normal"&&e.push(`font-weight: ${t}`);let r=this.config.fontStyle??"normal";return r!=="normal"&&e.push(`font-style: ${r}`),e.join("; ")+";"}};g(Yt,"WebFont");var _=Yt,Xt=class Xt{constructor(e,t){this.fontId=e;this.config=t}getFontId(){return this.fontId}getConfig(){return{charWidth:this.config.charWidth,charHeight:this.config.charHeight,cellWidth:this.config.cellWidth,cellHeight:this.config.cellHeight,glyphs:new Map(this.config.glyphs)}}getCharWidth(){return this.config.charWidth}getCharHeight(){return this.config.charHeight}getCellWidth(){return this.config.cellWidth??this.config.charWidth}getCellHeight(){return this.config.cellHeight??this.config.charHeight}getGlyph(e){return this.config.glyphs.get(e)}hasGlyph(e){return this.config.glyphs.has(e)}getGlyphCount(){return this.config.glyphs.size}getCharCodes(){return Array.from(this.config.glyphs.keys())}};g(Xt,"BitmapFont");var se=Xt;var Nt=class Nt{constructor(){b(this,"fonts",new Map)}loadFont(e,t){if(this.fonts.has(e))throw new Error(`WebFont with ID ${e} already exists`);let r=new _(e,t);this.fonts.set(e,r)}getFont(e){return this.fonts.get(e)}hasFont(e){return this.fonts.has(e)}unloadFont(e){return this.fonts.delete(e)}clearFonts(){this.fonts.clear()}getFontIds(){return Array.from(this.fonts.keys()).sort((e,t)=>e-t)}getAllFonts(){return Array.from(this.fonts.entries()).sort((e,t)=>e[0]-t[0]).map(e=>e[1])}getFontCount(){return this.fonts.size}};g(Nt,"WebFontRegistry");var ae=Nt;var _t=class _t{constructor(){b(this,"fonts",new Map)}loadFont(e,t){if(this.fonts.has(e))throw new Error(`BitmapFont with ID ${e} already exists`);let r=new se(e,t);this.fonts.set(e,r)}getFont(e){return this.fonts.get(e)}hasFont(e){return this.fonts.has(e)}unloadFont(e){return this.fonts.delete(e)}clearFonts(){this.fonts.clear()}getFontIds(){return Array.from(this.fonts.keys()).sort((e,t)=>e-t)}getAllFonts(){return Array.from(this.fonts.entries()).sort((e,t)=>e[0]-t[0]).map(e=>e[1])}getFontCount(){return this.fonts.size}};g(_t,"BitmapFontRegistry");var de=_t;var Ht=class Ht{constructor(){b(this,"sounds",new Map);b(this,"nameToId",new Map);b(this,"nextId",0)}registerFile(e,t,r){let n=this.allocateId(e),o={soundId:n,name:e,loadType:"file",format:t,data:r};return this.sounds.set(n,o),this.nameToId.set(e,n),n}registerFileWithId(e,t,r,n){this.validateId(e),this.checkIdAvailable(e,t);let o={soundId:e,name:t,loadType:"file",format:r,data:n};this.sounds.set(e,o),this.nameToId.set(t,e)}registerExternal(e,t,r,n,o){let i=this.allocateId(e),s={soundId:i,name:e,loadType:"external",format:t,url:r,size:n,checksum:o};return this.sounds.set(i,s),this.nameToId.set(e,i),i}registerExternalWithId(e,t,r,n,o,i){this.validateId(e),this.checkIdAvailable(e,t);let s={soundId:e,name:t,loadType:"external",format:r,url:n,size:o,checksum:i};this.sounds.set(e,s),this.nameToId.set(t,e)}get(e){if(typeof e=="number")return this.sounds.get(e);let t=this.nameToId.get(e);return t!==void 0?this.sounds.get(t):void 0}has(e){return this.get(e)!==void 0}getAll(){return Array.from(this.sounds.values())}getFileSounds(){return this.getAll().filter(e=>e.loadType==="file")}getExternalSounds(){return this.getAll().filter(e=>e.loadType==="external")}getNames(){return Array.from(this.nameToId.keys())}getId(e){return this.nameToId.get(e)}toLoadPackets(){let e=[],t=this.getFileSounds();if(t.length>0){let n=t.map(o=>({soundId:o.soundId,name:o.name,format:o.format,data:o.data}));e.push({type:"sound",mode:"file",sounds:n})}let r=this.getExternalSounds();if(r.length>0){let n=r.map(o=>({soundId:o.soundId,name:o.name,format:o.format,url:o.url,size:o.size,checksum:o.checksum}));e.push({type:"sound",mode:"external",sounds:n})}return e}toLoadPacket(e){let t=this.get(e);return t?t.loadType==="file"?{type:"sound",mode:"file",sounds:[{soundId:t.soundId,name:t.name,format:t.format,data:t.data}]}:{type:"sound",mode:"external",sounds:[{soundId:t.soundId,name:t.name,format:t.format,url:t.url,size:t.size,checksum:t.checksum}]}:null}unregister(e){let t=this.get(e);return t?(this.sounds.delete(t.soundId),this.nameToId.delete(t.name),!0):!1}clear(){this.sounds.clear(),this.nameToId.clear(),this.nextId=0}get size(){return this.sounds.size}getStats(){let e=this.getAll(),t=e.filter(n=>n.loadType==="file"),r=t.reduce((n,o)=>n+(o.data?.length??0),0);return{total:e.length,file:t.length,external:e.length-t.length,totalFileSize:r}}allocateId(e){if(this.nameToId.has(e))throw new Error(`Sound with name "${e}" already exists`);for(;this.sounds.has(this.nextId);)if(this.nextId++,this.nextId>255)throw new Error("Maximum number of sounds (256) reached");return this.nextId++}validateId(e){if(!Number.isInteger(e)||e<0||e>255)throw new Error(`Invalid sound ID: ${e}. Must be an integer between 0 and 255.`)}checkIdAvailable(e,t){if(this.sounds.has(e)){let r=this.sounds.get(e);throw new Error(`Sound ID ${e} is already used by "${r.name}". Cannot register "${t}".`)}if(this.nameToId.has(t))throw new Error(`Sound with name "${t}" already exists`)}};g(Ht,"SoundRegistry");var ce=Ht;var Wt=class Wt{constructor(e){this.soundRegistry=e}collectFromUser(e){let t=[],r=e.flushSoundCommands();for(let o of r){let i=this.convertSoundCommand(o);i&&t.push(i)}let n=e.flushAudioConfigCommands();for(let o of n){let i=this.convertConfigCommand(o);i&&t.push(i)}return t}convertSoundCommand(e){return"setEffects"in e&&e.setEffects===!0?this.convertSetEffectsCommand(e):"fadeOut"in e&&e.fadeOut===!0?this.convertFadeOutCommand(e):"pause"in e&&e.pause===!0?this.convertPauseCommand(e):"resume"in e&&e.resume===!0?this.convertResumeCommand(e):"instanceId"in e||"volume"in e||"pitch"in e||"loop"in e||"fadeIn"in e||"x"in e||"y"in e||"lowpass"in e||"highpass"in e||"reverb"in e?this.convertPlayCommand(e):this.convertStopCommand(e)}convertPlayCommand(e){let t=this.resolveSoundId(e.sound);if(t===null)return console.warn(`[AudioOrderCollector] Unknown sound: ${e.sound}`),null;let r=0;e.loop&&(r|=1),e.volume!==void 0&&(r|=2),e.pitch!==void 0&&(r|=4),e.fadeIn!==void 0&&(r|=8),e.lowpass!==void 0&&e.lowpass>0&&(r|=32),e.highpass!==void 0&&e.highpass>0&&(r|=64),e.reverb!==void 0&&e.reverb>0&&(r|=128);let n=e.x!==void 0&&e.y!==void 0;return n&&(r|=16),n?{type:1,soundId:t,instanceId:e.instanceId??0,flags:r,volume:e.volume!==void 0?this.encodeVolume(e.volume):void 0,pitch:e.pitch!==void 0?this.encodePitch(e.pitch):void 0,fadeIn:e.fadeIn!==void 0?this.encodeFadeTime(e.fadeIn):void 0,posX:this.encodePosition(e.x),posY:this.encodePosition(e.y),lowpass:e.lowpass!==void 0&&e.lowpass>0?this.encodeFilterFreq(e.lowpass):void 0,highpass:e.highpass!==void 0&&e.highpass>0?this.encodeFilterFreq(e.highpass):void 0,reverb:e.reverb!==void 0&&e.reverb>0?this.encodeReverb(e.reverb):void 0}:{type:2,soundId:t,instanceId:e.instanceId??0,flags:r&-17,volume:e.volume!==void 0?this.encodeVolume(e.volume):void 0,pitch:e.pitch!==void 0?this.encodePitch(e.pitch):void 0,fadeIn:e.fadeIn!==void 0?this.encodeFadeTime(e.fadeIn):void 0,lowpass:e.lowpass!==void 0&&e.lowpass>0?this.encodeFilterFreq(e.lowpass):void 0,highpass:e.highpass!==void 0&&e.highpass>0?this.encodeFilterFreq(e.highpass):void 0,reverb:e.reverb!==void 0&&e.reverb>0?this.encodeReverb(e.reverb):void 0}}convertStopCommand(e){let{targetType:t,target:r}=this.resolveTarget(e.sound);return{type:3,targetType:t,target:r}}convertFadeOutCommand(e){let{targetType:t,target:r}=this.resolveTarget(e.sound);return{type:4,targetType:t,duration:this.encodeFadeTime(e.duration),target:r}}convertPauseCommand(e){let{targetType:t,target:r}=this.resolveTarget(e.sound);return{type:5,targetType:t,target:r}}convertResumeCommand(e){let{targetType:t,target:r}=this.resolveTarget(e.sound);return{type:6,targetType:t,target:r}}convertSetEffectsCommand(e){let t=0;return e.lowpass!==void 0&&(t|=1),e.highpass!==void 0&&(t|=2),e.reverb!==void 0&&(t|=4),{type:9,instanceId:e.instanceId,flags:t,lowpass:e.lowpass!==void 0?this.encodeFilterFreq(e.lowpass):void 0,highpass:e.highpass!==void 0?this.encodeFilterFreq(e.highpass):void 0,reverb:e.reverb!==void 0?this.encodeReverb(e.reverb):void 0}}convertConfigCommand(e){return e.type==="set-listener-position"?{type:7,x:this.encodePosition(e.x),y:this.encodePosition(e.y)}:e.type==="configure-spatial"?{type:8,maxDistance:this.encodeDistance(e.maxDistance??1e3),referenceDistance:this.encodeDistance(e.referenceDistance??100),rolloffFactor:this.encodeRolloff(e.rolloffFactor??1),panSpread:this.encodePanSpread(e.panSpread??.5)}:null}resolveSoundId(e){if(typeof e=="number")return e>=0&&e<=255?e:null;let t=this.soundRegistry.getId(e);return t!==void 0?t:null}resolveTarget(e){if(e==="all")return{targetType:2,target:void 0};if(typeof e=="number")return{targetType:0,target:e};let t=this.soundRegistry.getId(e);return t!==void 0?{targetType:1,target:t}:(console.warn(`[AudioOrderCollector] Unknown sound name: ${e}, treating as 'all'`),{targetType:2,target:void 0})}encodeVolume(e){return Math.round(Math.max(0,Math.min(1,e))*255)}encodePitch(e){let t=Math.max(.25,Math.min(4,e)),r=64*Math.log2(t/.25);return Math.round(Math.max(0,Math.min(255,r)))}encodeFadeTime(e){return Math.round(Math.max(0,Math.min(25.5,e))*10)}encodeDistance(e){return Math.round(Math.max(0,Math.min(25500,e))/100)}encodeRolloff(e){return Math.round(Math.max(0,Math.min(2.55,e))*100)}encodePanSpread(e){return Math.round(Math.max(0,Math.min(1,e))*255)}encodePosition(e){return Math.round(Math.max(0,Math.min(65535,e)))}encodeFilterFreq(e){return e<=0?0:Math.round(Math.max(1,Math.min(255,e/100)))}encodeReverb(e){return Math.round(Math.max(0,Math.min(1,e))*255)}};g(Wt,"AudioOrderCollector");var le=Wt;var z=require("@utsp/types");var Vt=class Vt{collectFromUser(e){let t=e.flushPostProcessCommands();return this.convertCommands(t)}convertCommands(e){let t=[];for(let r of e){let n=this.convertCommand(r);n&&t.push(n)}return t}convertCommand(e){switch(e.type){case"set-config":return this.convertSetConfig(e);case"set-scanlines-enabled":return this.createSetScanlinesOrder(e.enabled??!1,e.opacity);case"set-scanlines-opacity":return this.createSetScanlinesOrder(!0,e.opacity??z.POST_PROCESS_DEFAULTS.scanlines.opacity);case"set-ambient-effect-enabled":return this.createSetAmbientEffectOrder(e.enabled??!1);case"set-ambient-effect-blur":return this.createSetAmbientEffectOrder(!0,e.blur);case"set-ambient-effect-scale":return this.createSetAmbientEffectOrder(!0,void 0,e.scale);case"set-scaling-mode":return this.createSetScalingModeOrder(e.scalingMode);case"set-grid":return this.createSetGridOrder(e.gridConfig);default:return console.warn(`[PostProcessOrderCollector] Unknown command type: ${e.type}`),null}}convertSetConfig(e){if(!e.config)return{type:1,flags:3,scanlines:{enabled:!1,opacity:0,pattern:0,colorR:0,colorG:0,colorB:0},ambientEffect:{enabled:!1,blur:0,scale:1,opacity:0}};let t=0,r={type:1,flags:0};if(e.config.scanlines){t|=1;let n=e.config.scanlines;r.scanlines={enabled:n.enabled,opacity:n.opacity??z.POST_PROCESS_DEFAULTS.scanlines.opacity,pattern:this.patternToType(n.pattern??"horizontal"),colorR:n.color?.r??0,colorG:n.color?.g??0,colorB:n.color?.b??0}}if(e.config.ambientEffect){t|=2;let n=e.config.ambientEffect;r.ambientEffect={enabled:n.enabled,blur:n.blur??z.POST_PROCESS_DEFAULTS.ambientEffect.blur,scale:n.scale??z.POST_PROCESS_DEFAULTS.ambientEffect.scale,opacity:n.opacity??z.POST_PROCESS_DEFAULTS.ambientEffect.opacity}}return r.flags=t,r}createSetScanlinesOrder(e,t){return{type:2,enabled:e,opacity:t??z.POST_PROCESS_DEFAULTS.scanlines.opacity,pattern:0,colorR:0,colorG:0,colorB:0}}createSetAmbientEffectOrder(e,t,r){return{type:3,enabled:e,blur:t??z.POST_PROCESS_DEFAULTS.ambientEffect.blur,scale:r??z.POST_PROCESS_DEFAULTS.ambientEffect.scale,opacity:z.POST_PROCESS_DEFAULTS.ambientEffect.opacity}}patternToType(e){switch(e){case"horizontal":return 0;case"vertical":return 1;case"grid":return 2;default:return 0}}createSetScalingModeOrder(e){return{type:4,mode:(0,z.scalingModeToValue)(e)}}createSetGridOrder(e){let{r:t,g:r,b:n,a:o}=this.parseColor(e.color??z.GRID_DEFAULTS.color);return{type:5,enabled:e.enabled,colorR:t,colorG:r,colorB:n,colorA:o,lineWidth:e.lineWidth??z.GRID_DEFAULTS.lineWidth}}parseColor(e){let t=e.match(/rgba?\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+))?\s*\)/);if(t)return{r:parseInt(t[1],10),g:parseInt(t[2],10),b:parseInt(t[3],10),a:t[4]?Math.round(parseFloat(t[4])*255):255};let r=e.match(/^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$/);if(r){let n=r[1];return n.length===3?{r:parseInt(n[0]+n[0],16),g:parseInt(n[1]+n[1],16),b:parseInt(n[2]+n[2],16),a:255}:{r:parseInt(n.slice(0,2),16),g:parseInt(n.slice(2,4),16),b:parseInt(n.slice(4,6),16),a:255}}return{r:144,g:24,b:24,a:255}}};g(Vt,"PostProcessOrderCollector");var ue=Vt;var ge=class ge{constructor(e={}){b(this,"users",new Map);b(this,"mode");b(this,"maxUsers");b(this,"strictMode");b(this,"currentTick",0);b(this,"encoder");b(this,"displayRasterizer");b(this,"colorPalette",new Map);b(this,"stats",new oe);b(this,"spriteRegistry",new ie);b(this,"webFontRegistry",new ae);b(this,"bitmapFontRegistry",new de);b(this,"soundRegistry",new ce);b(this,"audioOrderCollector");b(this,"postProcessOrderCollector");b(this,"activeWebFontId",0);b(this,"_renderCallCount",0);b(this,"onPaletteChangedCallback");b(this,"onBitmapFontChangedCallback");this.mode=e.mode??"server",this.maxUsers=e.maxUsers??64,this.strictMode=e.strictMode??!1,this.encoder=new We,this.displayRasterizer=new Ge(this),this.audioOrderCollector=new le(this.soundRegistry),this.postProcessOrderCollector=new ue,this.initializeDefaultPalette(),this.displayRasterizer.rebuildColorCache(),this.loadDefaultWebFont()}initializeDefaultPalette(){ge.ANSI_VGA_COLORS.forEach(e=>{this.colorPalette.set(e.colorId,{r:e.r,g:e.g,b:e.b,a:e.a,e:e.e})}),this.colorPalette.set(255,{r:0,g:0,b:0,a:0,e:0})}getMode(){return this.mode}getMaxUsers(){return this.maxUsers}isStrictMode(){return this.strictMode}isServer(){return this.mode==="server"}isClient(){return this.mode==="client"}isStandalone(){return this.mode==="standalone"}createUser(e,t){if(this.users.has(e))throw new Error(`User with ID ${e} already exists`);if(this.mode==="server"&&this.users.size>=this.maxUsers)throw new Error(`Maximum number of users reached (${this.maxUsers}). Cannot create user ${e}`);if(this.mode==="client"&&this.users.size>=1)throw new Error(`Client mode only allows one user. Cannot create user ${e}`);let r=new re(e,t,this.mode);return r.setSpriteRegistry(this.spriteRegistry),this.users.set(e,r),r}getUser(e){return this.users.get(e)??null}getUsers(){return Array.from(this.users.values())}hasUser(e){return this.users.has(e)}removeUser(e){return this.users.delete(e)}getUserCount(){return this.users.size}clearAllUsers(){this.users.clear()}setColor(e,t,r,n,o=255,i=0){if(e<0||e>255)throw new Error(`Color ID must be between 0 and 255, got ${e}`);if(e>=240)throw new Error("Color IDs 240-255 are reserved (240-254: UI palette, 255: skip color). Use IDs 0-239 for custom colors.");if(t<0||t>255||r<0||r>255||n<0||n>255||o<0||o>255||i<0||i>255)throw new Error("Color components must be between 0 and 255");this.colorPalette.set(e,{r:t,g:r,b:n,a:o,e:i}),this.onPaletteChangedCallback&&this.onPaletteChangedCallback(this.colorPalette)}onPaletteChanged(e){this.onPaletteChangedCallback=e}onBitmapFontChanged(e){this.onBitmapFontChangedCallback=e}getColor(e){return this.colorPalette.get(e)??null}loadPalette(e){for(let t of e)t.colorId<0||t.colorId>255||this.colorPalette.set(t.colorId,{r:t.r,g:t.g,b:t.b,a:t.a,e:t.e??0});ge.ANSI_VGA_COLORS.forEach(t=>{this.colorPalette.set(t.colorId,{r:t.r,g:t.g,b:t.b,a:t.a,e:t.e})}),this.colorPalette.set(255,{r:0,g:0,b:0,a:0,e:0}),this.displayRasterizer.rebuildColorCache(),this.onPaletteChangedCallback&&this.onPaletteChangedCallback(this.colorPalette)}getPalette(){return new Map(this.colorPalette)}resetPalette(){this.colorPalette.clear(),this.initializeDefaultPalette(),this.onPaletteChangedCallback&&this.onPaletteChangedCallback(this.colorPalette)}getColorCSS(e){let t=this.getColor(e);if(!t)return null;let r=t.a/255;return`rgba(${t.r}, ${t.g}, ${t.b}, ${r})`}getUserIds(){return Array.from(this.users.keys())}forEachUser(e){this.users.forEach(e)}filterUsers(e){return this.getUsers().filter(e)}findUser(e){return this.getUsers().find(e)}getCurrentTick(){return this.currentTick}getStats(){return this.stats}endTick(){this.stats.isEnabled()&&this.stats.startTick(this.currentTick);let e=new Map,t=0,r=0;return this.users.forEach((n,o)=>{let i=n.getLayers(),s=n.getDisplays();t+=i.length,n.getStats().isEnabled()&&n.getStats().startTick(this.currentTick);let a=s.map(x=>{let v=x.getOrigin(),U=x.getSize();return{id:x.getId(),originX:v.x,originY:v.y,sizeX:U.x,sizeY:U.y}});s.forEach(x=>x.resetChangeTracking());let d=[],c=[];i.forEach((x,v)=>{let U=x.getOrigin(),S=x.getOrders(),w=x.getStatic(),I=x.calculateUpdateFlags();x.resetChangeTracking(),x.getId()===0&&x.setId(v);let M={id:x.getId(),updateFlags:I,zIndex:x.getZOrder(),originX:U.x,originY:U.y,width:x.getWidth(),height:x.getHeight(),orderCount:S.length,orders:S};w?d.push(M):c.push(M)}),r+=d.length+c.length;let l=this.audioOrderCollector.collectFromUser(n),u=n.flushMacroOrders(),p=this.postProcessOrderCollector.collectFromUser(n),h=[...d,...c],y=this.encoder.encode({tick:this.currentTick,displayCount:a.length,displays:a,layerCount:h.length,layers:h,audioOrderCount:l.length,audioOrders:l,macroOrderCount:u.length,macroOrders:u,postProcessOrderCount:p.length,postProcessOrders:p});if(e.set(o,y),this.stats.isEnabled()){h.forEach((S,w)=>{this.stats.recordLayerOrders(w,S.orders)}),s.forEach((S,w)=>{this.stats.recordDisplayLayers(w,h.length)});let x=s.length*12,v=h.length*20,U=y.length-x-v;this.stats.recordUpdatePacketSize(y.length,x,v,U>0?U:0)}}),this.stats.isEnabled()&&(this.stats.recordLayers(t,r),this.stats.endTick()),this.currentTick++,e}endTickSplit(){this.stats.isEnabled()&&this.stats.startTick(this.currentTick);let e=new Map,t=0,r=0;return this.users.forEach((n,o)=>{let i=n.getLayers(),s=n.getDisplays();t+=i.length,n.getStats().isEnabled()&&n.getStats().startTick(this.currentTick);let a=s.map(x=>{let v=x.getOrigin(),U=x.getSize();return{id:x.getId(),originX:v.x,originY:v.y,sizeX:U.x,sizeY:U.y}});s.forEach(x=>x.resetChangeTracking());let d=[],c=[];i.forEach((x,v)=>{if(!x.getNeedsCommit())return;let U=x.getOrigin(),S=x.getOrders(),w=x.getStatic(),I=x.calculateUpdateFlags();x.resetChangeTracking(),x.resetCommit(),x.getId()===0&&x.setId(v);let M={id:x.getId(),updateFlags:I,zIndex:x.getZOrder(),originX:U.x,originY:U.y,width:x.getWidth(),height:x.getHeight(),orderCount:S.length,orders:S};S.length>0&&this.stats.isEnabled()&&this.stats.recordLayerInfo(x.getId(),w,S.length,I),w?d.push(M):c.push(M)}),r+=d.length+c.length;let l=this.audioOrderCollector.collectFromUser(n),u=this.postProcessOrderCollector.collectFromUser(n),p=n.flushMacroOrders(),h=null,y=null;if(this.stats.isEnabled()&&this.stats.recordPacketSplit(o,a.length,d.length,c.length),d.length>0&&(h=this.encoder.encode({tick:this.currentTick,displayCount:a.length,displays:a,layerCount:d.length,layers:d,audioOrderCount:0,audioOrders:[],macroOrderCount:0,macroOrders:[],postProcessOrderCount:0,postProcessOrders:[]})),y=this.encoder.encode({tick:this.currentTick,displayCount:a.length,displays:a,layerCount:c.length,layers:c,audioOrderCount:l.length,audioOrders:l,macroOrderCount:p.length,macroOrders:p,postProcessOrderCount:u.length,postProcessOrders:u}),e.set(o,{static:h,dynamic:y}),n.getStats().isEnabled()){let x=s.reduce((w,I)=>{let M=I.getSize();return w+M.x*M.y},0);n.getStats().recordDisplays(s.length,x),n.getStats().recordLayers(i.length,d.length+c.length,d.length,c.length),[...d,...c].forEach(w=>{n.getStats().recordLayerOrders(w.id,w.orders.length)});let v=h?.length||0,U=y?.length||0;n.getStats().recordPacketSizes(v,U);let S=n.getInputBindingRegistry();n.getStats().recordInput(!1,S.getAxisCount(),S.getButtonCount()),n.getStats().endTick()}if(this.stats.isEnabled()){let x=[...d,...c];x.forEach((I,M)=>{this.stats.recordLayerOrders(M,I.orders)}),s.forEach((I,M)=>{this.stats.recordDisplayLayers(M,x.length)});let v=(h?.length||0)+(y?.length||0),U=s.length*12,S=x.length*20,w=v-U-S;this.stats.recordUpdatePacketSize(v,U,S,w>0?w:0)}}),this.stats.isEnabled()&&(this.stats.recordLayers(t,r),this.stats.endTick()),this.currentTick++,e}getSnapshot(e){let t=this.getUser(e);if(!t)return null;let r=t.getDisplays(),n=t.getLayers(),o=r.map((s,a)=>{let d=s.getOrigin(),c=s.getSize();return{id:a,originX:d.x,originY:d.y,sizeX:c.x,sizeY:c.y}}),i=n.map((s,a)=>{let d=s.getOrigin(),c=s.getOrders(),l=7;return s.getId()===0&&s.setId(a),{id:s.getId(),updateFlags:l,zIndex:s.getZOrder(),originX:d.x,originY:d.y,width:s.getWidth(),height:s.getHeight(),orderCount:c.length,orders:c}});return this.encoder.encode({tick:this.currentTick,displayCount:o.length,displays:o,layerCount:i.length,layers:i,audioOrderCount:0,audioOrders:[],macroOrderCount:0,macroOrders:[],postProcessOrderCount:0,postProcessOrders:[]})}resetTick(){this.currentTick=0}applyUpdatePacket(e,t){let r=this.getUser(e);if(!r){if(this.strictMode)throw new Error(`Cannot apply update packet: user ${e} does not exist`);return!1}return r.applyUpdate(t),t.audioOrders&&t.audioOrders.length>0&&r.applyAudioOrders(t.audioOrders),!0}applyUpdatePacketBuffer(e,t){let{UpdatePacketDecoder:r}=(tr(),T(Fr)),o=new r().decode(t);return this.applyUpdatePacket(e,o)?o:null}applyLoadPacket(e){try{let{LoadDecoder:t}=(Yr(),T(Dr)),{LoadType:r}=(N(),T($)),i=new t().decode(e).load;switch(i.loadType){case r.ColorPalette:this.loadPalette(i.colors);break;case r.Sprite:this.loadUnicolorSprites(i);break;case r.MulticolorSprite:this.loadMulticolorSprites(i);break;case r.BitmapFont:{let s=this.getBitmapFontRegistry();s.hasFont(i.fontId)&&s.unloadFont(i.fontId),s.loadFont(i.fontId,{charWidth:i.width,charHeight:i.height,cellWidth:i.cellWidth,cellHeight:i.cellHeight,glyphs:new Map(i.characters.map(a=>[a.charCode,a.bitmap]))});break}case r.WebFont:{let s=this.getWebFontRegistry();s.hasFont(i.fontId)&&s.unloadFont(i.fontId),this.loadWebFontById(i.fontId,{fontFamily:i.fontFamily,fontSize:i.fontSize,offsetX:i.offsetX,offsetY:i.offsetY,charSpacing:i.charSpacing,lineHeight:i.lineHeight,fontWeight:i.fontWeight,fontStyle:i.fontStyle});break}case r.Sound:console.warn("[Core] Sound loading not yet implemented");break;case r.Macro:{for(let s of this.users.values())s.loadMacroTemplate(i.macroId,i.template);break}default:return console.error(`[Core] Unknown LoadType: ${i.loadType}`),!1}return!0}catch(t){return console.error("[Core] Failed to apply LoadPacket:",t),!1}}generatePaletteLoadPacket(){let e=this.getPalette();if(e.size===0)return null;let{LoadEncoder:t}=(be(),T(he)),{LoadType:r}=(N(),T($)),n=new t,o=[];return e.forEach((i,s)=>{s!==255&&o.push({colorId:s,r:i.r,g:i.g,b:i.b,a:i.a,e:i.e})}),n.encode({loadType:r.ColorPalette,colors:o})}generateUnicolorSpritesLoadPacket(){let e=this.getSpriteRegistry(),t=[];for(let i=0;i<=255;i++){let s=e.getUnicolorSprite(i);if(s){let a=[];for(let d=0;d<s.sizeX*s.sizeY;d++)a.push(s.data.get(d));t.push({spriteId:s.id,sizeX:s.sizeX,sizeY:s.sizeY,data:a})}}if(t.length===0)return null;let{LoadEncoder:r}=(be(),T(he)),{LoadType:n}=(N(),T($));return new r().encode({loadType:n.Sprite,sprites:t})}generateMulticolorSpritesLoadPacket(){let e=this.getSpriteRegistry(),t=[];for(let i=0;i<=255;i++){let s=e.getMulticolorSprite(i);if(s){let a=[];for(let d=0;d<s.sizeX*s.sizeY;d++){let c=s.data.get(d);a.push({charCode:c.charCode,fgColorId:c.fgColorCode,bgColorId:c.bgColorCode})}t.push({spriteId:s.id,sizeX:s.sizeX,sizeY:s.sizeY,data:a})}}if(t.length===0)return null;let{LoadEncoder:r}=(be(),T(he)),{LoadType:n}=(N(),T($));return new r().encode({loadType:n.MulticolorSprite,sprites:t})}generateWebFontsLoadPackets(){let e=this.getWebFontRegistry(),t=e.getFontIds(),r=[],{LoadEncoder:n}=(be(),T(he)),{LoadType:o}=(N(),T($)),i=new n;for(let s of t){let a=e.getFont(s);if(a){let d=a.getConfig(),c=i.encode({loadType:o.WebFont,fontId:s,fontFamily:d.fontFamily,fontSize:d.fontSize,offsetX:d.offsetX,offsetY:d.offsetY,charSpacing:d.charSpacing,lineHeight:d.lineHeight,fontWeight:d.fontWeight,fontStyle:d.fontStyle});r.push(c)}}return r}generateBitmapFontsLoadPackets(){let e=this.getBitmapFontRegistry(),t=e.getFontIds(),r=[],{LoadEncoder:n}=(be(),T(he)),{LoadType:o}=(N(),T($)),i=new n;for(let s of t){let a=e.getFont(s);if(a){let d=[];for(let c=0;c<256;c++){let l=a.getGlyph(c);l&&d.push({charCode:c,bitmap:l})}if(d.length>0){let c=i.encode({loadType:o.BitmapFont,fontId:s,width:a.getCharWidth(),height:a.getCharHeight(),cellWidth:a.getCellWidth(),cellHeight:a.getCellHeight(),characters:d});r.push(c)}}}return r}generateAllLoadPackets(){let e=[],t=this.generatePaletteLoadPacket();t&&e.push(t);let r=this.generateUnicolorSpritesLoadPacket();r&&e.push(r);let n=this.generateMulticolorSpritesLoadPacket();n&&e.push(n);let o=this.generateWebFontsLoadPackets();e.push(...o);let i=this.generateBitmapFontsLoadPackets();return e.push(...i),e}generateMacroLoadPackets(e){let t=this.getUser(e);if(!t)return[];let r=t.getMacroLoads();if(r.length===0)return[];let n=new $e;return r.map(o=>n.encode(o))}applyInputBindingsLoadPacket(e,t){let r=this.getUser(e);if(!r){if(this.strictMode)throw new Error(`Cannot apply input bindings: user ${e} does not exist`);return!1}try{return r.applyInputBindingsLoadPacket(t),!0}catch(n){return console.error(`[Core] Failed to apply input bindings for user ${e}:`,n),!1}}getRenderState(e){let t=this.getUser(e);if(!t)return null;let r=t.getDisplays(),n=t.getLayers(),o=performance.now(),i=new Array(r.length);for(let a=0;a<r.length;a++){let d=r[a],c=d.getOrigin(),l=d.getSize();i[a]=this.displayRasterizer.rasterize({x:c.x,y:c.y,width:l.x,height:l.y},n)}let s=performance.now()-o;return this._renderCallCount||(this._renderCallCount=0),this._renderCallCount++,{userId:t.id,userName:t.name,tick:this.currentTick,displays:i}}getAllRenderStates(){let e=new Map;return this.users.forEach((t,r)=>{let n=this.getRenderState(r);n&&e.set(r,n)}),e}enableStats(e){this.stats.setEnabled(e)}getStatsInstance(){return this.stats}resetStats(){this.stats.reset()}loadUnicolorSprites(e){this.spriteRegistry.loadUnicolorSprites(e)}loadMulticolorSprites(e){this.spriteRegistry.loadMulticolorSprites(e)}unloadUnicolorSprite(e){return this.spriteRegistry.unloadUnicolorSprite(e)}unloadMulticolorSprite(e){return this.spriteRegistry.unloadMulticolorSprite(e)}clearUnicolorSprites(){this.spriteRegistry.clearUnicolorSprites()}clearMulticolorSprites(){this.spriteRegistry.clearMulticolorSprites()}clearAllSprites(){this.spriteRegistry.clearAll()}getUnicolorSpriteCount(){return this.spriteRegistry.getUnicolorSpriteCount()}getMulticolorSpriteCount(){return this.spriteRegistry.getMulticolorSpriteCount()}getTotalSpriteCount(){return this.spriteRegistry.getTotalSpriteCount()}hasUnicolorSprite(e){return this.spriteRegistry.hasUnicolorSprite(e)}hasMulticolorSprite(e){return this.spriteRegistry.hasMulticolorSprite(e)}getSpriteRegistry(){return this.spriteRegistry}getSoundRegistry(){return this.soundRegistry}async loadSound(e,t){let r=this.detectSoundFormat(t),n=await this.loadSoundData(t);return this.soundRegistry.registerFile(e,r,n)}async loadSounds(e){let t={},n=Object.entries(e).map(async([o,i])=>{let s=await this.loadSound(o,i);t[o]=s});return await Promise.all(n),t}detectSoundFormat(e){let t=e.split(".").pop()?.toLowerCase()??"",r={mp3:"mp3",wav:"wav",ogg:"ogg",webm:"webm",aac:"aac",m4a:"aac"},n=r[t];if(!n)throw new Error(`Unsupported audio format: .${t}. Supported: ${Object.keys(r).join(", ")}`);return n}async loadSoundData(e){let t=globalThis;if(typeof t.document<"u"||typeof t.window<"u"||typeof t.fetch=="function")try{let n=await fetch(e);if(!n.ok)throw new Error(`HTTP ${n.status}: ${n.statusText}`);let o=await n.arrayBuffer();return new Uint8Array(o)}catch(n){let o=n instanceof Error?n.message:String(n);throw new Error(`Failed to load sound "${e}": ${o}`)}else{let n=typeof require<"u"?require:null;if(!n)throw new Error("Node.js require is not available");let s=n("fs").readFileSync(e);return new Uint8Array(s)}}registerSound(e,t,r){return this.soundRegistry.registerFile(e,t,r)}registerExternalSound(e,t,r,n){return this.soundRegistry.registerExternal(e,t,r,n)}hasSound(e){return this.soundRegistry.has(e)}generateSoundLoadPackets(){return this.soundRegistry.toLoadPackets()}loadDefaultWebFont(){this.webFontRegistry.loadFont(0,{fontFamily:"Courier New",fontSize:16,offsetX:0,offsetY:0,charSpacing:0,lineHeight:1,fontWeight:"normal",fontStyle:"normal"}),this.activeWebFontId=0}loadWebFont(e){let t=e.getFontId(),r=e.getConfig();this.webFontRegistry.loadFont(t,r)}getWebFont(e){return this.webFontRegistry.getFont(e)??null}hasWebFont(e){return this.webFontRegistry.hasFont(e)}unloadWebFont(e){if(e===0)throw new Error("Cannot unload default font (fontId 0)");return this.webFontRegistry.unloadFont(e)}clearWebFonts(){this.webFontRegistry.clearFonts(),this.loadDefaultWebFont()}setActiveWebFont(e){if(!this.webFontRegistry.hasFont(e))throw new Error(`WebFont with ID ${e} does not exist`);this.activeWebFontId=e}getActiveWebFontId(){return this.activeWebFontId}getActiveWebFont(){let e=this.webFontRegistry.getFont(this.activeWebFontId);if(!e)throw new Error(`Active WebFont ${this.activeWebFontId} not found. This should not happen.`);return e}getWebFontCount(){return this.webFontRegistry.getFontCount()}getWebFontIds(){return this.webFontRegistry.getFontIds()}getWebFontRegistry(){return this.webFontRegistry}getBitmapFontRegistry(){return this.bitmapFontRegistry}loadWebFontById(e,t){let r=new _(e,t);this.loadWebFont(r)}loadBitmapFontById(e,t){this.bitmapFontRegistry.loadFont(e,t),this.onBitmapFontChangedCallback&&this.onBitmapFontChangedCallback(e)}getBitmapFont(e){return this.bitmapFontRegistry.getFont(e)??null}hasBitmapFont(e){return this.bitmapFontRegistry.hasFont(e)}unloadBitmapFont(e){return this.bitmapFontRegistry.unloadFont(e)}clearBitmapFonts(){this.bitmapFontRegistry.clearFonts()}getBitmapFontCount(){return this.bitmapFontRegistry.getFontCount()}getBitmapFontIds(){return this.bitmapFontRegistry.getFontIds()}};g(ge,"Core"),b(ge,"ANSI_VGA_COLORS",[{colorId:240,r:16,g:16,b:16,a:255,e:0},{colorId:241,r:128,g:128,b:128,a:255,e:0},{colorId:242,r:192,g:192,b:192,a:255,e:0},{colorId:243,r:240,g:240,b:240,a:255,e:0},{colorId:244,r:200,g:50,b:50,a:255,e:0},{colorId:245,r:50,g:200,b:50,a:255,e:0},{colorId:246,r:220,g:180,b:50,a:255,e:0},{colorId:247,r:50,g:100,b:220,a:255,e:0},{colorId:248,r:50,g:200,b:200,a:255,e:0},{colorId:249,r:200,g:50,b:200,a:255,e:0},{colorId:250,r:220,g:120,b:50,a:255,e:0},{colorId:251,r:120,g:220,b:120,a:255,e:0},{colorId:252,r:120,g:180,b:220,a:255,e:0},{colorId:253,r:220,g:150,b:200,a:255,e:0},{colorId:254,r:250,g:220,b:150,a:255,e:0}]);var Qe=ge;var $r=require("@utsp/types");var G=new Map([[24,new Uint8Array([0,24,60,126,255,255,0,0])],[25,new Uint8Array([0,0,255,255,126,60,24,0])],[26,new Uint8Array([0,48,120,252,252,120,48,0])],[27,new Uint8Array([0,12,30,63,63,30,12,0])],[32,new Uint8Array([0,0,0,0,0,0,0,0])],[33,new Uint8Array([24,24,24,24,24,0,24,0])],[34,new Uint8Array([108,108,108,0,0,0,0,0])],[35,new Uint8Array([54,54,127,54,127,54,54,0])],[36,new Uint8Array([12,63,104,62,11,126,24,0])],[37,new Uint8Array([96,102,12,24,48,102,6,0])],[38,new Uint8Array([56,108,108,56,109,102,59,0])],[39,new Uint8Array([24,24,24,0,0,0,0,0])],[40,new Uint8Array([12,24,48,48,48,24,12,0])],[41,new Uint8Array([48,24,12,12,12,24,48,0])],[42,new Uint8Array([0,102,60,255,60,102,0,0])],[43,new Uint8Array([0,24,24,126,24,24,0,0])],[44,new Uint8Array([0,0,0,0,0,24,24,48])],[45,new Uint8Array([0,0,0,126,0,0,0,0])],[46,new Uint8Array([0,0,0,0,0,24,24,0])],[47,new Uint8Array([0,6,12,24,48,96,0,0])],[48,new Uint8Array([60,102,110,126,118,102,60,0])],[49,new Uint8Array([24,56,24,24,24,24,126,0])],[50,new Uint8Array([60,102,6,12,24,48,126,0])],[51,new Uint8Array([60,102,6,28,6,102,60,0])],[52,new Uint8Array([12,28,60,108,126,12,12,0])],[53,new Uint8Array([126,96,124,6,6,102,60,0])],[54,new Uint8Array([28,48,96,124,102,102,60,0])],[55,new Uint8Array([126,6,12,24,48,48,48,0])],[56,new Uint8Array([60,102,102,60,102,102,60,0])],[57,new Uint8Array([60,102,102,62,6,12,56,0])],[58,new Uint8Array([0,0,24,24,0,24,24,0])],[59,new Uint8Array([0,0,24,24,0,24,24,48])],[60,new Uint8Array([12,24,48,96,48,24,12,0])],[61,new Uint8Array([0,0,126,0,126,0,0,0])],[62,new Uint8Array([48,24,12,6,12,24,48,0])],[63,new Uint8Array([60,102,12,24,24,0,24,0])],[64,new Uint8Array([60,102,110,106,110,96,60,0])],[65,new Uint8Array([60,102,102,126,102,102,102,0])],[66,new Uint8Array([124,102,102,124,102,102,124,0])],[67,new Uint8Array([60,102,96,96,96,102,60,0])],[68,new Uint8Array([120,108,102,102,102,108,120,0])],[69,new Uint8Array([126,96,96,124,96,96,126,0])],[70,new Uint8Array([126,96,96,124,96,96,96,0])],[71,new Uint8Array([60,102,96,110,102,102,60,0])],[72,new Uint8Array([102,102,102,126,102,102,102,0])],[73,new Uint8Array([126,24,24,24,24,24,126,0])],[74,new Uint8Array([62,12,12,12,12,108,56,0])],[75,new Uint8Array([102,108,120,112,120,108,102,0])],[76,new Uint8Array([96,96,96,96,96,96,126,0])],[77,new Uint8Array([99,119,127,107,99,99,99,0])],[78,new Uint8Array([102,102,118,126,110,102,102,0])],[79,new Uint8Array([60,102,102,102,102,102,60,0])],[80,new Uint8Array([124,102,102,124,96,96,96,0])],[81,new Uint8Array([60,102,102,102,106,108,54,0])],[82,new Uint8Array([124,102,102,124,108,102,102,0])],[83,new Uint8Array([60,102,96,60,6,102,60,0])],[84,new Uint8Array([126,24,24,24,24,24,24,0])],[85,new Uint8Array([102,102,102,102,102,102,60,0])],[86,new Uint8Array([102,102,102,102,102,60,24,0])],[87,new Uint8Array([99,99,99,107,127,119,99,0])],[88,new Uint8Array([102,102,60,24,60,102,102,0])],[89,new Uint8Array([102,102,102,60,24,24,24,0])],[90,new Uint8Array([126,6,12,24,48,96,126,0])],[91,new Uint8Array([60,48,48,48,48,48,60,0])],[92,new Uint8Array([0,96,48,24,12,6,0,0])],[93,new Uint8Array([60,12,12,12,12,12,60,0])],[94,new Uint8Array([24,60,102,0,0,0,0,0])],[95,new Uint8Array([0,0,0,0,0,0,255,0])],[96,new Uint8Array([48,24,12,0,0,0,0,0])],[97,new Uint8Array([0,0,60,6,62,102,62,0])],[98,new Uint8Array([96,96,124,102,102,102,124,0])],[99,new Uint8Array([0,0,60,102,96,102,60,0])],[100,new Uint8Array([6,6,62,102,102,102,62,0])],[101,new Uint8Array([0,0,60,102,126,96,60,0])],[102,new Uint8Array([28,54,48,124,48,48,48,0])],[103,new Uint8Array([0,0,62,102,102,62,6,60])],[104,new Uint8Array([96,96,124,102,102,102,102,0])],[105,new Uint8Array([24,0,56,24,24,24,60,0])],[106,new Uint8Array([12,0,28,12,12,12,108,56])],[107,new Uint8Array([96,96,102,108,120,108,102,0])],[108,new Uint8Array([56,24,24,24,24,24,60,0])],[109,new Uint8Array([0,0,102,127,107,107,99,0])],[110,new Uint8Array([0,0,124,102,102,102,102,0])],[111,new Uint8Array([0,0,60,102,102,102,60,0])],[112,new Uint8Array([0,0,124,102,102,124,96,96])],[113,new Uint8Array([0,0,62,102,102,62,6,6])],[114,new Uint8Array([0,0,108,118,96,96,96,0])],[115,new Uint8Array([0,0,62,96,60,6,124,0])],[116,new Uint8Array([48,48,124,48,48,54,28,0])],[117,new Uint8Array([0,0,102,102,102,102,62,0])],[118,new Uint8Array([0,0,102,102,102,60,24,0])],[119,new Uint8Array([0,0,99,107,107,127,54,0])],[120,new Uint8Array([0,0,102,60,24,60,102,0])],[121,new Uint8Array([0,0,102,102,102,62,6,60])],[122,new Uint8Array([0,0,126,12,24,48,126,0])],[123,new Uint8Array([14,24,24,112,24,24,14,0])],[124,new Uint8Array([24,24,24,24,24,24,24,0])],[125,new Uint8Array([112,24,24,14,24,24,112,0])],[126,new Uint8Array([49,107,70,0,0,0,0,0])],[179,new Uint8Array([24,24,24,24,24,24,24,24])],[196,new Uint8Array([0,0,0,255,0,0,0,0])],[218,new Uint8Array([0,0,0,31,24,24,24,24])],[191,new Uint8Array([0,0,0,248,24,24,24,24])],[192,new Uint8Array([24,24,24,31,0,0,0,0])],[217,new Uint8Array([24,24,24,248,0,0,0,0])],[195,new Uint8Array([24,24,24,31,24,24,24,24])],[180,new Uint8Array([24,24,24,248,24,24,24,24])],[194,new Uint8Array([0,0,0,255,24,24,24,24])],[193,new Uint8Array([24,24,24,255,0,0,0,0])],[197,new Uint8Array([24,24,24,255,24,24,24,24])],[186,new Uint8Array([54,54,54,54,54,54,54,54])],[205,new Uint8Array([0,0,0,255,0,255,0,0])],[201,new Uint8Array([0,0,0,63,54,54,54,54])],[187,new Uint8Array([0,0,0,252,54,54,54,54])],[200,new Uint8Array([54,54,54,63,0,0,0,0])],[188,new Uint8Array([54,54,54,252,0,0,0,0])],[204,new Uint8Array([54,54,54,63,54,54,54,54])],[185,new Uint8Array([54,54,54,252,54,54,54,54])],[203,new Uint8Array([0,0,0,255,54,54,54,54])],[202,new Uint8Array([54,54,54,255,0,0,0,0])],[206,new Uint8Array([54,54,54,255,54,54,54,54])],[219,new Uint8Array([255,255,255,255,255,255,255,255])],[178,new Uint8Array([170,85,170,85,170,85,170,85])],[177,new Uint8Array([136,34,136,34,136,34,136,34])],[176,new Uint8Array([34,136,34,136,34,136,34,136])],[223,new Uint8Array([255,255,255,255,0,0,0,0])],[220,new Uint8Array([0,0,0,0,255,255,255,255])],[221,new Uint8Array([240,240,240,240,240,240,240,240])],[222,new Uint8Array([15,15,15,15,15,15,15,15])]]);function Xr(m){return G.get(m)}g(Xr,"getCharBitmap");function Nr(m){return G.has(m)}g(Nr,"hasChar");function _r(){return Array.from(G.keys()).sort((m,e)=>m-e)}g(_r,"getAllCharCodes");function Hr(m){let e=Array.from(G.entries()).map(([t,r])=>({charCode:t,bitmap:r}));return{loadType:4,fontId:m,width:8,height:8,cellWidth:8,cellHeight:8,characters:e}}g(Hr,"createASCII8x8FontLoad");function Wr(){return{charWidth:8,charHeight:8,glyphs:new Map(G)}}g(Wr,"getASCII8x8FontConfig");F();var ar=class ar{encode(e){switch(e.type){case 1:return this.encodeClick(e);case 2:return this.encodeChange(e);case 3:return this.encodeSubmit(e);case 4:return this.encodeSelect(e);default:throw new Error(`Unknown macro event type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return 2;case 2:return this.calculateChangeSize(e);case 3:return this.calculateSubmitSize(e);case 4:return 4;default:throw new Error(`Unknown macro event type: ${e.type}`)}}encodeClick(e){let t=C.allocUnsafe(2);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.toUint8Array()}encodeChange(e){if(typeof e.value=="boolean"){let r=C.allocUnsafe(4);return r.writeUInt8(e.type,0),r.writeUInt8(e.instanceId,1),r.writeUInt8(1,2),r.writeUInt8(e.value?1:0,3),r.toUint8Array()}else{let r=C.allocUnsafe(7);return r.writeUInt8(e.type,0),r.writeUInt8(e.instanceId,1),r.writeUInt8(0,2),r.writeFloatBE(e.value,3),r.toUint8Array()}}calculateChangeSize(e){return typeof e.value=="boolean"?4:7}encodeSubmit(e){let t=new TextEncoder().encode(e.text);if(t.length>65535)throw new Error(`Submit text too large: ${t.length} bytes (max 65535)`);let r=4+t.length,n=C.allocUnsafe(r),o=0;return n.writeUInt8(e.type,o++),n.writeUInt8(e.instanceId,o++),n.writeUInt16BE(t.length,o),o+=2,n.toUint8Array().set(t,o),n.toUint8Array()}calculateSubmitSize(e){return 4+new TextEncoder().encode(e.text).length}encodeSelect(e){let t=C.allocUnsafe(4);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.writeUInt16BE(e.index,2),t.toUint8Array()}};g(ar,"MacroEventEncoder");var et=ar;function Vr(m,e,t,r,n,o,i,s=[],a=[]){let d=Array.from(e.entries()).sort((A,O)=>A[0]-O[0]),c=Array.from(t.entries()).sort((A,O)=>A[0]-O[0]),l=d.length,u=c.length,p=Be(l,u),h=new TextEncoder,y=s.map(A=>h.encode(A)),x=1+y.reduce((A,O)=>A+1+O.length,0),v=new et,U=a.map(A=>v.encode(A)),S=1+U.reduce((A,O)=>A+O.length,0),w=p+x+S,I=new Uint8Array(w),M=new DataView(I.buffer),f=0;M.setBigUint64(f,m,!0),f+=8;for(let[,A]of d){let O=ke(A);I[f]=O+256&255,f+=1}let k=V(u);for(let A=0;A<k;A++){let O=0;for(let Oe=0;Oe<8;Oe++){let cr=A*8+Oe;if(cr<u){let[,Gr]=c[cr];Gr&&(O|=1<<Oe)}}I[f]=O,f+=1}I[f]=r&255,f+=1,I[f]=n&255,f+=1,I[f]=o&255,f+=1;let H=0;i&&(H|=1),I[f]=H,f+=1,I[f]=Math.min(s.length,255),f+=1;for(let A of y)I[f]=Math.min(A.length,255),f+=1,I.set(A.slice(0,255),f),f+=A.length;I[f]=Math.min(a.length,255),f+=1;for(let A of U)I.set(A,f),f+=A.length;return I}g(Vr,"encodeCompressedInput");var E=class E{static toCharCode(e){if(typeof e=="number")return e&255;let t=e.charCodeAt(0);return Ce(t)}static dedent(e){let t=e.split(`
|
|
9
9
|
`);if(t.length>0&&t[0].trim()===""&&t.shift(),t.length>0&&t[t.length-1].trim()===""&&t.pop(),t.length===0)return"";let r=t.filter(o=>o.trim().length>0);if(r.length===0)return"";let n=Math.min(...r.map(o=>{let i=o.match(/^(\s*)/);return i?i[1].length:0}));return t.map(o=>o.slice(n)).join(`
|
|
10
10
|
`)}static char(e,t,r,n=15,o=0){return{type:1,posX:e,posY:t,charCode:E.toCharCode(r),bgColorCode:o,fgColorCode:n}}static text(e,t,r,n=15,o=0){return{type:2,posX:e,posY:t,text:r,bgColorCode:o,fgColorCode:n}}static textMultiline(e,t,r,n=15,o=0){return{type:23,posX:e,posY:t,text:E.dedent(r),bgColorCode:o,fgColorCode:n}}static subFrame(e,t,r,n,o,i=15,s=0){return{type:3,posX:e,posY:t,sizeX:r,sizeY:n,frame:o.map(a=>E.toCharCode(a)),bgColorCode:s,fgColorCode:i}}static subFrameMultiColor(e,t,r,n,o){return{type:4,posX:e,posY:t,sizeX:r,sizeY:n,frame:o.map(i=>({charCode:E.toCharCode(i.charCode),bgColorCode:i.bgColorCode,fgColorCode:i.fgColorCode}))}}static fullFrame(e,t=15,r=0){return{type:5,frame:e.map(n=>E.toCharCode(n)),bgColorCode:r,fgColorCode:t}}static fullFrameMultiColor(e){return{type:6,frame:e.map(t=>({charCode:E.toCharCode(t.charCode),bgColorCode:t.bgColorCode,fgColorCode:t.fgColorCode}))}}static sprite(e,t,r,n=15,o=0){return{type:7,posX:e,posY:t,spriteIndex:r,bgColorCode:o,fgColorCode:n}}static spriteMultiColor(e,t,r){return{type:8,posX:e,posY:t,spriteIndex:r}}static colorMap(e,t,r,n,o){return{type:9,posX:e,posY:t,sizeX:r,sizeY:n,colorData:o}}static rectangle(e,t,r,n,o={}){return{type:10,shapeType:1,shapeData:{posX:e,posY:t,width:r,height:n,filled:o.filled??!0,charCode:E.toCharCode(o.charCode??9608),bgColorCode:o.bgColor??0,fgColorCode:o.fgColor??15}}}static circle(e,t,r,n={}){return{type:10,shapeType:2,shapeData:{centerX:e,centerY:t,radius:r,filled:n.filled??!0,charCode:E.toCharCode(n.charCode??9608),bgColorCode:n.bgColor??0,fgColorCode:n.fgColor??15}}}static line(e,t,r,n,o={}){return{type:10,shapeType:3,shapeData:{x1:e,y1:t,x2:r,y2:n,charCode:E.toCharCode(o.charCode??9608),bgColorCode:o.bgColor??0,fgColorCode:o.fgColor??15}}}static ellipse(e,t,r,n,o={}){return{type:10,shapeType:4,shapeData:{centerX:e,centerY:t,radiusX:r,radiusY:n,filled:o.filled??!0,charCode:E.toCharCode(o.charCode??9608),bgColorCode:o.bgColor??0,fgColorCode:o.fgColor??15}}}static triangle(e,t,r,n,o,i,s={}){return{type:10,shapeType:5,shapeData:{x1:e,y1:t,x2:r,y2:n,x3:o,y3:i,filled:s.filled??!0,charCode:E.toCharCode(s.charCode??9608),bgColorCode:s.bgColor??0,fgColorCode:s.fgColor??15}}}static dotCloud(e,t,r=15,n=0){return{type:11,charCode:E.toCharCode(t),bgColorCode:n,fgColorCode:r,positions:e}}static dotCloudMultiColor(e){return{type:12,dots:e.map(t=>({...t,charCode:E.toCharCode(t.charCode)}))}}static bitmask(e,t,r,n,o,i,s=15,a=0,d=!1){let c=r*n,l=Math.ceil(c/8),u=new Uint8Array(l);for(let p=0;p<c;p++)if(o[p]){let h=Math.floor(p/8),y=p%8;u[h]|=1<<y}return{type:17,posX:e,posY:t,sizeX:r,sizeY:n,charCode:E.toCharCode(i),bgColorCode:a,fgColorCode:s,override:d,mask:u}}static bitmask4(e,t,r,n,o,i,s=!1){let a={char:"?",fgColor:15,bgColor:0},d=[i[0]??a,i[1]??a,i[2]??a],c=r*n,l=Math.ceil(c/4),u=new Uint8Array(l);for(let p=0;p<c;p++){let h=o[p]&3,y=Math.floor(p/4),x=p%4*2;u[y]|=h<<x}return{type:18,posX:e,posY:t,sizeX:r,sizeY:n,override:s,variants:[{charCode:E.toCharCode(d[0].char),fgColorCode:d[0].fgColor,bgColorCode:d[0].bgColor},{charCode:E.toCharCode(d[1].char),fgColorCode:d[1].fgColor,bgColorCode:d[1].bgColor},{charCode:E.toCharCode(d[2].char),fgColorCode:d[2].fgColor,bgColorCode:d[2].bgColor}],mask:u}}static bitmask16(e,t,r,n,o,i,s=!1){let a={char:"?",fgColor:15,bgColor:0},d=[];for(let p=0;p<15;p++)d.push(i[p]??a);let c=r*n,l=Math.ceil(c/2),u=new Uint8Array(l);for(let p=0;p<c;p++){let h=o[p]&15,y=Math.floor(p/2),x=p%2*4;u[y]|=h<<x}return{type:24,posX:e,posY:t,sizeX:r,sizeY:n,override:s,variants:d.map(p=>({charCode:E.toCharCode(p.char),fgColorCode:p.fgColor,bgColorCode:p.bgColor})),mask:u}}static spriteCloud(e,t,r=15,n=0){return{type:13,spriteIndex:e,bgColorCode:n,fgColorCode:r,positions:t}}static spriteCloudMultiColor(e,t){return{type:14,spriteIndex:e,positions:t}}static spriteCloudVaried(e){return{type:15,sprites:e}}static spriteCloudVariedMultiColor(e){return{type:16,sprites:e}}static clear(e=32,t=15,r=0){return{type:19,charCode:E.toCharCode(e),bgColorCode:r,fgColorCode:t}}static fillChar(e,t,r,n=15,o=0){return{type:20,patternWidth:e,patternHeight:t,pattern:r.map(i=>E.toCharCode(i)),bgColorCode:o,fgColorCode:n}}static fillSprite(e,t=15,r=0){return{type:21,spriteIndex:e,bgColorCode:r,fgColorCode:t}}static fillSpriteMultiColor(e){return{type:22,spriteIndex:e}}static boxWithBorder(e,t,r,n,o,i){return[this.rectangle(e+1,t+1,r-2,n-2,{charCode:i.charCode??9608,bgColor:i.bgColor??0,fgColor:i.fgColor??8,filled:!0}),this.rectangle(e,t,r,n,{charCode:o.charCode??9608,bgColor:o.bgColor??0,fgColor:o.fgColor??15,filled:!1})]}static grid(e,t,r,n,o,i,s={}){let a=[];for(let d=0;d<=o;d++)for(let c=0;c<=i;c++)a.push({posX:e+c*r,posY:t+d*n});return this.dotCloud(a,s.charCode??"+",s.fgColor??15,s.bgColor??0)}static polyline(e,t="*",r=15,n=0){return{type:25,charCode:E.toCharCode(t),fgColorCode:r,bgColorCode:n,points:e.map(o=>({x:o.x&255,y:o.y&255}))}}static polylineFromCoords(e,t="*",r=15,n=0){let o=[];for(let i=0;i<e.length-1;i+=2)o.push({x:e[i],y:e[i+1]});return this.polyline(o,t,r,n)}static polygon(e,t="*",r=15,n=0){if(e.length<2)return this.polyline(e,t,r,n);let o=[...e,e[0]];return this.polyline(o,t,r,n)}};g(E,"OrderBuilder");var tt=E;Ut();N();gr();var dr=(u=>(u[u.LayerEnabled=1]="LayerEnabled",u[u.SetMode=2]="SetMode",u[u.UpdatePosition=4]="UpdatePosition",u[u.UpdateZOrder=8]="UpdateZOrder",u[u.Disabled=0]="Disabled",u[u.EnabledAddMode=1]="EnabledAddMode",u[u.EnabledSetMode=3]="EnabledSetMode",u[u.EnabledAddMoveOnly=5]="EnabledAddMoveOnly",u[u.EnabledSetMoveOnly=7]="EnabledSetMoveOnly",u[u.EnabledAddReorderOnly=9]="EnabledAddReorderOnly",u[u.EnabledSetReorderOnly=11]="EnabledSetReorderOnly",u[u.FullUpdate=15]="FullUpdate",u))(dr||{}),rt;(c=>{function m(l,u){return(l&u)!==0}c.hasFlag=m,g(m,"hasFlag");function e(l,u){return l|u}c.addFlag=e,g(e,"addFlag");function t(l,u){return l&~u}c.removeFlag=t,g(t,"removeFlag");function r(...l){return l.reduce((u,p)=>u|p,0)}c.combine=r,g(r,"combine");function n(l){return(l&240)===0}c.isValid=n,g(n,"isValid");function o(l){return m(l,1)}c.isEnabled=o,g(o,"isEnabled");function i(l){return m(l,2)}c.isSetMode=i,g(i,"isSetMode");function s(l){return m(l,4)}c.hasPositionChanged=s,g(s,"hasPositionChanged");function a(l){return m(l,8)}c.hasZOrderChanged=a,g(a,"hasZOrderChanged");function d(l){if(l===0)return"Disabled";let u=[];return m(l,1)?u.push("Enabled"):u.push("Disabled"),m(l,2)?u.push("SET"):u.push("ADD"),m(l,4)&&u.push("Position"),m(l,8)&&u.push("ZOrder"),u.join(" | ")}c.describe=d,g(d,"describe")})(rt||(rt={}));Ir();tr();wt();Jt();kr();Rr();Qt();
|
package/dist/index.d.ts
CHANGED
|
@@ -4337,6 +4337,13 @@ declare class User<TData = Record<string, any>> {
|
|
|
4337
4337
|
* @returns Update result with events and sounds to play
|
|
4338
4338
|
*/
|
|
4339
4339
|
updateMacros(): MacroUpdateResult;
|
|
4340
|
+
/**
|
|
4341
|
+
* Process macro events from MacroUpdateResult
|
|
4342
|
+
* Dispatches events to registered handlers (used in standalone mode)
|
|
4343
|
+
*
|
|
4344
|
+
* @param result - The result from updateMacros()
|
|
4345
|
+
*/
|
|
4346
|
+
processMacroEvents(result: MacroUpdateResult): void;
|
|
4340
4347
|
/**
|
|
4341
4348
|
* Update mouse state for the macro engine
|
|
4342
4349
|
* Converts display-local coordinates to world coordinates using the display's origin
|
package/dist/index.mjs
CHANGED
|
@@ -5,6 +5,6 @@ var Q=Object.defineProperty;var Lr=Object.getOwnPropertyDescriptor;var Dr=Object
|
|
|
5
5
|
`,this.axes.forEach(t=>{e+=` [${t.bindingId}] ${t.name}: `,e+=`${t.min} to ${t.max} (default: ${t.defaultValue})
|
|
6
6
|
`}),e+=`Buttons (${this.buttons.size}):
|
|
7
7
|
`,this.buttons.forEach(t=>{e+=` [${t.bindingId}] ${t.name}: `,e+=`(default: ${t.defaultValue})
|
|
8
|
-
`}),e}};g(st,"InputBindingRegistry");var de=st;function at(m=0n){return{tick:m,axes:new Map,buttons:new Map,displayId:0,mouseX:0,mouseY:0,mouseOverDisplay:!1,textInputs:[],macroEvents:[]}}g(at,"createEmptyCompressedInputPacket");function dt(m){let e=Math.max(-1,Math.min(1,m));return Math.round(e*127)}g(dt,"encodeAxisToInt8");function ct(m){return m/127}g(ct,"decodeInt8ToAxis");function G(m){return m===0?0:Math.ceil(m/8)}g(G,"getButtonByteCount");function lt(m,e){let r=m,n=G(e);return 8+r+n+4}g(lt,"getCompressedPacketSize");var ut=class ut{decode(e,t=0){let r=e.readUInt8(t);switch(r){case 1:return this.decodeClick(e,t);case 2:return this.decodeChange(e,t);case 3:return this.decodeSubmit(e,t);case 4:return this.decodeSelect(e,t);default:throw new Error(`Unknown macro event type: 0x${r.toString(16)}`)}}decodeAll(e,t,r){let n=[],o=0;for(let i=0;i<r;i++){let{event:s,bytesRead:a}=this.decode(e,t+o);n.push(s),o+=a}return{events:n,bytesRead:o}}decodeClick(e,t){let r=e.readUInt8(t),n=e.readUInt8(t+1);return{event:{type:r,instanceId:n},bytesRead:2}}decodeChange(e,t){let r=e.readUInt8(t),n=e.readUInt8(t+1),o=e.readUInt8(t+2),i,s;return o===1?(i=e.readUInt8(t+3)===1,s=4):(i=e.readFloatBE(t+3),s=7),{event:{type:r,instanceId:n,value:i},bytesRead:s}}decodeSubmit(e,t){let r=t,n=e.readUInt8(t++),o=e.readUInt8(t++),i=e.readUInt16BE(t);t+=2;let s=e.toUint8Array().subarray(t,t+i);t+=i;let a=new TextDecoder().decode(s);return{event:{type:n,instanceId:o,text:a},bytesRead:t-r}}decodeSelect(e,t){let r=e.readUInt8(t),n=e.readUInt8(t+1),o=e.readUInt16BE(t+2);return{event:{type:r,instanceId:n,index:o},bytesRead:4}}};g(ut,"MacroEventDecoder");var Ee=ut;T();function pt(m,e){let t=e.getAllAxes().length,r=e.getAllButtons().length,n=G(r),o=8+t+n+4;if(m.length<o)throw new Error(`Invalid compressed input packet: expected at least ${o} bytes (${t} axes + ${r} buttons), got ${m.length}`);let i=new DataView(m.buffer,m.byteOffset,m.byteLength),s=0,a=at();a.tick=i.getBigUint64(s,!0),s+=8;for(let c=0;c<t;c++){let l=m[s],u=l>127?l-256:l,p=ct(u);a.axes.set(c,p),s+=1}for(let c=0;c<n;c++){let l=m[s];for(let u=0;u<8;u++){let p=c*8+u;if(p<r){let h=(l&1<<u)!==0;a.buttons.set(p,h)}}s+=1}a.displayId=m[s],s+=1,a.mouseX=m[s],s+=1,a.mouseY=m[s],s+=1;let d=m[s];if(a.mouseOverDisplay=(d&1)!==0,s+=1,s<m.length){let c=m[s];s+=1;let l=new TextDecoder;a.textInputs=[];for(let u=0;u<c&&s<m.length;u++){let p=m[s];if(s+=1,s+p<=m.length){let h=m.slice(s,s+p),y=l.decode(h);a.textInputs.push(y),s+=p}}}if(s<m.length){let c=m[s];s+=1;let l=new Ee,u=[],p=C.from(m);for(let h=0;h<c&&s<m.length;h++){let y=l.decode(p,s);u.push(y.event),s+=y.bytesRead}a.macroEvents=u}return a}g(pt,"decodeCompressedInput");import{Vector2 as Re,POST_PROCESS_DEFAULTS as z,GRID_DEFAULTS as ke}from"@utsp/types";var mt=class mt{constructor(e,t){b(this,"enabled",!1);b(this,"currentStats",null);b(this,"_userId");b(this,"_userName");this._userId=e,this._userName=t}setEnabled(e){this.enabled=e,e||(this.currentStats=null)}isEnabled(){return this.enabled}get userId(){return this.currentStats?.userId??this._userId}get userName(){return this.currentStats?.userName??this._userName}get tick(){return this.currentStats?.tick??0}get timestamp(){return this.currentStats?.timestamp??0}get displayCount(){return this.currentStats?.displayCount??0}get totalDisplayArea(){return this.currentStats?.totalDisplayArea??0}get totalLayers(){return this.currentStats?.totalLayers??0}get visibleLayers(){return this.currentStats?.visibleLayers??0}get staticLayers(){return this.currentStats?.staticLayers??0}get dynamicLayers(){return this.currentStats?.dynamicLayers??0}get totalOrders(){return this.currentStats?.totalOrders??0}get ordersByLayer(){return this.currentStats?.ordersByLayer??new Map}get staticPacketSize(){return this.currentStats?.staticPacketSize??0}get dynamicPacketSize(){return this.currentStats?.dynamicPacketSize??0}get totalPacketSize(){return this.currentStats?.totalPacketSize??0}get compressedPacketSize(){return Math.round(this.totalPacketSize*.25)}get hasInput(){return this.currentStats?.hasInput??!1}get axisCount(){return this.currentStats?.axisCount??0}get buttonCount(){return this.currentStats?.buttonCount??0}startTick(e){this.enabled&&(this.currentStats={userId:this._userId,userName:this._userName,tick:e,timestamp:Date.now(),displayCount:0,totalDisplayArea:0,totalLayers:0,visibleLayers:0,staticLayers:0,dynamicLayers:0,totalOrders:0,ordersByLayer:new Map,staticPacketSize:0,dynamicPacketSize:0,totalPacketSize:0,hasInput:!1,axisCount:0,buttonCount:0})}recordDisplays(e,t){!this.enabled||!this.currentStats||(this.currentStats.displayCount=e,this.currentStats.totalDisplayArea=t)}recordLayers(e,t,r,n){!this.enabled||!this.currentStats||(this.currentStats.totalLayers=e,this.currentStats.visibleLayers=t,this.currentStats.staticLayers=r,this.currentStats.dynamicLayers=n)}recordLayerOrders(e,t){!this.enabled||!this.currentStats||(this.currentStats.totalOrders+=t,this.currentStats.ordersByLayer.set(e,t))}recordPacketSizes(e,t){!this.enabled||!this.currentStats||(this.currentStats.staticPacketSize=e,this.currentStats.dynamicPacketSize=t,this.currentStats.totalPacketSize=e+t)}recordInput(e,t,r){!this.enabled||!this.currentStats||(this.currentStats.hasInput=e,this.currentStats.axisCount=t,this.currentStats.buttonCount=r)}endTick(){}reset(){this.currentStats=null}};g(mt,"UserStats");var ce=mt;var Ct=class Ct{constructor(e,t,r){this.id=e;this.name=t;b(this,"displays",[]);b(this,"layers",[]);b(this,"spriteRegistry");b(this,"mode");b(this,"axes",new Map);b(this,"buttons",new Map);b(this,"textInputs",[]);b(this,"mouseX",0);b(this,"mouseY",0);b(this,"mouseOver",!1);b(this,"mouseDisplayId",0);b(this,"touchPositions",new Map);b(this,"activeTouchId",null);b(this,"inputBindings",new de);b(this,"stats");b(this,"soundCommands",[]);b(this,"nextSoundInstanceId",1);b(this,"audioConfigCommands",[]);b(this,"lastListenerX",-1);b(this,"lastListenerY",-1);b(this,"pendingSendSounds",!1);b(this,"audioProcessor");b(this,"loadedSounds",new Map);b(this,"soundLoadErrors",new Map);b(this,"playingSounds",new Map);b(this,"macroRegistry",new oe);b(this,"macroEngine",new ae);b(this,"macroEventHandlers",new Map);b(this,"postProcessCommands",[]);b(this,"currentPostProcessConfig",null);b(this,"data");b(this,"currentScalingMode",null);b(this,"currentGridConfig",null);this.mode=r,this.stats=new ce(e,t),this.data={}}setSpriteRegistry(e){this.spriteRegistry=e;for(let t of this.layers)t.setSpriteRegistry(e);this.macroEngine.setSpriteRegistry(e)}getDisplays(){return this.displays}addDisplay(e){this.displays.push(e)}removeDisplay(e){let t=this.displays.indexOf(e);return t!==-1?(this.displays.splice(t,1),!0):!1}clearDisplays(){this.displays=[]}getLayers(){return this.layers}getLayerById(e){return this.layers.find(t=>t.getId()===e)}addLayer(e,t){e.setMode(this.mode);let r=this.layers.length+1;e.setId(r),this.layers.push(e),this.spriteRegistry&&e.setSpriteRegistry(this.spriteRegistry),t&&this.macroRegistry.setLayerMapping(t,e.getId())}removeLayer(e){let t=this.layers.indexOf(e);return t!==-1?(this.layers.splice(t,1),!0):!1}clearLayers(){this.layers=[]}setMousePosition(e,t,r=!0){this.mouseX=Math.max(0,Math.min(255,e)),this.mouseY=Math.max(0,Math.min(255,t)),this.mouseOver=r}setTouchPosition(e,t,r,n=!0,o=0){if(e<0||e>9){console.warn(`Invalid touchId ${e}, must be 0-9`);return}n?(this.touchPositions.set(e,{x:Math.max(0,Math.min(255,t)),y:Math.max(0,Math.min(255,r)),over:!0,displayId:o}),this.activeTouchId=e):(this.touchPositions.delete(e),this.activeTouchId===e&&(this.activeTouchId=null))}setAxis(e,t){let r=Math.max(-1,Math.min(1,t));this.axes.set(e,r)}getAxis(e){return this.axes.get(e)??0}setButton(e,t){this.buttons.set(e,t)}getButton(e){return this.buttons.get(e)??!1}getButtonJustPressed(e){let t=`${e}_justPressed`;return this.buttons.get(t)??!1}getButtonJustReleased(e){let t=`${e}_justReleased`;return this.buttons.get(t)??!1}setTextInputs(e){this.textInputs=e}getTextInputs(){return this.textInputs}clearTextInputs(){this.textInputs=[]}getAxisNames(){return Array.from(this.axes.keys())}getButtonNames(){return Array.from(this.buttons.keys())}clearAxes(){this.axes.clear()}clearButtons(){this.buttons.clear()}getMouseDisplayInfo(){if(!this.mouseOver||this.displays.length===0)return null;let e=this.displays[0],t=0,r=this.mouseX,n=this.mouseY,o=e.getOrigin(),i=o.x+r,s=o.y+n;return{displayId:t,localX:r,localY:n,worldX:i,worldY:s}}getTouchDisplayInfo(e=0){if(e<0||e>9)return console.warn(`Invalid touchId ${e}, must be 0-9`),null;let t=this.touchPositions.get(e);if(!t||!t.over||this.displays.length===0)return null;let r=this.displays[0],n=t.displayId,o=t.x,i=t.y,s=r.getOrigin(),a=s.x+o,d=s.y+i;return{displayId:n,localX:o,localY:i,worldX:a,worldY:d}}getIsMouseOnADisplay(){return this.mouseOver}getMouseDisplayHover(){let e=this.getMouseDisplayInfo();return e?e.displayId:null}findLayerById(e){return this.layers.find(t=>t.getId()===e)??null}applyUpdate(e){if(this.updateDisplaysFromPacket(e.displays),this.updateLayersFromPacket(e.layers),e.macroOrders&&e.macroOrders.length>0)for(let t of e.macroOrders)this.macroEngine.applyOrder(t)}updateDisplaysFromPacket(e){for(let t of e){let r=this.displays[t.id];if(!r){for(r=new ee(t.id,t.sizeX,t.sizeY);this.displays.length<=t.id;)this.displays.push(null);this.displays[t.id]=r}r.setOrigin(new Re(t.originX,t.originY)),r.setSize(new Re(t.sizeX,t.sizeY))}}updateLayersFromPacket(e){for(let t of e){let r=this.findLayerById(t.id);r||(r=new ne(new Re(t.originX,t.originY),t.zIndex,t.width,t.height,!1),r.setId(t.id),r.setMode(this.mode),this.spriteRegistry&&r.setSpriteRegistry(this.spriteRegistry),this.addLayer(r)),t.updateFlags&1&&r.setOrigin(new Re(t.originX,t.originY)),t.updateFlags&2&&r.setZOrder(t.zIndex),t.updateFlags&4&&r.setOrders(t.orders)}}defineAxisBinding(e,t,r=[],n=-1,o=1,i=0){this.inputBindings.defineAxis(e,t,r,n,o,i)}defineButtonBinding(e,t,r=[],n=!1){this.inputBindings.defineButton(e,t,r,n)}defineAxisBindings(e){e.forEach(({bindingId:t,name:r,sources:n,min:o,max:i,defaultValue:s})=>{this.defineAxisBinding(t,r,n??[],o,i,s)})}defineButtonBindings(e){e.forEach(({bindingId:t,name:r,sources:n,defaultValue:o})=>{this.defineButtonBinding(t,r,n??[],o)})}getInputBindingsLoadPacket(){return this.inputBindings.toLoadPacket()}applyInputBindingsLoadPacket(e){try{let t=JSON.parse(e);if(t.type!=="input-binding")throw new Error(`Invalid packet type: ${t.type}`);for(let r of t.axes)this.defineAxisBinding(r.bindingId,r.name,r.sources||[],r.min,r.max,r.defaultValue);for(let r of t.buttons)this.defineButtonBinding(r.bindingId,r.name,r.sources||[],r.defaultValue)}catch(t){throw console.error("[User] Failed to apply input bindings:",t),t}}getInputBindingRegistry(){return this.inputBindings}getStats(){return this.stats}getAxisBindingId(e){return this.inputBindings.getAxisBindingId(e)}getButtonBindingId(e){return this.inputBindings.getButtonBindingId(e)}decodeAndApplyCompressedInput(e){let t=pt(e,this.inputBindings),r=this.inputBindings.getAllAxes(),n=this.inputBindings.getAllButtons(),o=r.sort((s,a)=>s.bindingId-a.bindingId),i=n.sort((s,a)=>s.bindingId-a.bindingId);for(let[s,a]of t.axes)if(s<o.length){let d=o[s];this.setAxis(d.name,a)}for(let[s,a]of t.buttons)if(s<i.length){let d=i[s];this.setButton(d.name,a)}this.mouseX=t.mouseX,this.mouseY=t.mouseY,this.mouseOver=t.mouseOverDisplay,this.mouseDisplayId=t.displayId}playSound(e,t){let r=this.nextSoundInstanceId++,n={sound:e,instanceId:r,volume:t?.volume,pitch:t?.pitch,loop:t?.loop,fadeIn:t?.fadeIn,x:t?.x,y:t?.y,lowpass:t?.lowpass,highpass:t?.highpass,reverb:t?.reverb};return this.soundCommands.push(n),r}stopSound(e){let t={sound:e};this.soundCommands.push(t)}fadeOutSound(e,t){let r={fadeOut:!0,sound:e,duration:t};this.soundCommands.push(r)}fadeOutAllSounds(e){let t={fadeOut:!0,sound:"all",duration:e};this.soundCommands.push(t)}stopAllSounds(){let e={sound:"all"};this.soundCommands.push(e)}pauseSound(e){let t={pause:!0,sound:e};this.soundCommands.push(t)}pauseAllSounds(){let e={pause:!0,sound:"all"};this.soundCommands.push(e)}resumeSound(e){let t={resume:!0,sound:e};this.soundCommands.push(t)}resumeAllSounds(){let e={resume:!0,sound:"all"};this.soundCommands.push(e)}setSoundEffects(e,t){let r={setEffects:!0,instanceId:e,lowpass:t.lowpass,highpass:t.highpass,reverb:t.reverb};this.soundCommands.push(r)}setListenerPosition(e,t){e===this.lastListenerX&&t===this.lastListenerY||(this.lastListenerX=e,this.lastListenerY=t,this.audioConfigCommands.push({type:"set-listener-position",x:e,y:t}))}configureSpatialAudio(e){this.audioConfigCommands.push({type:"configure-spatial",...e})}flushAudioConfigCommands(){let e=this.audioConfigCommands;return this.audioConfigCommands=[],e}hasAudioConfigCommands(){return this.audioConfigCommands.length>0}flushSoundCommands(){let e=this.soundCommands;return this.soundCommands=[],e}hasSoundCommands(){return this.soundCommands.length>0}sendSounds(){this.pendingSendSounds=!0}needsSendSounds(){return this.pendingSendSounds}clearSendSounds(){this.pendingSendSounds=!1}setAudioProcessor(e){this.audioProcessor=e,this.macroEngine.setAudioCallback(t=>{e.play(t)})}getAudioProcessor(){return this.audioProcessor}applyAudioCommands(e){if(this.audioProcessor&&this.mode!=="server")for(let t of e){if("setEffects"in t&&t.setEffects===!0){let n=t;this.audioProcessor.setEffects(n.instanceId,n.lowpass,n.highpass,n.reverb);continue}if("fadeOut"in t&&t.fadeOut===!0){let n=t;this.audioProcessor.fadeOut(n.sound,n.duration);continue}if("pause"in t&&t.pause===!0){let n=t;this.audioProcessor.pause(n.sound);continue}if("resume"in t&&t.resume===!0){let n=t;this.audioProcessor.resume(n.sound);continue}if("instanceId"in t||"volume"in t||"pitch"in t||"loop"in t||"fadeIn"in t||"x"in t||"y"in t||"lowpass"in t||"highpass"in t||"reverb"in t){let n=t,o=n.x!==void 0&&n.y!==void 0?{x:n.x,y:n.y}:void 0;this.audioProcessor.play(n.sound,{volume:n.volume,pitch:n.pitch,loop:n.loop,fadeIn:n.fadeIn,position:o,instanceId:n.instanceId,lowpass:n.lowpass,highpass:n.highpass,reverb:n.reverb})}else{let n=t;n.sound==="all"?this.audioProcessor.stopAll():this.audioProcessor.stop(n.sound)}}}applyAudioConfigCommands(e){if(this.audioProcessor&&this.mode!=="server")for(let t of e)t.type==="set-listener-position"?this.audioProcessor.setListenerPosition(t.x,t.y):t.type==="configure-spatial"&&this.audioProcessor.configureSpatial({maxDistance:t.maxDistance,referenceDistance:t.referenceDistance,rolloffFactor:t.rolloffFactor,panSpread:t.panSpread})}applyAudioOrders(e){if(!this.audioProcessor||this.mode==="server")return;let{AudioOrderType:t,AudioTargetType:r}=(gt(),B(Cr)),{PlaySoundFlags:n}=(yt(),B(Sr));for(let o of e)switch(o.type){case t.PlaySound:case t.PlayGlobalSound:{let i=o,s=i.volume!==void 0?i.volume/255:void 0,a=i.pitch!==void 0?.25*Math.pow(2,i.pitch/64):void 0,d=i.fadeIn!==void 0?i.fadeIn/10:void 0,c=(i.flags&n.Loop)!==0,l=i.posX!==void 0&&i.posY!==void 0?{x:i.posX,y:i.posY}:void 0;this.audioProcessor.play(i.soundId,{volume:s,pitch:a,loop:c,fadeIn:d,position:l,instanceId:i.instanceId,lowpass:i.lowpass,highpass:i.highpass,reverb:i.reverb});break}case t.StopSound:{let i=o;i.targetType===r.All?this.audioProcessor.stopAll():i.targetType===r.InstanceId?this.audioProcessor.stop(i.target):this.audioProcessor.stop(i.target);break}case t.FadeOutSound:{let i=o,s=i.duration/10;i.targetType===r.All?this.audioProcessor.fadeOut("all",s):this.audioProcessor.fadeOut(i.target,s);break}case t.PauseSound:{let i=o;i.targetType===r.All?this.audioProcessor.pause("all"):this.audioProcessor.pause(i.target);break}case t.ResumeSound:{let i=o;i.targetType===r.All?this.audioProcessor.resume("all"):this.audioProcessor.resume(i.target);break}case t.SetListenerPosition:{let i=o;this.audioProcessor.setListenerPosition(i.x,i.y);break}case t.ConfigureSpatial:{let i=o;this.audioProcessor.configureSpatial({maxDistance:i.maxDistance*100,referenceDistance:i.referenceDistance*100,rolloffFactor:i.rolloffFactor/100,panSpread:i.panSpread/255});break}case t.SetSoundEffects:{let i=o;this.audioProcessor.setEffects(i.instanceId,i.lowpass,i.highpass,i.reverb);break}}}handleAudioAck(e){switch(e.type){case"sound-loaded":this.loadedSounds.set(e.soundId,{name:e.name,loadedAt:Date.now()}),this.soundLoadErrors.delete(e.soundId);break;case"sound-error":this.soundLoadErrors.set(e.soundId,{name:e.name,error:e.error,at:Date.now()});break;case"playback-started":this.playingSounds.set(e.instanceId,{soundId:e.soundId,startedAt:Date.now()});break;case"playback-ended":this.playingSounds.delete(e.instanceId);break;case"playback-error":e.instanceId!==void 0&&this.playingSounds.delete(e.instanceId);break}}isSoundLoaded(e){return this.loadedSounds.has(e)}getSoundLoadError(e){return this.soundLoadErrors.get(e)?.error}getLoadedSounds(){return this.loadedSounds}getSoundLoadErrors(){return this.soundLoadErrors}isSoundPlaying(e){return this.playingSounds.has(e)}getPlayingSounds(){return this.playingSounds}getPlayingSoundCount(){return this.playingSounds.size}loadMacro(e,t){let r={...t,id:e},n=this.macroRegistry.registerMacro(r);return this.mode==="client"&&this.macroEngine.loadTemplate(n,r),n}createInstance(e){return this.updateLayerMappings(),this.macroRegistry.createInstance(e)}updateInstance(e,t){return this.macroRegistry.updateInstance(e,t)}removeInstance(e){return this.macroEventHandlers.delete(e),this.macroRegistry.removeInstance(e)}onMacroEvent(e,t,r){this.macroEventHandlers.has(e)||this.macroEventHandlers.set(e,new Map),this.macroEventHandlers.get(e).set(t,r)}offMacroEvent(e,t){t?this.macroEventHandlers.get(e)?.delete(t):this.macroEventHandlers.delete(e)}handleMacroEvent(e){let t=this.macroRegistry.getInstanceName(e.instanceId);if(!t){console.warn(`MacroEvent: Unknown instance ID ${e.instanceId}`);return}let r=this.macroEventHandlers.get(t);if(!r)return;let n,o;switch(e.type){case 1:n="click",o=void 0;break;case 2:n="change",o=e.value;break;case 3:n="submit",o=e.text;break;case 4:n="select",o=e.index;break;default:return}let i=r.get(n);i&&i(o)}flushMacroOrders(){return this.macroRegistry.flushPendingOrders()}hasPendingMacroOrders(){return this.macroRegistry.hasPendingOrders()}applyMacroOrders(e){for(let t of e)this.macroEngine.applyOrder(t)}getMacroRegistry(){return this.macroRegistry}getMacroLoads(){return this.macroRegistry.toAllMacroLoads()}updateLayerMappings(){for(let e of this.layers){let t=e.getId()}}registerLayerName(e,t){this.macroRegistry.setLayerMapping(e,t.getId())}loadMacroTemplate(e,t){this.macroEngine.loadTemplate(e,t)}updateMacros(){return this.macroEngine.update()}updateMacroMouse(e,t,r){let n=this.displays.find(o=>o.getId()===this.mouseDisplayId);if(!n&&this.displays.length>0&&(n=this.displays[0]),n){let o=n.getOrigin(),i=e+o.x,s=t+o.y;this.macroEngine.updateMouse(i,s,r)}else this.macroEngine.updateMouse(e,t,r)}getMacroRenderOrders(){let e=this.macroEngine.getOrdersByLayer(),t=this.displays[0];if(!t)return e;let r=t.getOrigin();if(r.x===0&&r.y===0)return e;let n=new Map;for(let[o,i]of e){let s=i.map(a=>{let d={...a};return"posX"in d&&typeof d.posX=="number"&&(d.posX=d.posX-r.x),"posY"in d&&typeof d.posY=="number"&&(d.posY=d.posY-r.y),d});n.set(o,s)}return n}getMacroEffectOffset(){return this.macroEngine.getEffectOffset()}getMacroEngine(){return this.macroEngine}macroFocusNext(){this.macroEngine.focusNext()}macroFocusPrevious(){this.macroEngine.focusPrevious()}macroActivateFocused(){this.macroEngine.activateFocused()}setPostProcess(e){let t=JSON.stringify(e),r=JSON.stringify(this.currentPostProcessConfig);t!==r&&(this.currentPostProcessConfig=e,this.postProcessCommands.push({type:"set-config",config:e??void 0}))}setScanlinesEnabled(e){if(e){let t=this.currentPostProcessConfig?.scanlines;this.setPostProcess({scanlines:{enabled:!0,opacity:t?.opacity??z.scanlines.opacity,pattern:t?.pattern??z.scanlines.pattern,color:t?.color??z.scanlines.color}})}else this.setPostProcess({scanlines:{enabled:!1}})}setScanlinesOpacity(e){let t=Math.max(0,Math.min(1,e)),r=this.currentPostProcessConfig?.scanlines;this.setPostProcess({scanlines:{enabled:!0,opacity:t,pattern:r?.pattern??"horizontal",color:r?.color??{r:0,g:0,b:0}}})}setScanlinesPattern(e){let t=this.currentPostProcessConfig?.scanlines;this.setPostProcess({scanlines:{enabled:t?.enabled??!0,opacity:t?.opacity??z.scanlines.opacity,pattern:e,color:t?.color??{r:0,g:0,b:0}}})}setAmbientEffect(e){let t=this.currentPostProcessConfig?.ambientEffect;typeof e=="boolean"?this.setPostProcess({...this.currentPostProcessConfig,ambientEffect:{enabled:e,blur:t?.blur??z.ambientEffect.blur,scale:t?.scale??z.ambientEffect.scale}}):this.setPostProcess({...this.currentPostProcessConfig,ambientEffect:{enabled:!0,blur:e.blur??t?.blur??z.ambientEffect.blur,scale:e.scale??t?.scale??z.ambientEffect.scale}})}setAmbientEffectEnabled(e){this.setAmbientEffect(e)}setAmbientEffectBlur(e){let t=this.currentPostProcessConfig?.ambientEffect;this.setPostProcess({...this.currentPostProcessConfig,ambientEffect:{enabled:t?.enabled??!0,blur:Math.max(0,e),scale:t?.scale??z.ambientEffect.scale}})}setAmbientEffectScale(e){let t=this.currentPostProcessConfig?.ambientEffect;this.setPostProcess({...this.currentPostProcessConfig,ambientEffect:{enabled:t?.enabled??!0,blur:t?.blur??z.ambientEffect.blur,scale:Math.max(1,e)}})}isAmbientEffectEnabled(){return this.currentPostProcessConfig?.ambientEffect?.enabled??!1}getAmbientEffectConfig(){let e=this.currentPostProcessConfig?.ambientEffect;return e?{enabled:e.enabled,blur:e.blur??z.ambientEffect.blur,scale:e.scale??z.ambientEffect.scale}:null}getPostProcessConfig(){return this.currentPostProcessConfig}hasPostProcessCommands(){return this.postProcessCommands.length>0}flushPostProcessCommands(){let e=this.postProcessCommands;return this.postProcessCommands=[],e}setScalingMode(e){this.currentScalingMode!==e&&(this.currentScalingMode=e,this.postProcessCommands.push({type:"set-scaling-mode",scalingMode:e}))}getScalingMode(){return this.currentScalingMode}setGrid(e){let t;typeof e=="boolean"?t={enabled:e,color:ke.color,lineWidth:ke.lineWidth}:t={enabled:e.enabled,color:e.color??ke.color,lineWidth:e.lineWidth??ke.lineWidth},this.currentGridConfig=t,this.postProcessCommands.push({type:"set-grid",gridConfig:t})}setGridEnabled(e){this.setGrid(e)}isGridEnabled(){return this.currentGridConfig?.enabled??!1}getGridConfig(){return this.currentGridConfig}};g(Ct,"User");var le=Ct;T();var ft=class ft{encode(e){switch(e.type){case 1:return this.encodeCharOrder(e);case 2:return this.encodeTextOrder(e);case 23:return this.encodeTextMultilineOrder(e);case 3:return this.encodeSubFrameOrder(e);case 4:return this.encodeSubFrameMultiColorOrder(e);case 5:return this.encodeFullFrameOrder(e);case 6:return this.encodeFullFrameMultiColorOrder(e);case 7:return this.encodeSpriteOrder(e);case 8:return this.encodeSpriteMultiColorOrder(e);case 9:return this.encodeColorMapOrder(e);case 10:return this.encodeShapeOrder(e);case 11:return this.encodeDotCloudOrder(e);case 12:return this.encodeDotCloudMultiColorOrder(e);case 17:return this.encodeBitmaskOrder(e);case 18:return this.encodeBitmask4Order(e);case 24:return this.encodeBitmask16Order(e);case 25:return this.encodePolylineOrder(e);case 13:return this.encodeSpriteCloudOrder(e);case 14:return this.encodeSpriteCloudMultiColorOrder(e);case 15:return this.encodeSpriteCloudVariedOrder(e);case 16:return this.encodeSpriteCloudVariedMultiColorOrder(e);case 19:return this.encodeClearOrder(e);case 20:return this.encodeFillCharOrder(e);case 21:return this.encodeFillSpriteOrder(e);case 22:return this.encodeFillSpriteMultiColorOrder(e);case 32:return this.encodeTriggerSoundOrder(e);case 33:return this.encodeTriggerGlobalSoundOrder(e);default:throw new Error(`Unknown order type: ${e.type}`)}}encodeCharOrder(e){let t=C.allocUnsafe(6),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.posX,r++),t.writeUInt8(e.posY,r++),t.writeUInt8(e.charCode,r++),t.writeUInt8(e.bgColorCode,r++),t.writeUInt8(e.fgColorCode,r++),t.toUint8Array()}encodeTextOrder(e){let t=new TextEncoder().encode(e.text),r=C.allocUnsafe(6+t.length),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(t.length,n++);for(let o=0;o<t.length;o++)r.writeUInt8(t[o],n++);return r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.toUint8Array()}encodeTextMultilineOrder(e){let t=new TextEncoder().encode(e.text),r=C.allocUnsafe(6+t.length),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(t.length,n++);for(let o=0;o<t.length;o++)r.writeUInt8(t[o],n++);return r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.toUint8Array()}encodeSubFrameOrder(e){let t=e.sizeX*e.sizeY,r=C.allocUnsafe(7+t),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(e.sizeX,n++),r.writeUInt8(e.sizeY,n++),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++);for(let o of e.frame)r.writeUInt8(o,n++);return r.toUint8Array()}encodeSubFrameMultiColorOrder(e){let t=e.sizeX*e.sizeY,r=C.allocUnsafe(5+t*3),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(e.sizeX,n++),r.writeUInt8(e.sizeY,n++);for(let o of e.frame)r.writeUInt8(o.charCode,n++),r.writeUInt8(o.bgColorCode,n++),r.writeUInt8(o.fgColorCode,n++);return r.toUint8Array()}encodeFullFrameOrder(e){let t=e.frame.length,r=C.allocUnsafe(3+t),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++);for(let o of e.frame)r.writeUInt8(o,n++);return r.toUint8Array()}encodeFullFrameMultiColorOrder(e){let t=e.frame.length,r=C.allocUnsafe(1+t*3),n=0;r.writeUInt8(e.type,n++);for(let o of e.frame)r.writeUInt8(o.charCode,n++),r.writeUInt8(o.bgColorCode,n++),r.writeUInt8(o.fgColorCode,n++);return r.toUint8Array()}encodeSpriteOrder(e){let t=C.allocUnsafe(6),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.posX,r++),t.writeUInt8(e.posY,r++),t.writeUInt8(e.spriteIndex,r++),t.writeUInt8(e.bgColorCode,r++),t.writeUInt8(e.fgColorCode,r++),t.toUint8Array()}encodeSpriteMultiColorOrder(e){let t=C.allocUnsafe(4),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.posX,r++),t.writeUInt8(e.posY,r++),t.writeUInt8(e.spriteIndex,r++),t.toUint8Array()}encodeColorMapOrder(e){let t=e.sizeX*e.sizeY,r=C.allocUnsafe(5+t*2),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(e.sizeX,n++),r.writeUInt8(e.sizeY,n++);for(let o of e.colorData)r.writeUInt8(o.bgColorCode,n++),r.writeUInt8(o.fgColorCode,n++);return r.toUint8Array()}encodeShapeOrder(e){let t=this.encodeShapeData(e.shapeType,e.shapeData),r=C.allocUnsafe(2+t.length),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.shapeType,n++);for(let o=0;o<t.length;o++)r.writeUInt8(t[o],n++);return r.toUint8Array()}encodeShapeData(e,t){switch(e){case 1:{let r=C.allocUnsafe(8),n=0;return r.writeUInt8(t.posX,n++),r.writeUInt8(t.posY,n++),r.writeUInt8(t.width,n++),r.writeUInt8(t.height,n++),r.writeUInt8(t.filled?1:0,n++),r.writeUInt8(t.charCode,n++),r.writeUInt8(t.bgColorCode,n++),r.writeUInt8(t.fgColorCode,n++),r.toUint8Array()}case 2:{let r=C.allocUnsafe(7),n=0;return r.writeUInt8(t.centerX,n++),r.writeUInt8(t.centerY,n++),r.writeUInt8(t.radius,n++),r.writeUInt8(t.filled?1:0,n++),r.writeUInt8(t.charCode,n++),r.writeUInt8(t.bgColorCode,n++),r.writeUInt8(t.fgColorCode,n++),r.toUint8Array()}case 3:{let r=C.allocUnsafe(7),n=0;return r.writeUInt8(t.x1,n++),r.writeUInt8(t.y1,n++),r.writeUInt8(t.x2,n++),r.writeUInt8(t.y2,n++),r.writeUInt8(t.charCode,n++),r.writeUInt8(t.bgColorCode,n++),r.writeUInt8(t.fgColorCode,n++),r.toUint8Array()}case 4:{let r=C.allocUnsafe(8),n=0;return r.writeUInt8(t.centerX,n++),r.writeUInt8(t.centerY,n++),r.writeUInt8(t.radiusX,n++),r.writeUInt8(t.radiusY,n++),r.writeUInt8(t.filled?1:0,n++),r.writeUInt8(t.charCode,n++),r.writeUInt8(t.bgColorCode,n++),r.writeUInt8(t.fgColorCode,n++),r.toUint8Array()}case 5:{let r=C.allocUnsafe(10),n=0;return r.writeUInt8(t.x1,n++),r.writeUInt8(t.y1,n++),r.writeUInt8(t.x2,n++),r.writeUInt8(t.y2,n++),r.writeUInt8(t.x3,n++),r.writeUInt8(t.y3,n++),r.writeUInt8(t.filled?1:0,n++),r.writeUInt8(t.charCode,n++),r.writeUInt8(t.bgColorCode,n++),r.writeUInt8(t.fgColorCode,n++),r.toUint8Array()}default:throw new Error(`Unknown shape type: ${e}`)}}encodeDotCloudOrder(e){let t=e.positions.length,r=C.allocUnsafe(6+t*2),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.charCode,n++),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.positions)r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeDotCloudMultiColorOrder(e){let t=e.dots.length,r=C.allocUnsafe(5+t*5),n=0;r.writeUInt8(e.type,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.dots)r.writeUInt8(o.charCode,n++),r.writeUInt8(o.bgColorCode,n++),r.writeUInt8(o.fgColorCode,n++),r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeBitmaskOrder(e){let t=e.mask.length,r=C.allocUnsafe(9+t),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(e.sizeX,n++),r.writeUInt8(e.sizeY,n++),r.writeUInt8(e.charCode,n++),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.writeUInt8(e.override?1:0,n++);for(let o=0;o<t;o++)r.writeUInt8(e.mask[o],n++);return r.toUint8Array()}encodeBitmask4Order(e){let t=e.mask.length,r=C.allocUnsafe(15+t),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(e.sizeX,n++),r.writeUInt8(e.sizeY,n++),r.writeUInt8(e.override?1:0,n++);for(let o of e.variants)r.writeUInt8(o.charCode,n++),r.writeUInt8(o.bgColorCode,n++),r.writeUInt8(o.fgColorCode,n++);for(let o=0;o<t;o++)r.writeUInt8(e.mask[o],n++);return r.toUint8Array()}encodeBitmask16Order(e){let t=e.mask.length,r=C.allocUnsafe(51+t),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(e.sizeX,n++),r.writeUInt8(e.sizeY,n++),r.writeUInt8(e.override?1:0,n++);for(let o of e.variants)r.writeUInt8(o.charCode,n++),r.writeUInt8(o.bgColorCode,n++),r.writeUInt8(o.fgColorCode,n++);for(let o=0;o<t;o++)r.writeUInt8(e.mask[o],n++);return r.toUint8Array()}encodePolylineOrder(e){let t=e.points.length,r=C.allocUnsafe(5+t*2),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.charCode,n++),r.writeUInt8(e.fgColorCode,n++),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(t,n++);for(let o of e.points)r.writeUInt8(o.x,n++),r.writeUInt8(o.y,n++);return r.toUint8Array()}encodeSpriteCloudOrder(e){let t=e.positions.length,r=C.allocUnsafe(8+t*2),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.spriteIndex,n++),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.positions)r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeSpriteCloudMultiColorOrder(e){let t=e.positions.length,r=C.allocUnsafe(6+t*2),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.spriteIndex,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.positions)r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeSpriteCloudVariedOrder(e){let t=e.sprites.length,r=C.allocUnsafe(3+t*5),n=0;r.writeUInt8(e.type,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.sprites)r.writeUInt8(o.spriteIndex,n++),r.writeUInt8(o.bgColorCode,n++),r.writeUInt8(o.fgColorCode,n++),r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeSpriteCloudVariedMultiColorOrder(e){let t=e.sprites.length,r=C.allocUnsafe(3+t*3),n=0;r.writeUInt8(e.type,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.sprites)r.writeUInt8(o.spriteIndex,n++),r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeClearOrder(e){let t=C.allocUnsafe(4),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.charCode,r++),t.writeUInt8(e.bgColorCode,r++),t.writeUInt8(e.fgColorCode,r++),t.toUint8Array()}encodeFillCharOrder(e){let t=e.patternWidth*e.patternHeight,r=C.allocUnsafe(5+t),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.patternWidth,n++),r.writeUInt8(e.patternHeight,n++),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++);for(let o of e.pattern)r.writeUInt8(o,n++);return r.toUint8Array()}encodeFillSpriteOrder(e){let t=C.allocUnsafe(4),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.spriteIndex,r++),t.writeUInt8(e.bgColorCode,r++),t.writeUInt8(e.fgColorCode,r++),t.toUint8Array()}encodeFillSpriteMultiColorOrder(e){let t=C.allocUnsafe(2),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.spriteIndex,r++),t.toUint8Array()}encodeTriggerSoundOrder(e){let t=C.allocUnsafe(5),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.posX,r++),t.writeUInt8(e.posY,r++),t.writeUInt8(e.soundId,r++),t.writeUInt8(e.loop?1:0,r++),t.toUint8Array()}encodeTriggerGlobalSoundOrder(e){let t=C.allocUnsafe(3),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.soundId,r++),t.writeUInt8(e.loop?1:0,r++),t.toUint8Array()}};g(ft,"OrderEncoder");var Pe=ft;T();var St=class St{constructor(){b(this,"orderEncoder");this.orderEncoder=new Pe}encode(e){let t=e.orders.map(a=>this.orderEncoder.encode(a)),r=13,n=t.reduce((a,d)=>a+d.length,0),o=r+n,i=C.allocUnsafe(o),s=0;i.writeUInt16BE(e.id,s),s+=2,i.writeUInt8(e.updateFlags,s++),i.writeUInt8(e.zIndex,s++),i.writeUInt16BE(e.originX,s),s+=2,i.writeUInt16BE(e.originY,s),s+=2,i.writeUInt16BE(e.width,s),s+=2,i.writeUInt16BE(e.height,s),s+=2,i.writeUInt8(e.orders.length,s++);for(let a of t)C.from(a).copy(i,s),s+=a.length;return i.toUint8Array()}calculateSize(e){return 13+e.orders.reduce((n,o)=>n+this.orderEncoder.encode(o).length,0)}};g(St,"LayerEncoder");var Be=St;T();var It=class It{encode(e){switch(e.type){case 1:return this.encodePlaySoundOrder(e);case 2:return this.encodePlayGlobalSoundOrder(e);case 3:return this.encodeStopSoundOrder(e);case 4:return this.encodeFadeOutSoundOrder(e);case 5:return this.encodePauseSoundOrder(e);case 6:return this.encodeResumeSoundOrder(e);case 7:return this.encodeSetListenerPositionOrder(e);case 8:return this.encodeConfigureSpatialOrder(e);case 9:return this.encodeSetSoundEffectsOrder(e);default:throw new Error(`Unknown audio order type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return this.calculatePlaySoundSize(e);case 2:return this.calculatePlayGlobalSoundSize(e);case 3:case 5:case 6:return this.calculateTargetOrderSize(e);case 4:return this.calculateFadeOutSize(e);case 7:return 5;case 8:return 5;case 9:return this.calculateSetSoundEffectsSize(e);default:throw new Error(`Unknown audio order type: ${e.type}`)}}encodePlaySoundOrder(e){let t=this.calculatePlaySoundSize(e),r=C.allocUnsafe(t),n=0;return r.writeUInt8(e.type,n++),r.writeUInt8(e.soundId,n++),r.writeUInt16BE(e.instanceId,n),n+=2,r.writeUInt8(e.flags,n++),e.flags&2&&r.writeUInt8(e.volume??255,n++),e.flags&4&&r.writeUInt8(e.pitch??128,n++),e.flags&8&&r.writeUInt8(e.fadeIn??0,n++),e.flags&16&&(r.writeUInt16BE(e.posX??0,n),n+=2,r.writeUInt16BE(e.posY??0,n),n+=2),e.flags&32&&r.writeUInt8(e.lowpass??0,n++),e.flags&64&&r.writeUInt8(e.highpass??0,n++),e.flags&128&&r.writeUInt8(e.reverb??0,n++),r.toUint8Array()}encodePlayGlobalSoundOrder(e){let t=this.calculatePlayGlobalSoundSize(e),r=C.allocUnsafe(t),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.soundId,n++),r.writeUInt16BE(e.instanceId,n),n+=2;let o=e.flags&-17;return r.writeUInt8(o,n++),o&2&&r.writeUInt8(e.volume??255,n++),o&4&&r.writeUInt8(e.pitch??128,n++),o&8&&r.writeUInt8(e.fadeIn??0,n++),o&32&&r.writeUInt8(e.lowpass??0,n++),o&64&&r.writeUInt8(e.highpass??0,n++),o&128&&r.writeUInt8(e.reverb??0,n++),r.toUint8Array()}calculatePlaySoundSize(e){let t=5;return e.flags&2&&(t+=1),e.flags&4&&(t+=1),e.flags&8&&(t+=1),e.flags&16&&(t+=4),e.flags&32&&(t+=1),e.flags&64&&(t+=1),e.flags&128&&(t+=1),t}calculatePlayGlobalSoundSize(e){let t=5,r=e.flags&-17;return r&2&&(t+=1),r&4&&(t+=1),r&8&&(t+=1),r&32&&(t+=1),r&64&&(t+=1),r&128&&(t+=1),t}encodeStopSoundOrder(e){return this.encodeTargetOrder(e.type,e.targetType,e.target)}encodePauseSoundOrder(e){return this.encodeTargetOrder(e.type,e.targetType,e.target)}encodeResumeSoundOrder(e){return this.encodeTargetOrder(e.type,e.targetType,e.target)}encodeFadeOutSoundOrder(e){let t=this.calculateFadeOutSize(e),r=C.allocUnsafe(t),n=0;return r.writeUInt8(e.type,n++),r.writeUInt8(e.targetType,n++),r.writeUInt8(e.duration,n++),e.targetType===0?r.writeUInt16BE(e.target??0,n):e.targetType===1&&r.writeUInt8(e.target??0,n),r.toUint8Array()}encodeTargetOrder(e,t,r){let n=2;t===0?n+=2:t===1&&(n+=1);let o=C.allocUnsafe(n),i=0;return o.writeUInt8(e,i++),o.writeUInt8(t,i++),t===0?o.writeUInt16BE(r??0,i):t===1&&o.writeUInt8(r??0,i),o.toUint8Array()}calculateTargetOrderSize(e){let t=2;return e.targetType===0?t+=2:e.targetType===1&&(t+=1),t}calculateFadeOutSize(e){let t=3;return e.targetType===0?t+=2:e.targetType===1&&(t+=1),t}encodeSetListenerPositionOrder(e){let t=C.allocUnsafe(5),r=0;return t.writeUInt8(e.type,r++),t.writeUInt16BE(e.x,r),r+=2,t.writeUInt16BE(e.y,r),t.toUint8Array()}encodeConfigureSpatialOrder(e){let t=C.allocUnsafe(5),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.maxDistance,r++),t.writeUInt8(e.referenceDistance,r++),t.writeUInt8(e.rolloffFactor,r++),t.writeUInt8(e.panSpread,r++),t.toUint8Array()}encodeSetSoundEffectsOrder(e){let t=this.calculateSetSoundEffectsSize(e),r=C.allocUnsafe(t),n=0;return r.writeUInt8(e.type,n++),r.writeUInt16BE(e.instanceId,n),n+=2,r.writeUInt8(e.flags,n++),e.flags&1&&r.writeUInt8(e.lowpass??0,n++),e.flags&2&&r.writeUInt8(e.highpass??0,n++),e.flags&4&&r.writeUInt8(e.reverb??0,n++),r.toUint8Array()}calculateSetSoundEffectsSize(e){let t=4;return e.flags&1&&(t+=1),e.flags&2&&(t+=1),e.flags&4&&(t+=1),t}};g(It,"AudioOrderEncoder");var Te=It;T();var Ot=class Ot{encode(e){switch(e.type){case 1:return this.encodeCreateInstance(e);case 2:return this.encodeUpdateInstance(e);case 3:return this.encodeRemoveInstance(e);default:throw new Error(`Unknown macro order type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return this.calculateCreateInstanceSize(e);case 2:return this.calculateUpdateInstanceSize(e);case 3:return 2;default:throw new Error(`Unknown macro order type: ${e.type}`)}}encodeCreateInstance(e){let t=JSON.stringify(e.params),r=new TextEncoder().encode(t);if(r.length>65535)throw new Error(`Params JSON too large: ${r.length} bytes (max 65535)`);let n=11+r.length,o=C.allocUnsafe(n),i=0;return o.writeUInt8(e.type,i++),o.writeUInt8(e.instanceId,i++),o.writeUInt8(e.macroId,i++),o.writeUInt8(e.layerId,i++),o.writeInt16BE(e.x,i),i+=2,o.writeInt16BE(e.y,i),i+=2,o.writeUInt8(e.tabIndex,i++),o.writeUInt16BE(r.length,i),i+=2,o.toUint8Array().set(r,i),o.toUint8Array()}calculateCreateInstanceSize(e){let t=JSON.stringify(e.params);return 11+new TextEncoder().encode(t).length}encodeUpdateInstance(e){let t=JSON.stringify(e.params),r=new TextEncoder().encode(t);if(r.length>65535)throw new Error(`Params JSON too large: ${r.length} bytes (max 65535)`);let n=4+r.length,o=C.allocUnsafe(n),i=0;return o.writeUInt8(e.type,i++),o.writeUInt8(e.instanceId,i++),o.writeUInt16BE(r.length,i),i+=2,o.toUint8Array().set(r,i),o.toUint8Array()}calculateUpdateInstanceSize(e){let t=JSON.stringify(e.params);return 4+new TextEncoder().encode(t).length}encodeRemoveInstance(e){let t=C.allocUnsafe(2);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.toUint8Array()}};g(Ot,"MacroOrderEncoder");var ze=Ot;T();var Ut=class Ut{encode(e){switch(e.type){case 1:return this.encodeSetConfigOrder(e);case 2:return this.encodeSetScanlinesOrder(e);case 3:return this.encodeSetAmbientEffectOrder(e);case 4:return this.encodeSetScalingModeOrder(e);case 5:return this.encodeSetGridOrder(e);default:throw new Error(`Unknown post-process order type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return this.calculateSetConfigSize(e);case 2:return 7;case 3:return 5;case 4:return 2;case 5:return 7;default:throw new Error(`Unknown post-process order type: ${e.type}`)}}encodeSetConfigOrder(e){let t=this.calculateSetConfigSize(e),r=C.allocUnsafe(t),n=0;return r.writeUInt8(e.type,n++),r.writeUInt8(e.flags,n++),e.flags&1&&e.scanlines&&(r.writeUInt8(e.scanlines.enabled?1:0,n++),r.writeUInt8(Math.round(e.scanlines.opacity*255),n++),r.writeUInt8(e.scanlines.pattern,n++),r.writeUInt8(e.scanlines.colorR,n++),r.writeUInt8(e.scanlines.colorG,n++),r.writeUInt8(e.scanlines.colorB,n++)),e.flags&2&&e.ambientEffect&&(r.writeUInt8(e.ambientEffect.enabled?1:0,n++),r.writeUInt8(Math.min(255,Math.round(e.ambientEffect.blur)),n++),r.writeUInt8(Math.min(255,Math.max(100,Math.round(e.ambientEffect.scale*100))),n++),r.writeUInt8(Math.round(e.ambientEffect.opacity*255),n++)),r.toUint8Array()}calculateSetConfigSize(e){let t=2;return e.flags&1&&(t+=6),e.flags&2&&(t+=4),t}encodeSetScanlinesOrder(e){let t=C.allocUnsafe(7),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.enabled?1:0,r++),t.writeUInt8(Math.round(e.opacity*255),r++),t.writeUInt8(e.pattern,r++),t.writeUInt8(e.colorR,r++),t.writeUInt8(e.colorG,r++),t.writeUInt8(e.colorB,r++),t.toUint8Array()}encodeSetAmbientEffectOrder(e){let t=C.allocUnsafe(5),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.enabled?1:0,r++),t.writeUInt8(Math.min(255,Math.round(e.blur)),r++),t.writeUInt8(Math.min(255,Math.max(100,Math.round(e.scale*100))),r++),t.writeUInt8(Math.round(e.opacity*255),r++),t.toUint8Array()}encodeSetScalingModeOrder(e){let t=C.allocUnsafe(2),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.mode,r++),t.toUint8Array()}encodeSetGridOrder(e){let t=C.allocUnsafe(7),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.enabled?1:0,r++),t.writeUInt8(e.colorR,r++),t.writeUInt8(e.colorG,r++),t.writeUInt8(e.colorB,r++),t.writeUInt8(e.colorA,r++),t.writeUInt8(Math.min(10,Math.max(1,e.lineWidth)),r++),t.toUint8Array()}};g(Ut,"PostProcessOrderEncoder");var Fe=Ut;T();var wt=class wt{constructor(){b(this,"layerEncoder");b(this,"audioOrderEncoder");b(this,"macroOrderEncoder");b(this,"postProcessOrderEncoder");this.layerEncoder=new Be,this.audioOrderEncoder=new Te,this.macroOrderEncoder=new ze,this.postProcessOrderEncoder=new Fe}encode(e){let t=e.layers.map(f=>this.layerEncoder.encode(f)),r=e.audioOrders||[],n=r.map(f=>this.audioOrderEncoder.encode(f)),o=e.macroOrders||[],i=o.map(f=>this.macroOrderEncoder.encode(f)),s=e.postProcessOrders||[],a=s.map(f=>this.postProcessOrderEncoder.encode(f)),d=9,c=e.displays.length*7,l=2,u=t.reduce((f,R)=>f+R.length,0),p=1,h=n.reduce((f,R)=>f+R.length,0),y=1,x=i.reduce((f,R)=>f+R.length,0),v=1,U=a.reduce((f,R)=>f+R.length,0),S=d+c+l+u+p+h+y+x+v+U,w=C.allocUnsafe(S),I=0,M=typeof e.tick=="bigint"?e.tick:BigInt(e.tick);w.writeBigUInt64BE(M,I),I+=8,w.writeUInt8(e.displays.length,I),I+=1;for(let f of e.displays)w.writeUInt8(f.id,I++),w.writeUInt16BE(f.originX,I),I+=2,w.writeUInt16BE(f.originY,I),I+=2,w.writeUInt8(Math.max(1,Math.min(256,f.sizeX))-1,I++),w.writeUInt8(Math.max(1,Math.min(256,f.sizeY))-1,I++);w.writeUInt16BE(e.layers.length,I),I+=2;for(let f of t)C.from(f).copy(w,I),I+=f.length;w.writeUInt8(r.length,I),I+=1;for(let f of n)C.from(f).copy(w,I),I+=f.length;w.writeUInt8(o.length,I),I+=1;for(let f of i)C.from(f).copy(w,I),I+=f.length;w.writeUInt8(s.length,I),I+=1;for(let f of a)C.from(f).copy(w,I),I+=f.length;return w.toUint8Array()}calculateSize(e){let r=e.displays.length*7,n=2,o=e.layers.reduce((y,x)=>y+this.layerEncoder.calculateSize(x),0),i=1,a=(e.audioOrders||[]).reduce((y,x)=>y+this.audioOrderEncoder.calculateSize(x),0),d=1,l=(e.macroOrders||[]).reduce((y,x)=>y+this.macroOrderEncoder.calculateSize(x),0),u=1,h=(e.postProcessOrders||[]).reduce((y,x)=>y+this.postProcessOrderEncoder.calculateSize(x),0);return 9+r+n+o+i+a+d+l+u+h}static createEmptyPacket(e){return{tick:typeof e=="bigint"?Number(e):e,displayCount:0,displays:[],layerCount:0,layers:[],audioOrderCount:0,audioOrders:[],macroOrderCount:0,macroOrders:[],postProcessOrderCount:0,postProcessOrders:[]}}encodeEmpty(e){let t=C.allocUnsafe(14),r=typeof e=="bigint"?e:BigInt(e);return t.writeBigUInt64BE(r,0),t.writeUInt8(0,8),t.writeUInt16BE(0,9),t.writeUInt8(0,11),t.writeUInt8(0,12),t.writeUInt8(0,13),t.toUint8Array()}};g(wt,"UpdatePacketEncoder");var Le=wt;T();var Mt=class Mt{encode(e){let t=JSON.stringify(e.template),r=new TextEncoder().encode(t);if(r.length>65535)throw new Error(`Macro template JSON too large: ${r.length} bytes (max 65535)`);let n=4+r.length,o=C.allocUnsafe(n),i=0;return o.writeUInt8(7,i++),o.writeUInt8(e.macroId,i++),o.writeUInt16BE(r.length,i),i+=2,o.toUint8Array().set(r,i),o.toUint8Array()}calculateSize(e){let t=JSON.stringify(e.template);return 4+new TextEncoder().encode(t).length}};g(Mt,"MacroLoadEncoder");var De=Mt;var Z=class Z{constructor(e){this.engine=e;b(this,"colorCache",new Array(256));b(this,"cellsBuffer",[]);b(this,"opacityBuffer",new Uint8Array(0));b(this,"visibleLayersBuffer",[]);this.rebuildColorCache()}rebuildColorCache(){for(let e=0;e<256;e++){let t=this.engine.getColor(e);t?this.colorCache[e]={r:t.r,g:t.g,b:t.b,a:t.a}:this.colorCache[e]={r:0,g:0,b:0,a:0}}}getColorRGB(e){return this.colorCache[e]??this.colorCache[255]}getColorEmission(e){let t=this.engine.getColor(e);return t?t.e:0}isLayerVisible(e,t){let r=e.x,n=e.x+e.width,o=e.y,i=e.y+e.height,s=t.x,a=t.x+256,d=t.y,c=t.y+256;return!(n<=s||r>=a||i<=d||o>=c)}rasterize(e,t){let r=e.width*e.height,n=this.cellsBuffer;n.length=r;for(let s=0;s<r;s++)n[s]?(n[s].char=" ",n[s].fgColorIndex=255,n[s].bgColorIndex=255,n[s].fgEmission=0,n[s].bgEmission=0):n[s]={char:" ",fgColorIndex:255,bgColorIndex:255,fgEmission:0,bgEmission:0};this.opacityBuffer.length<r?this.opacityBuffer=new Uint8Array(r):this.opacityBuffer.fill(0,0,r);let o=this.opacityBuffer,i=this.visibleLayersBuffer;i.length=0;for(let s=0;s<t.length;s++){let a=t[s];a.isEnabled()&&this.isLayerVisible(e,a.getOrigin())&&i.push(a)}i.sort((s,a)=>a.getZOrder()-s.getZOrder());for(let s=0;s<e.height;s++)for(let a=0;a<e.width;a++){let d=s*e.width+a;if(o[d])continue;let c=e.x+a,l=e.y+s;for(let u=0;u<i.length;u++){let p=i[u],h=c-p.getOrigin().x,y=l-p.getOrigin().y,x=p.getWidth(),v=p.getHeight();if(h<0||h>=x||y<0||y>=v)continue;let U=y*x+h,S=p.getData(),w=S.getCharCode(U),I=S.getFgColorCode(U),M=S.getBgColorCode(U),f=n[d];if(w!==0&&w<256&&f.char===" "&&(f.char=Z.charCache[w]),I!==255&&f.fgColorIndex===255&&(f.fgColorIndex=I,f.fgEmission=this.getColorEmission(I)),M!==255){f.bgColorIndex===255&&(f.bgColorIndex=M,f.bgEmission=this.getColorEmission(M)),o[d]=1;break}}}return{width:e.width,height:e.height,cells:n,palette:this.colorCache}}rasterizeWithSortedLayers(e,t){let r=e.width*e.height,n=this.cellsBuffer;n.length=r;for(let s=0;s<r;s++)n[s]?(n[s].char=" ",n[s].fgColorIndex=255,n[s].bgColorIndex=255,n[s].fgEmission=0,n[s].bgEmission=0):n[s]={char:" ",fgColorIndex:255,bgColorIndex:255,fgEmission:0,bgEmission:0};this.opacityBuffer.length<r?this.opacityBuffer=new Uint8Array(r):this.opacityBuffer.fill(0,0,r);let o=this.opacityBuffer,i=this.visibleLayersBuffer;i.length=0;for(let s=0;s<t.length;s++){let a=t[s];this.isLayerVisible(e,a.getOrigin())&&i.push(a)}for(let s=0;s<e.height;s++)for(let a=0;a<e.width;a++){let d=s*e.width+a;if(o[d])continue;let c=e.x+a,l=e.y+s;for(let u=0;u<i.length;u++){let p=i[u],h=c-p.getOrigin().x,y=l-p.getOrigin().y,x=p.getWidth(),v=p.getHeight();if(h<0||h>=x||y<0||y>=v)continue;let U=y*x+h,S=p.getData(),w=S.getCharCode(U),I=S.getFgColorCode(U),M=S.getBgColorCode(U),f=n[d];if(w!==0&&w<256&&f.char===" "&&(f.char=Z.charCache[w]),I!==255&&f.fgColorIndex===255&&(f.fgColorIndex=I,f.fgEmission=this.getColorEmission(I)),M!==255){f.bgColorIndex===255&&(f.bgColorIndex=M,f.bgEmission=this.getColorEmission(M)),o[d]=1;break}}}return{width:e.width,height:e.height,cells:n,palette:this.colorCache}}calculateIntersection(e,t){let r=e.x,n=e.x+e.width,o=e.y,i=e.y+e.height,s=t.x,a=t.x+256,d=t.y,c=t.y+256,l=Math.max(r,s),u=Math.min(n,a),p=Math.max(o,d),h=Math.min(i,c);return{visible:l<u&&p<h,originStart:{x:l-e.x,y:p-e.y},originEnd:{x:u-e.x,y:h-e.y},layerStart:{x:l-t.x,y:p-t.y},layerEnd:{x:u-t.x,y:h-t.y}}}};g(Z,"DisplayRasterizer"),b(Z,"charCache",(()=>{let e=new Array(256);for(let t=0;t<256;t++)e[t]=String.fromCharCode(t);return e})());var Ye=Z;var At=class At{constructor(){b(this,"enabled",!1);b(this,"currentStats",null)}setEnabled(e){this.enabled=e,e||(this.currentStats=null)}isEnabled(){return this.enabled}get tick(){return this.currentStats?.tick??0}get timestamp(){return this.currentStats?.timestamp??0}get totalOrders(){return this.currentStats?.totalOrders??0}get ordersByLayer(){return this.currentStats?.ordersByLayer??new Map}get ordersByType(){return this.currentStats?.ordersByType??new Map}get totalLayers(){return this.currentStats?.totalLayers??0}get visibleLayers(){return this.currentStats?.visibleLayers??0}get layersPerDisplay(){return this.currentStats?.layersPerDisplay??new Map}get updatePacketSize(){return this.currentStats?.updatePacketSize??0}get displayHeaderSize(){return this.currentStats?.displayHeaderSize??0}get layerHeaderSize(){return this.currentStats?.layerHeaderSize??0}get orderDataSize(){return this.currentStats?.orderDataSize??0}get compressionRatio(){return this.currentStats?.compressionRatio??0}get compressedPacketSize(){return Math.round(this.updatePacketSize*this.compressionRatio)}get totalCells(){return this.currentStats?.totalCells??0}get nonEmptyCells(){return this.currentStats?.nonEmptyCells??0}get cellsWithBackground(){return this.currentStats?.cellsWithBackground??0}get rasterizationTimeMs(){return this.currentStats?.rasterizationTimeMs??0}get encodingTimeMs(){return this.currentStats?.encodingTimeMs??0}get packetSplit(){return this.currentStats?.packetSplit}get layerDetails(){return this.currentStats?.layerDetails}startTick(e){this.enabled&&(this.currentStats={tick:e,timestamp:Date.now(),totalOrders:0,ordersByLayer:new Map,ordersByType:new Map,totalLayers:0,visibleLayers:0,layersPerDisplay:new Map,updatePacketSize:0,displayHeaderSize:0,layerHeaderSize:0,orderDataSize:0,compressionRatio:0,totalCells:0,nonEmptyCells:0,cellsWithBackground:0,rasterizationTimeMs:0,encodingTimeMs:0})}recordLayerOrders(e,t){if(!(!this.enabled||!this.currentStats)){this.currentStats.totalOrders+=t.length,this.currentStats.ordersByLayer.set(e,t.length);for(let r of t){let n=this.currentStats.ordersByType.get(r.type)||0;this.currentStats.ordersByType.set(r.type,n+1)}}}recordLayers(e,t){!this.enabled||!this.currentStats||(this.currentStats.totalLayers=e,this.currentStats.visibleLayers=t)}recordDisplayLayers(e,t){!this.enabled||!this.currentStats||this.currentStats.layersPerDisplay.set(e,t)}recordUpdatePacketSize(e,t,r,n){!this.enabled||!this.currentStats||(this.currentStats.updatePacketSize=e,this.currentStats.displayHeaderSize=t,this.currentStats.layerHeaderSize=r,this.currentStats.orderDataSize=n,this.currentStats.compressionRatio=.25)}recordPacketSplit(e,t,r,n){!this.enabled||!this.currentStats||(this.currentStats.packetSplit={userId:e,displayCount:t,staticLayerCount:r,dynamicLayerCount:n})}recordLayerInfo(e,t,r,n){!this.enabled||!this.currentStats||(this.currentStats.layerDetails||(this.currentStats.layerDetails=[]),this.currentStats.layerDetails.push({layerId:e,isStatic:t,orderCount:r,updateFlags:n}))}recordRenderStats(e,t,r){!this.enabled||!this.currentStats||(this.currentStats.totalCells=e,this.currentStats.nonEmptyCells=t,this.currentStats.cellsWithBackground=r)}recordRasterizationTime(e){!this.enabled||!this.currentStats||(this.currentStats.rasterizationTimeMs=e)}recordEncodingTime(e){!this.enabled||!this.currentStats||(this.currentStats.encodingTimeMs=e)}endTick(){}reset(){this.currentStats=null}};g(At,"CoreStats");var ue=At;var Et=class Et{constructor(){b(this,"unicolorSprites",new Map);b(this,"multicolorSprites",new Map)}loadUnicolorSprites(e){for(let t of e.sprites){let r=new te(t.sizeX*t.sizeY);for(let o=0;o<t.data.length;o++)r.set(o,t.data[o]);let n={id:t.spriteId,sizeX:t.sizeX,sizeY:t.sizeY,data:r};this.unicolorSprites.set(n.id,n)}}loadMulticolorSprites(e){for(let t of e.sprites){let r=new _(t.sizeX*t.sizeY);for(let o=0;o<t.data.length;o++){let i=t.data[o];r.set(o,i.charCode,i.fgColorId,i.bgColorId)}let n={id:t.spriteId,sizeX:t.sizeX,sizeY:t.sizeY,data:r};this.multicolorSprites.set(n.id,n)}}getUnicolorSprite(e){return this.unicolorSprites.get(e)}getMulticolorSprite(e){return this.multicolorSprites.get(e)}hasUnicolorSprite(e){return this.unicolorSprites.has(e)}hasMulticolorSprite(e){return this.multicolorSprites.has(e)}unloadUnicolorSprite(e){return this.unicolorSprites.delete(e)}unloadMulticolorSprite(e){return this.multicolorSprites.delete(e)}clearUnicolorSprites(){this.unicolorSprites.clear()}clearMulticolorSprites(){this.multicolorSprites.clear()}clearAll(){this.unicolorSprites.clear(),this.multicolorSprites.clear()}getUnicolorSpriteCount(){return this.unicolorSprites.size}getMulticolorSpriteCount(){return this.multicolorSprites.size}getTotalSpriteCount(){return this.unicolorSprites.size+this.multicolorSprites.size}};g(Et,"SpriteRegistry");var pe=Et;var wr=(t=>(t.Web="web",t.Bitmap="bitmap",t))(wr||{}),Rt=class Rt{constructor(e,t){this.fontId=e;this.config=t}getFontId(){return this.fontId}getConfig(){return{...this.config}}getFontFamily(){return this.config.fontFamily}getFontSize(){return this.config.fontSize}getOffsetX(){return this.config.offsetX??0}getOffsetY(){return this.config.offsetY??0}getCharSpacing(){return this.config.charSpacing??0}getLineHeight(){return this.config.lineHeight??1.2}getFontWeight(){return this.config.fontWeight??"normal"}getFontStyle(){return this.config.fontStyle??"normal"}toCSS(){let e=[];e.push(`font-family: ${this.config.fontFamily}`),e.push(`font-size: ${this.config.fontSize}px`);let t=this.config.fontWeight??"normal";t!=="normal"&&e.push(`font-weight: ${t}`);let r=this.config.fontStyle??"normal";return r!=="normal"&&e.push(`font-style: ${r}`),e.join("; ")+";"}};g(Rt,"WebFont");var W=Rt,kt=class kt{constructor(e,t){this.fontId=e;this.config=t}getFontId(){return this.fontId}getConfig(){return{charWidth:this.config.charWidth,charHeight:this.config.charHeight,cellWidth:this.config.cellWidth,cellHeight:this.config.cellHeight,glyphs:new Map(this.config.glyphs)}}getCharWidth(){return this.config.charWidth}getCharHeight(){return this.config.charHeight}getCellWidth(){return this.config.cellWidth??this.config.charWidth}getCellHeight(){return this.config.cellHeight??this.config.charHeight}getGlyph(e){return this.config.glyphs.get(e)}hasGlyph(e){return this.config.glyphs.has(e)}getGlyphCount(){return this.config.glyphs.size}getCharCodes(){return Array.from(this.config.glyphs.keys())}};g(kt,"BitmapFont");var me=kt;var Pt=class Pt{constructor(){b(this,"fonts",new Map)}loadFont(e,t){if(this.fonts.has(e))throw new Error(`WebFont with ID ${e} already exists`);let r=new W(e,t);this.fonts.set(e,r)}getFont(e){return this.fonts.get(e)}hasFont(e){return this.fonts.has(e)}unloadFont(e){return this.fonts.delete(e)}clearFonts(){this.fonts.clear()}getFontIds(){return Array.from(this.fonts.keys()).sort((e,t)=>e-t)}getAllFonts(){return Array.from(this.fonts.entries()).sort((e,t)=>e[0]-t[0]).map(e=>e[1])}getFontCount(){return this.fonts.size}};g(Pt,"WebFontRegistry");var he=Pt;var Bt=class Bt{constructor(){b(this,"fonts",new Map)}loadFont(e,t){if(this.fonts.has(e))throw new Error(`BitmapFont with ID ${e} already exists`);let r=new me(e,t);this.fonts.set(e,r)}getFont(e){return this.fonts.get(e)}hasFont(e){return this.fonts.has(e)}unloadFont(e){return this.fonts.delete(e)}clearFonts(){this.fonts.clear()}getFontIds(){return Array.from(this.fonts.keys()).sort((e,t)=>e-t)}getAllFonts(){return Array.from(this.fonts.entries()).sort((e,t)=>e[0]-t[0]).map(e=>e[1])}getFontCount(){return this.fonts.size}};g(Bt,"BitmapFontRegistry");var be=Bt;var Tt=class Tt{constructor(){b(this,"sounds",new Map);b(this,"nameToId",new Map);b(this,"nextId",0)}registerFile(e,t,r){let n=this.allocateId(e),o={soundId:n,name:e,loadType:"file",format:t,data:r};return this.sounds.set(n,o),this.nameToId.set(e,n),n}registerFileWithId(e,t,r,n){this.validateId(e),this.checkIdAvailable(e,t);let o={soundId:e,name:t,loadType:"file",format:r,data:n};this.sounds.set(e,o),this.nameToId.set(t,e)}registerExternal(e,t,r,n,o){let i=this.allocateId(e),s={soundId:i,name:e,loadType:"external",format:t,url:r,size:n,checksum:o};return this.sounds.set(i,s),this.nameToId.set(e,i),i}registerExternalWithId(e,t,r,n,o,i){this.validateId(e),this.checkIdAvailable(e,t);let s={soundId:e,name:t,loadType:"external",format:r,url:n,size:o,checksum:i};this.sounds.set(e,s),this.nameToId.set(t,e)}get(e){if(typeof e=="number")return this.sounds.get(e);let t=this.nameToId.get(e);return t!==void 0?this.sounds.get(t):void 0}has(e){return this.get(e)!==void 0}getAll(){return Array.from(this.sounds.values())}getFileSounds(){return this.getAll().filter(e=>e.loadType==="file")}getExternalSounds(){return this.getAll().filter(e=>e.loadType==="external")}getNames(){return Array.from(this.nameToId.keys())}getId(e){return this.nameToId.get(e)}toLoadPackets(){let e=[],t=this.getFileSounds();if(t.length>0){let n=t.map(o=>({soundId:o.soundId,name:o.name,format:o.format,data:o.data}));e.push({type:"sound",mode:"file",sounds:n})}let r=this.getExternalSounds();if(r.length>0){let n=r.map(o=>({soundId:o.soundId,name:o.name,format:o.format,url:o.url,size:o.size,checksum:o.checksum}));e.push({type:"sound",mode:"external",sounds:n})}return e}toLoadPacket(e){let t=this.get(e);return t?t.loadType==="file"?{type:"sound",mode:"file",sounds:[{soundId:t.soundId,name:t.name,format:t.format,data:t.data}]}:{type:"sound",mode:"external",sounds:[{soundId:t.soundId,name:t.name,format:t.format,url:t.url,size:t.size,checksum:t.checksum}]}:null}unregister(e){let t=this.get(e);return t?(this.sounds.delete(t.soundId),this.nameToId.delete(t.name),!0):!1}clear(){this.sounds.clear(),this.nameToId.clear(),this.nextId=0}get size(){return this.sounds.size}getStats(){let e=this.getAll(),t=e.filter(n=>n.loadType==="file"),r=t.reduce((n,o)=>n+(o.data?.length??0),0);return{total:e.length,file:t.length,external:e.length-t.length,totalFileSize:r}}allocateId(e){if(this.nameToId.has(e))throw new Error(`Sound with name "${e}" already exists`);for(;this.sounds.has(this.nextId);)if(this.nextId++,this.nextId>255)throw new Error("Maximum number of sounds (256) reached");return this.nextId++}validateId(e){if(!Number.isInteger(e)||e<0||e>255)throw new Error(`Invalid sound ID: ${e}. Must be an integer between 0 and 255.`)}checkIdAvailable(e,t){if(this.sounds.has(e)){let r=this.sounds.get(e);throw new Error(`Sound ID ${e} is already used by "${r.name}". Cannot register "${t}".`)}if(this.nameToId.has(t))throw new Error(`Sound with name "${t}" already exists`)}};g(Tt,"SoundRegistry");var ge=Tt;var zt=class zt{constructor(e){this.soundRegistry=e}collectFromUser(e){let t=[],r=e.flushSoundCommands();for(let o of r){let i=this.convertSoundCommand(o);i&&t.push(i)}let n=e.flushAudioConfigCommands();for(let o of n){let i=this.convertConfigCommand(o);i&&t.push(i)}return t}convertSoundCommand(e){return"setEffects"in e&&e.setEffects===!0?this.convertSetEffectsCommand(e):"fadeOut"in e&&e.fadeOut===!0?this.convertFadeOutCommand(e):"pause"in e&&e.pause===!0?this.convertPauseCommand(e):"resume"in e&&e.resume===!0?this.convertResumeCommand(e):"instanceId"in e||"volume"in e||"pitch"in e||"loop"in e||"fadeIn"in e||"x"in e||"y"in e||"lowpass"in e||"highpass"in e||"reverb"in e?this.convertPlayCommand(e):this.convertStopCommand(e)}convertPlayCommand(e){let t=this.resolveSoundId(e.sound);if(t===null)return console.warn(`[AudioOrderCollector] Unknown sound: ${e.sound}`),null;let r=0;e.loop&&(r|=1),e.volume!==void 0&&(r|=2),e.pitch!==void 0&&(r|=4),e.fadeIn!==void 0&&(r|=8),e.lowpass!==void 0&&e.lowpass>0&&(r|=32),e.highpass!==void 0&&e.highpass>0&&(r|=64),e.reverb!==void 0&&e.reverb>0&&(r|=128);let n=e.x!==void 0&&e.y!==void 0;return n&&(r|=16),n?{type:1,soundId:t,instanceId:e.instanceId??0,flags:r,volume:e.volume!==void 0?this.encodeVolume(e.volume):void 0,pitch:e.pitch!==void 0?this.encodePitch(e.pitch):void 0,fadeIn:e.fadeIn!==void 0?this.encodeFadeTime(e.fadeIn):void 0,posX:this.encodePosition(e.x),posY:this.encodePosition(e.y),lowpass:e.lowpass!==void 0&&e.lowpass>0?this.encodeFilterFreq(e.lowpass):void 0,highpass:e.highpass!==void 0&&e.highpass>0?this.encodeFilterFreq(e.highpass):void 0,reverb:e.reverb!==void 0&&e.reverb>0?this.encodeReverb(e.reverb):void 0}:{type:2,soundId:t,instanceId:e.instanceId??0,flags:r&-17,volume:e.volume!==void 0?this.encodeVolume(e.volume):void 0,pitch:e.pitch!==void 0?this.encodePitch(e.pitch):void 0,fadeIn:e.fadeIn!==void 0?this.encodeFadeTime(e.fadeIn):void 0,lowpass:e.lowpass!==void 0&&e.lowpass>0?this.encodeFilterFreq(e.lowpass):void 0,highpass:e.highpass!==void 0&&e.highpass>0?this.encodeFilterFreq(e.highpass):void 0,reverb:e.reverb!==void 0&&e.reverb>0?this.encodeReverb(e.reverb):void 0}}convertStopCommand(e){let{targetType:t,target:r}=this.resolveTarget(e.sound);return{type:3,targetType:t,target:r}}convertFadeOutCommand(e){let{targetType:t,target:r}=this.resolveTarget(e.sound);return{type:4,targetType:t,duration:this.encodeFadeTime(e.duration),target:r}}convertPauseCommand(e){let{targetType:t,target:r}=this.resolveTarget(e.sound);return{type:5,targetType:t,target:r}}convertResumeCommand(e){let{targetType:t,target:r}=this.resolveTarget(e.sound);return{type:6,targetType:t,target:r}}convertSetEffectsCommand(e){let t=0;return e.lowpass!==void 0&&(t|=1),e.highpass!==void 0&&(t|=2),e.reverb!==void 0&&(t|=4),{type:9,instanceId:e.instanceId,flags:t,lowpass:e.lowpass!==void 0?this.encodeFilterFreq(e.lowpass):void 0,highpass:e.highpass!==void 0?this.encodeFilterFreq(e.highpass):void 0,reverb:e.reverb!==void 0?this.encodeReverb(e.reverb):void 0}}convertConfigCommand(e){return e.type==="set-listener-position"?{type:7,x:this.encodePosition(e.x),y:this.encodePosition(e.y)}:e.type==="configure-spatial"?{type:8,maxDistance:this.encodeDistance(e.maxDistance??1e3),referenceDistance:this.encodeDistance(e.referenceDistance??100),rolloffFactor:this.encodeRolloff(e.rolloffFactor??1),panSpread:this.encodePanSpread(e.panSpread??.5)}:null}resolveSoundId(e){if(typeof e=="number")return e>=0&&e<=255?e:null;let t=this.soundRegistry.getId(e);return t!==void 0?t:null}resolveTarget(e){if(e==="all")return{targetType:2,target:void 0};if(typeof e=="number")return{targetType:0,target:e};let t=this.soundRegistry.getId(e);return t!==void 0?{targetType:1,target:t}:(console.warn(`[AudioOrderCollector] Unknown sound name: ${e}, treating as 'all'`),{targetType:2,target:void 0})}encodeVolume(e){return Math.round(Math.max(0,Math.min(1,e))*255)}encodePitch(e){let t=Math.max(.25,Math.min(4,e)),r=64*Math.log2(t/.25);return Math.round(Math.max(0,Math.min(255,r)))}encodeFadeTime(e){return Math.round(Math.max(0,Math.min(25.5,e))*10)}encodeDistance(e){return Math.round(Math.max(0,Math.min(25500,e))/100)}encodeRolloff(e){return Math.round(Math.max(0,Math.min(2.55,e))*100)}encodePanSpread(e){return Math.round(Math.max(0,Math.min(1,e))*255)}encodePosition(e){return Math.round(Math.max(0,Math.min(65535,e)))}encodeFilterFreq(e){return e<=0?0:Math.round(Math.max(1,Math.min(255,e/100)))}encodeReverb(e){return Math.round(Math.max(0,Math.min(1,e))*255)}};g(zt,"AudioOrderCollector");var xe=zt;import{POST_PROCESS_DEFAULTS as D,GRID_DEFAULTS as vr,scalingModeToValue as Nn}from"@utsp/types";var Ft=class Ft{collectFromUser(e){let t=e.flushPostProcessCommands();return this.convertCommands(t)}convertCommands(e){let t=[];for(let r of e){let n=this.convertCommand(r);n&&t.push(n)}return t}convertCommand(e){switch(e.type){case"set-config":return this.convertSetConfig(e);case"set-scanlines-enabled":return this.createSetScanlinesOrder(e.enabled??!1,e.opacity);case"set-scanlines-opacity":return this.createSetScanlinesOrder(!0,e.opacity??D.scanlines.opacity);case"set-ambient-effect-enabled":return this.createSetAmbientEffectOrder(e.enabled??!1);case"set-ambient-effect-blur":return this.createSetAmbientEffectOrder(!0,e.blur);case"set-ambient-effect-scale":return this.createSetAmbientEffectOrder(!0,void 0,e.scale);case"set-scaling-mode":return this.createSetScalingModeOrder(e.scalingMode);case"set-grid":return this.createSetGridOrder(e.gridConfig);default:return console.warn(`[PostProcessOrderCollector] Unknown command type: ${e.type}`),null}}convertSetConfig(e){if(!e.config)return{type:1,flags:3,scanlines:{enabled:!1,opacity:0,pattern:0,colorR:0,colorG:0,colorB:0},ambientEffect:{enabled:!1,blur:0,scale:1,opacity:0}};let t=0,r={type:1,flags:0};if(e.config.scanlines){t|=1;let n=e.config.scanlines;r.scanlines={enabled:n.enabled,opacity:n.opacity??D.scanlines.opacity,pattern:this.patternToType(n.pattern??"horizontal"),colorR:n.color?.r??0,colorG:n.color?.g??0,colorB:n.color?.b??0}}if(e.config.ambientEffect){t|=2;let n=e.config.ambientEffect;r.ambientEffect={enabled:n.enabled,blur:n.blur??D.ambientEffect.blur,scale:n.scale??D.ambientEffect.scale,opacity:n.opacity??D.ambientEffect.opacity}}return r.flags=t,r}createSetScanlinesOrder(e,t){return{type:2,enabled:e,opacity:t??D.scanlines.opacity,pattern:0,colorR:0,colorG:0,colorB:0}}createSetAmbientEffectOrder(e,t,r){return{type:3,enabled:e,blur:t??D.ambientEffect.blur,scale:r??D.ambientEffect.scale,opacity:D.ambientEffect.opacity}}patternToType(e){switch(e){case"horizontal":return 0;case"vertical":return 1;case"grid":return 2;default:return 0}}createSetScalingModeOrder(e){return{type:4,mode:Nn(e)}}createSetGridOrder(e){let{r:t,g:r,b:n,a:o}=this.parseColor(e.color??vr.color);return{type:5,enabled:e.enabled,colorR:t,colorG:r,colorB:n,colorA:o,lineWidth:e.lineWidth??vr.lineWidth}}parseColor(e){let t=e.match(/rgba?\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+))?\s*\)/);if(t)return{r:parseInt(t[1],10),g:parseInt(t[2],10),b:parseInt(t[3],10),a:t[4]?Math.round(parseFloat(t[4])*255):255};let r=e.match(/^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$/);if(r){let n=r[1];return n.length===3?{r:parseInt(n[0]+n[0],16),g:parseInt(n[1]+n[1],16),b:parseInt(n[2]+n[2],16),a:255}:{r:parseInt(n.slice(0,2),16),g:parseInt(n.slice(2,4),16),b:parseInt(n.slice(4,6),16),a:255}}return{r:144,g:24,b:24,a:255}}};g(Ft,"PostProcessOrderCollector");var ye=Ft;var q=class q{constructor(e={}){b(this,"users",new Map);b(this,"mode");b(this,"maxUsers");b(this,"strictMode");b(this,"currentTick",0);b(this,"encoder");b(this,"displayRasterizer");b(this,"colorPalette",new Map);b(this,"stats",new ue);b(this,"spriteRegistry",new pe);b(this,"webFontRegistry",new he);b(this,"bitmapFontRegistry",new be);b(this,"soundRegistry",new ge);b(this,"audioOrderCollector");b(this,"postProcessOrderCollector");b(this,"activeWebFontId",0);b(this,"_renderCallCount",0);b(this,"onPaletteChangedCallback");b(this,"onBitmapFontChangedCallback");this.mode=e.mode??"server",this.maxUsers=e.maxUsers??64,this.strictMode=e.strictMode??!1,this.encoder=new Le,this.displayRasterizer=new Ye(this),this.audioOrderCollector=new xe(this.soundRegistry),this.postProcessOrderCollector=new ye,this.initializeDefaultPalette(),this.displayRasterizer.rebuildColorCache(),this.loadDefaultWebFont()}initializeDefaultPalette(){q.ANSI_VGA_COLORS.forEach(e=>{this.colorPalette.set(e.colorId,{r:e.r,g:e.g,b:e.b,a:e.a,e:e.e})}),this.colorPalette.set(255,{r:0,g:0,b:0,a:0,e:0})}getMode(){return this.mode}getMaxUsers(){return this.maxUsers}isStrictMode(){return this.strictMode}isServer(){return this.mode==="server"}isClient(){return this.mode==="client"}isStandalone(){return this.mode==="standalone"}createUser(e,t){if(this.users.has(e))throw new Error(`User with ID ${e} already exists`);if(this.mode==="server"&&this.users.size>=this.maxUsers)throw new Error(`Maximum number of users reached (${this.maxUsers}). Cannot create user ${e}`);if(this.mode==="client"&&this.users.size>=1)throw new Error(`Client mode only allows one user. Cannot create user ${e}`);let r=new le(e,t,this.mode);return r.setSpriteRegistry(this.spriteRegistry),this.users.set(e,r),r}getUser(e){return this.users.get(e)??null}getUsers(){return Array.from(this.users.values())}hasUser(e){return this.users.has(e)}removeUser(e){return this.users.delete(e)}getUserCount(){return this.users.size}clearAllUsers(){this.users.clear()}setColor(e,t,r,n,o=255,i=0){if(e<0||e>255)throw new Error(`Color ID must be between 0 and 255, got ${e}`);if(e>=240)throw new Error("Color IDs 240-255 are reserved (240-254: UI palette, 255: skip color). Use IDs 0-239 for custom colors.");if(t<0||t>255||r<0||r>255||n<0||n>255||o<0||o>255||i<0||i>255)throw new Error("Color components must be between 0 and 255");this.colorPalette.set(e,{r:t,g:r,b:n,a:o,e:i}),this.onPaletteChangedCallback&&this.onPaletteChangedCallback(this.colorPalette)}onPaletteChanged(e){this.onPaletteChangedCallback=e}onBitmapFontChanged(e){this.onBitmapFontChangedCallback=e}getColor(e){return this.colorPalette.get(e)??null}loadPalette(e){for(let t of e)t.colorId<0||t.colorId>255||this.colorPalette.set(t.colorId,{r:t.r,g:t.g,b:t.b,a:t.a,e:t.e??0});q.ANSI_VGA_COLORS.forEach(t=>{this.colorPalette.set(t.colorId,{r:t.r,g:t.g,b:t.b,a:t.a,e:t.e})}),this.colorPalette.set(255,{r:0,g:0,b:0,a:0,e:0}),this.displayRasterizer.rebuildColorCache(),this.onPaletteChangedCallback&&this.onPaletteChangedCallback(this.colorPalette)}getPalette(){return new Map(this.colorPalette)}resetPalette(){this.colorPalette.clear(),this.initializeDefaultPalette(),this.onPaletteChangedCallback&&this.onPaletteChangedCallback(this.colorPalette)}getColorCSS(e){let t=this.getColor(e);if(!t)return null;let r=t.a/255;return`rgba(${t.r}, ${t.g}, ${t.b}, ${r})`}getUserIds(){return Array.from(this.users.keys())}forEachUser(e){this.users.forEach(e)}filterUsers(e){return this.getUsers().filter(e)}findUser(e){return this.getUsers().find(e)}getCurrentTick(){return this.currentTick}getStats(){return this.stats}endTick(){this.stats.isEnabled()&&this.stats.startTick(this.currentTick);let e=new Map,t=0,r=0;return this.users.forEach((n,o)=>{let i=n.getLayers(),s=n.getDisplays();t+=i.length,n.getStats().isEnabled()&&n.getStats().startTick(this.currentTick);let a=s.map(x=>{let v=x.getOrigin(),U=x.getSize();return{id:x.getId(),originX:v.x,originY:v.y,sizeX:U.x,sizeY:U.y}});s.forEach(x=>x.resetChangeTracking());let d=[],c=[];i.forEach((x,v)=>{let U=x.getOrigin(),S=x.getOrders(),w=x.getStatic(),I=x.calculateUpdateFlags();x.resetChangeTracking(),x.getId()===0&&x.setId(v);let M={id:x.getId(),updateFlags:I,zIndex:x.getZOrder(),originX:U.x,originY:U.y,width:x.getWidth(),height:x.getHeight(),orderCount:S.length,orders:S};w?d.push(M):c.push(M)}),r+=d.length+c.length;let l=this.audioOrderCollector.collectFromUser(n),u=n.flushMacroOrders(),p=this.postProcessOrderCollector.collectFromUser(n),h=[...d,...c],y=this.encoder.encode({tick:this.currentTick,displayCount:a.length,displays:a,layerCount:h.length,layers:h,audioOrderCount:l.length,audioOrders:l,macroOrderCount:u.length,macroOrders:u,postProcessOrderCount:p.length,postProcessOrders:p});if(e.set(o,y),this.stats.isEnabled()){h.forEach((S,w)=>{this.stats.recordLayerOrders(w,S.orders)}),s.forEach((S,w)=>{this.stats.recordDisplayLayers(w,h.length)});let x=s.length*12,v=h.length*20,U=y.length-x-v;this.stats.recordUpdatePacketSize(y.length,x,v,U>0?U:0)}}),this.stats.isEnabled()&&(this.stats.recordLayers(t,r),this.stats.endTick()),this.currentTick++,e}endTickSplit(){this.stats.isEnabled()&&this.stats.startTick(this.currentTick);let e=new Map,t=0,r=0;return this.users.forEach((n,o)=>{let i=n.getLayers(),s=n.getDisplays();t+=i.length,n.getStats().isEnabled()&&n.getStats().startTick(this.currentTick);let a=s.map(x=>{let v=x.getOrigin(),U=x.getSize();return{id:x.getId(),originX:v.x,originY:v.y,sizeX:U.x,sizeY:U.y}});s.forEach(x=>x.resetChangeTracking());let d=[],c=[];i.forEach((x,v)=>{if(!x.getNeedsCommit())return;let U=x.getOrigin(),S=x.getOrders(),w=x.getStatic(),I=x.calculateUpdateFlags();x.resetChangeTracking(),x.resetCommit(),x.getId()===0&&x.setId(v);let M={id:x.getId(),updateFlags:I,zIndex:x.getZOrder(),originX:U.x,originY:U.y,width:x.getWidth(),height:x.getHeight(),orderCount:S.length,orders:S};S.length>0&&this.stats.isEnabled()&&this.stats.recordLayerInfo(x.getId(),w,S.length,I),w?d.push(M):c.push(M)}),r+=d.length+c.length;let l=this.audioOrderCollector.collectFromUser(n),u=this.postProcessOrderCollector.collectFromUser(n),p=n.flushMacroOrders(),h=null,y=null;if(this.stats.isEnabled()&&this.stats.recordPacketSplit(o,a.length,d.length,c.length),d.length>0&&(h=this.encoder.encode({tick:this.currentTick,displayCount:a.length,displays:a,layerCount:d.length,layers:d,audioOrderCount:0,audioOrders:[],macroOrderCount:0,macroOrders:[],postProcessOrderCount:0,postProcessOrders:[]})),y=this.encoder.encode({tick:this.currentTick,displayCount:a.length,displays:a,layerCount:c.length,layers:c,audioOrderCount:l.length,audioOrders:l,macroOrderCount:p.length,macroOrders:p,postProcessOrderCount:u.length,postProcessOrders:u}),e.set(o,{static:h,dynamic:y}),n.getStats().isEnabled()){let x=s.reduce((w,I)=>{let M=I.getSize();return w+M.x*M.y},0);n.getStats().recordDisplays(s.length,x),n.getStats().recordLayers(i.length,d.length+c.length,d.length,c.length),[...d,...c].forEach(w=>{n.getStats().recordLayerOrders(w.id,w.orders.length)});let v=h?.length||0,U=y?.length||0;n.getStats().recordPacketSizes(v,U);let S=n.getInputBindingRegistry();n.getStats().recordInput(!1,S.getAxisCount(),S.getButtonCount()),n.getStats().endTick()}if(this.stats.isEnabled()){let x=[...d,...c];x.forEach((I,M)=>{this.stats.recordLayerOrders(M,I.orders)}),s.forEach((I,M)=>{this.stats.recordDisplayLayers(M,x.length)});let v=(h?.length||0)+(y?.length||0),U=s.length*12,S=x.length*20,w=v-U-S;this.stats.recordUpdatePacketSize(v,U,S,w>0?w:0)}}),this.stats.isEnabled()&&(this.stats.recordLayers(t,r),this.stats.endTick()),this.currentTick++,e}getSnapshot(e){let t=this.getUser(e);if(!t)return null;let r=t.getDisplays(),n=t.getLayers(),o=r.map((s,a)=>{let d=s.getOrigin(),c=s.getSize();return{id:a,originX:d.x,originY:d.y,sizeX:c.x,sizeY:c.y}}),i=n.map((s,a)=>{let d=s.getOrigin(),c=s.getOrders(),l=7;return s.getId()===0&&s.setId(a),{id:s.getId(),updateFlags:l,zIndex:s.getZOrder(),originX:d.x,originY:d.y,width:s.getWidth(),height:s.getHeight(),orderCount:c.length,orders:c}});return this.encoder.encode({tick:this.currentTick,displayCount:o.length,displays:o,layerCount:i.length,layers:i,audioOrderCount:0,audioOrders:[],macroOrderCount:0,macroOrders:[],postProcessOrderCount:0,postProcessOrders:[]})}resetTick(){this.currentTick=0}applyUpdatePacket(e,t){let r=this.getUser(e);if(!r){if(this.strictMode)throw new Error(`Cannot apply update packet: user ${e} does not exist`);return!1}return r.applyUpdate(t),t.audioOrders&&t.audioOrders.length>0&&r.applyAudioOrders(t.audioOrders),!0}applyUpdatePacketBuffer(e,t){let{UpdatePacketDecoder:r}=($t(),B(kr)),o=new r().decode(t);return this.applyUpdatePacket(e,o)?o:null}applyLoadPacket(e){try{let{LoadDecoder:t}=(Tr(),B(Br)),{LoadType:r}=(X(),B(H)),i=new t().decode(e).load;switch(i.loadType){case r.ColorPalette:this.loadPalette(i.colors);break;case r.Sprite:this.loadUnicolorSprites(i);break;case r.MulticolorSprite:this.loadMulticolorSprites(i);break;case r.BitmapFont:{let s=this.getBitmapFontRegistry();s.hasFont(i.fontId)&&s.unloadFont(i.fontId),s.loadFont(i.fontId,{charWidth:i.width,charHeight:i.height,cellWidth:i.cellWidth,cellHeight:i.cellHeight,glyphs:new Map(i.characters.map(a=>[a.charCode,a.bitmap]))});break}case r.WebFont:{let s=this.getWebFontRegistry();s.hasFont(i.fontId)&&s.unloadFont(i.fontId),this.loadWebFontById(i.fontId,{fontFamily:i.fontFamily,fontSize:i.fontSize,offsetX:i.offsetX,offsetY:i.offsetY,charSpacing:i.charSpacing,lineHeight:i.lineHeight,fontWeight:i.fontWeight,fontStyle:i.fontStyle});break}case r.Sound:console.warn("[Core] Sound loading not yet implemented");break;case r.Macro:{for(let s of this.users.values())s.loadMacroTemplate(i.macroId,i.template);break}default:return console.error(`[Core] Unknown LoadType: ${i.loadType}`),!1}return!0}catch(t){return console.error("[Core] Failed to apply LoadPacket:",t),!1}}generatePaletteLoadPacket(){let e=this.getPalette();if(e.size===0)return null;let{LoadEncoder:t}=(J(),B(j)),{LoadType:r}=(X(),B(H)),n=new t,o=[];return e.forEach((i,s)=>{s!==255&&o.push({colorId:s,r:i.r,g:i.g,b:i.b,a:i.a,e:i.e})}),n.encode({loadType:r.ColorPalette,colors:o})}generateUnicolorSpritesLoadPacket(){let e=this.getSpriteRegistry(),t=[];for(let i=0;i<=255;i++){let s=e.getUnicolorSprite(i);if(s){let a=[];for(let d=0;d<s.sizeX*s.sizeY;d++)a.push(s.data.get(d));t.push({spriteId:s.id,sizeX:s.sizeX,sizeY:s.sizeY,data:a})}}if(t.length===0)return null;let{LoadEncoder:r}=(J(),B(j)),{LoadType:n}=(X(),B(H));return new r().encode({loadType:n.Sprite,sprites:t})}generateMulticolorSpritesLoadPacket(){let e=this.getSpriteRegistry(),t=[];for(let i=0;i<=255;i++){let s=e.getMulticolorSprite(i);if(s){let a=[];for(let d=0;d<s.sizeX*s.sizeY;d++){let c=s.data.get(d);a.push({charCode:c.charCode,fgColorId:c.fgColorCode,bgColorId:c.bgColorCode})}t.push({spriteId:s.id,sizeX:s.sizeX,sizeY:s.sizeY,data:a})}}if(t.length===0)return null;let{LoadEncoder:r}=(J(),B(j)),{LoadType:n}=(X(),B(H));return new r().encode({loadType:n.MulticolorSprite,sprites:t})}generateWebFontsLoadPackets(){let e=this.getWebFontRegistry(),t=e.getFontIds(),r=[],{LoadEncoder:n}=(J(),B(j)),{LoadType:o}=(X(),B(H)),i=new n;for(let s of t){let a=e.getFont(s);if(a){let d=a.getConfig(),c=i.encode({loadType:o.WebFont,fontId:s,fontFamily:d.fontFamily,fontSize:d.fontSize,offsetX:d.offsetX,offsetY:d.offsetY,charSpacing:d.charSpacing,lineHeight:d.lineHeight,fontWeight:d.fontWeight,fontStyle:d.fontStyle});r.push(c)}}return r}generateBitmapFontsLoadPackets(){let e=this.getBitmapFontRegistry(),t=e.getFontIds(),r=[],{LoadEncoder:n}=(J(),B(j)),{LoadType:o}=(X(),B(H)),i=new n;for(let s of t){let a=e.getFont(s);if(a){let d=[];for(let c=0;c<256;c++){let l=a.getGlyph(c);l&&d.push({charCode:c,bitmap:l})}if(d.length>0){let c=i.encode({loadType:o.BitmapFont,fontId:s,width:a.getCharWidth(),height:a.getCharHeight(),cellWidth:a.getCellWidth(),cellHeight:a.getCellHeight(),characters:d});r.push(c)}}}return r}generateAllLoadPackets(){let e=[],t=this.generatePaletteLoadPacket();t&&e.push(t);let r=this.generateUnicolorSpritesLoadPacket();r&&e.push(r);let n=this.generateMulticolorSpritesLoadPacket();n&&e.push(n);let o=this.generateWebFontsLoadPackets();e.push(...o);let i=this.generateBitmapFontsLoadPackets();return e.push(...i),e}generateMacroLoadPackets(e){let t=this.getUser(e);if(!t)return[];let r=t.getMacroLoads();if(r.length===0)return[];let n=new De;return r.map(o=>n.encode(o))}applyInputBindingsLoadPacket(e,t){let r=this.getUser(e);if(!r){if(this.strictMode)throw new Error(`Cannot apply input bindings: user ${e} does not exist`);return!1}try{return r.applyInputBindingsLoadPacket(t),!0}catch(n){return console.error(`[Core] Failed to apply input bindings for user ${e}:`,n),!1}}getRenderState(e){let t=this.getUser(e);if(!t)return null;let r=t.getDisplays(),n=t.getLayers(),o=performance.now(),i=new Array(r.length);for(let a=0;a<r.length;a++){let d=r[a],c=d.getOrigin(),l=d.getSize();i[a]=this.displayRasterizer.rasterize({x:c.x,y:c.y,width:l.x,height:l.y},n)}let s=performance.now()-o;return this._renderCallCount||(this._renderCallCount=0),this._renderCallCount++,{userId:t.id,userName:t.name,tick:this.currentTick,displays:i}}getAllRenderStates(){let e=new Map;return this.users.forEach((t,r)=>{let n=this.getRenderState(r);n&&e.set(r,n)}),e}enableStats(e){this.stats.setEnabled(e)}getStatsInstance(){return this.stats}resetStats(){this.stats.reset()}loadUnicolorSprites(e){this.spriteRegistry.loadUnicolorSprites(e)}loadMulticolorSprites(e){this.spriteRegistry.loadMulticolorSprites(e)}unloadUnicolorSprite(e){return this.spriteRegistry.unloadUnicolorSprite(e)}unloadMulticolorSprite(e){return this.spriteRegistry.unloadMulticolorSprite(e)}clearUnicolorSprites(){this.spriteRegistry.clearUnicolorSprites()}clearMulticolorSprites(){this.spriteRegistry.clearMulticolorSprites()}clearAllSprites(){this.spriteRegistry.clearAll()}getUnicolorSpriteCount(){return this.spriteRegistry.getUnicolorSpriteCount()}getMulticolorSpriteCount(){return this.spriteRegistry.getMulticolorSpriteCount()}getTotalSpriteCount(){return this.spriteRegistry.getTotalSpriteCount()}hasUnicolorSprite(e){return this.spriteRegistry.hasUnicolorSprite(e)}hasMulticolorSprite(e){return this.spriteRegistry.hasMulticolorSprite(e)}getSpriteRegistry(){return this.spriteRegistry}getSoundRegistry(){return this.soundRegistry}async loadSound(e,t){let r=this.detectSoundFormat(t),n=await this.loadSoundData(t);return this.soundRegistry.registerFile(e,r,n)}async loadSounds(e){let t={},n=Object.entries(e).map(async([o,i])=>{let s=await this.loadSound(o,i);t[o]=s});return await Promise.all(n),t}detectSoundFormat(e){let t=e.split(".").pop()?.toLowerCase()??"",r={mp3:"mp3",wav:"wav",ogg:"ogg",webm:"webm",aac:"aac",m4a:"aac"},n=r[t];if(!n)throw new Error(`Unsupported audio format: .${t}. Supported: ${Object.keys(r).join(", ")}`);return n}async loadSoundData(e){let t=globalThis;if(typeof t.document<"u"||typeof t.window<"u"||typeof t.fetch=="function")try{let n=await fetch(e);if(!n.ok)throw new Error(`HTTP ${n.status}: ${n.statusText}`);let o=await n.arrayBuffer();return new Uint8Array(o)}catch(n){let o=n instanceof Error?n.message:String(n);throw new Error(`Failed to load sound "${e}": ${o}`)}else{let n=typeof Ge<"u"?Ge:null;if(!n)throw new Error("Node.js require is not available");let s=n("fs").readFileSync(e);return new Uint8Array(s)}}registerSound(e,t,r){return this.soundRegistry.registerFile(e,t,r)}registerExternalSound(e,t,r,n){return this.soundRegistry.registerExternal(e,t,r,n)}hasSound(e){return this.soundRegistry.has(e)}generateSoundLoadPackets(){return this.soundRegistry.toLoadPackets()}loadDefaultWebFont(){this.webFontRegistry.loadFont(0,{fontFamily:"Courier New",fontSize:16,offsetX:0,offsetY:0,charSpacing:0,lineHeight:1,fontWeight:"normal",fontStyle:"normal"}),this.activeWebFontId=0}loadWebFont(e){let t=e.getFontId(),r=e.getConfig();this.webFontRegistry.loadFont(t,r)}getWebFont(e){return this.webFontRegistry.getFont(e)??null}hasWebFont(e){return this.webFontRegistry.hasFont(e)}unloadWebFont(e){if(e===0)throw new Error("Cannot unload default font (fontId 0)");return this.webFontRegistry.unloadFont(e)}clearWebFonts(){this.webFontRegistry.clearFonts(),this.loadDefaultWebFont()}setActiveWebFont(e){if(!this.webFontRegistry.hasFont(e))throw new Error(`WebFont with ID ${e} does not exist`);this.activeWebFontId=e}getActiveWebFontId(){return this.activeWebFontId}getActiveWebFont(){let e=this.webFontRegistry.getFont(this.activeWebFontId);if(!e)throw new Error(`Active WebFont ${this.activeWebFontId} not found. This should not happen.`);return e}getWebFontCount(){return this.webFontRegistry.getFontCount()}getWebFontIds(){return this.webFontRegistry.getFontIds()}getWebFontRegistry(){return this.webFontRegistry}getBitmapFontRegistry(){return this.bitmapFontRegistry}loadWebFontById(e,t){let r=new W(e,t);this.loadWebFont(r)}loadBitmapFontById(e,t){this.bitmapFontRegistry.loadFont(e,t),this.onBitmapFontChangedCallback&&this.onBitmapFontChangedCallback(e)}getBitmapFont(e){return this.bitmapFontRegistry.getFont(e)??null}hasBitmapFont(e){return this.bitmapFontRegistry.hasFont(e)}unloadBitmapFont(e){return this.bitmapFontRegistry.unloadFont(e)}clearBitmapFonts(){this.bitmapFontRegistry.clearFonts()}getBitmapFontCount(){return this.bitmapFontRegistry.getFontCount()}getBitmapFontIds(){return this.bitmapFontRegistry.getFontIds()}};g(q,"Core"),b(q,"ANSI_VGA_COLORS",[{colorId:240,r:16,g:16,b:16,a:255,e:0},{colorId:241,r:128,g:128,b:128,a:255,e:0},{colorId:242,r:192,g:192,b:192,a:255,e:0},{colorId:243,r:240,g:240,b:240,a:255,e:0},{colorId:244,r:200,g:50,b:50,a:255,e:0},{colorId:245,r:50,g:200,b:50,a:255,e:0},{colorId:246,r:220,g:180,b:50,a:255,e:0},{colorId:247,r:50,g:100,b:220,a:255,e:0},{colorId:248,r:50,g:200,b:200,a:255,e:0},{colorId:249,r:200,g:50,b:200,a:255,e:0},{colorId:250,r:220,g:120,b:50,a:255,e:0},{colorId:251,r:120,g:220,b:120,a:255,e:0},{colorId:252,r:120,g:180,b:220,a:255,e:0},{colorId:253,r:220,g:150,b:200,a:255,e:0},{colorId:254,r:250,g:220,b:150,a:255,e:0}]);var Kt=q;import{Vector2 as Ba}from"@utsp/types";var K=new Map([[24,new Uint8Array([0,24,60,126,255,255,0,0])],[25,new Uint8Array([0,0,255,255,126,60,24,0])],[26,new Uint8Array([0,48,120,252,252,120,48,0])],[27,new Uint8Array([0,12,30,63,63,30,12,0])],[32,new Uint8Array([0,0,0,0,0,0,0,0])],[33,new Uint8Array([24,24,24,24,24,0,24,0])],[34,new Uint8Array([108,108,108,0,0,0,0,0])],[35,new Uint8Array([54,54,127,54,127,54,54,0])],[36,new Uint8Array([12,63,104,62,11,126,24,0])],[37,new Uint8Array([96,102,12,24,48,102,6,0])],[38,new Uint8Array([56,108,108,56,109,102,59,0])],[39,new Uint8Array([24,24,24,0,0,0,0,0])],[40,new Uint8Array([12,24,48,48,48,24,12,0])],[41,new Uint8Array([48,24,12,12,12,24,48,0])],[42,new Uint8Array([0,102,60,255,60,102,0,0])],[43,new Uint8Array([0,24,24,126,24,24,0,0])],[44,new Uint8Array([0,0,0,0,0,24,24,48])],[45,new Uint8Array([0,0,0,126,0,0,0,0])],[46,new Uint8Array([0,0,0,0,0,24,24,0])],[47,new Uint8Array([0,6,12,24,48,96,0,0])],[48,new Uint8Array([60,102,110,126,118,102,60,0])],[49,new Uint8Array([24,56,24,24,24,24,126,0])],[50,new Uint8Array([60,102,6,12,24,48,126,0])],[51,new Uint8Array([60,102,6,28,6,102,60,0])],[52,new Uint8Array([12,28,60,108,126,12,12,0])],[53,new Uint8Array([126,96,124,6,6,102,60,0])],[54,new Uint8Array([28,48,96,124,102,102,60,0])],[55,new Uint8Array([126,6,12,24,48,48,48,0])],[56,new Uint8Array([60,102,102,60,102,102,60,0])],[57,new Uint8Array([60,102,102,62,6,12,56,0])],[58,new Uint8Array([0,0,24,24,0,24,24,0])],[59,new Uint8Array([0,0,24,24,0,24,24,48])],[60,new Uint8Array([12,24,48,96,48,24,12,0])],[61,new Uint8Array([0,0,126,0,126,0,0,0])],[62,new Uint8Array([48,24,12,6,12,24,48,0])],[63,new Uint8Array([60,102,12,24,24,0,24,0])],[64,new Uint8Array([60,102,110,106,110,96,60,0])],[65,new Uint8Array([60,102,102,126,102,102,102,0])],[66,new Uint8Array([124,102,102,124,102,102,124,0])],[67,new Uint8Array([60,102,96,96,96,102,60,0])],[68,new Uint8Array([120,108,102,102,102,108,120,0])],[69,new Uint8Array([126,96,96,124,96,96,126,0])],[70,new Uint8Array([126,96,96,124,96,96,96,0])],[71,new Uint8Array([60,102,96,110,102,102,60,0])],[72,new Uint8Array([102,102,102,126,102,102,102,0])],[73,new Uint8Array([126,24,24,24,24,24,126,0])],[74,new Uint8Array([62,12,12,12,12,108,56,0])],[75,new Uint8Array([102,108,120,112,120,108,102,0])],[76,new Uint8Array([96,96,96,96,96,96,126,0])],[77,new Uint8Array([99,119,127,107,99,99,99,0])],[78,new Uint8Array([102,102,118,126,110,102,102,0])],[79,new Uint8Array([60,102,102,102,102,102,60,0])],[80,new Uint8Array([124,102,102,124,96,96,96,0])],[81,new Uint8Array([60,102,102,102,106,108,54,0])],[82,new Uint8Array([124,102,102,124,108,102,102,0])],[83,new Uint8Array([60,102,96,60,6,102,60,0])],[84,new Uint8Array([126,24,24,24,24,24,24,0])],[85,new Uint8Array([102,102,102,102,102,102,60,0])],[86,new Uint8Array([102,102,102,102,102,60,24,0])],[87,new Uint8Array([99,99,99,107,127,119,99,0])],[88,new Uint8Array([102,102,60,24,60,102,102,0])],[89,new Uint8Array([102,102,102,60,24,24,24,0])],[90,new Uint8Array([126,6,12,24,48,96,126,0])],[91,new Uint8Array([60,48,48,48,48,48,60,0])],[92,new Uint8Array([0,96,48,24,12,6,0,0])],[93,new Uint8Array([60,12,12,12,12,12,60,0])],[94,new Uint8Array([24,60,102,0,0,0,0,0])],[95,new Uint8Array([0,0,0,0,0,0,255,0])],[96,new Uint8Array([48,24,12,0,0,0,0,0])],[97,new Uint8Array([0,0,60,6,62,102,62,0])],[98,new Uint8Array([96,96,124,102,102,102,124,0])],[99,new Uint8Array([0,0,60,102,96,102,60,0])],[100,new Uint8Array([6,6,62,102,102,102,62,0])],[101,new Uint8Array([0,0,60,102,126,96,60,0])],[102,new Uint8Array([28,54,48,124,48,48,48,0])],[103,new Uint8Array([0,0,62,102,102,62,6,60])],[104,new Uint8Array([96,96,124,102,102,102,102,0])],[105,new Uint8Array([24,0,56,24,24,24,60,0])],[106,new Uint8Array([12,0,28,12,12,12,108,56])],[107,new Uint8Array([96,96,102,108,120,108,102,0])],[108,new Uint8Array([56,24,24,24,24,24,60,0])],[109,new Uint8Array([0,0,102,127,107,107,99,0])],[110,new Uint8Array([0,0,124,102,102,102,102,0])],[111,new Uint8Array([0,0,60,102,102,102,60,0])],[112,new Uint8Array([0,0,124,102,102,124,96,96])],[113,new Uint8Array([0,0,62,102,102,62,6,6])],[114,new Uint8Array([0,0,108,118,96,96,96,0])],[115,new Uint8Array([0,0,62,96,60,6,124,0])],[116,new Uint8Array([48,48,124,48,48,54,28,0])],[117,new Uint8Array([0,0,102,102,102,102,62,0])],[118,new Uint8Array([0,0,102,102,102,60,24,0])],[119,new Uint8Array([0,0,99,107,107,127,54,0])],[120,new Uint8Array([0,0,102,60,24,60,102,0])],[121,new Uint8Array([0,0,102,102,102,62,6,60])],[122,new Uint8Array([0,0,126,12,24,48,126,0])],[123,new Uint8Array([14,24,24,112,24,24,14,0])],[124,new Uint8Array([24,24,24,24,24,24,24,0])],[125,new Uint8Array([112,24,24,14,24,24,112,0])],[126,new Uint8Array([49,107,70,0,0,0,0,0])],[179,new Uint8Array([24,24,24,24,24,24,24,24])],[196,new Uint8Array([0,0,0,255,0,0,0,0])],[218,new Uint8Array([0,0,0,31,24,24,24,24])],[191,new Uint8Array([0,0,0,248,24,24,24,24])],[192,new Uint8Array([24,24,24,31,0,0,0,0])],[217,new Uint8Array([24,24,24,248,0,0,0,0])],[195,new Uint8Array([24,24,24,31,24,24,24,24])],[180,new Uint8Array([24,24,24,248,24,24,24,24])],[194,new Uint8Array([0,0,0,255,24,24,24,24])],[193,new Uint8Array([24,24,24,255,0,0,0,0])],[197,new Uint8Array([24,24,24,255,24,24,24,24])],[186,new Uint8Array([54,54,54,54,54,54,54,54])],[205,new Uint8Array([0,0,0,255,0,255,0,0])],[201,new Uint8Array([0,0,0,63,54,54,54,54])],[187,new Uint8Array([0,0,0,252,54,54,54,54])],[200,new Uint8Array([54,54,54,63,0,0,0,0])],[188,new Uint8Array([54,54,54,252,0,0,0,0])],[204,new Uint8Array([54,54,54,63,54,54,54,54])],[185,new Uint8Array([54,54,54,252,54,54,54,54])],[203,new Uint8Array([0,0,0,255,54,54,54,54])],[202,new Uint8Array([54,54,54,255,0,0,0,0])],[206,new Uint8Array([54,54,54,255,54,54,54,54])],[219,new Uint8Array([255,255,255,255,255,255,255,255])],[178,new Uint8Array([170,85,170,85,170,85,170,85])],[177,new Uint8Array([136,34,136,34,136,34,136,34])],[176,new Uint8Array([34,136,34,136,34,136,34,136])],[223,new Uint8Array([255,255,255,255,0,0,0,0])],[220,new Uint8Array([0,0,0,0,255,255,255,255])],[221,new Uint8Array([240,240,240,240,240,240,240,240])],[222,new Uint8Array([15,15,15,15,15,15,15,15])]]);function _n(m){return K.get(m)}g(_n,"getCharBitmap");function Hn(m){return K.has(m)}g(Hn,"hasChar");function Wn(){return Array.from(K.keys()).sort((m,e)=>m-e)}g(Wn,"getAllCharCodes");function Vn(m){let e=Array.from(K.entries()).map(([t,r])=>({charCode:t,bitmap:r}));return{loadType:4,fontId:m,width:8,height:8,cellWidth:8,cellHeight:8,characters:e}}g(Vn,"createASCII8x8FontLoad");function $n(){return{charWidth:8,charHeight:8,glyphs:new Map(K)}}g($n,"getASCII8x8FontConfig");T();var Qt=class Qt{encode(e){switch(e.type){case 1:return this.encodeClick(e);case 2:return this.encodeChange(e);case 3:return this.encodeSubmit(e);case 4:return this.encodeSelect(e);default:throw new Error(`Unknown macro event type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return 2;case 2:return this.calculateChangeSize(e);case 3:return this.calculateSubmitSize(e);case 4:return 4;default:throw new Error(`Unknown macro event type: ${e.type}`)}}encodeClick(e){let t=C.allocUnsafe(2);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.toUint8Array()}encodeChange(e){if(typeof e.value=="boolean"){let r=C.allocUnsafe(4);return r.writeUInt8(e.type,0),r.writeUInt8(e.instanceId,1),r.writeUInt8(1,2),r.writeUInt8(e.value?1:0,3),r.toUint8Array()}else{let r=C.allocUnsafe(7);return r.writeUInt8(e.type,0),r.writeUInt8(e.instanceId,1),r.writeUInt8(0,2),r.writeFloatBE(e.value,3),r.toUint8Array()}}calculateChangeSize(e){return typeof e.value=="boolean"?4:7}encodeSubmit(e){let t=new TextEncoder().encode(e.text);if(t.length>65535)throw new Error(`Submit text too large: ${t.length} bytes (max 65535)`);let r=4+t.length,n=C.allocUnsafe(r),o=0;return n.writeUInt8(e.type,o++),n.writeUInt8(e.instanceId,o++),n.writeUInt16BE(t.length,o),o+=2,n.toUint8Array().set(t,o),n.toUint8Array()}calculateSubmitSize(e){return 4+new TextEncoder().encode(e.text).length}encodeSelect(e){let t=C.allocUnsafe(4);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.writeUInt16BE(e.index,2),t.toUint8Array()}};g(Qt,"MacroEventEncoder");var $e=Qt;function Gn(m,e,t,r,n,o,i,s=[],a=[]){let d=Array.from(e.entries()).sort((A,O)=>A[0]-O[0]),c=Array.from(t.entries()).sort((A,O)=>A[0]-O[0]),l=d.length,u=c.length,p=lt(l,u),h=new TextEncoder,y=s.map(A=>h.encode(A)),x=1+y.reduce((A,O)=>A+1+O.length,0),v=new $e,U=a.map(A=>v.encode(A)),S=1+U.reduce((A,O)=>A+O.length,0),w=p+x+S,I=new Uint8Array(w),M=new DataView(I.buffer),f=0;M.setBigUint64(f,m,!0),f+=8;for(let[,A]of d){let O=dt(A);I[f]=O+256&255,f+=1}let R=G(u);for(let A=0;A<R;A++){let O=0;for(let Se=0;Se<8;Se++){let rr=A*8+Se;if(rr<u){let[,Fr]=c[rr];Fr&&(O|=1<<Se)}}I[f]=O,f+=1}I[f]=r&255,f+=1,I[f]=n&255,f+=1,I[f]=o&255,f+=1;let N=0;i&&(N|=1),I[f]=N,f+=1,I[f]=Math.min(s.length,255),f+=1;for(let A of y)I[f]=Math.min(A.length,255),f+=1,I.set(A.slice(0,255),f),f+=A.length;I[f]=Math.min(a.length,255),f+=1;for(let A of U)I.set(A,f),f+=A.length;return I}g(Gn,"encodeCompressedInput");var E=class E{static toCharCode(e){if(typeof e=="number")return e&255;let t=e.charCodeAt(0);return re(t)}static dedent(e){let t=e.split(`
|
|
8
|
+
`}),e}};g(st,"InputBindingRegistry");var de=st;function at(m=0n){return{tick:m,axes:new Map,buttons:new Map,displayId:0,mouseX:0,mouseY:0,mouseOverDisplay:!1,textInputs:[],macroEvents:[]}}g(at,"createEmptyCompressedInputPacket");function dt(m){let e=Math.max(-1,Math.min(1,m));return Math.round(e*127)}g(dt,"encodeAxisToInt8");function ct(m){return m/127}g(ct,"decodeInt8ToAxis");function G(m){return m===0?0:Math.ceil(m/8)}g(G,"getButtonByteCount");function lt(m,e){let r=m,n=G(e);return 8+r+n+4}g(lt,"getCompressedPacketSize");var ut=class ut{decode(e,t=0){let r=e.readUInt8(t);switch(r){case 1:return this.decodeClick(e,t);case 2:return this.decodeChange(e,t);case 3:return this.decodeSubmit(e,t);case 4:return this.decodeSelect(e,t);default:throw new Error(`Unknown macro event type: 0x${r.toString(16)}`)}}decodeAll(e,t,r){let n=[],o=0;for(let i=0;i<r;i++){let{event:s,bytesRead:a}=this.decode(e,t+o);n.push(s),o+=a}return{events:n,bytesRead:o}}decodeClick(e,t){let r=e.readUInt8(t),n=e.readUInt8(t+1);return{event:{type:r,instanceId:n},bytesRead:2}}decodeChange(e,t){let r=e.readUInt8(t),n=e.readUInt8(t+1),o=e.readUInt8(t+2),i,s;return o===1?(i=e.readUInt8(t+3)===1,s=4):(i=e.readFloatBE(t+3),s=7),{event:{type:r,instanceId:n,value:i},bytesRead:s}}decodeSubmit(e,t){let r=t,n=e.readUInt8(t++),o=e.readUInt8(t++),i=e.readUInt16BE(t);t+=2;let s=e.toUint8Array().subarray(t,t+i);t+=i;let a=new TextDecoder().decode(s);return{event:{type:n,instanceId:o,text:a},bytesRead:t-r}}decodeSelect(e,t){let r=e.readUInt8(t),n=e.readUInt8(t+1),o=e.readUInt16BE(t+2);return{event:{type:r,instanceId:n,index:o},bytesRead:4}}};g(ut,"MacroEventDecoder");var Ee=ut;T();function pt(m,e){let t=e.getAllAxes().length,r=e.getAllButtons().length,n=G(r),o=8+t+n+4;if(m.length<o)throw new Error(`Invalid compressed input packet: expected at least ${o} bytes (${t} axes + ${r} buttons), got ${m.length}`);let i=new DataView(m.buffer,m.byteOffset,m.byteLength),s=0,a=at();a.tick=i.getBigUint64(s,!0),s+=8;for(let c=0;c<t;c++){let l=m[s],u=l>127?l-256:l,p=ct(u);a.axes.set(c,p),s+=1}for(let c=0;c<n;c++){let l=m[s];for(let u=0;u<8;u++){let p=c*8+u;if(p<r){let h=(l&1<<u)!==0;a.buttons.set(p,h)}}s+=1}a.displayId=m[s],s+=1,a.mouseX=m[s],s+=1,a.mouseY=m[s],s+=1;let d=m[s];if(a.mouseOverDisplay=(d&1)!==0,s+=1,s<m.length){let c=m[s];s+=1;let l=new TextDecoder;a.textInputs=[];for(let u=0;u<c&&s<m.length;u++){let p=m[s];if(s+=1,s+p<=m.length){let h=m.slice(s,s+p),y=l.decode(h);a.textInputs.push(y),s+=p}}}if(s<m.length){let c=m[s];s+=1;let l=new Ee,u=[],p=C.from(m);for(let h=0;h<c&&s<m.length;h++){let y=l.decode(p,s);u.push(y.event),s+=y.bytesRead}a.macroEvents=u}return a}g(pt,"decodeCompressedInput");import{Vector2 as Re,POST_PROCESS_DEFAULTS as z,GRID_DEFAULTS as ke}from"@utsp/types";var mt=class mt{constructor(e,t){b(this,"enabled",!1);b(this,"currentStats",null);b(this,"_userId");b(this,"_userName");this._userId=e,this._userName=t}setEnabled(e){this.enabled=e,e||(this.currentStats=null)}isEnabled(){return this.enabled}get userId(){return this.currentStats?.userId??this._userId}get userName(){return this.currentStats?.userName??this._userName}get tick(){return this.currentStats?.tick??0}get timestamp(){return this.currentStats?.timestamp??0}get displayCount(){return this.currentStats?.displayCount??0}get totalDisplayArea(){return this.currentStats?.totalDisplayArea??0}get totalLayers(){return this.currentStats?.totalLayers??0}get visibleLayers(){return this.currentStats?.visibleLayers??0}get staticLayers(){return this.currentStats?.staticLayers??0}get dynamicLayers(){return this.currentStats?.dynamicLayers??0}get totalOrders(){return this.currentStats?.totalOrders??0}get ordersByLayer(){return this.currentStats?.ordersByLayer??new Map}get staticPacketSize(){return this.currentStats?.staticPacketSize??0}get dynamicPacketSize(){return this.currentStats?.dynamicPacketSize??0}get totalPacketSize(){return this.currentStats?.totalPacketSize??0}get compressedPacketSize(){return Math.round(this.totalPacketSize*.25)}get hasInput(){return this.currentStats?.hasInput??!1}get axisCount(){return this.currentStats?.axisCount??0}get buttonCount(){return this.currentStats?.buttonCount??0}startTick(e){this.enabled&&(this.currentStats={userId:this._userId,userName:this._userName,tick:e,timestamp:Date.now(),displayCount:0,totalDisplayArea:0,totalLayers:0,visibleLayers:0,staticLayers:0,dynamicLayers:0,totalOrders:0,ordersByLayer:new Map,staticPacketSize:0,dynamicPacketSize:0,totalPacketSize:0,hasInput:!1,axisCount:0,buttonCount:0})}recordDisplays(e,t){!this.enabled||!this.currentStats||(this.currentStats.displayCount=e,this.currentStats.totalDisplayArea=t)}recordLayers(e,t,r,n){!this.enabled||!this.currentStats||(this.currentStats.totalLayers=e,this.currentStats.visibleLayers=t,this.currentStats.staticLayers=r,this.currentStats.dynamicLayers=n)}recordLayerOrders(e,t){!this.enabled||!this.currentStats||(this.currentStats.totalOrders+=t,this.currentStats.ordersByLayer.set(e,t))}recordPacketSizes(e,t){!this.enabled||!this.currentStats||(this.currentStats.staticPacketSize=e,this.currentStats.dynamicPacketSize=t,this.currentStats.totalPacketSize=e+t)}recordInput(e,t,r){!this.enabled||!this.currentStats||(this.currentStats.hasInput=e,this.currentStats.axisCount=t,this.currentStats.buttonCount=r)}endTick(){}reset(){this.currentStats=null}};g(mt,"UserStats");var ce=mt;var Ct=class Ct{constructor(e,t,r){this.id=e;this.name=t;b(this,"displays",[]);b(this,"layers",[]);b(this,"spriteRegistry");b(this,"mode");b(this,"axes",new Map);b(this,"buttons",new Map);b(this,"textInputs",[]);b(this,"mouseX",0);b(this,"mouseY",0);b(this,"mouseOver",!1);b(this,"mouseDisplayId",0);b(this,"touchPositions",new Map);b(this,"activeTouchId",null);b(this,"inputBindings",new de);b(this,"stats");b(this,"soundCommands",[]);b(this,"nextSoundInstanceId",1);b(this,"audioConfigCommands",[]);b(this,"lastListenerX",-1);b(this,"lastListenerY",-1);b(this,"pendingSendSounds",!1);b(this,"audioProcessor");b(this,"loadedSounds",new Map);b(this,"soundLoadErrors",new Map);b(this,"playingSounds",new Map);b(this,"macroRegistry",new oe);b(this,"macroEngine",new ae);b(this,"macroEventHandlers",new Map);b(this,"postProcessCommands",[]);b(this,"currentPostProcessConfig",null);b(this,"data");b(this,"currentScalingMode",null);b(this,"currentGridConfig",null);this.mode=r,this.stats=new ce(e,t),this.data={}}setSpriteRegistry(e){this.spriteRegistry=e;for(let t of this.layers)t.setSpriteRegistry(e);this.macroEngine.setSpriteRegistry(e)}getDisplays(){return this.displays}addDisplay(e){this.displays.push(e)}removeDisplay(e){let t=this.displays.indexOf(e);return t!==-1?(this.displays.splice(t,1),!0):!1}clearDisplays(){this.displays=[]}getLayers(){return this.layers}getLayerById(e){return this.layers.find(t=>t.getId()===e)}addLayer(e,t){e.setMode(this.mode);let r=this.layers.length+1;e.setId(r),this.layers.push(e),this.spriteRegistry&&e.setSpriteRegistry(this.spriteRegistry),t&&this.macroRegistry.setLayerMapping(t,e.getId())}removeLayer(e){let t=this.layers.indexOf(e);return t!==-1?(this.layers.splice(t,1),!0):!1}clearLayers(){this.layers=[]}setMousePosition(e,t,r=!0){this.mouseX=Math.max(0,Math.min(255,e)),this.mouseY=Math.max(0,Math.min(255,t)),this.mouseOver=r}setTouchPosition(e,t,r,n=!0,o=0){if(e<0||e>9){console.warn(`Invalid touchId ${e}, must be 0-9`);return}n?(this.touchPositions.set(e,{x:Math.max(0,Math.min(255,t)),y:Math.max(0,Math.min(255,r)),over:!0,displayId:o}),this.activeTouchId=e):(this.touchPositions.delete(e),this.activeTouchId===e&&(this.activeTouchId=null))}setAxis(e,t){let r=Math.max(-1,Math.min(1,t));this.axes.set(e,r)}getAxis(e){return this.axes.get(e)??0}setButton(e,t){this.buttons.set(e,t)}getButton(e){return this.buttons.get(e)??!1}getButtonJustPressed(e){let t=`${e}_justPressed`;return this.buttons.get(t)??!1}getButtonJustReleased(e){let t=`${e}_justReleased`;return this.buttons.get(t)??!1}setTextInputs(e){this.textInputs=e}getTextInputs(){return this.textInputs}clearTextInputs(){this.textInputs=[]}getAxisNames(){return Array.from(this.axes.keys())}getButtonNames(){return Array.from(this.buttons.keys())}clearAxes(){this.axes.clear()}clearButtons(){this.buttons.clear()}getMouseDisplayInfo(){if(!this.mouseOver||this.displays.length===0)return null;let e=this.displays[0],t=0,r=this.mouseX,n=this.mouseY,o=e.getOrigin(),i=o.x+r,s=o.y+n;return{displayId:t,localX:r,localY:n,worldX:i,worldY:s}}getTouchDisplayInfo(e=0){if(e<0||e>9)return console.warn(`Invalid touchId ${e}, must be 0-9`),null;let t=this.touchPositions.get(e);if(!t||!t.over||this.displays.length===0)return null;let r=this.displays[0],n=t.displayId,o=t.x,i=t.y,s=r.getOrigin(),a=s.x+o,d=s.y+i;return{displayId:n,localX:o,localY:i,worldX:a,worldY:d}}getIsMouseOnADisplay(){return this.mouseOver}getMouseDisplayHover(){let e=this.getMouseDisplayInfo();return e?e.displayId:null}findLayerById(e){return this.layers.find(t=>t.getId()===e)??null}applyUpdate(e){if(this.updateDisplaysFromPacket(e.displays),this.updateLayersFromPacket(e.layers),e.macroOrders&&e.macroOrders.length>0)for(let t of e.macroOrders)this.macroEngine.applyOrder(t)}updateDisplaysFromPacket(e){for(let t of e){let r=this.displays[t.id];if(!r){for(r=new ee(t.id,t.sizeX,t.sizeY);this.displays.length<=t.id;)this.displays.push(null);this.displays[t.id]=r}r.setOrigin(new Re(t.originX,t.originY)),r.setSize(new Re(t.sizeX,t.sizeY))}}updateLayersFromPacket(e){for(let t of e){let r=this.findLayerById(t.id);r||(r=new ne(new Re(t.originX,t.originY),t.zIndex,t.width,t.height,!1),r.setId(t.id),r.setMode(this.mode),this.spriteRegistry&&r.setSpriteRegistry(this.spriteRegistry),this.addLayer(r)),t.updateFlags&1&&r.setOrigin(new Re(t.originX,t.originY)),t.updateFlags&2&&r.setZOrder(t.zIndex),t.updateFlags&4&&r.setOrders(t.orders)}}defineAxisBinding(e,t,r=[],n=-1,o=1,i=0){this.inputBindings.defineAxis(e,t,r,n,o,i)}defineButtonBinding(e,t,r=[],n=!1){this.inputBindings.defineButton(e,t,r,n)}defineAxisBindings(e){e.forEach(({bindingId:t,name:r,sources:n,min:o,max:i,defaultValue:s})=>{this.defineAxisBinding(t,r,n??[],o,i,s)})}defineButtonBindings(e){e.forEach(({bindingId:t,name:r,sources:n,defaultValue:o})=>{this.defineButtonBinding(t,r,n??[],o)})}getInputBindingsLoadPacket(){return this.inputBindings.toLoadPacket()}applyInputBindingsLoadPacket(e){try{let t=JSON.parse(e);if(t.type!=="input-binding")throw new Error(`Invalid packet type: ${t.type}`);for(let r of t.axes)this.defineAxisBinding(r.bindingId,r.name,r.sources||[],r.min,r.max,r.defaultValue);for(let r of t.buttons)this.defineButtonBinding(r.bindingId,r.name,r.sources||[],r.defaultValue)}catch(t){throw console.error("[User] Failed to apply input bindings:",t),t}}getInputBindingRegistry(){return this.inputBindings}getStats(){return this.stats}getAxisBindingId(e){return this.inputBindings.getAxisBindingId(e)}getButtonBindingId(e){return this.inputBindings.getButtonBindingId(e)}decodeAndApplyCompressedInput(e){let t=pt(e,this.inputBindings),r=this.inputBindings.getAllAxes(),n=this.inputBindings.getAllButtons(),o=r.sort((s,a)=>s.bindingId-a.bindingId),i=n.sort((s,a)=>s.bindingId-a.bindingId);for(let[s,a]of t.axes)if(s<o.length){let d=o[s];this.setAxis(d.name,a)}for(let[s,a]of t.buttons)if(s<i.length){let d=i[s];this.setButton(d.name,a)}this.mouseX=t.mouseX,this.mouseY=t.mouseY,this.mouseOver=t.mouseOverDisplay,this.mouseDisplayId=t.displayId}playSound(e,t){let r=this.nextSoundInstanceId++,n={sound:e,instanceId:r,volume:t?.volume,pitch:t?.pitch,loop:t?.loop,fadeIn:t?.fadeIn,x:t?.x,y:t?.y,lowpass:t?.lowpass,highpass:t?.highpass,reverb:t?.reverb};return this.soundCommands.push(n),r}stopSound(e){let t={sound:e};this.soundCommands.push(t)}fadeOutSound(e,t){let r={fadeOut:!0,sound:e,duration:t};this.soundCommands.push(r)}fadeOutAllSounds(e){let t={fadeOut:!0,sound:"all",duration:e};this.soundCommands.push(t)}stopAllSounds(){let e={sound:"all"};this.soundCommands.push(e)}pauseSound(e){let t={pause:!0,sound:e};this.soundCommands.push(t)}pauseAllSounds(){let e={pause:!0,sound:"all"};this.soundCommands.push(e)}resumeSound(e){let t={resume:!0,sound:e};this.soundCommands.push(t)}resumeAllSounds(){let e={resume:!0,sound:"all"};this.soundCommands.push(e)}setSoundEffects(e,t){let r={setEffects:!0,instanceId:e,lowpass:t.lowpass,highpass:t.highpass,reverb:t.reverb};this.soundCommands.push(r)}setListenerPosition(e,t){e===this.lastListenerX&&t===this.lastListenerY||(this.lastListenerX=e,this.lastListenerY=t,this.audioConfigCommands.push({type:"set-listener-position",x:e,y:t}))}configureSpatialAudio(e){this.audioConfigCommands.push({type:"configure-spatial",...e})}flushAudioConfigCommands(){let e=this.audioConfigCommands;return this.audioConfigCommands=[],e}hasAudioConfigCommands(){return this.audioConfigCommands.length>0}flushSoundCommands(){let e=this.soundCommands;return this.soundCommands=[],e}hasSoundCommands(){return this.soundCommands.length>0}sendSounds(){this.pendingSendSounds=!0}needsSendSounds(){return this.pendingSendSounds}clearSendSounds(){this.pendingSendSounds=!1}setAudioProcessor(e){this.audioProcessor=e,this.macroEngine.setAudioCallback(t=>{e.play(t)})}getAudioProcessor(){return this.audioProcessor}applyAudioCommands(e){if(this.audioProcessor&&this.mode!=="server")for(let t of e){if("setEffects"in t&&t.setEffects===!0){let n=t;this.audioProcessor.setEffects(n.instanceId,n.lowpass,n.highpass,n.reverb);continue}if("fadeOut"in t&&t.fadeOut===!0){let n=t;this.audioProcessor.fadeOut(n.sound,n.duration);continue}if("pause"in t&&t.pause===!0){let n=t;this.audioProcessor.pause(n.sound);continue}if("resume"in t&&t.resume===!0){let n=t;this.audioProcessor.resume(n.sound);continue}if("instanceId"in t||"volume"in t||"pitch"in t||"loop"in t||"fadeIn"in t||"x"in t||"y"in t||"lowpass"in t||"highpass"in t||"reverb"in t){let n=t,o=n.x!==void 0&&n.y!==void 0?{x:n.x,y:n.y}:void 0;this.audioProcessor.play(n.sound,{volume:n.volume,pitch:n.pitch,loop:n.loop,fadeIn:n.fadeIn,position:o,instanceId:n.instanceId,lowpass:n.lowpass,highpass:n.highpass,reverb:n.reverb})}else{let n=t;n.sound==="all"?this.audioProcessor.stopAll():this.audioProcessor.stop(n.sound)}}}applyAudioConfigCommands(e){if(this.audioProcessor&&this.mode!=="server")for(let t of e)t.type==="set-listener-position"?this.audioProcessor.setListenerPosition(t.x,t.y):t.type==="configure-spatial"&&this.audioProcessor.configureSpatial({maxDistance:t.maxDistance,referenceDistance:t.referenceDistance,rolloffFactor:t.rolloffFactor,panSpread:t.panSpread})}applyAudioOrders(e){if(!this.audioProcessor||this.mode==="server")return;let{AudioOrderType:t,AudioTargetType:r}=(gt(),B(Cr)),{PlaySoundFlags:n}=(yt(),B(Sr));for(let o of e)switch(o.type){case t.PlaySound:case t.PlayGlobalSound:{let i=o,s=i.volume!==void 0?i.volume/255:void 0,a=i.pitch!==void 0?.25*Math.pow(2,i.pitch/64):void 0,d=i.fadeIn!==void 0?i.fadeIn/10:void 0,c=(i.flags&n.Loop)!==0,l=i.posX!==void 0&&i.posY!==void 0?{x:i.posX,y:i.posY}:void 0;this.audioProcessor.play(i.soundId,{volume:s,pitch:a,loop:c,fadeIn:d,position:l,instanceId:i.instanceId,lowpass:i.lowpass,highpass:i.highpass,reverb:i.reverb});break}case t.StopSound:{let i=o;i.targetType===r.All?this.audioProcessor.stopAll():i.targetType===r.InstanceId?this.audioProcessor.stop(i.target):this.audioProcessor.stop(i.target);break}case t.FadeOutSound:{let i=o,s=i.duration/10;i.targetType===r.All?this.audioProcessor.fadeOut("all",s):this.audioProcessor.fadeOut(i.target,s);break}case t.PauseSound:{let i=o;i.targetType===r.All?this.audioProcessor.pause("all"):this.audioProcessor.pause(i.target);break}case t.ResumeSound:{let i=o;i.targetType===r.All?this.audioProcessor.resume("all"):this.audioProcessor.resume(i.target);break}case t.SetListenerPosition:{let i=o;this.audioProcessor.setListenerPosition(i.x,i.y);break}case t.ConfigureSpatial:{let i=o;this.audioProcessor.configureSpatial({maxDistance:i.maxDistance*100,referenceDistance:i.referenceDistance*100,rolloffFactor:i.rolloffFactor/100,panSpread:i.panSpread/255});break}case t.SetSoundEffects:{let i=o;this.audioProcessor.setEffects(i.instanceId,i.lowpass,i.highpass,i.reverb);break}}}handleAudioAck(e){switch(e.type){case"sound-loaded":this.loadedSounds.set(e.soundId,{name:e.name,loadedAt:Date.now()}),this.soundLoadErrors.delete(e.soundId);break;case"sound-error":this.soundLoadErrors.set(e.soundId,{name:e.name,error:e.error,at:Date.now()});break;case"playback-started":this.playingSounds.set(e.instanceId,{soundId:e.soundId,startedAt:Date.now()});break;case"playback-ended":this.playingSounds.delete(e.instanceId);break;case"playback-error":e.instanceId!==void 0&&this.playingSounds.delete(e.instanceId);break}}isSoundLoaded(e){return this.loadedSounds.has(e)}getSoundLoadError(e){return this.soundLoadErrors.get(e)?.error}getLoadedSounds(){return this.loadedSounds}getSoundLoadErrors(){return this.soundLoadErrors}isSoundPlaying(e){return this.playingSounds.has(e)}getPlayingSounds(){return this.playingSounds}getPlayingSoundCount(){return this.playingSounds.size}loadMacro(e,t){let r={...t,id:e},n=this.macroRegistry.registerMacro(r);return this.mode==="client"&&this.macroEngine.loadTemplate(n,r),n}createInstance(e){return this.updateLayerMappings(),this.macroRegistry.createInstance(e)}updateInstance(e,t){return this.macroRegistry.updateInstance(e,t)}removeInstance(e){return this.macroEventHandlers.delete(e),this.macroRegistry.removeInstance(e)}onMacroEvent(e,t,r){this.macroEventHandlers.has(e)||this.macroEventHandlers.set(e,new Map),this.macroEventHandlers.get(e).set(t,r)}offMacroEvent(e,t){t?this.macroEventHandlers.get(e)?.delete(t):this.macroEventHandlers.delete(e)}handleMacroEvent(e){let t=this.macroRegistry.getInstanceName(e.instanceId);if(!t){console.warn(`MacroEvent: Unknown instance ID ${e.instanceId}`);return}let r=this.macroEventHandlers.get(t);if(!r)return;let n,o;switch(e.type){case 1:n="click",o=void 0;break;case 2:n="change",o=e.value;break;case 3:n="submit",o=e.text;break;case 4:n="select",o=e.index;break;default:return}let i=r.get(n);i&&i(o)}flushMacroOrders(){return this.macroRegistry.flushPendingOrders()}hasPendingMacroOrders(){return this.macroRegistry.hasPendingOrders()}applyMacroOrders(e){for(let t of e)this.macroEngine.applyOrder(t)}getMacroRegistry(){return this.macroRegistry}getMacroLoads(){return this.macroRegistry.toAllMacroLoads()}updateLayerMappings(){for(let e of this.layers){let t=e.getId()}}registerLayerName(e,t){this.macroRegistry.setLayerMapping(e,t.getId())}loadMacroTemplate(e,t){this.macroEngine.loadTemplate(e,t)}updateMacros(){return this.macroEngine.update()}processMacroEvents(e){for(let t of e.events){let r=this.macroRegistry.getInstanceName(t.instanceId);if(!r)continue;let n=this.macroEventHandlers.get(r);if(!n)continue;let o=n.get(t.event);o&&o(t.data)}}updateMacroMouse(e,t,r){let n=this.displays.find(o=>o.getId()===this.mouseDisplayId);if(!n&&this.displays.length>0&&(n=this.displays[0]),n){let o=n.getOrigin(),i=e+o.x,s=t+o.y;this.macroEngine.updateMouse(i,s,r)}else this.macroEngine.updateMouse(e,t,r)}getMacroRenderOrders(){let e=this.macroEngine.getOrdersByLayer(),t=this.displays[0];if(!t)return e;let r=t.getOrigin();if(r.x===0&&r.y===0)return e;let n=new Map;for(let[o,i]of e){let s=i.map(a=>{let d={...a};return"posX"in d&&typeof d.posX=="number"&&(d.posX=d.posX-r.x),"posY"in d&&typeof d.posY=="number"&&(d.posY=d.posY-r.y),d});n.set(o,s)}return n}getMacroEffectOffset(){return this.macroEngine.getEffectOffset()}getMacroEngine(){return this.macroEngine}macroFocusNext(){this.macroEngine.focusNext()}macroFocusPrevious(){this.macroEngine.focusPrevious()}macroActivateFocused(){this.macroEngine.activateFocused()}setPostProcess(e){let t=JSON.stringify(e),r=JSON.stringify(this.currentPostProcessConfig);t!==r&&(this.currentPostProcessConfig=e,this.postProcessCommands.push({type:"set-config",config:e??void 0}))}setScanlinesEnabled(e){if(e){let t=this.currentPostProcessConfig?.scanlines;this.setPostProcess({scanlines:{enabled:!0,opacity:t?.opacity??z.scanlines.opacity,pattern:t?.pattern??z.scanlines.pattern,color:t?.color??z.scanlines.color}})}else this.setPostProcess({scanlines:{enabled:!1}})}setScanlinesOpacity(e){let t=Math.max(0,Math.min(1,e)),r=this.currentPostProcessConfig?.scanlines;this.setPostProcess({scanlines:{enabled:!0,opacity:t,pattern:r?.pattern??"horizontal",color:r?.color??{r:0,g:0,b:0}}})}setScanlinesPattern(e){let t=this.currentPostProcessConfig?.scanlines;this.setPostProcess({scanlines:{enabled:t?.enabled??!0,opacity:t?.opacity??z.scanlines.opacity,pattern:e,color:t?.color??{r:0,g:0,b:0}}})}setAmbientEffect(e){let t=this.currentPostProcessConfig?.ambientEffect;typeof e=="boolean"?this.setPostProcess({...this.currentPostProcessConfig,ambientEffect:{enabled:e,blur:t?.blur??z.ambientEffect.blur,scale:t?.scale??z.ambientEffect.scale}}):this.setPostProcess({...this.currentPostProcessConfig,ambientEffect:{enabled:!0,blur:e.blur??t?.blur??z.ambientEffect.blur,scale:e.scale??t?.scale??z.ambientEffect.scale}})}setAmbientEffectEnabled(e){this.setAmbientEffect(e)}setAmbientEffectBlur(e){let t=this.currentPostProcessConfig?.ambientEffect;this.setPostProcess({...this.currentPostProcessConfig,ambientEffect:{enabled:t?.enabled??!0,blur:Math.max(0,e),scale:t?.scale??z.ambientEffect.scale}})}setAmbientEffectScale(e){let t=this.currentPostProcessConfig?.ambientEffect;this.setPostProcess({...this.currentPostProcessConfig,ambientEffect:{enabled:t?.enabled??!0,blur:t?.blur??z.ambientEffect.blur,scale:Math.max(1,e)}})}isAmbientEffectEnabled(){return this.currentPostProcessConfig?.ambientEffect?.enabled??!1}getAmbientEffectConfig(){let e=this.currentPostProcessConfig?.ambientEffect;return e?{enabled:e.enabled,blur:e.blur??z.ambientEffect.blur,scale:e.scale??z.ambientEffect.scale}:null}getPostProcessConfig(){return this.currentPostProcessConfig}hasPostProcessCommands(){return this.postProcessCommands.length>0}flushPostProcessCommands(){let e=this.postProcessCommands;return this.postProcessCommands=[],e}setScalingMode(e){this.currentScalingMode!==e&&(this.currentScalingMode=e,this.postProcessCommands.push({type:"set-scaling-mode",scalingMode:e}))}getScalingMode(){return this.currentScalingMode}setGrid(e){let t;typeof e=="boolean"?t={enabled:e,color:ke.color,lineWidth:ke.lineWidth}:t={enabled:e.enabled,color:e.color??ke.color,lineWidth:e.lineWidth??ke.lineWidth},this.currentGridConfig=t,this.postProcessCommands.push({type:"set-grid",gridConfig:t})}setGridEnabled(e){this.setGrid(e)}isGridEnabled(){return this.currentGridConfig?.enabled??!1}getGridConfig(){return this.currentGridConfig}};g(Ct,"User");var le=Ct;T();var ft=class ft{encode(e){switch(e.type){case 1:return this.encodeCharOrder(e);case 2:return this.encodeTextOrder(e);case 23:return this.encodeTextMultilineOrder(e);case 3:return this.encodeSubFrameOrder(e);case 4:return this.encodeSubFrameMultiColorOrder(e);case 5:return this.encodeFullFrameOrder(e);case 6:return this.encodeFullFrameMultiColorOrder(e);case 7:return this.encodeSpriteOrder(e);case 8:return this.encodeSpriteMultiColorOrder(e);case 9:return this.encodeColorMapOrder(e);case 10:return this.encodeShapeOrder(e);case 11:return this.encodeDotCloudOrder(e);case 12:return this.encodeDotCloudMultiColorOrder(e);case 17:return this.encodeBitmaskOrder(e);case 18:return this.encodeBitmask4Order(e);case 24:return this.encodeBitmask16Order(e);case 25:return this.encodePolylineOrder(e);case 13:return this.encodeSpriteCloudOrder(e);case 14:return this.encodeSpriteCloudMultiColorOrder(e);case 15:return this.encodeSpriteCloudVariedOrder(e);case 16:return this.encodeSpriteCloudVariedMultiColorOrder(e);case 19:return this.encodeClearOrder(e);case 20:return this.encodeFillCharOrder(e);case 21:return this.encodeFillSpriteOrder(e);case 22:return this.encodeFillSpriteMultiColorOrder(e);case 32:return this.encodeTriggerSoundOrder(e);case 33:return this.encodeTriggerGlobalSoundOrder(e);default:throw new Error(`Unknown order type: ${e.type}`)}}encodeCharOrder(e){let t=C.allocUnsafe(6),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.posX,r++),t.writeUInt8(e.posY,r++),t.writeUInt8(e.charCode,r++),t.writeUInt8(e.bgColorCode,r++),t.writeUInt8(e.fgColorCode,r++),t.toUint8Array()}encodeTextOrder(e){let t=new TextEncoder().encode(e.text),r=C.allocUnsafe(6+t.length),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(t.length,n++);for(let o=0;o<t.length;o++)r.writeUInt8(t[o],n++);return r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.toUint8Array()}encodeTextMultilineOrder(e){let t=new TextEncoder().encode(e.text),r=C.allocUnsafe(6+t.length),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(t.length,n++);for(let o=0;o<t.length;o++)r.writeUInt8(t[o],n++);return r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.toUint8Array()}encodeSubFrameOrder(e){let t=e.sizeX*e.sizeY,r=C.allocUnsafe(7+t),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(e.sizeX,n++),r.writeUInt8(e.sizeY,n++),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++);for(let o of e.frame)r.writeUInt8(o,n++);return r.toUint8Array()}encodeSubFrameMultiColorOrder(e){let t=e.sizeX*e.sizeY,r=C.allocUnsafe(5+t*3),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(e.sizeX,n++),r.writeUInt8(e.sizeY,n++);for(let o of e.frame)r.writeUInt8(o.charCode,n++),r.writeUInt8(o.bgColorCode,n++),r.writeUInt8(o.fgColorCode,n++);return r.toUint8Array()}encodeFullFrameOrder(e){let t=e.frame.length,r=C.allocUnsafe(3+t),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++);for(let o of e.frame)r.writeUInt8(o,n++);return r.toUint8Array()}encodeFullFrameMultiColorOrder(e){let t=e.frame.length,r=C.allocUnsafe(1+t*3),n=0;r.writeUInt8(e.type,n++);for(let o of e.frame)r.writeUInt8(o.charCode,n++),r.writeUInt8(o.bgColorCode,n++),r.writeUInt8(o.fgColorCode,n++);return r.toUint8Array()}encodeSpriteOrder(e){let t=C.allocUnsafe(6),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.posX,r++),t.writeUInt8(e.posY,r++),t.writeUInt8(e.spriteIndex,r++),t.writeUInt8(e.bgColorCode,r++),t.writeUInt8(e.fgColorCode,r++),t.toUint8Array()}encodeSpriteMultiColorOrder(e){let t=C.allocUnsafe(4),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.posX,r++),t.writeUInt8(e.posY,r++),t.writeUInt8(e.spriteIndex,r++),t.toUint8Array()}encodeColorMapOrder(e){let t=e.sizeX*e.sizeY,r=C.allocUnsafe(5+t*2),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(e.sizeX,n++),r.writeUInt8(e.sizeY,n++);for(let o of e.colorData)r.writeUInt8(o.bgColorCode,n++),r.writeUInt8(o.fgColorCode,n++);return r.toUint8Array()}encodeShapeOrder(e){let t=this.encodeShapeData(e.shapeType,e.shapeData),r=C.allocUnsafe(2+t.length),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.shapeType,n++);for(let o=0;o<t.length;o++)r.writeUInt8(t[o],n++);return r.toUint8Array()}encodeShapeData(e,t){switch(e){case 1:{let r=C.allocUnsafe(8),n=0;return r.writeUInt8(t.posX,n++),r.writeUInt8(t.posY,n++),r.writeUInt8(t.width,n++),r.writeUInt8(t.height,n++),r.writeUInt8(t.filled?1:0,n++),r.writeUInt8(t.charCode,n++),r.writeUInt8(t.bgColorCode,n++),r.writeUInt8(t.fgColorCode,n++),r.toUint8Array()}case 2:{let r=C.allocUnsafe(7),n=0;return r.writeUInt8(t.centerX,n++),r.writeUInt8(t.centerY,n++),r.writeUInt8(t.radius,n++),r.writeUInt8(t.filled?1:0,n++),r.writeUInt8(t.charCode,n++),r.writeUInt8(t.bgColorCode,n++),r.writeUInt8(t.fgColorCode,n++),r.toUint8Array()}case 3:{let r=C.allocUnsafe(7),n=0;return r.writeUInt8(t.x1,n++),r.writeUInt8(t.y1,n++),r.writeUInt8(t.x2,n++),r.writeUInt8(t.y2,n++),r.writeUInt8(t.charCode,n++),r.writeUInt8(t.bgColorCode,n++),r.writeUInt8(t.fgColorCode,n++),r.toUint8Array()}case 4:{let r=C.allocUnsafe(8),n=0;return r.writeUInt8(t.centerX,n++),r.writeUInt8(t.centerY,n++),r.writeUInt8(t.radiusX,n++),r.writeUInt8(t.radiusY,n++),r.writeUInt8(t.filled?1:0,n++),r.writeUInt8(t.charCode,n++),r.writeUInt8(t.bgColorCode,n++),r.writeUInt8(t.fgColorCode,n++),r.toUint8Array()}case 5:{let r=C.allocUnsafe(10),n=0;return r.writeUInt8(t.x1,n++),r.writeUInt8(t.y1,n++),r.writeUInt8(t.x2,n++),r.writeUInt8(t.y2,n++),r.writeUInt8(t.x3,n++),r.writeUInt8(t.y3,n++),r.writeUInt8(t.filled?1:0,n++),r.writeUInt8(t.charCode,n++),r.writeUInt8(t.bgColorCode,n++),r.writeUInt8(t.fgColorCode,n++),r.toUint8Array()}default:throw new Error(`Unknown shape type: ${e}`)}}encodeDotCloudOrder(e){let t=e.positions.length,r=C.allocUnsafe(6+t*2),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.charCode,n++),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.positions)r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeDotCloudMultiColorOrder(e){let t=e.dots.length,r=C.allocUnsafe(5+t*5),n=0;r.writeUInt8(e.type,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.dots)r.writeUInt8(o.charCode,n++),r.writeUInt8(o.bgColorCode,n++),r.writeUInt8(o.fgColorCode,n++),r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeBitmaskOrder(e){let t=e.mask.length,r=C.allocUnsafe(9+t),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(e.sizeX,n++),r.writeUInt8(e.sizeY,n++),r.writeUInt8(e.charCode,n++),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.writeUInt8(e.override?1:0,n++);for(let o=0;o<t;o++)r.writeUInt8(e.mask[o],n++);return r.toUint8Array()}encodeBitmask4Order(e){let t=e.mask.length,r=C.allocUnsafe(15+t),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(e.sizeX,n++),r.writeUInt8(e.sizeY,n++),r.writeUInt8(e.override?1:0,n++);for(let o of e.variants)r.writeUInt8(o.charCode,n++),r.writeUInt8(o.bgColorCode,n++),r.writeUInt8(o.fgColorCode,n++);for(let o=0;o<t;o++)r.writeUInt8(e.mask[o],n++);return r.toUint8Array()}encodeBitmask16Order(e){let t=e.mask.length,r=C.allocUnsafe(51+t),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(e.sizeX,n++),r.writeUInt8(e.sizeY,n++),r.writeUInt8(e.override?1:0,n++);for(let o of e.variants)r.writeUInt8(o.charCode,n++),r.writeUInt8(o.bgColorCode,n++),r.writeUInt8(o.fgColorCode,n++);for(let o=0;o<t;o++)r.writeUInt8(e.mask[o],n++);return r.toUint8Array()}encodePolylineOrder(e){let t=e.points.length,r=C.allocUnsafe(5+t*2),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.charCode,n++),r.writeUInt8(e.fgColorCode,n++),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(t,n++);for(let o of e.points)r.writeUInt8(o.x,n++),r.writeUInt8(o.y,n++);return r.toUint8Array()}encodeSpriteCloudOrder(e){let t=e.positions.length,r=C.allocUnsafe(8+t*2),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.spriteIndex,n++),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.positions)r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeSpriteCloudMultiColorOrder(e){let t=e.positions.length,r=C.allocUnsafe(6+t*2),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.spriteIndex,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.positions)r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeSpriteCloudVariedOrder(e){let t=e.sprites.length,r=C.allocUnsafe(3+t*5),n=0;r.writeUInt8(e.type,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.sprites)r.writeUInt8(o.spriteIndex,n++),r.writeUInt8(o.bgColorCode,n++),r.writeUInt8(o.fgColorCode,n++),r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeSpriteCloudVariedMultiColorOrder(e){let t=e.sprites.length,r=C.allocUnsafe(3+t*3),n=0;r.writeUInt8(e.type,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.sprites)r.writeUInt8(o.spriteIndex,n++),r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeClearOrder(e){let t=C.allocUnsafe(4),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.charCode,r++),t.writeUInt8(e.bgColorCode,r++),t.writeUInt8(e.fgColorCode,r++),t.toUint8Array()}encodeFillCharOrder(e){let t=e.patternWidth*e.patternHeight,r=C.allocUnsafe(5+t),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.patternWidth,n++),r.writeUInt8(e.patternHeight,n++),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++);for(let o of e.pattern)r.writeUInt8(o,n++);return r.toUint8Array()}encodeFillSpriteOrder(e){let t=C.allocUnsafe(4),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.spriteIndex,r++),t.writeUInt8(e.bgColorCode,r++),t.writeUInt8(e.fgColorCode,r++),t.toUint8Array()}encodeFillSpriteMultiColorOrder(e){let t=C.allocUnsafe(2),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.spriteIndex,r++),t.toUint8Array()}encodeTriggerSoundOrder(e){let t=C.allocUnsafe(5),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.posX,r++),t.writeUInt8(e.posY,r++),t.writeUInt8(e.soundId,r++),t.writeUInt8(e.loop?1:0,r++),t.toUint8Array()}encodeTriggerGlobalSoundOrder(e){let t=C.allocUnsafe(3),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.soundId,r++),t.writeUInt8(e.loop?1:0,r++),t.toUint8Array()}};g(ft,"OrderEncoder");var Pe=ft;T();var St=class St{constructor(){b(this,"orderEncoder");this.orderEncoder=new Pe}encode(e){let t=e.orders.map(a=>this.orderEncoder.encode(a)),r=13,n=t.reduce((a,d)=>a+d.length,0),o=r+n,i=C.allocUnsafe(o),s=0;i.writeUInt16BE(e.id,s),s+=2,i.writeUInt8(e.updateFlags,s++),i.writeUInt8(e.zIndex,s++),i.writeUInt16BE(e.originX,s),s+=2,i.writeUInt16BE(e.originY,s),s+=2,i.writeUInt16BE(e.width,s),s+=2,i.writeUInt16BE(e.height,s),s+=2,i.writeUInt8(e.orders.length,s++);for(let a of t)C.from(a).copy(i,s),s+=a.length;return i.toUint8Array()}calculateSize(e){return 13+e.orders.reduce((n,o)=>n+this.orderEncoder.encode(o).length,0)}};g(St,"LayerEncoder");var Be=St;T();var It=class It{encode(e){switch(e.type){case 1:return this.encodePlaySoundOrder(e);case 2:return this.encodePlayGlobalSoundOrder(e);case 3:return this.encodeStopSoundOrder(e);case 4:return this.encodeFadeOutSoundOrder(e);case 5:return this.encodePauseSoundOrder(e);case 6:return this.encodeResumeSoundOrder(e);case 7:return this.encodeSetListenerPositionOrder(e);case 8:return this.encodeConfigureSpatialOrder(e);case 9:return this.encodeSetSoundEffectsOrder(e);default:throw new Error(`Unknown audio order type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return this.calculatePlaySoundSize(e);case 2:return this.calculatePlayGlobalSoundSize(e);case 3:case 5:case 6:return this.calculateTargetOrderSize(e);case 4:return this.calculateFadeOutSize(e);case 7:return 5;case 8:return 5;case 9:return this.calculateSetSoundEffectsSize(e);default:throw new Error(`Unknown audio order type: ${e.type}`)}}encodePlaySoundOrder(e){let t=this.calculatePlaySoundSize(e),r=C.allocUnsafe(t),n=0;return r.writeUInt8(e.type,n++),r.writeUInt8(e.soundId,n++),r.writeUInt16BE(e.instanceId,n),n+=2,r.writeUInt8(e.flags,n++),e.flags&2&&r.writeUInt8(e.volume??255,n++),e.flags&4&&r.writeUInt8(e.pitch??128,n++),e.flags&8&&r.writeUInt8(e.fadeIn??0,n++),e.flags&16&&(r.writeUInt16BE(e.posX??0,n),n+=2,r.writeUInt16BE(e.posY??0,n),n+=2),e.flags&32&&r.writeUInt8(e.lowpass??0,n++),e.flags&64&&r.writeUInt8(e.highpass??0,n++),e.flags&128&&r.writeUInt8(e.reverb??0,n++),r.toUint8Array()}encodePlayGlobalSoundOrder(e){let t=this.calculatePlayGlobalSoundSize(e),r=C.allocUnsafe(t),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.soundId,n++),r.writeUInt16BE(e.instanceId,n),n+=2;let o=e.flags&-17;return r.writeUInt8(o,n++),o&2&&r.writeUInt8(e.volume??255,n++),o&4&&r.writeUInt8(e.pitch??128,n++),o&8&&r.writeUInt8(e.fadeIn??0,n++),o&32&&r.writeUInt8(e.lowpass??0,n++),o&64&&r.writeUInt8(e.highpass??0,n++),o&128&&r.writeUInt8(e.reverb??0,n++),r.toUint8Array()}calculatePlaySoundSize(e){let t=5;return e.flags&2&&(t+=1),e.flags&4&&(t+=1),e.flags&8&&(t+=1),e.flags&16&&(t+=4),e.flags&32&&(t+=1),e.flags&64&&(t+=1),e.flags&128&&(t+=1),t}calculatePlayGlobalSoundSize(e){let t=5,r=e.flags&-17;return r&2&&(t+=1),r&4&&(t+=1),r&8&&(t+=1),r&32&&(t+=1),r&64&&(t+=1),r&128&&(t+=1),t}encodeStopSoundOrder(e){return this.encodeTargetOrder(e.type,e.targetType,e.target)}encodePauseSoundOrder(e){return this.encodeTargetOrder(e.type,e.targetType,e.target)}encodeResumeSoundOrder(e){return this.encodeTargetOrder(e.type,e.targetType,e.target)}encodeFadeOutSoundOrder(e){let t=this.calculateFadeOutSize(e),r=C.allocUnsafe(t),n=0;return r.writeUInt8(e.type,n++),r.writeUInt8(e.targetType,n++),r.writeUInt8(e.duration,n++),e.targetType===0?r.writeUInt16BE(e.target??0,n):e.targetType===1&&r.writeUInt8(e.target??0,n),r.toUint8Array()}encodeTargetOrder(e,t,r){let n=2;t===0?n+=2:t===1&&(n+=1);let o=C.allocUnsafe(n),i=0;return o.writeUInt8(e,i++),o.writeUInt8(t,i++),t===0?o.writeUInt16BE(r??0,i):t===1&&o.writeUInt8(r??0,i),o.toUint8Array()}calculateTargetOrderSize(e){let t=2;return e.targetType===0?t+=2:e.targetType===1&&(t+=1),t}calculateFadeOutSize(e){let t=3;return e.targetType===0?t+=2:e.targetType===1&&(t+=1),t}encodeSetListenerPositionOrder(e){let t=C.allocUnsafe(5),r=0;return t.writeUInt8(e.type,r++),t.writeUInt16BE(e.x,r),r+=2,t.writeUInt16BE(e.y,r),t.toUint8Array()}encodeConfigureSpatialOrder(e){let t=C.allocUnsafe(5),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.maxDistance,r++),t.writeUInt8(e.referenceDistance,r++),t.writeUInt8(e.rolloffFactor,r++),t.writeUInt8(e.panSpread,r++),t.toUint8Array()}encodeSetSoundEffectsOrder(e){let t=this.calculateSetSoundEffectsSize(e),r=C.allocUnsafe(t),n=0;return r.writeUInt8(e.type,n++),r.writeUInt16BE(e.instanceId,n),n+=2,r.writeUInt8(e.flags,n++),e.flags&1&&r.writeUInt8(e.lowpass??0,n++),e.flags&2&&r.writeUInt8(e.highpass??0,n++),e.flags&4&&r.writeUInt8(e.reverb??0,n++),r.toUint8Array()}calculateSetSoundEffectsSize(e){let t=4;return e.flags&1&&(t+=1),e.flags&2&&(t+=1),e.flags&4&&(t+=1),t}};g(It,"AudioOrderEncoder");var Te=It;T();var Ot=class Ot{encode(e){switch(e.type){case 1:return this.encodeCreateInstance(e);case 2:return this.encodeUpdateInstance(e);case 3:return this.encodeRemoveInstance(e);default:throw new Error(`Unknown macro order type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return this.calculateCreateInstanceSize(e);case 2:return this.calculateUpdateInstanceSize(e);case 3:return 2;default:throw new Error(`Unknown macro order type: ${e.type}`)}}encodeCreateInstance(e){let t=JSON.stringify(e.params),r=new TextEncoder().encode(t);if(r.length>65535)throw new Error(`Params JSON too large: ${r.length} bytes (max 65535)`);let n=11+r.length,o=C.allocUnsafe(n),i=0;return o.writeUInt8(e.type,i++),o.writeUInt8(e.instanceId,i++),o.writeUInt8(e.macroId,i++),o.writeUInt8(e.layerId,i++),o.writeInt16BE(e.x,i),i+=2,o.writeInt16BE(e.y,i),i+=2,o.writeUInt8(e.tabIndex,i++),o.writeUInt16BE(r.length,i),i+=2,o.toUint8Array().set(r,i),o.toUint8Array()}calculateCreateInstanceSize(e){let t=JSON.stringify(e.params);return 11+new TextEncoder().encode(t).length}encodeUpdateInstance(e){let t=JSON.stringify(e.params),r=new TextEncoder().encode(t);if(r.length>65535)throw new Error(`Params JSON too large: ${r.length} bytes (max 65535)`);let n=4+r.length,o=C.allocUnsafe(n),i=0;return o.writeUInt8(e.type,i++),o.writeUInt8(e.instanceId,i++),o.writeUInt16BE(r.length,i),i+=2,o.toUint8Array().set(r,i),o.toUint8Array()}calculateUpdateInstanceSize(e){let t=JSON.stringify(e.params);return 4+new TextEncoder().encode(t).length}encodeRemoveInstance(e){let t=C.allocUnsafe(2);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.toUint8Array()}};g(Ot,"MacroOrderEncoder");var ze=Ot;T();var Ut=class Ut{encode(e){switch(e.type){case 1:return this.encodeSetConfigOrder(e);case 2:return this.encodeSetScanlinesOrder(e);case 3:return this.encodeSetAmbientEffectOrder(e);case 4:return this.encodeSetScalingModeOrder(e);case 5:return this.encodeSetGridOrder(e);default:throw new Error(`Unknown post-process order type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return this.calculateSetConfigSize(e);case 2:return 7;case 3:return 5;case 4:return 2;case 5:return 7;default:throw new Error(`Unknown post-process order type: ${e.type}`)}}encodeSetConfigOrder(e){let t=this.calculateSetConfigSize(e),r=C.allocUnsafe(t),n=0;return r.writeUInt8(e.type,n++),r.writeUInt8(e.flags,n++),e.flags&1&&e.scanlines&&(r.writeUInt8(e.scanlines.enabled?1:0,n++),r.writeUInt8(Math.round(e.scanlines.opacity*255),n++),r.writeUInt8(e.scanlines.pattern,n++),r.writeUInt8(e.scanlines.colorR,n++),r.writeUInt8(e.scanlines.colorG,n++),r.writeUInt8(e.scanlines.colorB,n++)),e.flags&2&&e.ambientEffect&&(r.writeUInt8(e.ambientEffect.enabled?1:0,n++),r.writeUInt8(Math.min(255,Math.round(e.ambientEffect.blur)),n++),r.writeUInt8(Math.min(255,Math.max(100,Math.round(e.ambientEffect.scale*100))),n++),r.writeUInt8(Math.round(e.ambientEffect.opacity*255),n++)),r.toUint8Array()}calculateSetConfigSize(e){let t=2;return e.flags&1&&(t+=6),e.flags&2&&(t+=4),t}encodeSetScanlinesOrder(e){let t=C.allocUnsafe(7),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.enabled?1:0,r++),t.writeUInt8(Math.round(e.opacity*255),r++),t.writeUInt8(e.pattern,r++),t.writeUInt8(e.colorR,r++),t.writeUInt8(e.colorG,r++),t.writeUInt8(e.colorB,r++),t.toUint8Array()}encodeSetAmbientEffectOrder(e){let t=C.allocUnsafe(5),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.enabled?1:0,r++),t.writeUInt8(Math.min(255,Math.round(e.blur)),r++),t.writeUInt8(Math.min(255,Math.max(100,Math.round(e.scale*100))),r++),t.writeUInt8(Math.round(e.opacity*255),r++),t.toUint8Array()}encodeSetScalingModeOrder(e){let t=C.allocUnsafe(2),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.mode,r++),t.toUint8Array()}encodeSetGridOrder(e){let t=C.allocUnsafe(7),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.enabled?1:0,r++),t.writeUInt8(e.colorR,r++),t.writeUInt8(e.colorG,r++),t.writeUInt8(e.colorB,r++),t.writeUInt8(e.colorA,r++),t.writeUInt8(Math.min(10,Math.max(1,e.lineWidth)),r++),t.toUint8Array()}};g(Ut,"PostProcessOrderEncoder");var Fe=Ut;T();var wt=class wt{constructor(){b(this,"layerEncoder");b(this,"audioOrderEncoder");b(this,"macroOrderEncoder");b(this,"postProcessOrderEncoder");this.layerEncoder=new Be,this.audioOrderEncoder=new Te,this.macroOrderEncoder=new ze,this.postProcessOrderEncoder=new Fe}encode(e){let t=e.layers.map(f=>this.layerEncoder.encode(f)),r=e.audioOrders||[],n=r.map(f=>this.audioOrderEncoder.encode(f)),o=e.macroOrders||[],i=o.map(f=>this.macroOrderEncoder.encode(f)),s=e.postProcessOrders||[],a=s.map(f=>this.postProcessOrderEncoder.encode(f)),d=9,c=e.displays.length*7,l=2,u=t.reduce((f,R)=>f+R.length,0),p=1,h=n.reduce((f,R)=>f+R.length,0),y=1,x=i.reduce((f,R)=>f+R.length,0),v=1,U=a.reduce((f,R)=>f+R.length,0),S=d+c+l+u+p+h+y+x+v+U,w=C.allocUnsafe(S),I=0,M=typeof e.tick=="bigint"?e.tick:BigInt(e.tick);w.writeBigUInt64BE(M,I),I+=8,w.writeUInt8(e.displays.length,I),I+=1;for(let f of e.displays)w.writeUInt8(f.id,I++),w.writeUInt16BE(f.originX,I),I+=2,w.writeUInt16BE(f.originY,I),I+=2,w.writeUInt8(Math.max(1,Math.min(256,f.sizeX))-1,I++),w.writeUInt8(Math.max(1,Math.min(256,f.sizeY))-1,I++);w.writeUInt16BE(e.layers.length,I),I+=2;for(let f of t)C.from(f).copy(w,I),I+=f.length;w.writeUInt8(r.length,I),I+=1;for(let f of n)C.from(f).copy(w,I),I+=f.length;w.writeUInt8(o.length,I),I+=1;for(let f of i)C.from(f).copy(w,I),I+=f.length;w.writeUInt8(s.length,I),I+=1;for(let f of a)C.from(f).copy(w,I),I+=f.length;return w.toUint8Array()}calculateSize(e){let r=e.displays.length*7,n=2,o=e.layers.reduce((y,x)=>y+this.layerEncoder.calculateSize(x),0),i=1,a=(e.audioOrders||[]).reduce((y,x)=>y+this.audioOrderEncoder.calculateSize(x),0),d=1,l=(e.macroOrders||[]).reduce((y,x)=>y+this.macroOrderEncoder.calculateSize(x),0),u=1,h=(e.postProcessOrders||[]).reduce((y,x)=>y+this.postProcessOrderEncoder.calculateSize(x),0);return 9+r+n+o+i+a+d+l+u+h}static createEmptyPacket(e){return{tick:typeof e=="bigint"?Number(e):e,displayCount:0,displays:[],layerCount:0,layers:[],audioOrderCount:0,audioOrders:[],macroOrderCount:0,macroOrders:[],postProcessOrderCount:0,postProcessOrders:[]}}encodeEmpty(e){let t=C.allocUnsafe(14),r=typeof e=="bigint"?e:BigInt(e);return t.writeBigUInt64BE(r,0),t.writeUInt8(0,8),t.writeUInt16BE(0,9),t.writeUInt8(0,11),t.writeUInt8(0,12),t.writeUInt8(0,13),t.toUint8Array()}};g(wt,"UpdatePacketEncoder");var Le=wt;T();var Mt=class Mt{encode(e){let t=JSON.stringify(e.template),r=new TextEncoder().encode(t);if(r.length>65535)throw new Error(`Macro template JSON too large: ${r.length} bytes (max 65535)`);let n=4+r.length,o=C.allocUnsafe(n),i=0;return o.writeUInt8(7,i++),o.writeUInt8(e.macroId,i++),o.writeUInt16BE(r.length,i),i+=2,o.toUint8Array().set(r,i),o.toUint8Array()}calculateSize(e){let t=JSON.stringify(e.template);return 4+new TextEncoder().encode(t).length}};g(Mt,"MacroLoadEncoder");var De=Mt;var Z=class Z{constructor(e){this.engine=e;b(this,"colorCache",new Array(256));b(this,"cellsBuffer",[]);b(this,"opacityBuffer",new Uint8Array(0));b(this,"visibleLayersBuffer",[]);this.rebuildColorCache()}rebuildColorCache(){for(let e=0;e<256;e++){let t=this.engine.getColor(e);t?this.colorCache[e]={r:t.r,g:t.g,b:t.b,a:t.a}:this.colorCache[e]={r:0,g:0,b:0,a:0}}}getColorRGB(e){return this.colorCache[e]??this.colorCache[255]}getColorEmission(e){let t=this.engine.getColor(e);return t?t.e:0}isLayerVisible(e,t){let r=e.x,n=e.x+e.width,o=e.y,i=e.y+e.height,s=t.x,a=t.x+256,d=t.y,c=t.y+256;return!(n<=s||r>=a||i<=d||o>=c)}rasterize(e,t){let r=e.width*e.height,n=this.cellsBuffer;n.length=r;for(let s=0;s<r;s++)n[s]?(n[s].char=" ",n[s].fgColorIndex=255,n[s].bgColorIndex=255,n[s].fgEmission=0,n[s].bgEmission=0):n[s]={char:" ",fgColorIndex:255,bgColorIndex:255,fgEmission:0,bgEmission:0};this.opacityBuffer.length<r?this.opacityBuffer=new Uint8Array(r):this.opacityBuffer.fill(0,0,r);let o=this.opacityBuffer,i=this.visibleLayersBuffer;i.length=0;for(let s=0;s<t.length;s++){let a=t[s];a.isEnabled()&&this.isLayerVisible(e,a.getOrigin())&&i.push(a)}i.sort((s,a)=>a.getZOrder()-s.getZOrder());for(let s=0;s<e.height;s++)for(let a=0;a<e.width;a++){let d=s*e.width+a;if(o[d])continue;let c=e.x+a,l=e.y+s;for(let u=0;u<i.length;u++){let p=i[u],h=c-p.getOrigin().x,y=l-p.getOrigin().y,x=p.getWidth(),v=p.getHeight();if(h<0||h>=x||y<0||y>=v)continue;let U=y*x+h,S=p.getData(),w=S.getCharCode(U),I=S.getFgColorCode(U),M=S.getBgColorCode(U),f=n[d];if(w!==0&&w<256&&f.char===" "&&(f.char=Z.charCache[w]),I!==255&&f.fgColorIndex===255&&(f.fgColorIndex=I,f.fgEmission=this.getColorEmission(I)),M!==255){f.bgColorIndex===255&&(f.bgColorIndex=M,f.bgEmission=this.getColorEmission(M)),o[d]=1;break}}}return{width:e.width,height:e.height,cells:n,palette:this.colorCache}}rasterizeWithSortedLayers(e,t){let r=e.width*e.height,n=this.cellsBuffer;n.length=r;for(let s=0;s<r;s++)n[s]?(n[s].char=" ",n[s].fgColorIndex=255,n[s].bgColorIndex=255,n[s].fgEmission=0,n[s].bgEmission=0):n[s]={char:" ",fgColorIndex:255,bgColorIndex:255,fgEmission:0,bgEmission:0};this.opacityBuffer.length<r?this.opacityBuffer=new Uint8Array(r):this.opacityBuffer.fill(0,0,r);let o=this.opacityBuffer,i=this.visibleLayersBuffer;i.length=0;for(let s=0;s<t.length;s++){let a=t[s];this.isLayerVisible(e,a.getOrigin())&&i.push(a)}for(let s=0;s<e.height;s++)for(let a=0;a<e.width;a++){let d=s*e.width+a;if(o[d])continue;let c=e.x+a,l=e.y+s;for(let u=0;u<i.length;u++){let p=i[u],h=c-p.getOrigin().x,y=l-p.getOrigin().y,x=p.getWidth(),v=p.getHeight();if(h<0||h>=x||y<0||y>=v)continue;let U=y*x+h,S=p.getData(),w=S.getCharCode(U),I=S.getFgColorCode(U),M=S.getBgColorCode(U),f=n[d];if(w!==0&&w<256&&f.char===" "&&(f.char=Z.charCache[w]),I!==255&&f.fgColorIndex===255&&(f.fgColorIndex=I,f.fgEmission=this.getColorEmission(I)),M!==255){f.bgColorIndex===255&&(f.bgColorIndex=M,f.bgEmission=this.getColorEmission(M)),o[d]=1;break}}}return{width:e.width,height:e.height,cells:n,palette:this.colorCache}}calculateIntersection(e,t){let r=e.x,n=e.x+e.width,o=e.y,i=e.y+e.height,s=t.x,a=t.x+256,d=t.y,c=t.y+256,l=Math.max(r,s),u=Math.min(n,a),p=Math.max(o,d),h=Math.min(i,c);return{visible:l<u&&p<h,originStart:{x:l-e.x,y:p-e.y},originEnd:{x:u-e.x,y:h-e.y},layerStart:{x:l-t.x,y:p-t.y},layerEnd:{x:u-t.x,y:h-t.y}}}};g(Z,"DisplayRasterizer"),b(Z,"charCache",(()=>{let e=new Array(256);for(let t=0;t<256;t++)e[t]=String.fromCharCode(t);return e})());var Ye=Z;var At=class At{constructor(){b(this,"enabled",!1);b(this,"currentStats",null)}setEnabled(e){this.enabled=e,e||(this.currentStats=null)}isEnabled(){return this.enabled}get tick(){return this.currentStats?.tick??0}get timestamp(){return this.currentStats?.timestamp??0}get totalOrders(){return this.currentStats?.totalOrders??0}get ordersByLayer(){return this.currentStats?.ordersByLayer??new Map}get ordersByType(){return this.currentStats?.ordersByType??new Map}get totalLayers(){return this.currentStats?.totalLayers??0}get visibleLayers(){return this.currentStats?.visibleLayers??0}get layersPerDisplay(){return this.currentStats?.layersPerDisplay??new Map}get updatePacketSize(){return this.currentStats?.updatePacketSize??0}get displayHeaderSize(){return this.currentStats?.displayHeaderSize??0}get layerHeaderSize(){return this.currentStats?.layerHeaderSize??0}get orderDataSize(){return this.currentStats?.orderDataSize??0}get compressionRatio(){return this.currentStats?.compressionRatio??0}get compressedPacketSize(){return Math.round(this.updatePacketSize*this.compressionRatio)}get totalCells(){return this.currentStats?.totalCells??0}get nonEmptyCells(){return this.currentStats?.nonEmptyCells??0}get cellsWithBackground(){return this.currentStats?.cellsWithBackground??0}get rasterizationTimeMs(){return this.currentStats?.rasterizationTimeMs??0}get encodingTimeMs(){return this.currentStats?.encodingTimeMs??0}get packetSplit(){return this.currentStats?.packetSplit}get layerDetails(){return this.currentStats?.layerDetails}startTick(e){this.enabled&&(this.currentStats={tick:e,timestamp:Date.now(),totalOrders:0,ordersByLayer:new Map,ordersByType:new Map,totalLayers:0,visibleLayers:0,layersPerDisplay:new Map,updatePacketSize:0,displayHeaderSize:0,layerHeaderSize:0,orderDataSize:0,compressionRatio:0,totalCells:0,nonEmptyCells:0,cellsWithBackground:0,rasterizationTimeMs:0,encodingTimeMs:0})}recordLayerOrders(e,t){if(!(!this.enabled||!this.currentStats)){this.currentStats.totalOrders+=t.length,this.currentStats.ordersByLayer.set(e,t.length);for(let r of t){let n=this.currentStats.ordersByType.get(r.type)||0;this.currentStats.ordersByType.set(r.type,n+1)}}}recordLayers(e,t){!this.enabled||!this.currentStats||(this.currentStats.totalLayers=e,this.currentStats.visibleLayers=t)}recordDisplayLayers(e,t){!this.enabled||!this.currentStats||this.currentStats.layersPerDisplay.set(e,t)}recordUpdatePacketSize(e,t,r,n){!this.enabled||!this.currentStats||(this.currentStats.updatePacketSize=e,this.currentStats.displayHeaderSize=t,this.currentStats.layerHeaderSize=r,this.currentStats.orderDataSize=n,this.currentStats.compressionRatio=.25)}recordPacketSplit(e,t,r,n){!this.enabled||!this.currentStats||(this.currentStats.packetSplit={userId:e,displayCount:t,staticLayerCount:r,dynamicLayerCount:n})}recordLayerInfo(e,t,r,n){!this.enabled||!this.currentStats||(this.currentStats.layerDetails||(this.currentStats.layerDetails=[]),this.currentStats.layerDetails.push({layerId:e,isStatic:t,orderCount:r,updateFlags:n}))}recordRenderStats(e,t,r){!this.enabled||!this.currentStats||(this.currentStats.totalCells=e,this.currentStats.nonEmptyCells=t,this.currentStats.cellsWithBackground=r)}recordRasterizationTime(e){!this.enabled||!this.currentStats||(this.currentStats.rasterizationTimeMs=e)}recordEncodingTime(e){!this.enabled||!this.currentStats||(this.currentStats.encodingTimeMs=e)}endTick(){}reset(){this.currentStats=null}};g(At,"CoreStats");var ue=At;var Et=class Et{constructor(){b(this,"unicolorSprites",new Map);b(this,"multicolorSprites",new Map)}loadUnicolorSprites(e){for(let t of e.sprites){let r=new te(t.sizeX*t.sizeY);for(let o=0;o<t.data.length;o++)r.set(o,t.data[o]);let n={id:t.spriteId,sizeX:t.sizeX,sizeY:t.sizeY,data:r};this.unicolorSprites.set(n.id,n)}}loadMulticolorSprites(e){for(let t of e.sprites){let r=new _(t.sizeX*t.sizeY);for(let o=0;o<t.data.length;o++){let i=t.data[o];r.set(o,i.charCode,i.fgColorId,i.bgColorId)}let n={id:t.spriteId,sizeX:t.sizeX,sizeY:t.sizeY,data:r};this.multicolorSprites.set(n.id,n)}}getUnicolorSprite(e){return this.unicolorSprites.get(e)}getMulticolorSprite(e){return this.multicolorSprites.get(e)}hasUnicolorSprite(e){return this.unicolorSprites.has(e)}hasMulticolorSprite(e){return this.multicolorSprites.has(e)}unloadUnicolorSprite(e){return this.unicolorSprites.delete(e)}unloadMulticolorSprite(e){return this.multicolorSprites.delete(e)}clearUnicolorSprites(){this.unicolorSprites.clear()}clearMulticolorSprites(){this.multicolorSprites.clear()}clearAll(){this.unicolorSprites.clear(),this.multicolorSprites.clear()}getUnicolorSpriteCount(){return this.unicolorSprites.size}getMulticolorSpriteCount(){return this.multicolorSprites.size}getTotalSpriteCount(){return this.unicolorSprites.size+this.multicolorSprites.size}};g(Et,"SpriteRegistry");var pe=Et;var wr=(t=>(t.Web="web",t.Bitmap="bitmap",t))(wr||{}),Rt=class Rt{constructor(e,t){this.fontId=e;this.config=t}getFontId(){return this.fontId}getConfig(){return{...this.config}}getFontFamily(){return this.config.fontFamily}getFontSize(){return this.config.fontSize}getOffsetX(){return this.config.offsetX??0}getOffsetY(){return this.config.offsetY??0}getCharSpacing(){return this.config.charSpacing??0}getLineHeight(){return this.config.lineHeight??1.2}getFontWeight(){return this.config.fontWeight??"normal"}getFontStyle(){return this.config.fontStyle??"normal"}toCSS(){let e=[];e.push(`font-family: ${this.config.fontFamily}`),e.push(`font-size: ${this.config.fontSize}px`);let t=this.config.fontWeight??"normal";t!=="normal"&&e.push(`font-weight: ${t}`);let r=this.config.fontStyle??"normal";return r!=="normal"&&e.push(`font-style: ${r}`),e.join("; ")+";"}};g(Rt,"WebFont");var W=Rt,kt=class kt{constructor(e,t){this.fontId=e;this.config=t}getFontId(){return this.fontId}getConfig(){return{charWidth:this.config.charWidth,charHeight:this.config.charHeight,cellWidth:this.config.cellWidth,cellHeight:this.config.cellHeight,glyphs:new Map(this.config.glyphs)}}getCharWidth(){return this.config.charWidth}getCharHeight(){return this.config.charHeight}getCellWidth(){return this.config.cellWidth??this.config.charWidth}getCellHeight(){return this.config.cellHeight??this.config.charHeight}getGlyph(e){return this.config.glyphs.get(e)}hasGlyph(e){return this.config.glyphs.has(e)}getGlyphCount(){return this.config.glyphs.size}getCharCodes(){return Array.from(this.config.glyphs.keys())}};g(kt,"BitmapFont");var me=kt;var Pt=class Pt{constructor(){b(this,"fonts",new Map)}loadFont(e,t){if(this.fonts.has(e))throw new Error(`WebFont with ID ${e} already exists`);let r=new W(e,t);this.fonts.set(e,r)}getFont(e){return this.fonts.get(e)}hasFont(e){return this.fonts.has(e)}unloadFont(e){return this.fonts.delete(e)}clearFonts(){this.fonts.clear()}getFontIds(){return Array.from(this.fonts.keys()).sort((e,t)=>e-t)}getAllFonts(){return Array.from(this.fonts.entries()).sort((e,t)=>e[0]-t[0]).map(e=>e[1])}getFontCount(){return this.fonts.size}};g(Pt,"WebFontRegistry");var he=Pt;var Bt=class Bt{constructor(){b(this,"fonts",new Map)}loadFont(e,t){if(this.fonts.has(e))throw new Error(`BitmapFont with ID ${e} already exists`);let r=new me(e,t);this.fonts.set(e,r)}getFont(e){return this.fonts.get(e)}hasFont(e){return this.fonts.has(e)}unloadFont(e){return this.fonts.delete(e)}clearFonts(){this.fonts.clear()}getFontIds(){return Array.from(this.fonts.keys()).sort((e,t)=>e-t)}getAllFonts(){return Array.from(this.fonts.entries()).sort((e,t)=>e[0]-t[0]).map(e=>e[1])}getFontCount(){return this.fonts.size}};g(Bt,"BitmapFontRegistry");var be=Bt;var Tt=class Tt{constructor(){b(this,"sounds",new Map);b(this,"nameToId",new Map);b(this,"nextId",0)}registerFile(e,t,r){let n=this.allocateId(e),o={soundId:n,name:e,loadType:"file",format:t,data:r};return this.sounds.set(n,o),this.nameToId.set(e,n),n}registerFileWithId(e,t,r,n){this.validateId(e),this.checkIdAvailable(e,t);let o={soundId:e,name:t,loadType:"file",format:r,data:n};this.sounds.set(e,o),this.nameToId.set(t,e)}registerExternal(e,t,r,n,o){let i=this.allocateId(e),s={soundId:i,name:e,loadType:"external",format:t,url:r,size:n,checksum:o};return this.sounds.set(i,s),this.nameToId.set(e,i),i}registerExternalWithId(e,t,r,n,o,i){this.validateId(e),this.checkIdAvailable(e,t);let s={soundId:e,name:t,loadType:"external",format:r,url:n,size:o,checksum:i};this.sounds.set(e,s),this.nameToId.set(t,e)}get(e){if(typeof e=="number")return this.sounds.get(e);let t=this.nameToId.get(e);return t!==void 0?this.sounds.get(t):void 0}has(e){return this.get(e)!==void 0}getAll(){return Array.from(this.sounds.values())}getFileSounds(){return this.getAll().filter(e=>e.loadType==="file")}getExternalSounds(){return this.getAll().filter(e=>e.loadType==="external")}getNames(){return Array.from(this.nameToId.keys())}getId(e){return this.nameToId.get(e)}toLoadPackets(){let e=[],t=this.getFileSounds();if(t.length>0){let n=t.map(o=>({soundId:o.soundId,name:o.name,format:o.format,data:o.data}));e.push({type:"sound",mode:"file",sounds:n})}let r=this.getExternalSounds();if(r.length>0){let n=r.map(o=>({soundId:o.soundId,name:o.name,format:o.format,url:o.url,size:o.size,checksum:o.checksum}));e.push({type:"sound",mode:"external",sounds:n})}return e}toLoadPacket(e){let t=this.get(e);return t?t.loadType==="file"?{type:"sound",mode:"file",sounds:[{soundId:t.soundId,name:t.name,format:t.format,data:t.data}]}:{type:"sound",mode:"external",sounds:[{soundId:t.soundId,name:t.name,format:t.format,url:t.url,size:t.size,checksum:t.checksum}]}:null}unregister(e){let t=this.get(e);return t?(this.sounds.delete(t.soundId),this.nameToId.delete(t.name),!0):!1}clear(){this.sounds.clear(),this.nameToId.clear(),this.nextId=0}get size(){return this.sounds.size}getStats(){let e=this.getAll(),t=e.filter(n=>n.loadType==="file"),r=t.reduce((n,o)=>n+(o.data?.length??0),0);return{total:e.length,file:t.length,external:e.length-t.length,totalFileSize:r}}allocateId(e){if(this.nameToId.has(e))throw new Error(`Sound with name "${e}" already exists`);for(;this.sounds.has(this.nextId);)if(this.nextId++,this.nextId>255)throw new Error("Maximum number of sounds (256) reached");return this.nextId++}validateId(e){if(!Number.isInteger(e)||e<0||e>255)throw new Error(`Invalid sound ID: ${e}. Must be an integer between 0 and 255.`)}checkIdAvailable(e,t){if(this.sounds.has(e)){let r=this.sounds.get(e);throw new Error(`Sound ID ${e} is already used by "${r.name}". Cannot register "${t}".`)}if(this.nameToId.has(t))throw new Error(`Sound with name "${t}" already exists`)}};g(Tt,"SoundRegistry");var ge=Tt;var zt=class zt{constructor(e){this.soundRegistry=e}collectFromUser(e){let t=[],r=e.flushSoundCommands();for(let o of r){let i=this.convertSoundCommand(o);i&&t.push(i)}let n=e.flushAudioConfigCommands();for(let o of n){let i=this.convertConfigCommand(o);i&&t.push(i)}return t}convertSoundCommand(e){return"setEffects"in e&&e.setEffects===!0?this.convertSetEffectsCommand(e):"fadeOut"in e&&e.fadeOut===!0?this.convertFadeOutCommand(e):"pause"in e&&e.pause===!0?this.convertPauseCommand(e):"resume"in e&&e.resume===!0?this.convertResumeCommand(e):"instanceId"in e||"volume"in e||"pitch"in e||"loop"in e||"fadeIn"in e||"x"in e||"y"in e||"lowpass"in e||"highpass"in e||"reverb"in e?this.convertPlayCommand(e):this.convertStopCommand(e)}convertPlayCommand(e){let t=this.resolveSoundId(e.sound);if(t===null)return console.warn(`[AudioOrderCollector] Unknown sound: ${e.sound}`),null;let r=0;e.loop&&(r|=1),e.volume!==void 0&&(r|=2),e.pitch!==void 0&&(r|=4),e.fadeIn!==void 0&&(r|=8),e.lowpass!==void 0&&e.lowpass>0&&(r|=32),e.highpass!==void 0&&e.highpass>0&&(r|=64),e.reverb!==void 0&&e.reverb>0&&(r|=128);let n=e.x!==void 0&&e.y!==void 0;return n&&(r|=16),n?{type:1,soundId:t,instanceId:e.instanceId??0,flags:r,volume:e.volume!==void 0?this.encodeVolume(e.volume):void 0,pitch:e.pitch!==void 0?this.encodePitch(e.pitch):void 0,fadeIn:e.fadeIn!==void 0?this.encodeFadeTime(e.fadeIn):void 0,posX:this.encodePosition(e.x),posY:this.encodePosition(e.y),lowpass:e.lowpass!==void 0&&e.lowpass>0?this.encodeFilterFreq(e.lowpass):void 0,highpass:e.highpass!==void 0&&e.highpass>0?this.encodeFilterFreq(e.highpass):void 0,reverb:e.reverb!==void 0&&e.reverb>0?this.encodeReverb(e.reverb):void 0}:{type:2,soundId:t,instanceId:e.instanceId??0,flags:r&-17,volume:e.volume!==void 0?this.encodeVolume(e.volume):void 0,pitch:e.pitch!==void 0?this.encodePitch(e.pitch):void 0,fadeIn:e.fadeIn!==void 0?this.encodeFadeTime(e.fadeIn):void 0,lowpass:e.lowpass!==void 0&&e.lowpass>0?this.encodeFilterFreq(e.lowpass):void 0,highpass:e.highpass!==void 0&&e.highpass>0?this.encodeFilterFreq(e.highpass):void 0,reverb:e.reverb!==void 0&&e.reverb>0?this.encodeReverb(e.reverb):void 0}}convertStopCommand(e){let{targetType:t,target:r}=this.resolveTarget(e.sound);return{type:3,targetType:t,target:r}}convertFadeOutCommand(e){let{targetType:t,target:r}=this.resolveTarget(e.sound);return{type:4,targetType:t,duration:this.encodeFadeTime(e.duration),target:r}}convertPauseCommand(e){let{targetType:t,target:r}=this.resolveTarget(e.sound);return{type:5,targetType:t,target:r}}convertResumeCommand(e){let{targetType:t,target:r}=this.resolveTarget(e.sound);return{type:6,targetType:t,target:r}}convertSetEffectsCommand(e){let t=0;return e.lowpass!==void 0&&(t|=1),e.highpass!==void 0&&(t|=2),e.reverb!==void 0&&(t|=4),{type:9,instanceId:e.instanceId,flags:t,lowpass:e.lowpass!==void 0?this.encodeFilterFreq(e.lowpass):void 0,highpass:e.highpass!==void 0?this.encodeFilterFreq(e.highpass):void 0,reverb:e.reverb!==void 0?this.encodeReverb(e.reverb):void 0}}convertConfigCommand(e){return e.type==="set-listener-position"?{type:7,x:this.encodePosition(e.x),y:this.encodePosition(e.y)}:e.type==="configure-spatial"?{type:8,maxDistance:this.encodeDistance(e.maxDistance??1e3),referenceDistance:this.encodeDistance(e.referenceDistance??100),rolloffFactor:this.encodeRolloff(e.rolloffFactor??1),panSpread:this.encodePanSpread(e.panSpread??.5)}:null}resolveSoundId(e){if(typeof e=="number")return e>=0&&e<=255?e:null;let t=this.soundRegistry.getId(e);return t!==void 0?t:null}resolveTarget(e){if(e==="all")return{targetType:2,target:void 0};if(typeof e=="number")return{targetType:0,target:e};let t=this.soundRegistry.getId(e);return t!==void 0?{targetType:1,target:t}:(console.warn(`[AudioOrderCollector] Unknown sound name: ${e}, treating as 'all'`),{targetType:2,target:void 0})}encodeVolume(e){return Math.round(Math.max(0,Math.min(1,e))*255)}encodePitch(e){let t=Math.max(.25,Math.min(4,e)),r=64*Math.log2(t/.25);return Math.round(Math.max(0,Math.min(255,r)))}encodeFadeTime(e){return Math.round(Math.max(0,Math.min(25.5,e))*10)}encodeDistance(e){return Math.round(Math.max(0,Math.min(25500,e))/100)}encodeRolloff(e){return Math.round(Math.max(0,Math.min(2.55,e))*100)}encodePanSpread(e){return Math.round(Math.max(0,Math.min(1,e))*255)}encodePosition(e){return Math.round(Math.max(0,Math.min(65535,e)))}encodeFilterFreq(e){return e<=0?0:Math.round(Math.max(1,Math.min(255,e/100)))}encodeReverb(e){return Math.round(Math.max(0,Math.min(1,e))*255)}};g(zt,"AudioOrderCollector");var xe=zt;import{POST_PROCESS_DEFAULTS as D,GRID_DEFAULTS as vr,scalingModeToValue as Nn}from"@utsp/types";var Ft=class Ft{collectFromUser(e){let t=e.flushPostProcessCommands();return this.convertCommands(t)}convertCommands(e){let t=[];for(let r of e){let n=this.convertCommand(r);n&&t.push(n)}return t}convertCommand(e){switch(e.type){case"set-config":return this.convertSetConfig(e);case"set-scanlines-enabled":return this.createSetScanlinesOrder(e.enabled??!1,e.opacity);case"set-scanlines-opacity":return this.createSetScanlinesOrder(!0,e.opacity??D.scanlines.opacity);case"set-ambient-effect-enabled":return this.createSetAmbientEffectOrder(e.enabled??!1);case"set-ambient-effect-blur":return this.createSetAmbientEffectOrder(!0,e.blur);case"set-ambient-effect-scale":return this.createSetAmbientEffectOrder(!0,void 0,e.scale);case"set-scaling-mode":return this.createSetScalingModeOrder(e.scalingMode);case"set-grid":return this.createSetGridOrder(e.gridConfig);default:return console.warn(`[PostProcessOrderCollector] Unknown command type: ${e.type}`),null}}convertSetConfig(e){if(!e.config)return{type:1,flags:3,scanlines:{enabled:!1,opacity:0,pattern:0,colorR:0,colorG:0,colorB:0},ambientEffect:{enabled:!1,blur:0,scale:1,opacity:0}};let t=0,r={type:1,flags:0};if(e.config.scanlines){t|=1;let n=e.config.scanlines;r.scanlines={enabled:n.enabled,opacity:n.opacity??D.scanlines.opacity,pattern:this.patternToType(n.pattern??"horizontal"),colorR:n.color?.r??0,colorG:n.color?.g??0,colorB:n.color?.b??0}}if(e.config.ambientEffect){t|=2;let n=e.config.ambientEffect;r.ambientEffect={enabled:n.enabled,blur:n.blur??D.ambientEffect.blur,scale:n.scale??D.ambientEffect.scale,opacity:n.opacity??D.ambientEffect.opacity}}return r.flags=t,r}createSetScanlinesOrder(e,t){return{type:2,enabled:e,opacity:t??D.scanlines.opacity,pattern:0,colorR:0,colorG:0,colorB:0}}createSetAmbientEffectOrder(e,t,r){return{type:3,enabled:e,blur:t??D.ambientEffect.blur,scale:r??D.ambientEffect.scale,opacity:D.ambientEffect.opacity}}patternToType(e){switch(e){case"horizontal":return 0;case"vertical":return 1;case"grid":return 2;default:return 0}}createSetScalingModeOrder(e){return{type:4,mode:Nn(e)}}createSetGridOrder(e){let{r:t,g:r,b:n,a:o}=this.parseColor(e.color??vr.color);return{type:5,enabled:e.enabled,colorR:t,colorG:r,colorB:n,colorA:o,lineWidth:e.lineWidth??vr.lineWidth}}parseColor(e){let t=e.match(/rgba?\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+))?\s*\)/);if(t)return{r:parseInt(t[1],10),g:parseInt(t[2],10),b:parseInt(t[3],10),a:t[4]?Math.round(parseFloat(t[4])*255):255};let r=e.match(/^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$/);if(r){let n=r[1];return n.length===3?{r:parseInt(n[0]+n[0],16),g:parseInt(n[1]+n[1],16),b:parseInt(n[2]+n[2],16),a:255}:{r:parseInt(n.slice(0,2),16),g:parseInt(n.slice(2,4),16),b:parseInt(n.slice(4,6),16),a:255}}return{r:144,g:24,b:24,a:255}}};g(Ft,"PostProcessOrderCollector");var ye=Ft;var q=class q{constructor(e={}){b(this,"users",new Map);b(this,"mode");b(this,"maxUsers");b(this,"strictMode");b(this,"currentTick",0);b(this,"encoder");b(this,"displayRasterizer");b(this,"colorPalette",new Map);b(this,"stats",new ue);b(this,"spriteRegistry",new pe);b(this,"webFontRegistry",new he);b(this,"bitmapFontRegistry",new be);b(this,"soundRegistry",new ge);b(this,"audioOrderCollector");b(this,"postProcessOrderCollector");b(this,"activeWebFontId",0);b(this,"_renderCallCount",0);b(this,"onPaletteChangedCallback");b(this,"onBitmapFontChangedCallback");this.mode=e.mode??"server",this.maxUsers=e.maxUsers??64,this.strictMode=e.strictMode??!1,this.encoder=new Le,this.displayRasterizer=new Ye(this),this.audioOrderCollector=new xe(this.soundRegistry),this.postProcessOrderCollector=new ye,this.initializeDefaultPalette(),this.displayRasterizer.rebuildColorCache(),this.loadDefaultWebFont()}initializeDefaultPalette(){q.ANSI_VGA_COLORS.forEach(e=>{this.colorPalette.set(e.colorId,{r:e.r,g:e.g,b:e.b,a:e.a,e:e.e})}),this.colorPalette.set(255,{r:0,g:0,b:0,a:0,e:0})}getMode(){return this.mode}getMaxUsers(){return this.maxUsers}isStrictMode(){return this.strictMode}isServer(){return this.mode==="server"}isClient(){return this.mode==="client"}isStandalone(){return this.mode==="standalone"}createUser(e,t){if(this.users.has(e))throw new Error(`User with ID ${e} already exists`);if(this.mode==="server"&&this.users.size>=this.maxUsers)throw new Error(`Maximum number of users reached (${this.maxUsers}). Cannot create user ${e}`);if(this.mode==="client"&&this.users.size>=1)throw new Error(`Client mode only allows one user. Cannot create user ${e}`);let r=new le(e,t,this.mode);return r.setSpriteRegistry(this.spriteRegistry),this.users.set(e,r),r}getUser(e){return this.users.get(e)??null}getUsers(){return Array.from(this.users.values())}hasUser(e){return this.users.has(e)}removeUser(e){return this.users.delete(e)}getUserCount(){return this.users.size}clearAllUsers(){this.users.clear()}setColor(e,t,r,n,o=255,i=0){if(e<0||e>255)throw new Error(`Color ID must be between 0 and 255, got ${e}`);if(e>=240)throw new Error("Color IDs 240-255 are reserved (240-254: UI palette, 255: skip color). Use IDs 0-239 for custom colors.");if(t<0||t>255||r<0||r>255||n<0||n>255||o<0||o>255||i<0||i>255)throw new Error("Color components must be between 0 and 255");this.colorPalette.set(e,{r:t,g:r,b:n,a:o,e:i}),this.onPaletteChangedCallback&&this.onPaletteChangedCallback(this.colorPalette)}onPaletteChanged(e){this.onPaletteChangedCallback=e}onBitmapFontChanged(e){this.onBitmapFontChangedCallback=e}getColor(e){return this.colorPalette.get(e)??null}loadPalette(e){for(let t of e)t.colorId<0||t.colorId>255||this.colorPalette.set(t.colorId,{r:t.r,g:t.g,b:t.b,a:t.a,e:t.e??0});q.ANSI_VGA_COLORS.forEach(t=>{this.colorPalette.set(t.colorId,{r:t.r,g:t.g,b:t.b,a:t.a,e:t.e})}),this.colorPalette.set(255,{r:0,g:0,b:0,a:0,e:0}),this.displayRasterizer.rebuildColorCache(),this.onPaletteChangedCallback&&this.onPaletteChangedCallback(this.colorPalette)}getPalette(){return new Map(this.colorPalette)}resetPalette(){this.colorPalette.clear(),this.initializeDefaultPalette(),this.onPaletteChangedCallback&&this.onPaletteChangedCallback(this.colorPalette)}getColorCSS(e){let t=this.getColor(e);if(!t)return null;let r=t.a/255;return`rgba(${t.r}, ${t.g}, ${t.b}, ${r})`}getUserIds(){return Array.from(this.users.keys())}forEachUser(e){this.users.forEach(e)}filterUsers(e){return this.getUsers().filter(e)}findUser(e){return this.getUsers().find(e)}getCurrentTick(){return this.currentTick}getStats(){return this.stats}endTick(){this.stats.isEnabled()&&this.stats.startTick(this.currentTick);let e=new Map,t=0,r=0;return this.users.forEach((n,o)=>{let i=n.getLayers(),s=n.getDisplays();t+=i.length,n.getStats().isEnabled()&&n.getStats().startTick(this.currentTick);let a=s.map(x=>{let v=x.getOrigin(),U=x.getSize();return{id:x.getId(),originX:v.x,originY:v.y,sizeX:U.x,sizeY:U.y}});s.forEach(x=>x.resetChangeTracking());let d=[],c=[];i.forEach((x,v)=>{let U=x.getOrigin(),S=x.getOrders(),w=x.getStatic(),I=x.calculateUpdateFlags();x.resetChangeTracking(),x.getId()===0&&x.setId(v);let M={id:x.getId(),updateFlags:I,zIndex:x.getZOrder(),originX:U.x,originY:U.y,width:x.getWidth(),height:x.getHeight(),orderCount:S.length,orders:S};w?d.push(M):c.push(M)}),r+=d.length+c.length;let l=this.audioOrderCollector.collectFromUser(n),u=n.flushMacroOrders(),p=this.postProcessOrderCollector.collectFromUser(n),h=[...d,...c],y=this.encoder.encode({tick:this.currentTick,displayCount:a.length,displays:a,layerCount:h.length,layers:h,audioOrderCount:l.length,audioOrders:l,macroOrderCount:u.length,macroOrders:u,postProcessOrderCount:p.length,postProcessOrders:p});if(e.set(o,y),this.stats.isEnabled()){h.forEach((S,w)=>{this.stats.recordLayerOrders(w,S.orders)}),s.forEach((S,w)=>{this.stats.recordDisplayLayers(w,h.length)});let x=s.length*12,v=h.length*20,U=y.length-x-v;this.stats.recordUpdatePacketSize(y.length,x,v,U>0?U:0)}}),this.stats.isEnabled()&&(this.stats.recordLayers(t,r),this.stats.endTick()),this.currentTick++,e}endTickSplit(){this.stats.isEnabled()&&this.stats.startTick(this.currentTick);let e=new Map,t=0,r=0;return this.users.forEach((n,o)=>{let i=n.getLayers(),s=n.getDisplays();t+=i.length,n.getStats().isEnabled()&&n.getStats().startTick(this.currentTick);let a=s.map(x=>{let v=x.getOrigin(),U=x.getSize();return{id:x.getId(),originX:v.x,originY:v.y,sizeX:U.x,sizeY:U.y}});s.forEach(x=>x.resetChangeTracking());let d=[],c=[];i.forEach((x,v)=>{if(!x.getNeedsCommit())return;let U=x.getOrigin(),S=x.getOrders(),w=x.getStatic(),I=x.calculateUpdateFlags();x.resetChangeTracking(),x.resetCommit(),x.getId()===0&&x.setId(v);let M={id:x.getId(),updateFlags:I,zIndex:x.getZOrder(),originX:U.x,originY:U.y,width:x.getWidth(),height:x.getHeight(),orderCount:S.length,orders:S};S.length>0&&this.stats.isEnabled()&&this.stats.recordLayerInfo(x.getId(),w,S.length,I),w?d.push(M):c.push(M)}),r+=d.length+c.length;let l=this.audioOrderCollector.collectFromUser(n),u=this.postProcessOrderCollector.collectFromUser(n),p=n.flushMacroOrders(),h=null,y=null;if(this.stats.isEnabled()&&this.stats.recordPacketSplit(o,a.length,d.length,c.length),d.length>0&&(h=this.encoder.encode({tick:this.currentTick,displayCount:a.length,displays:a,layerCount:d.length,layers:d,audioOrderCount:0,audioOrders:[],macroOrderCount:0,macroOrders:[],postProcessOrderCount:0,postProcessOrders:[]})),y=this.encoder.encode({tick:this.currentTick,displayCount:a.length,displays:a,layerCount:c.length,layers:c,audioOrderCount:l.length,audioOrders:l,macroOrderCount:p.length,macroOrders:p,postProcessOrderCount:u.length,postProcessOrders:u}),e.set(o,{static:h,dynamic:y}),n.getStats().isEnabled()){let x=s.reduce((w,I)=>{let M=I.getSize();return w+M.x*M.y},0);n.getStats().recordDisplays(s.length,x),n.getStats().recordLayers(i.length,d.length+c.length,d.length,c.length),[...d,...c].forEach(w=>{n.getStats().recordLayerOrders(w.id,w.orders.length)});let v=h?.length||0,U=y?.length||0;n.getStats().recordPacketSizes(v,U);let S=n.getInputBindingRegistry();n.getStats().recordInput(!1,S.getAxisCount(),S.getButtonCount()),n.getStats().endTick()}if(this.stats.isEnabled()){let x=[...d,...c];x.forEach((I,M)=>{this.stats.recordLayerOrders(M,I.orders)}),s.forEach((I,M)=>{this.stats.recordDisplayLayers(M,x.length)});let v=(h?.length||0)+(y?.length||0),U=s.length*12,S=x.length*20,w=v-U-S;this.stats.recordUpdatePacketSize(v,U,S,w>0?w:0)}}),this.stats.isEnabled()&&(this.stats.recordLayers(t,r),this.stats.endTick()),this.currentTick++,e}getSnapshot(e){let t=this.getUser(e);if(!t)return null;let r=t.getDisplays(),n=t.getLayers(),o=r.map((s,a)=>{let d=s.getOrigin(),c=s.getSize();return{id:a,originX:d.x,originY:d.y,sizeX:c.x,sizeY:c.y}}),i=n.map((s,a)=>{let d=s.getOrigin(),c=s.getOrders(),l=7;return s.getId()===0&&s.setId(a),{id:s.getId(),updateFlags:l,zIndex:s.getZOrder(),originX:d.x,originY:d.y,width:s.getWidth(),height:s.getHeight(),orderCount:c.length,orders:c}});return this.encoder.encode({tick:this.currentTick,displayCount:o.length,displays:o,layerCount:i.length,layers:i,audioOrderCount:0,audioOrders:[],macroOrderCount:0,macroOrders:[],postProcessOrderCount:0,postProcessOrders:[]})}resetTick(){this.currentTick=0}applyUpdatePacket(e,t){let r=this.getUser(e);if(!r){if(this.strictMode)throw new Error(`Cannot apply update packet: user ${e} does not exist`);return!1}return r.applyUpdate(t),t.audioOrders&&t.audioOrders.length>0&&r.applyAudioOrders(t.audioOrders),!0}applyUpdatePacketBuffer(e,t){let{UpdatePacketDecoder:r}=($t(),B(kr)),o=new r().decode(t);return this.applyUpdatePacket(e,o)?o:null}applyLoadPacket(e){try{let{LoadDecoder:t}=(Tr(),B(Br)),{LoadType:r}=(X(),B(H)),i=new t().decode(e).load;switch(i.loadType){case r.ColorPalette:this.loadPalette(i.colors);break;case r.Sprite:this.loadUnicolorSprites(i);break;case r.MulticolorSprite:this.loadMulticolorSprites(i);break;case r.BitmapFont:{let s=this.getBitmapFontRegistry();s.hasFont(i.fontId)&&s.unloadFont(i.fontId),s.loadFont(i.fontId,{charWidth:i.width,charHeight:i.height,cellWidth:i.cellWidth,cellHeight:i.cellHeight,glyphs:new Map(i.characters.map(a=>[a.charCode,a.bitmap]))});break}case r.WebFont:{let s=this.getWebFontRegistry();s.hasFont(i.fontId)&&s.unloadFont(i.fontId),this.loadWebFontById(i.fontId,{fontFamily:i.fontFamily,fontSize:i.fontSize,offsetX:i.offsetX,offsetY:i.offsetY,charSpacing:i.charSpacing,lineHeight:i.lineHeight,fontWeight:i.fontWeight,fontStyle:i.fontStyle});break}case r.Sound:console.warn("[Core] Sound loading not yet implemented");break;case r.Macro:{for(let s of this.users.values())s.loadMacroTemplate(i.macroId,i.template);break}default:return console.error(`[Core] Unknown LoadType: ${i.loadType}`),!1}return!0}catch(t){return console.error("[Core] Failed to apply LoadPacket:",t),!1}}generatePaletteLoadPacket(){let e=this.getPalette();if(e.size===0)return null;let{LoadEncoder:t}=(J(),B(j)),{LoadType:r}=(X(),B(H)),n=new t,o=[];return e.forEach((i,s)=>{s!==255&&o.push({colorId:s,r:i.r,g:i.g,b:i.b,a:i.a,e:i.e})}),n.encode({loadType:r.ColorPalette,colors:o})}generateUnicolorSpritesLoadPacket(){let e=this.getSpriteRegistry(),t=[];for(let i=0;i<=255;i++){let s=e.getUnicolorSprite(i);if(s){let a=[];for(let d=0;d<s.sizeX*s.sizeY;d++)a.push(s.data.get(d));t.push({spriteId:s.id,sizeX:s.sizeX,sizeY:s.sizeY,data:a})}}if(t.length===0)return null;let{LoadEncoder:r}=(J(),B(j)),{LoadType:n}=(X(),B(H));return new r().encode({loadType:n.Sprite,sprites:t})}generateMulticolorSpritesLoadPacket(){let e=this.getSpriteRegistry(),t=[];for(let i=0;i<=255;i++){let s=e.getMulticolorSprite(i);if(s){let a=[];for(let d=0;d<s.sizeX*s.sizeY;d++){let c=s.data.get(d);a.push({charCode:c.charCode,fgColorId:c.fgColorCode,bgColorId:c.bgColorCode})}t.push({spriteId:s.id,sizeX:s.sizeX,sizeY:s.sizeY,data:a})}}if(t.length===0)return null;let{LoadEncoder:r}=(J(),B(j)),{LoadType:n}=(X(),B(H));return new r().encode({loadType:n.MulticolorSprite,sprites:t})}generateWebFontsLoadPackets(){let e=this.getWebFontRegistry(),t=e.getFontIds(),r=[],{LoadEncoder:n}=(J(),B(j)),{LoadType:o}=(X(),B(H)),i=new n;for(let s of t){let a=e.getFont(s);if(a){let d=a.getConfig(),c=i.encode({loadType:o.WebFont,fontId:s,fontFamily:d.fontFamily,fontSize:d.fontSize,offsetX:d.offsetX,offsetY:d.offsetY,charSpacing:d.charSpacing,lineHeight:d.lineHeight,fontWeight:d.fontWeight,fontStyle:d.fontStyle});r.push(c)}}return r}generateBitmapFontsLoadPackets(){let e=this.getBitmapFontRegistry(),t=e.getFontIds(),r=[],{LoadEncoder:n}=(J(),B(j)),{LoadType:o}=(X(),B(H)),i=new n;for(let s of t){let a=e.getFont(s);if(a){let d=[];for(let c=0;c<256;c++){let l=a.getGlyph(c);l&&d.push({charCode:c,bitmap:l})}if(d.length>0){let c=i.encode({loadType:o.BitmapFont,fontId:s,width:a.getCharWidth(),height:a.getCharHeight(),cellWidth:a.getCellWidth(),cellHeight:a.getCellHeight(),characters:d});r.push(c)}}}return r}generateAllLoadPackets(){let e=[],t=this.generatePaletteLoadPacket();t&&e.push(t);let r=this.generateUnicolorSpritesLoadPacket();r&&e.push(r);let n=this.generateMulticolorSpritesLoadPacket();n&&e.push(n);let o=this.generateWebFontsLoadPackets();e.push(...o);let i=this.generateBitmapFontsLoadPackets();return e.push(...i),e}generateMacroLoadPackets(e){let t=this.getUser(e);if(!t)return[];let r=t.getMacroLoads();if(r.length===0)return[];let n=new De;return r.map(o=>n.encode(o))}applyInputBindingsLoadPacket(e,t){let r=this.getUser(e);if(!r){if(this.strictMode)throw new Error(`Cannot apply input bindings: user ${e} does not exist`);return!1}try{return r.applyInputBindingsLoadPacket(t),!0}catch(n){return console.error(`[Core] Failed to apply input bindings for user ${e}:`,n),!1}}getRenderState(e){let t=this.getUser(e);if(!t)return null;let r=t.getDisplays(),n=t.getLayers(),o=performance.now(),i=new Array(r.length);for(let a=0;a<r.length;a++){let d=r[a],c=d.getOrigin(),l=d.getSize();i[a]=this.displayRasterizer.rasterize({x:c.x,y:c.y,width:l.x,height:l.y},n)}let s=performance.now()-o;return this._renderCallCount||(this._renderCallCount=0),this._renderCallCount++,{userId:t.id,userName:t.name,tick:this.currentTick,displays:i}}getAllRenderStates(){let e=new Map;return this.users.forEach((t,r)=>{let n=this.getRenderState(r);n&&e.set(r,n)}),e}enableStats(e){this.stats.setEnabled(e)}getStatsInstance(){return this.stats}resetStats(){this.stats.reset()}loadUnicolorSprites(e){this.spriteRegistry.loadUnicolorSprites(e)}loadMulticolorSprites(e){this.spriteRegistry.loadMulticolorSprites(e)}unloadUnicolorSprite(e){return this.spriteRegistry.unloadUnicolorSprite(e)}unloadMulticolorSprite(e){return this.spriteRegistry.unloadMulticolorSprite(e)}clearUnicolorSprites(){this.spriteRegistry.clearUnicolorSprites()}clearMulticolorSprites(){this.spriteRegistry.clearMulticolorSprites()}clearAllSprites(){this.spriteRegistry.clearAll()}getUnicolorSpriteCount(){return this.spriteRegistry.getUnicolorSpriteCount()}getMulticolorSpriteCount(){return this.spriteRegistry.getMulticolorSpriteCount()}getTotalSpriteCount(){return this.spriteRegistry.getTotalSpriteCount()}hasUnicolorSprite(e){return this.spriteRegistry.hasUnicolorSprite(e)}hasMulticolorSprite(e){return this.spriteRegistry.hasMulticolorSprite(e)}getSpriteRegistry(){return this.spriteRegistry}getSoundRegistry(){return this.soundRegistry}async loadSound(e,t){let r=this.detectSoundFormat(t),n=await this.loadSoundData(t);return this.soundRegistry.registerFile(e,r,n)}async loadSounds(e){let t={},n=Object.entries(e).map(async([o,i])=>{let s=await this.loadSound(o,i);t[o]=s});return await Promise.all(n),t}detectSoundFormat(e){let t=e.split(".").pop()?.toLowerCase()??"",r={mp3:"mp3",wav:"wav",ogg:"ogg",webm:"webm",aac:"aac",m4a:"aac"},n=r[t];if(!n)throw new Error(`Unsupported audio format: .${t}. Supported: ${Object.keys(r).join(", ")}`);return n}async loadSoundData(e){let t=globalThis;if(typeof t.document<"u"||typeof t.window<"u"||typeof t.fetch=="function")try{let n=await fetch(e);if(!n.ok)throw new Error(`HTTP ${n.status}: ${n.statusText}`);let o=await n.arrayBuffer();return new Uint8Array(o)}catch(n){let o=n instanceof Error?n.message:String(n);throw new Error(`Failed to load sound "${e}": ${o}`)}else{let n=typeof Ge<"u"?Ge:null;if(!n)throw new Error("Node.js require is not available");let s=n("fs").readFileSync(e);return new Uint8Array(s)}}registerSound(e,t,r){return this.soundRegistry.registerFile(e,t,r)}registerExternalSound(e,t,r,n){return this.soundRegistry.registerExternal(e,t,r,n)}hasSound(e){return this.soundRegistry.has(e)}generateSoundLoadPackets(){return this.soundRegistry.toLoadPackets()}loadDefaultWebFont(){this.webFontRegistry.loadFont(0,{fontFamily:"Courier New",fontSize:16,offsetX:0,offsetY:0,charSpacing:0,lineHeight:1,fontWeight:"normal",fontStyle:"normal"}),this.activeWebFontId=0}loadWebFont(e){let t=e.getFontId(),r=e.getConfig();this.webFontRegistry.loadFont(t,r)}getWebFont(e){return this.webFontRegistry.getFont(e)??null}hasWebFont(e){return this.webFontRegistry.hasFont(e)}unloadWebFont(e){if(e===0)throw new Error("Cannot unload default font (fontId 0)");return this.webFontRegistry.unloadFont(e)}clearWebFonts(){this.webFontRegistry.clearFonts(),this.loadDefaultWebFont()}setActiveWebFont(e){if(!this.webFontRegistry.hasFont(e))throw new Error(`WebFont with ID ${e} does not exist`);this.activeWebFontId=e}getActiveWebFontId(){return this.activeWebFontId}getActiveWebFont(){let e=this.webFontRegistry.getFont(this.activeWebFontId);if(!e)throw new Error(`Active WebFont ${this.activeWebFontId} not found. This should not happen.`);return e}getWebFontCount(){return this.webFontRegistry.getFontCount()}getWebFontIds(){return this.webFontRegistry.getFontIds()}getWebFontRegistry(){return this.webFontRegistry}getBitmapFontRegistry(){return this.bitmapFontRegistry}loadWebFontById(e,t){let r=new W(e,t);this.loadWebFont(r)}loadBitmapFontById(e,t){this.bitmapFontRegistry.loadFont(e,t),this.onBitmapFontChangedCallback&&this.onBitmapFontChangedCallback(e)}getBitmapFont(e){return this.bitmapFontRegistry.getFont(e)??null}hasBitmapFont(e){return this.bitmapFontRegistry.hasFont(e)}unloadBitmapFont(e){return this.bitmapFontRegistry.unloadFont(e)}clearBitmapFonts(){this.bitmapFontRegistry.clearFonts()}getBitmapFontCount(){return this.bitmapFontRegistry.getFontCount()}getBitmapFontIds(){return this.bitmapFontRegistry.getFontIds()}};g(q,"Core"),b(q,"ANSI_VGA_COLORS",[{colorId:240,r:16,g:16,b:16,a:255,e:0},{colorId:241,r:128,g:128,b:128,a:255,e:0},{colorId:242,r:192,g:192,b:192,a:255,e:0},{colorId:243,r:240,g:240,b:240,a:255,e:0},{colorId:244,r:200,g:50,b:50,a:255,e:0},{colorId:245,r:50,g:200,b:50,a:255,e:0},{colorId:246,r:220,g:180,b:50,a:255,e:0},{colorId:247,r:50,g:100,b:220,a:255,e:0},{colorId:248,r:50,g:200,b:200,a:255,e:0},{colorId:249,r:200,g:50,b:200,a:255,e:0},{colorId:250,r:220,g:120,b:50,a:255,e:0},{colorId:251,r:120,g:220,b:120,a:255,e:0},{colorId:252,r:120,g:180,b:220,a:255,e:0},{colorId:253,r:220,g:150,b:200,a:255,e:0},{colorId:254,r:250,g:220,b:150,a:255,e:0}]);var Kt=q;import{Vector2 as Ba}from"@utsp/types";var K=new Map([[24,new Uint8Array([0,24,60,126,255,255,0,0])],[25,new Uint8Array([0,0,255,255,126,60,24,0])],[26,new Uint8Array([0,48,120,252,252,120,48,0])],[27,new Uint8Array([0,12,30,63,63,30,12,0])],[32,new Uint8Array([0,0,0,0,0,0,0,0])],[33,new Uint8Array([24,24,24,24,24,0,24,0])],[34,new Uint8Array([108,108,108,0,0,0,0,0])],[35,new Uint8Array([54,54,127,54,127,54,54,0])],[36,new Uint8Array([12,63,104,62,11,126,24,0])],[37,new Uint8Array([96,102,12,24,48,102,6,0])],[38,new Uint8Array([56,108,108,56,109,102,59,0])],[39,new Uint8Array([24,24,24,0,0,0,0,0])],[40,new Uint8Array([12,24,48,48,48,24,12,0])],[41,new Uint8Array([48,24,12,12,12,24,48,0])],[42,new Uint8Array([0,102,60,255,60,102,0,0])],[43,new Uint8Array([0,24,24,126,24,24,0,0])],[44,new Uint8Array([0,0,0,0,0,24,24,48])],[45,new Uint8Array([0,0,0,126,0,0,0,0])],[46,new Uint8Array([0,0,0,0,0,24,24,0])],[47,new Uint8Array([0,6,12,24,48,96,0,0])],[48,new Uint8Array([60,102,110,126,118,102,60,0])],[49,new Uint8Array([24,56,24,24,24,24,126,0])],[50,new Uint8Array([60,102,6,12,24,48,126,0])],[51,new Uint8Array([60,102,6,28,6,102,60,0])],[52,new Uint8Array([12,28,60,108,126,12,12,0])],[53,new Uint8Array([126,96,124,6,6,102,60,0])],[54,new Uint8Array([28,48,96,124,102,102,60,0])],[55,new Uint8Array([126,6,12,24,48,48,48,0])],[56,new Uint8Array([60,102,102,60,102,102,60,0])],[57,new Uint8Array([60,102,102,62,6,12,56,0])],[58,new Uint8Array([0,0,24,24,0,24,24,0])],[59,new Uint8Array([0,0,24,24,0,24,24,48])],[60,new Uint8Array([12,24,48,96,48,24,12,0])],[61,new Uint8Array([0,0,126,0,126,0,0,0])],[62,new Uint8Array([48,24,12,6,12,24,48,0])],[63,new Uint8Array([60,102,12,24,24,0,24,0])],[64,new Uint8Array([60,102,110,106,110,96,60,0])],[65,new Uint8Array([60,102,102,126,102,102,102,0])],[66,new Uint8Array([124,102,102,124,102,102,124,0])],[67,new Uint8Array([60,102,96,96,96,102,60,0])],[68,new Uint8Array([120,108,102,102,102,108,120,0])],[69,new Uint8Array([126,96,96,124,96,96,126,0])],[70,new Uint8Array([126,96,96,124,96,96,96,0])],[71,new Uint8Array([60,102,96,110,102,102,60,0])],[72,new Uint8Array([102,102,102,126,102,102,102,0])],[73,new Uint8Array([126,24,24,24,24,24,126,0])],[74,new Uint8Array([62,12,12,12,12,108,56,0])],[75,new Uint8Array([102,108,120,112,120,108,102,0])],[76,new Uint8Array([96,96,96,96,96,96,126,0])],[77,new Uint8Array([99,119,127,107,99,99,99,0])],[78,new Uint8Array([102,102,118,126,110,102,102,0])],[79,new Uint8Array([60,102,102,102,102,102,60,0])],[80,new Uint8Array([124,102,102,124,96,96,96,0])],[81,new Uint8Array([60,102,102,102,106,108,54,0])],[82,new Uint8Array([124,102,102,124,108,102,102,0])],[83,new Uint8Array([60,102,96,60,6,102,60,0])],[84,new Uint8Array([126,24,24,24,24,24,24,0])],[85,new Uint8Array([102,102,102,102,102,102,60,0])],[86,new Uint8Array([102,102,102,102,102,60,24,0])],[87,new Uint8Array([99,99,99,107,127,119,99,0])],[88,new Uint8Array([102,102,60,24,60,102,102,0])],[89,new Uint8Array([102,102,102,60,24,24,24,0])],[90,new Uint8Array([126,6,12,24,48,96,126,0])],[91,new Uint8Array([60,48,48,48,48,48,60,0])],[92,new Uint8Array([0,96,48,24,12,6,0,0])],[93,new Uint8Array([60,12,12,12,12,12,60,0])],[94,new Uint8Array([24,60,102,0,0,0,0,0])],[95,new Uint8Array([0,0,0,0,0,0,255,0])],[96,new Uint8Array([48,24,12,0,0,0,0,0])],[97,new Uint8Array([0,0,60,6,62,102,62,0])],[98,new Uint8Array([96,96,124,102,102,102,124,0])],[99,new Uint8Array([0,0,60,102,96,102,60,0])],[100,new Uint8Array([6,6,62,102,102,102,62,0])],[101,new Uint8Array([0,0,60,102,126,96,60,0])],[102,new Uint8Array([28,54,48,124,48,48,48,0])],[103,new Uint8Array([0,0,62,102,102,62,6,60])],[104,new Uint8Array([96,96,124,102,102,102,102,0])],[105,new Uint8Array([24,0,56,24,24,24,60,0])],[106,new Uint8Array([12,0,28,12,12,12,108,56])],[107,new Uint8Array([96,96,102,108,120,108,102,0])],[108,new Uint8Array([56,24,24,24,24,24,60,0])],[109,new Uint8Array([0,0,102,127,107,107,99,0])],[110,new Uint8Array([0,0,124,102,102,102,102,0])],[111,new Uint8Array([0,0,60,102,102,102,60,0])],[112,new Uint8Array([0,0,124,102,102,124,96,96])],[113,new Uint8Array([0,0,62,102,102,62,6,6])],[114,new Uint8Array([0,0,108,118,96,96,96,0])],[115,new Uint8Array([0,0,62,96,60,6,124,0])],[116,new Uint8Array([48,48,124,48,48,54,28,0])],[117,new Uint8Array([0,0,102,102,102,102,62,0])],[118,new Uint8Array([0,0,102,102,102,60,24,0])],[119,new Uint8Array([0,0,99,107,107,127,54,0])],[120,new Uint8Array([0,0,102,60,24,60,102,0])],[121,new Uint8Array([0,0,102,102,102,62,6,60])],[122,new Uint8Array([0,0,126,12,24,48,126,0])],[123,new Uint8Array([14,24,24,112,24,24,14,0])],[124,new Uint8Array([24,24,24,24,24,24,24,0])],[125,new Uint8Array([112,24,24,14,24,24,112,0])],[126,new Uint8Array([49,107,70,0,0,0,0,0])],[179,new Uint8Array([24,24,24,24,24,24,24,24])],[196,new Uint8Array([0,0,0,255,0,0,0,0])],[218,new Uint8Array([0,0,0,31,24,24,24,24])],[191,new Uint8Array([0,0,0,248,24,24,24,24])],[192,new Uint8Array([24,24,24,31,0,0,0,0])],[217,new Uint8Array([24,24,24,248,0,0,0,0])],[195,new Uint8Array([24,24,24,31,24,24,24,24])],[180,new Uint8Array([24,24,24,248,24,24,24,24])],[194,new Uint8Array([0,0,0,255,24,24,24,24])],[193,new Uint8Array([24,24,24,255,0,0,0,0])],[197,new Uint8Array([24,24,24,255,24,24,24,24])],[186,new Uint8Array([54,54,54,54,54,54,54,54])],[205,new Uint8Array([0,0,0,255,0,255,0,0])],[201,new Uint8Array([0,0,0,63,54,54,54,54])],[187,new Uint8Array([0,0,0,252,54,54,54,54])],[200,new Uint8Array([54,54,54,63,0,0,0,0])],[188,new Uint8Array([54,54,54,252,0,0,0,0])],[204,new Uint8Array([54,54,54,63,54,54,54,54])],[185,new Uint8Array([54,54,54,252,54,54,54,54])],[203,new Uint8Array([0,0,0,255,54,54,54,54])],[202,new Uint8Array([54,54,54,255,0,0,0,0])],[206,new Uint8Array([54,54,54,255,54,54,54,54])],[219,new Uint8Array([255,255,255,255,255,255,255,255])],[178,new Uint8Array([170,85,170,85,170,85,170,85])],[177,new Uint8Array([136,34,136,34,136,34,136,34])],[176,new Uint8Array([34,136,34,136,34,136,34,136])],[223,new Uint8Array([255,255,255,255,0,0,0,0])],[220,new Uint8Array([0,0,0,0,255,255,255,255])],[221,new Uint8Array([240,240,240,240,240,240,240,240])],[222,new Uint8Array([15,15,15,15,15,15,15,15])]]);function _n(m){return K.get(m)}g(_n,"getCharBitmap");function Hn(m){return K.has(m)}g(Hn,"hasChar");function Wn(){return Array.from(K.keys()).sort((m,e)=>m-e)}g(Wn,"getAllCharCodes");function Vn(m){let e=Array.from(K.entries()).map(([t,r])=>({charCode:t,bitmap:r}));return{loadType:4,fontId:m,width:8,height:8,cellWidth:8,cellHeight:8,characters:e}}g(Vn,"createASCII8x8FontLoad");function $n(){return{charWidth:8,charHeight:8,glyphs:new Map(K)}}g($n,"getASCII8x8FontConfig");T();var Qt=class Qt{encode(e){switch(e.type){case 1:return this.encodeClick(e);case 2:return this.encodeChange(e);case 3:return this.encodeSubmit(e);case 4:return this.encodeSelect(e);default:throw new Error(`Unknown macro event type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return 2;case 2:return this.calculateChangeSize(e);case 3:return this.calculateSubmitSize(e);case 4:return 4;default:throw new Error(`Unknown macro event type: ${e.type}`)}}encodeClick(e){let t=C.allocUnsafe(2);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.toUint8Array()}encodeChange(e){if(typeof e.value=="boolean"){let r=C.allocUnsafe(4);return r.writeUInt8(e.type,0),r.writeUInt8(e.instanceId,1),r.writeUInt8(1,2),r.writeUInt8(e.value?1:0,3),r.toUint8Array()}else{let r=C.allocUnsafe(7);return r.writeUInt8(e.type,0),r.writeUInt8(e.instanceId,1),r.writeUInt8(0,2),r.writeFloatBE(e.value,3),r.toUint8Array()}}calculateChangeSize(e){return typeof e.value=="boolean"?4:7}encodeSubmit(e){let t=new TextEncoder().encode(e.text);if(t.length>65535)throw new Error(`Submit text too large: ${t.length} bytes (max 65535)`);let r=4+t.length,n=C.allocUnsafe(r),o=0;return n.writeUInt8(e.type,o++),n.writeUInt8(e.instanceId,o++),n.writeUInt16BE(t.length,o),o+=2,n.toUint8Array().set(t,o),n.toUint8Array()}calculateSubmitSize(e){return 4+new TextEncoder().encode(e.text).length}encodeSelect(e){let t=C.allocUnsafe(4);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.writeUInt16BE(e.index,2),t.toUint8Array()}};g(Qt,"MacroEventEncoder");var $e=Qt;function Gn(m,e,t,r,n,o,i,s=[],a=[]){let d=Array.from(e.entries()).sort((A,O)=>A[0]-O[0]),c=Array.from(t.entries()).sort((A,O)=>A[0]-O[0]),l=d.length,u=c.length,p=lt(l,u),h=new TextEncoder,y=s.map(A=>h.encode(A)),x=1+y.reduce((A,O)=>A+1+O.length,0),v=new $e,U=a.map(A=>v.encode(A)),S=1+U.reduce((A,O)=>A+O.length,0),w=p+x+S,I=new Uint8Array(w),M=new DataView(I.buffer),f=0;M.setBigUint64(f,m,!0),f+=8;for(let[,A]of d){let O=dt(A);I[f]=O+256&255,f+=1}let R=G(u);for(let A=0;A<R;A++){let O=0;for(let Se=0;Se<8;Se++){let rr=A*8+Se;if(rr<u){let[,Fr]=c[rr];Fr&&(O|=1<<Se)}}I[f]=O,f+=1}I[f]=r&255,f+=1,I[f]=n&255,f+=1,I[f]=o&255,f+=1;let N=0;i&&(N|=1),I[f]=N,f+=1,I[f]=Math.min(s.length,255),f+=1;for(let A of y)I[f]=Math.min(A.length,255),f+=1,I.set(A.slice(0,255),f),f+=A.length;I[f]=Math.min(a.length,255),f+=1;for(let A of U)I.set(A,f),f+=A.length;return I}g(Gn,"encodeCompressedInput");var E=class E{static toCharCode(e){if(typeof e=="number")return e&255;let t=e.charCodeAt(0);return re(t)}static dedent(e){let t=e.split(`
|
|
9
9
|
`);if(t.length>0&&t[0].trim()===""&&t.shift(),t.length>0&&t[t.length-1].trim()===""&&t.pop(),t.length===0)return"";let r=t.filter(o=>o.trim().length>0);if(r.length===0)return"";let n=Math.min(...r.map(o=>{let i=o.match(/^(\s*)/);return i?i[1].length:0}));return t.map(o=>o.slice(n)).join(`
|
|
10
10
|
`)}static char(e,t,r,n=15,o=0){return{type:1,posX:e,posY:t,charCode:E.toCharCode(r),bgColorCode:o,fgColorCode:n}}static text(e,t,r,n=15,o=0){return{type:2,posX:e,posY:t,text:r,bgColorCode:o,fgColorCode:n}}static textMultiline(e,t,r,n=15,o=0){return{type:23,posX:e,posY:t,text:E.dedent(r),bgColorCode:o,fgColorCode:n}}static subFrame(e,t,r,n,o,i=15,s=0){return{type:3,posX:e,posY:t,sizeX:r,sizeY:n,frame:o.map(a=>E.toCharCode(a)),bgColorCode:s,fgColorCode:i}}static subFrameMultiColor(e,t,r,n,o){return{type:4,posX:e,posY:t,sizeX:r,sizeY:n,frame:o.map(i=>({charCode:E.toCharCode(i.charCode),bgColorCode:i.bgColorCode,fgColorCode:i.fgColorCode}))}}static fullFrame(e,t=15,r=0){return{type:5,frame:e.map(n=>E.toCharCode(n)),bgColorCode:r,fgColorCode:t}}static fullFrameMultiColor(e){return{type:6,frame:e.map(t=>({charCode:E.toCharCode(t.charCode),bgColorCode:t.bgColorCode,fgColorCode:t.fgColorCode}))}}static sprite(e,t,r,n=15,o=0){return{type:7,posX:e,posY:t,spriteIndex:r,bgColorCode:o,fgColorCode:n}}static spriteMultiColor(e,t,r){return{type:8,posX:e,posY:t,spriteIndex:r}}static colorMap(e,t,r,n,o){return{type:9,posX:e,posY:t,sizeX:r,sizeY:n,colorData:o}}static rectangle(e,t,r,n,o={}){return{type:10,shapeType:1,shapeData:{posX:e,posY:t,width:r,height:n,filled:o.filled??!0,charCode:E.toCharCode(o.charCode??9608),bgColorCode:o.bgColor??0,fgColorCode:o.fgColor??15}}}static circle(e,t,r,n={}){return{type:10,shapeType:2,shapeData:{centerX:e,centerY:t,radius:r,filled:n.filled??!0,charCode:E.toCharCode(n.charCode??9608),bgColorCode:n.bgColor??0,fgColorCode:n.fgColor??15}}}static line(e,t,r,n,o={}){return{type:10,shapeType:3,shapeData:{x1:e,y1:t,x2:r,y2:n,charCode:E.toCharCode(o.charCode??9608),bgColorCode:o.bgColor??0,fgColorCode:o.fgColor??15}}}static ellipse(e,t,r,n,o={}){return{type:10,shapeType:4,shapeData:{centerX:e,centerY:t,radiusX:r,radiusY:n,filled:o.filled??!0,charCode:E.toCharCode(o.charCode??9608),bgColorCode:o.bgColor??0,fgColorCode:o.fgColor??15}}}static triangle(e,t,r,n,o,i,s={}){return{type:10,shapeType:5,shapeData:{x1:e,y1:t,x2:r,y2:n,x3:o,y3:i,filled:s.filled??!0,charCode:E.toCharCode(s.charCode??9608),bgColorCode:s.bgColor??0,fgColorCode:s.fgColor??15}}}static dotCloud(e,t,r=15,n=0){return{type:11,charCode:E.toCharCode(t),bgColorCode:n,fgColorCode:r,positions:e}}static dotCloudMultiColor(e){return{type:12,dots:e.map(t=>({...t,charCode:E.toCharCode(t.charCode)}))}}static bitmask(e,t,r,n,o,i,s=15,a=0,d=!1){let c=r*n,l=Math.ceil(c/8),u=new Uint8Array(l);for(let p=0;p<c;p++)if(o[p]){let h=Math.floor(p/8),y=p%8;u[h]|=1<<y}return{type:17,posX:e,posY:t,sizeX:r,sizeY:n,charCode:E.toCharCode(i),bgColorCode:a,fgColorCode:s,override:d,mask:u}}static bitmask4(e,t,r,n,o,i,s=!1){let a={char:"?",fgColor:15,bgColor:0},d=[i[0]??a,i[1]??a,i[2]??a],c=r*n,l=Math.ceil(c/4),u=new Uint8Array(l);for(let p=0;p<c;p++){let h=o[p]&3,y=Math.floor(p/4),x=p%4*2;u[y]|=h<<x}return{type:18,posX:e,posY:t,sizeX:r,sizeY:n,override:s,variants:[{charCode:E.toCharCode(d[0].char),fgColorCode:d[0].fgColor,bgColorCode:d[0].bgColor},{charCode:E.toCharCode(d[1].char),fgColorCode:d[1].fgColor,bgColorCode:d[1].bgColor},{charCode:E.toCharCode(d[2].char),fgColorCode:d[2].fgColor,bgColorCode:d[2].bgColor}],mask:u}}static bitmask16(e,t,r,n,o,i,s=!1){let a={char:"?",fgColor:15,bgColor:0},d=[];for(let p=0;p<15;p++)d.push(i[p]??a);let c=r*n,l=Math.ceil(c/2),u=new Uint8Array(l);for(let p=0;p<c;p++){let h=o[p]&15,y=Math.floor(p/2),x=p%2*4;u[y]|=h<<x}return{type:24,posX:e,posY:t,sizeX:r,sizeY:n,override:s,variants:d.map(p=>({charCode:E.toCharCode(p.char),fgColorCode:p.fgColor,bgColorCode:p.bgColor})),mask:u}}static spriteCloud(e,t,r=15,n=0){return{type:13,spriteIndex:e,bgColorCode:n,fgColorCode:r,positions:t}}static spriteCloudMultiColor(e,t){return{type:14,spriteIndex:e,positions:t}}static spriteCloudVaried(e){return{type:15,sprites:e}}static spriteCloudVariedMultiColor(e){return{type:16,sprites:e}}static clear(e=32,t=15,r=0){return{type:19,charCode:E.toCharCode(e),bgColorCode:r,fgColorCode:t}}static fillChar(e,t,r,n=15,o=0){return{type:20,patternWidth:e,patternHeight:t,pattern:r.map(i=>E.toCharCode(i)),bgColorCode:o,fgColorCode:n}}static fillSprite(e,t=15,r=0){return{type:21,spriteIndex:e,bgColorCode:r,fgColorCode:t}}static fillSpriteMultiColor(e){return{type:22,spriteIndex:e}}static boxWithBorder(e,t,r,n,o,i){return[this.rectangle(e+1,t+1,r-2,n-2,{charCode:i.charCode??9608,bgColor:i.bgColor??0,fgColor:i.fgColor??8,filled:!0}),this.rectangle(e,t,r,n,{charCode:o.charCode??9608,bgColor:o.bgColor??0,fgColor:o.fgColor??15,filled:!1})]}static grid(e,t,r,n,o,i,s={}){let a=[];for(let d=0;d<=o;d++)for(let c=0;c<=i;c++)a.push({posX:e+c*r,posY:t+d*n});return this.dotCloud(a,s.charCode??"+",s.fgColor??15,s.bgColor??0)}static polyline(e,t="*",r=15,n=0){return{type:25,charCode:E.toCharCode(t),fgColorCode:r,bgColorCode:n,points:e.map(o=>({x:o.x&255,y:o.y&255}))}}static polylineFromCoords(e,t="*",r=15,n=0){let o=[];for(let i=0;i<e.length-1;i+=2)o.push({x:e[i],y:e[i+1]});return this.polyline(o,t,r,n)}static polygon(e,t="*",r=15,n=0){if(e.length<2)return this.polyline(e,t,r,n);let o=[...e,e[0]];return this.polyline(o,t,r,n)}};g(E,"OrderBuilder");var er=E;gt();X();lr();var zr=(u=>(u[u.LayerEnabled=1]="LayerEnabled",u[u.SetMode=2]="SetMode",u[u.UpdatePosition=4]="UpdatePosition",u[u.UpdateZOrder=8]="UpdateZOrder",u[u.Disabled=0]="Disabled",u[u.EnabledAddMode=1]="EnabledAddMode",u[u.EnabledSetMode=3]="EnabledSetMode",u[u.EnabledAddMoveOnly=5]="EnabledAddMoveOnly",u[u.EnabledSetMoveOnly=7]="EnabledSetMoveOnly",u[u.EnabledAddReorderOnly=9]="EnabledAddReorderOnly",u[u.EnabledSetReorderOnly=11]="EnabledSetReorderOnly",u[u.FullUpdate=15]="FullUpdate",u))(zr||{}),tr;(c=>{function m(l,u){return(l&u)!==0}c.hasFlag=m,g(m,"hasFlag");function e(l,u){return l|u}c.addFlag=e,g(e,"addFlag");function t(l,u){return l&~u}c.removeFlag=t,g(t,"removeFlag");function r(...l){return l.reduce((u,p)=>u|p,0)}c.combine=r,g(r,"combine");function n(l){return(l&240)===0}c.isValid=n,g(n,"isValid");function o(l){return m(l,1)}c.isEnabled=o,g(o,"isEnabled");function i(l){return m(l,2)}c.isSetMode=i,g(i,"isSetMode");function s(l){return m(l,4)}c.hasPositionChanged=s,g(s,"hasPositionChanged");function a(l){return m(l,8)}c.hasZOrderChanged=a,g(a,"hasZOrderChanged");function d(l){if(l===0)return"Disabled";let u=[];return m(l,1)?u.push("Enabled"):u.push("Disabled"),m(l,2)?u.push("SET"):u.push("ADD"),m(l,4)&&u.push("Position"),m(l,8)&&u.push("ZOrder"),u.join(" | ")}c.describe=d,g(d,"describe")})(tr||(tr={}));mr();$t();yt();Nt();Ur();Ir();Wt();export{K as ASCII_8X8_FONT,or as AUDIO_CONFIGURE_SPATIAL_SIZE,no as AUDIO_FADEOUT_SOUND_MIN_SIZE,oo as AUDIO_PAUSE_SOUND_MIN_SIZE,In as AUDIO_PLAY_GLOBAL_SOUND_MIN_SIZE,Sn as AUDIO_PLAY_SOUND_MIN_SIZE,io as AUDIO_RESUME_SOUND_MIN_SIZE,nr as AUDIO_SET_LISTENER_POSITION_SIZE,so as AUDIO_SET_SOUND_EFFECTS_MIN_SIZE,ro as AUDIO_STOP_SOUND_MIN_SIZE,xe as AudioOrderCollector,Ce as AudioOrderDecoder,ht as AudioOrderType,bt as AudioTargetType,cn as BITMASK16_ORDER_MIN_SIZE,dn as BITMASK4_ORDER_MIN_SIZE,an as BITMASK_ORDER_MIN_SIZE,me as BitmapFont,be as BitmapFontRegistry,_r as CHAR_ORDER_SIZE,en as CIRCLE_SHAPE_SIZE,bn as CLEAR_ORDER_SIZE,qr as COLORMAP_ORDER_MIN_SIZE,k as COLOR_SKIP,_ as CellBuffer,te as CharCodeBuffer,Kt as Core,ue as CoreStats,eo as DISPLAY_HEADER_SIZE,sn as DOTCLOUD_MULTICOLOR_ORDER_MIN_SIZE,on as DOTCLOUD_ORDER_MIN_SIZE,ee as Display,rn as ELLIPSE_SHAPE_SIZE,gn as FILLCHAR_ORDER_MIN_SIZE,yn as FILLSPRITE_MULTICOLOR_ORDER_SIZE,xn as FILLSPRITE_ORDER_SIZE,Zr as FULLFRAME_MULTICOLOR_ORDER_MIN_SIZE,Gr as FULLFRAME_ORDER_MIN_SIZE,wr as FontType,de as InputBindingRegistry,Kn as LAYER_CELL_COUNT,to as LAYER_HEADER_SIZE,Oe as LAYER_SIZE,tn as LINE_SHAPE_SIZE,ne as Layer,vt as LoadType,ae as MacroEngine,pr as MacroEventType,ur as MacroOrderType,oe as MacroRegistry,er as OrderBuilder,hr as OrderType,ln as POLYLINE_ORDER_MIN_SIZE,sr as POSTPROCESS_SET_AMBIENT_EFFECT_SIZE,On as POSTPROCESS_SET_CONFIG_MIN_SIZE,dr as POSTPROCESS_SET_GRID_SIZE,ar as POSTPROCESS_SET_SCALING_MODE_SIZE,ir as POSTPROCESS_SET_SCANLINES_SIZE,xt as PlaySoundFlags,ye as PostProcessOrderCollector,fe as PostProcessOrderDecoder,Or as PostProcessOrderType,Qr as RECTANGLE_SHAPE_SIZE,Kr as SHAPE_ORDER_MIN_SIZE,pn as SPRITECLOUD_MULTICOLOR_ORDER_MIN_SIZE,un as SPRITECLOUD_ORDER_MIN_SIZE,hn as SPRITECLOUD_VARIED_MULTICOLOR_ORDER_MIN_SIZE,mn as SPRITECLOUD_VARIED_ORDER_MIN_SIZE,Jr as SPRITE_MULTICOLOR_ORDER_SIZE,jr as SPRITE_ORDER_SIZE,$r as SUBFRAME_MULTICOLOR_ORDER_MIN_SIZE,Vr as SUBFRAME_ORDER_MIN_SIZE,Xn as ScalingModeValue,cr as ShapeType,ge as SoundRegistry,pe as SpriteRegistry,Wr as TEXT_MULTILINE_ORDER_MIN_SIZE,Hr as TEXT_ORDER_MIN_SIZE,nn as TRIANGLE_SHAPE_SIZE,fn as TRIGGERGLOBALSOUND_ORDER_SIZE,Cn as TRIGGERSOUND_ORDER_SIZE,Qn as UPDATE_PACKET_HEADER_SIZE,zr as UpdateFlags,tr as UpdateFlagsHelper,We as UpdatePacketDecoder,le as User,ce as UserStats,Ba as Vector2,W as WebFont,he as WebFontRegistry,Vn as createASCII8x8FontLoad,at as createEmptyCompressedInputPacket,pt as decodeCompressedInput,ct as decodeInt8ToAxis,dt as encodeAxisToInt8,Gn as encodeCompressedInput,$n as getASCII8x8FontConfig,Wn as getAllCharCodes,yr as getAudioOrderTypeName,G as getButtonByteCount,_n as getCharBitmap,lt as getCompressedPacketSize,En as getMacroEventTypeName,An as getMacroOrderTypeName,kn as getOrderTypeName,Hn as hasChar,xr as isValidAudioOrderType,Mn as isValidMacroEventType,vn as isValidMacroOrderType,Rn as isValidOrderType};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@utsp/core",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.1",
|
|
4
4
|
"description": "UTSP core engine - Universal Text Stream Protocol data management",
|
|
5
5
|
"author": "THP Software",
|
|
6
6
|
"license": "MIT",
|
|
@@ -46,7 +46,7 @@
|
|
|
46
46
|
"access": "public"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@utsp/types": "0.7.
|
|
49
|
+
"@utsp/types": "0.7.1"
|
|
50
50
|
},
|
|
51
51
|
"devDependencies": {
|
|
52
52
|
"@types/node": "^24.9.1",
|