@primitiv/client 0.18.0
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/LICENSE.txt +285 -0
- package/README.md +34 -0
- package/dist/audio.cjs +1 -0
- package/dist/audio.d.ts +1 -0
- package/dist/audio.mjs +1 -0
- package/dist/core.cjs +4 -0
- package/dist/core.d.ts +1 -0
- package/dist/core.mjs +4 -0
- package/dist/index.cjs +204 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.mjs +204 -0
- package/dist/input.cjs +1 -0
- package/dist/input.d.ts +1 -0
- package/dist/input.mjs +1 -0
- package/dist/network.cjs +1 -0
- package/dist/network.d.ts +2 -0
- package/dist/network.mjs +1 -0
- package/dist/render.cjs +204 -0
- package/dist/render.d.ts +1 -0
- package/dist/render.mjs +204 -0
- package/dist/types.cjs +1 -0
- package/dist/types.d.ts +1 -0
- package/dist/types.mjs +1 -0
- package/package.json +86 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
"use strict";var ze=Object.defineProperty;var ri=Object.getOwnPropertyDescriptor;var ai=Object.getOwnPropertyNames;var ni=Object.prototype.hasOwnProperty;var oi=(t,e)=>{for(var i in e)ze(t,i,{get:e[i],enumerable:!0})},li=(t,e,i,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ai(e))!ni.call(t,r)&&r!==i&&ze(t,r,{get:()=>e[r],enumerable:!(s=ri(e,r))||s.enumerable});return t};var hi=t=>li(ze({},"__esModule",{value:!0}),t);var Es={};oi(Es,{ClientRuntime:()=>_t,RendererType:()=>Q,RuntimeClient:()=>ei});module.exports=hi(Es);var N=class G{x;y;constructor(e=0,i=0){this.x=e,this.y=i}static zero(){return new G(0,0)}static one(){return new G(1,1)}static up(){return new G(0,-1)}static down(){return new G(0,1)}static left(){return new G(-1,0)}static right(){return new G(1,0)}add(e){return new G(this.x+e.x,this.y+e.y)}subtract(e){return new G(this.x-e.x,this.y-e.y)}multiply(e){return new G(this.x*e,this.y*e)}divide(e){if(e===0)throw new Error("Division by zero");return new G(this.x/e,this.y/e)}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}lengthSquared(){return this.x*this.x+this.y*this.y}normalize(){let e=this.length();return e===0?G.zero():this.divide(e)}distance(e){return this.subtract(e).length()}distanceSquared(e){return this.subtract(e).lengthSquared()}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}angle(){return Math.atan2(this.y,this.x)}angleTo(e){return Math.atan2(e.y-this.y,e.x-this.x)}rotate(e){let i=Math.cos(e),s=Math.sin(e);return new G(this.x*i-this.y*s,this.x*s+this.y*i)}lerp(e,i){return new G(this.x+(e.x-this.x)*i,this.y+(e.y-this.y)*i)}clone(){return new G(this.x,this.y)}equals(e){return this.x===e.x&&this.y===e.y}toString(){return`Vector2(${this.x}, ${this.y})`}toArray(){return[this.x,this.y]}set(e,i){return this.x=e,this.y=i,this}copy(e){return this.x=e.x,this.y=e.y,this}addInPlace(e){return this.x+=e.x,this.y+=e.y,this}subtractInPlace(e){return this.x-=e.x,this.y-=e.y,this}multiplyInPlace(e){return this.x*=e,this.y*=e,this}divideInPlace(e){if(e===0)throw new Error("Division by zero");return this.x/=e,this.y/=e,this}normalizeInPlace(){let e=this.length();return e===0?(this.x=0,this.y=0):(this.x/=e,this.y/=e),this}};var b=(t=>(t[t.Keyboard=0]="Keyboard",t[t.Mouse=1]="Mouse",t[t.Gamepad=2]="Gamepad",t[t.Touch=3]="Touch",t[t.TVRemote=4]="TVRemote",t[t.TextInput=5]="TextInput",t[t.Motion=6]="Motion",t[t.TouchZone=7]="TouchZone",t))(b||{}),ye=(t=>(t[t.KeyA=0]="KeyA",t[t.KeyB=1]="KeyB",t[t.KeyC=2]="KeyC",t[t.KeyD=3]="KeyD",t[t.KeyE=4]="KeyE",t[t.KeyF=5]="KeyF",t[t.KeyG=6]="KeyG",t[t.KeyH=7]="KeyH",t[t.KeyI=8]="KeyI",t[t.KeyJ=9]="KeyJ",t[t.KeyK=10]="KeyK",t[t.KeyL=11]="KeyL",t[t.KeyM=12]="KeyM",t[t.KeyN=13]="KeyN",t[t.KeyO=14]="KeyO",t[t.KeyP=15]="KeyP",t[t.KeyQ=16]="KeyQ",t[t.KeyR=17]="KeyR",t[t.KeyS=18]="KeyS",t[t.KeyT=19]="KeyT",t[t.KeyU=20]="KeyU",t[t.KeyV=21]="KeyV",t[t.KeyW=22]="KeyW",t[t.KeyX=23]="KeyX",t[t.KeyY=24]="KeyY",t[t.KeyZ=25]="KeyZ",t[t.Digit0=26]="Digit0",t[t.Digit1=27]="Digit1",t[t.Digit2=28]="Digit2",t[t.Digit3=29]="Digit3",t[t.Digit4=30]="Digit4",t[t.Digit5=31]="Digit5",t[t.Digit6=32]="Digit6",t[t.Digit7=33]="Digit7",t[t.Digit8=34]="Digit8",t[t.Digit9=35]="Digit9",t[t.ArrowUp=36]="ArrowUp",t[t.ArrowDown=37]="ArrowDown",t[t.ArrowLeft=38]="ArrowLeft",t[t.ArrowRight=39]="ArrowRight",t[t.Space=40]="Space",t[t.Enter=41]="Enter",t[t.Escape=42]="Escape",t[t.Backspace=43]="Backspace",t[t.Tab=44]="Tab",t[t.ShiftLeft=45]="ShiftLeft",t[t.ShiftRight=46]="ShiftRight",t[t.ControlLeft=47]="ControlLeft",t[t.ControlRight=48]="ControlRight",t[t.AltLeft=49]="AltLeft",t[t.AltRight=50]="AltRight",t[t.MetaLeft=51]="MetaLeft",t[t.MetaRight=52]="MetaRight",t[t.CapsLock=53]="CapsLock",t[t.Delete=54]="Delete",t[t.Insert=55]="Insert",t[t.Home=56]="Home",t[t.End=57]="End",t[t.PageUp=58]="PageUp",t[t.PageDown=59]="PageDown",t[t.F1=60]="F1",t[t.F2=61]="F2",t[t.F3=62]="F3",t[t.F4=63]="F4",t[t.F5=64]="F5",t[t.F6=65]="F6",t[t.F7=66]="F7",t[t.F8=67]="F8",t[t.F9=68]="F9",t[t.F10=69]="F10",t[t.F11=70]="F11",t[t.F12=71]="F12",t[t.Minus=72]="Minus",t[t.Equal=73]="Equal",t[t.BracketLeft=74]="BracketLeft",t[t.BracketRight=75]="BracketRight",t[t.Backslash=76]="Backslash",t[t.Semicolon=77]="Semicolon",t[t.Quote=78]="Quote",t[t.Comma=79]="Comma",t[t.Period=80]="Period",t[t.Slash=81]="Slash",t[t.Backquote=82]="Backquote",t[t.Numpad0=91]="Numpad0",t[t.Numpad1=92]="Numpad1",t[t.Numpad2=93]="Numpad2",t[t.Numpad3=94]="Numpad3",t[t.Numpad4=95]="Numpad4",t[t.Numpad5=96]="Numpad5",t[t.Numpad6=97]="Numpad6",t[t.Numpad7=98]="Numpad7",t[t.Numpad8=99]="Numpad8",t[t.Numpad9=100]="Numpad9",t[t.NumpadAdd=101]="NumpadAdd",t[t.NumpadSubtract=102]="NumpadSubtract",t[t.NumpadMultiply=103]="NumpadMultiply",t[t.NumpadDivide=104]="NumpadDivide",t[t.NumpadDecimal=105]="NumpadDecimal",t[t.NumpadEnter=106]="NumpadEnter",t[t.NumLock=107]="NumLock",t[t.PrintScreen=111]="PrintScreen",t[t.ScrollLock=112]="ScrollLock",t[t.Pause=113]="Pause",t[t.ContextMenu=114]="ContextMenu",t))(ye||{});var Y=(t=>(t[t.LeftButton=0]="LeftButton",t[t.MiddleButton=1]="MiddleButton",t[t.RightButton=2]="RightButton",t[t.Button4=3]="Button4",t[t.Button5=4]="Button5",t[t.PositionX=100]="PositionX",t[t.PositionY=101]="PositionY",t[t.DeltaX=102]="DeltaX",t[t.DeltaY=103]="DeltaY",t[t.WheelDeltaY=104]="WheelDeltaY",t[t.WheelDeltaX=105]="WheelDeltaX",t))(Y||{});var di=(t=>(t[t.ButtonA=0]="ButtonA",t[t.ButtonB=1]="ButtonB",t[t.ButtonX=2]="ButtonX",t[t.ButtonY=3]="ButtonY",t[t.LeftShoulder=4]="LeftShoulder",t[t.RightShoulder=5]="RightShoulder",t[t.LeftTrigger=6]="LeftTrigger",t[t.RightTrigger=7]="RightTrigger",t[t.Select=8]="Select",t[t.Start=9]="Start",t[t.LeftStick=10]="LeftStick",t[t.RightStick=11]="RightStick",t[t.DPadUp=12]="DPadUp",t[t.DPadDown=13]="DPadDown",t[t.DPadLeft=14]="DPadLeft",t[t.DPadRight=15]="DPadRight",t[t.Home=16]="Home",t[t.Touchpad=17]="Touchpad",t[t.LeftStickX=100]="LeftStickX",t[t.LeftStickY=101]="LeftStickY",t[t.RightStickX=102]="RightStickX",t[t.RightStickY=103]="RightStickY",t[t.LeftTriggerAxis=104]="LeftTriggerAxis",t[t.RightTriggerAxis=105]="RightTriggerAxis",t))(di||{});var ci=(t=>(t[t.Touch0=0]="Touch0",t[t.Touch1=1]="Touch1",t[t.Touch2=2]="Touch2",t[t.Touch3=3]="Touch3",t[t.Touch4=4]="Touch4",t[t.Touch5=5]="Touch5",t[t.Touch6=6]="Touch6",t[t.Touch7=7]="Touch7",t[t.Touch8=8]="Touch8",t[t.Touch9=9]="Touch9",t[t.Touch0X=100]="Touch0X",t[t.Touch0Y=101]="Touch0Y",t[t.Touch1X=102]="Touch1X",t[t.Touch1Y=103]="Touch1Y",t[t.Touch2X=104]="Touch2X",t[t.Touch2Y=105]="Touch2Y",t[t.Touch3X=106]="Touch3X",t[t.Touch3Y=107]="Touch3Y",t[t.Touch4X=108]="Touch4X",t[t.Touch4Y=109]="Touch4Y",t[t.Touch5X=110]="Touch5X",t[t.Touch5Y=111]="Touch5Y",t[t.Touch6X=112]="Touch6X",t[t.Touch6Y=113]="Touch6Y",t[t.Touch7X=114]="Touch7X",t[t.Touch7Y=115]="Touch7Y",t[t.Touch8X=116]="Touch8X",t[t.Touch8Y=117]="Touch8Y",t[t.Touch9X=118]="Touch9X",t[t.Touch9Y=119]="Touch9Y",t[t.PinchScale=200]="PinchScale",t[t.RotationAngle=201]="RotationAngle",t[t.SwipeVelocityX=202]="SwipeVelocityX",t[t.SwipeVelocityY=203]="SwipeVelocityY",t))(ci||{});var ui=(t=>(t[t.Zone0=0]="Zone0",t[t.Zone1=1]="Zone1",t[t.Zone2=2]="Zone2",t[t.Zone3=3]="Zone3",t[t.Zone4=4]="Zone4",t[t.Zone5=5]="Zone5",t[t.Zone6=6]="Zone6",t[t.Zone7=7]="Zone7",t[t.Zone8=8]="Zone8",t[t.Zone9=9]="Zone9",t[t.Zone10=10]="Zone10",t[t.Zone11=11]="Zone11",t[t.Zone12=12]="Zone12",t[t.Zone13=13]="Zone13",t[t.Zone14=14]="Zone14",t[t.Zone15=15]="Zone15",t[t.Zone16=16]="Zone16",t[t.Zone17=17]="Zone17",t[t.Zone18=18]="Zone18",t[t.Zone19=19]="Zone19",t[t.Zone20=20]="Zone20",t[t.Zone21=21]="Zone21",t[t.Zone22=22]="Zone22",t[t.Zone23=23]="Zone23",t[t.Zone24=24]="Zone24",t[t.Zone25=25]="Zone25",t[t.Zone26=26]="Zone26",t[t.Zone27=27]="Zone27",t[t.Zone28=28]="Zone28",t[t.Zone29=29]="Zone29",t[t.Zone30=30]="Zone30",t[t.Zone31=31]="Zone31",t[t.Zone0X=100]="Zone0X",t[t.Zone0Y=101]="Zone0Y",t[t.Zone1X=102]="Zone1X",t[t.Zone1Y=103]="Zone1Y",t[t.Zone2X=104]="Zone2X",t[t.Zone2Y=105]="Zone2Y",t[t.Zone3X=106]="Zone3X",t[t.Zone3Y=107]="Zone3Y",t[t.Zone4X=108]="Zone4X",t[t.Zone4Y=109]="Zone4Y",t[t.Zone5X=110]="Zone5X",t[t.Zone5Y=111]="Zone5Y",t[t.Zone6X=112]="Zone6X",t[t.Zone6Y=113]="Zone6Y",t[t.Zone7X=114]="Zone7X",t[t.Zone7Y=115]="Zone7Y",t[t.Zone8X=116]="Zone8X",t[t.Zone8Y=117]="Zone8Y",t[t.Zone9X=118]="Zone9X",t[t.Zone9Y=119]="Zone9Y",t[t.Zone10X=120]="Zone10X",t[t.Zone10Y=121]="Zone10Y",t[t.Zone11X=122]="Zone11X",t[t.Zone11Y=123]="Zone11Y",t[t.Zone12X=124]="Zone12X",t[t.Zone12Y=125]="Zone12Y",t[t.Zone13X=126]="Zone13X",t[t.Zone13Y=127]="Zone13Y",t[t.Zone14X=128]="Zone14X",t[t.Zone14Y=129]="Zone14Y",t[t.Zone15X=130]="Zone15X",t[t.Zone15Y=131]="Zone15Y",t[t.Zone16X=132]="Zone16X",t[t.Zone16Y=133]="Zone16Y",t[t.Zone17X=134]="Zone17X",t[t.Zone17Y=135]="Zone17Y",t[t.Zone18X=136]="Zone18X",t[t.Zone18Y=137]="Zone18Y",t[t.Zone19X=138]="Zone19X",t[t.Zone19Y=139]="Zone19Y",t[t.Zone20X=140]="Zone20X",t[t.Zone20Y=141]="Zone20Y",t[t.Zone21X=142]="Zone21X",t[t.Zone21Y=143]="Zone21Y",t[t.Zone22X=144]="Zone22X",t[t.Zone22Y=145]="Zone22Y",t[t.Zone23X=146]="Zone23X",t[t.Zone23Y=147]="Zone23Y",t[t.Zone24X=148]="Zone24X",t[t.Zone24Y=149]="Zone24Y",t[t.Zone25X=150]="Zone25X",t[t.Zone25Y=151]="Zone25Y",t[t.Zone26X=152]="Zone26X",t[t.Zone26Y=153]="Zone26Y",t[t.Zone27X=154]="Zone27X",t[t.Zone27Y=155]="Zone27Y",t[t.Zone28X=156]="Zone28X",t[t.Zone28Y=157]="Zone28Y",t[t.Zone29X=158]="Zone29X",t[t.Zone29Y=159]="Zone29Y",t[t.Zone30X=160]="Zone30X",t[t.Zone30Y=161]="Zone30Y",t[t.Zone31X=162]="Zone31X",t[t.Zone31Y=163]="Zone31Y",t))(ui||{});var gi=(t=>(t[t.DPadUp=0]="DPadUp",t[t.DPadDown=1]="DPadDown",t[t.DPadLeft=2]="DPadLeft",t[t.DPadRight=3]="DPadRight",t[t.DPadCenter=4]="DPadCenter",t[t.Play=5]="Play",t[t.Pause=6]="Pause",t[t.PlayPause=7]="PlayPause",t[t.Stop=8]="Stop",t[t.Rewind=9]="Rewind",t[t.FastForward=10]="FastForward",t[t.Previous=11]="Previous",t[t.Next=12]="Next",t[t.Record=13]="Record",t[t.VolumeUp=15]="VolumeUp",t[t.VolumeDown=16]="VolumeDown",t[t.Mute=17]="Mute",t[t.ChannelUp=18]="ChannelUp",t[t.ChannelDown=19]="ChannelDown",t[t.Back=20]="Back",t[t.Home=21]="Home",t[t.Menu=22]="Menu",t[t.Info=23]="Info",t[t.Guide=24]="Guide",t[t.Exit=25]="Exit",t[t.Red=30]="Red",t[t.Green=31]="Green",t[t.Yellow=32]="Yellow",t[t.Blue=33]="Blue",t[t.Digit0=40]="Digit0",t[t.Digit1=41]="Digit1",t[t.Digit2=42]="Digit2",t[t.Digit3=43]="Digit3",t[t.Digit4=44]="Digit4",t[t.Digit5=45]="Digit5",t[t.Digit6=46]="Digit6",t[t.Digit7=47]="Digit7",t[t.Digit8=48]="Digit8",t[t.Digit9=49]="Digit9",t[t.Input=50]="Input",t[t.Settings=51]="Settings",t[t.Subtitle=52]="Subtitle",t[t.Audio=53]="Audio",t[t.Power=54]="Power",t[t.PointerX=100]="PointerX",t[t.PointerY=101]="PointerY",t[t.GyroX=102]="GyroX",t[t.GyroY=103]="GyroY",t[t.GyroZ=104]="GyroZ",t))(gi||{});function Ke(){return{axes:new Map,buttons:new Map,displayId:0,mouseX:0,mouseY:0,mouseOverDisplay:!1,isTabHidden:!1,textInputs:[],displayViewports:[],touchPositions:[]}}function pt(t){return Math.round(Math.max(-1,Math.min(1,t))*127)}function mt(t){return Math.ceil(t/8)}var Q=(t=>(t.TerminalGL="webgl",t.Terminal2D="terminal2d",t.TerminalANSI="ansi",t))(Q||{}),T=(t=>(t[t.None=0]="None",t[t.Eighth=1]="Eighth",t[t.Quarter=2]="Quarter",t[t.Half=3]="Half",t[t.Integer=4]="Integer",t[t.Responsive=5]="Responsive",t))(T||{}),$={scanlines:{opacity:.15,pattern:"horizontal",spacing:2,thickness:1,color:{r:0,g:0,b:0}},ambientEffect:{blur:30,scale:1.3,opacity:.7}};var g=(t=>(t[t.Char=1]="Char",t[t.Text=2]="Text",t[t.SubFrame=3]="SubFrame",t[t.SubFrameMulti=4]="SubFrameMulti",t[t.FullFrame=5]="FullFrame",t[t.FullFrameMulti=6]="FullFrameMulti",t[t.Sprite=7]="Sprite",t[t.SpriteMulti=8]="SpriteMulti",t[t.ColorMap=9]="ColorMap",t[t.Shape=10]="Shape",t[t.DotCloud=11]="DotCloud",t[t.DotCloudMulti=12]="DotCloudMulti",t[t.SpriteCloud=13]="SpriteCloud",t[t.SpriteCloudMulti=14]="SpriteCloudMulti",t[t.SpriteCloudVaried=15]="SpriteCloudVaried",t[t.SpriteCloudVariedMulti=16]="SpriteCloudVariedMulti",t[t.Bitmask=17]="Bitmask",t[t.Bitmask4=18]="Bitmask4",t[t.Fill=19]="Fill",t[t.FillChar=20]="FillChar",t[t.FillSprite=21]="FillSprite",t[t.FillSpriteMulti=22]="FillSpriteMulti",t[t.TextMultiline=23]="TextMultiline",t[t.Bitmask16=24]="Bitmask16",t[t.Polyline=25]="Polyline",t[t.Audio=32]="Audio",t[t.Vibration=33]="Vibration",t[t.PostProcess=34]="PostProcess",t))(g||{}),B=(t=>(t[t.Rectangle=1]="Rectangle",t[t.Circle=2]="Circle",t[t.Line=3]="Line",t[t.Ellipse=4]="Ellipse",t[t.Triangle=5]="Triangle",t))(B||{}),fi=(t=>(t[t.FastPath=255]="FastPath",t[t.Fragment=254]="Fragment",t))(fi||{});var pi=(t=>(t[t.Enabled=1]="Enabled",t[t.SetMode=2]="SetMode",t[t.Position=4]="Position",t[t.ZOrder=8]="ZOrder",t[t.Orders=16]="Orders",t[t.IsMacroLayer=32]="IsMacroLayer",t[t.Is16BitMode=64]="Is16BitMode",t))(pi||{}),mi=(t=>(t.WAITING_FOR_WELCOME="waiting_for_welcome",t.AUTHENTICATING="authenticating",t.LOADING="loading",t.ACTIVE="active",t.DISCONNECTED="disconnected",t))(mi||{});var xe={trace:0,debug:1,info:2,warn:3,error:4,silent:5},_=[],Ze="info",Ee=new Map,se=new Map,yi=typeof performance<"u"&&typeof performance.now=="function"?()=>performance.now():()=>Date.now(),Ie=null;function Ct(t){let e=null,i=-1;for(let[s,r]of Ee)if(bi(s,t)){let a=s.length;a>i&&(i=a,e=r)}return e??Ze}function bi(t,e){if(t==="*")return!0;if(t.endsWith(":*")){let i=t.slice(0,-1);return e===t.slice(0,-2)||e.startsWith(i)}return t===e}function yt(){for(let[t,e]of se)e.c(Ct(t))}var U=class he{namespace;r;i;s;constructor(e,i,s){this.namespace=e,this.i=i,this.s=s,this.r=xe[Ct(e)]}static create(e){let i=se.get(e);return i||(i=new he(e),se.set(e,i)),i}child(e){return he.create(`${this.namespace}:${e}`)}forClient(e,i){let s=`${this.namespace}:client:${e}`,r=se.get(s);return r?(r.i=e,r.s=i):(r=new he(s,e,i),se.set(s,r)),r}static dispose(e){se.delete(e)}trace(e,i){this.n("trace",e,i)}debug(e,i){this.n("debug",e,i)}info(e,i){this.n("info",e,i)}warn(e,i){this.n("warn",e,i)}error(e,i){this.n("error",e,i)}isEnabled(e){return xe[e]>=this.r}c(e){this.r=xe[e]}n(e,i,s){if(xe[e]<this.r||_.length===0)return;let r=typeof i=="function"?i():i,a={timestamp:yi(),level:e,namespace:this.namespace,message:r};Ie!==null&&(a.tick=Ie()),s!==void 0&&(a.data=s),this.i!==void 0&&(a.clientId=this.i),this.s!==void 0&&(a.username=this.s);for(let n=0;n<_.length;n++)_[n](a)}static setLevel(e,i){i===void 0?Ze=e:Ee.set(e,i),yt()}static clearLevelOverrides(){Ee.clear(),yt()}static enable(e){he.setLevel(e,"trace")}static disable(e){he.setLevel(e,"silent")}static addHandler(e){return _.push(e),()=>{let i=_.indexOf(e);i!==-1&&_.splice(i,1)}}static clearHandlers(){_.length=0}static get handlerCount(){return _.length}static setTickProvider(e){Ie=e}static reset(){_.length=0,Ee.clear(),se.clear(),Ze="info",Ie=null}},be="\x1B[0m",wi={trace:"\x1B[90m",debug:"\x1B[36m",info:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m"},Ci="\x1B[35m",bt="\x1B[2m",vi="\x1B[93m",xi={trace:"color:#888",debug:"color:#0cc",info:"color:#0a0",warn:"color:#cc0",error:"color:#c00;font-weight:bold"},Ii="color:#c0c;font-weight:bold",wt="color:#888",Ei="color:#c90;font-weight:bold",vt={trace:"debug",debug:"debug",info:"info",warn:"warn",error:"error"},Ui=typeof globalThis<"u"&&typeof globalThis.process=="object"&&typeof globalThis.process?.versions=="object";function Ne(t,e){return String(t).padStart(e,"0")}function xt(t){let e=Math.floor(t/1e3)%60,i=Math.floor(t/6e4)%60,s=Math.floor(t%1e3);return`${Ne(i,2)}:${Ne(e,2)}.${Ne(s,3)}`}function It(t){return t.toUpperCase().padEnd(5)}function Et(t){if(t.clientId===void 0)return"";let e=t.username?`/${t.username}`:"";return` [client:${t.clientId}${e}]`}function Mi(t){let e=`${bt}${xt(t.timestamp)}${be}`,i=t.tick!==void 0?` ${vi}#${t.tick}${be}`:"",s=`${wi[t.level]}${It(t.level)}${be}`,r=`${Ci}${t.namespace}${be}`,a=t.clientId!==void 0?`${bt}${Et(t)}${be}`:"",n=vt[t.level],o=`${e}${i} ${s} ${r}${a}`;t.data!==void 0?console[n](o,t.message,t.data):console[n](o,t.message)}function Si(t){let e=vt[t.level],i=Et(t),s=t.tick!==void 0?` %c#${t.tick}`:"",r=t.tick!==void 0?[Ei]:[],a=`%c${xt(t.timestamp)}${s} %c${It(t.level)} %c${t.namespace}%c${i} %c${t.message}`,n=[wt,...r,xi[t.level],Ii,wt,""];t.data!==void 0?console[e](a,...n,t.data):console[e](a,...n)}var ki=Ui?Mi:Si;U.handlerCount===0&&U.addHandler(ki);var Se=class{canvas;ctx;container;cols=0;rows=0;cellWidth=0;cellHeight=0;offsetX=0;offsetY=0;strokeColor="rgba(80, 80, 80, 0.4)";lineWidth=1;constructor(t,e){this.container=t,this.canvas=document.createElement("canvas"),this.canvas.className="grid-overlay-canvas";let i=e?.zIndex??10;this.canvas.style.cssText=`
|
|
2
|
+
display: block !important;
|
|
3
|
+
position: absolute !important;
|
|
4
|
+
pointer-events: none !important;
|
|
5
|
+
image-rendering: pixelated !important;
|
|
6
|
+
image-rendering: crisp-edges !important;
|
|
7
|
+
z-index: ${i} !important;
|
|
8
|
+
`,this.container.appendChild(this.canvas);let s=this.canvas.getContext("2d");if(!s)throw new Error("[GridOverlay] Failed to create 2D context");this.ctx=s,e&&(e.strokeColor&&(this.strokeColor=e.strokeColor),e.lineWidth!==void 0&&(this.lineWidth=e.lineWidth))}setDimensions(t,e,i,s,r=0,a=0){this.cols=t,this.rows=e,this.cellWidth=i,this.cellHeight=s,this.offsetX=r,this.offsetY=a}setCanvasSize(t,e){this.canvas.width=t,this.canvas.height=e,this.ctx.setTransform(1,0,0,1,0,0)}setStyle(t){t.strokeColor&&(this.strokeColor=t.strokeColor),t.lineWidth!==void 0&&(this.lineWidth=t.lineWidth)}setTransform(t,e,i,s,r){let a=s.left-r.left,n=s.top-r.top,o=s.width,l=s.height;(this.canvas.width!==o||this.canvas.height!==l)&&(this.canvas.width=o,this.canvas.height=l);let h=this.canvas.style;h.width=`${o}px`,h.height=`${l}px`,h.left=`${a}px`,h.top=`${n}px`}render(){if(!this.ctx)return;let t=this.cols*this.cellWidth,e=this.rows*this.cellHeight,i=t>0?this.canvas.width/t:1,s=e>0?this.canvas.height/e:1,r=Math.min(i,s),a=this.cellWidth*r,n=this.cellHeight*r,o=this.cols*a,l=this.rows*n,h=this.offsetX*r,d=this.offsetY*r;if(!(o===0||l===0)){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.strokeStyle=this.strokeColor,this.ctx.lineWidth=Math.max(1,this.lineWidth*r),this.ctx.beginPath();for(let c=0;c<=this.cols;c++){let u=h+c*a+.5;this.ctx.moveTo(u,d),this.ctx.lineTo(u,d+l)}for(let c=0;c<=this.rows;c++){let u=d+c*n+.5;this.ctx.moveTo(h,u),this.ctx.lineTo(h+o,u)}this.ctx.stroke()}}update(t,e,i,s,r,a,n=0,o=0){this.setDimensions(t,e,i,s,n,o),this.setCanvasSize(r,a),this.render()}setVisible(t){this.canvas.style.display=t?"block":"none"}destroy(){this.canvas.parentElement&&this.canvas.parentElement.removeChild(this.canvas)}getCanvas(){return this.canvas}},ks=["#000000","#800000","#008000","#808000","#000080","#800080","#008080","#c0c0c0","#808080","#ff0000","#00ff00","#ffff00","#0000ff","#ff00ff","#00ffff","#ffffff","#080808","#121212","#1c1c1c","#262626","#303030","#3a3a3a","#444444","#4e4e4e","#585858","#626262","#6c6c6c","#767676","#808080","#8a8a8a","#949494","#9e9e9e","#a80000","#00a800","#a8a800","#0000a8","#a800a8","#00a8a8","#a8a8a8","#545454","#fc5454","#54fc54","#fcfc54","#5454fc","#fc54fc","#54fcfc","#fcfcfc","#000000",...Array(192).fill("#808080")];var ke=class{canvas;ctx;containerDiv;parentElement;resizeObserver;width=0;height=0;currentConfig=null;configHash="";constructor(t,e){this.parentElement=t,this.containerDiv=document.createElement("div"),this.containerDiv.className="postprocess-container",this.containerDiv.style.cssText=`
|
|
9
|
+
position: absolute !important;
|
|
10
|
+
top: 0 !important;
|
|
11
|
+
left: 0 !important;
|
|
12
|
+
right: 0 !important;
|
|
13
|
+
bottom: 0 !important;
|
|
14
|
+
width: 100% !important;
|
|
15
|
+
height: 100% !important;
|
|
16
|
+
pointer-events: none !important;
|
|
17
|
+
z-index: 10 !important;
|
|
18
|
+
overflow: hidden !important;
|
|
19
|
+
`,this.canvas=document.createElement("canvas"),this.canvas.className="postprocess-canvas",this.canvas.style.cssText=`
|
|
20
|
+
position: absolute !important;
|
|
21
|
+
top: 0 !important;
|
|
22
|
+
left: 0 !important;
|
|
23
|
+
width: 100% !important;
|
|
24
|
+
height: 100% !important;
|
|
25
|
+
pointer-events: none !important;
|
|
26
|
+
`;let i=this.canvas.getContext("2d",{alpha:!0});if(!i)throw new Error("PostProcessOverlay: Failed to get 2D context");this.ctx=i,this.containerDiv.appendChild(this.canvas),this.parentElement.appendChild(this.containerDiv),this.resizeObserver=new ResizeObserver(r=>{for(let a of r){let{width:n,height:o}=a.contentRect;n>0&&o>0&&this.handleResize(Math.floor(n),Math.floor(o))}}),this.resizeObserver.observe(this.parentElement);let s=this.parentElement.getBoundingClientRect();s.width>0&&s.height>0&&this.handleResize(Math.floor(s.width),Math.floor(s.height)),this.hide()}handleResize(t,e){this.width===t&&this.height===e||(this.width=t,this.height=e,this.canvas.width=t,this.canvas.height=e,this.currentConfig&&this.isActive()&&this.render())}setConfig(t){let e=this.hashConfig(t);if(e!==this.configHash){if(this.currentConfig=t,this.configHash=e,!t||!this.isActiveConfig(t)){this.clear(),this.hide();return}this.show(),this.render()}}setScanlines(t){t===null?this.setConfig({scanlines:{enabled:!1}}):this.setConfig({scanlines:t})}setScanlinesEnabled(t){if(t){let e=this.currentConfig?.scanlines;this.setScanlines({enabled:!0,opacity:e?.opacity??$.scanlines.opacity,pattern:e?.pattern??"horizontal",spacing:e?.spacing??2,thickness:e?.thickness??1,color:e?.color??{r:0,g:0,b:0}})}else this.setScanlines({enabled:!1})}setScanlinesOpacity(t){let e=Math.max(0,Math.min(1,t)),i=this.currentConfig?.scanlines;this.setScanlines({enabled:i?.enabled??!0,opacity:e,pattern:i?.pattern??"horizontal",spacing:i?.spacing??2,thickness:i?.thickness??1,color:i?.color??{r:0,g:0,b:0}})}setScanlinesPattern(t){let e=this.currentConfig?.scanlines;this.setScanlines({enabled:e?.enabled??!0,opacity:e?.opacity??$.scanlines.opacity,pattern:t,spacing:e?.spacing??2,thickness:e?.thickness??1,color:e?.color??{r:0,g:0,b:0}})}setScanlinesSpacing(t){let e=Math.max(2,Math.round(t)),i=this.currentConfig?.scanlines;this.setScanlines({enabled:i?.enabled??!0,opacity:i?.opacity??$.scanlines.opacity,pattern:i?.pattern??"horizontal",spacing:e,thickness:i?.thickness??1,color:i?.color??{r:0,g:0,b:0}})}getConfig(){return this.currentConfig}isActive(){return this.isActiveConfig(this.currentConfig)}destroy(){this.resizeObserver.disconnect(),this.containerDiv.parentElement&&this.containerDiv.parentElement.removeChild(this.containerDiv)}syncWithRenderer(t){}resize(t,e){}setCellDimensions(t,e){}show(){this.containerDiv.style.display="block"}hide(){this.containerDiv.style.display="none"}clear(){this.ctx.clearRect(0,0,this.width,this.height)}isActiveConfig(t){return t?.scanlines?.enabled??!1}render(){this.clear(),this.currentConfig?.scanlines?.enabled&&this.renderScanlines(this.currentConfig.scanlines)}renderScanlines(t){let e=t.opacity??$.scanlines.opacity,i=t.pattern??"horizontal",s=t.spacing??2,r=t.thickness??1,a=t.color??{r:0,g:0,b:0},n=this.ctx;switch(n.fillStyle=`rgba(${a.r}, ${a.g}, ${a.b}, ${e})`,i){case"horizontal":for(let o=s-1;o<this.height;o+=s)n.fillRect(0,o,this.width,r);break;case"vertical":for(let o=s-1;o<this.width;o+=s)n.fillRect(o,0,r,this.height);break;case"grid":for(let o=s-1;o<this.height;o+=s)n.fillRect(0,o,this.width,r);for(let o=s-1;o<this.width;o+=s)n.fillRect(o,0,r,this.height);break}}hashConfig(t){return t?JSON.stringify(t):"null"}},Mt=class{container;overlayDiv=null;button=null;options;started=!1;onStartCallback;constructor(t,e={}){this.container=t,this.options={buttonText:e.buttonText??"Click to Start",onStart:e.onStart??(()=>{}),backgroundColor:e.backgroundColor??"rgba(0, 0, 0, 0.8)",buttonColor:e.buttonColor??"#4a90d9",buttonHoverColor:e.buttonHoverColor??"#357abd",buttonTextColor:e.buttonTextColor??"#ffffff",zIndex:e.zIndex??1e3},this.onStartCallback=e.onStart,this.createOverlay()}createOverlay(){let t=window.getComputedStyle(this.container).position;t!=="relative"&&t!=="absolute"&&t!=="fixed"&&(this.container.style.position="relative"),this.overlayDiv=document.createElement("div"),this.overlayDiv.className="primitiv-autoplay-overlay",this.overlayDiv.style.cssText=`
|
|
27
|
+
position: absolute !important;
|
|
28
|
+
top: 0 !important;
|
|
29
|
+
left: 0 !important;
|
|
30
|
+
right: 0 !important;
|
|
31
|
+
bottom: 0 !important;
|
|
32
|
+
width: 100% !important;
|
|
33
|
+
height: 100% !important;
|
|
34
|
+
background-color: ${this.options.backgroundColor} !important;
|
|
35
|
+
display: flex !important;
|
|
36
|
+
justify-content: center !important;
|
|
37
|
+
align-items: center !important;
|
|
38
|
+
z-index: ${this.options.zIndex} !important;
|
|
39
|
+
cursor: pointer !important;
|
|
40
|
+
`,this.button=document.createElement("button"),this.button.className="primitiv-autoplay-button",this.button.textContent=this.options.buttonText,this.button.style.cssText=`
|
|
41
|
+
padding: 16px 32px !important;
|
|
42
|
+
font-size: 18px !important;
|
|
43
|
+
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif !important;
|
|
44
|
+
font-weight: 600 !important;
|
|
45
|
+
color: ${this.options.buttonTextColor} !important;
|
|
46
|
+
background-color: ${this.options.buttonColor} !important;
|
|
47
|
+
border: none !important;
|
|
48
|
+
border-radius: 8px !important;
|
|
49
|
+
cursor: pointer !important;
|
|
50
|
+
transition: background-color 0.2s ease, transform 0.1s ease !important;
|
|
51
|
+
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3) !important;
|
|
52
|
+
`,this.button.addEventListener("mouseenter",()=>{this.button&&(this.button.style.backgroundColor=`${this.options.buttonHoverColor} !important`,this.button.style.transform="scale(1.05)")}),this.button.addEventListener("mouseleave",()=>{this.button&&(this.button.style.backgroundColor=`${this.options.buttonColor} !important`,this.button.style.transform="scale(1)")}),this.button.addEventListener("click",e=>{e.stopPropagation(),this.start()}),this.overlayDiv.addEventListener("click",()=>{this.start()}),this.overlayDiv.appendChild(this.button),this.container.appendChild(this.overlayDiv)}start(){this.started||(this.started=!0,this.overlayDiv&&(this.overlayDiv.style.transition="opacity 0.3s ease",this.overlayDiv.style.opacity="0",setTimeout(()=>{this.removeOverlay()},300)),this.onStartCallback&&this.onStartCallback())}isStarted(){return this.started}isVisible(){return this.overlayDiv!==null&&!this.started}removeOverlay(){this.overlayDiv&&this.overlayDiv.parentElement&&this.overlayDiv.parentElement.removeChild(this.overlayDiv),this.overlayDiv=null,this.button=null}setButtonText(t){this.options.buttonText=t,this.button&&(this.button.textContent=t)}setOnStart(t){this.onStartCallback=t}destroy(){this.removeOverlay(),this.started=!1}};function Me(t){return Math.sqrt(t)*16}function Xe(t){return t*256-1}function Qe(t,e){let i=Math.floor(t/256),s=t%256,r=Math.sqrt(e),a=i%r,n=Math.floor(i/r),o=s%16,l=Math.floor(s/16);return{col:a*16+o,row:n*16+l}}var Ut=class{atlasCanvas=null;atlasCtx=null;atlasImage=null;glyphWidth;glyphHeight;cellWidth;cellHeight;atlasBlocks;atlasColumns;maxCharCode;isLoaded=!1;colorCache=new Map;MAX_CACHE_SIZE=1024;constructor(t){this.glyphWidth=t.glyphWidth,this.glyphHeight=t.glyphHeight,this.cellWidth=t.cellWidth??t.glyphWidth,this.cellHeight=t.cellHeight??t.glyphHeight,this.atlasBlocks=t.atlasBlocks,this.atlasColumns=Me(t.atlasBlocks),this.maxCharCode=Xe(t.atlasBlocks)}getCanvas(){return this.atlasCanvas}getGlyphWidth(){return this.glyphWidth}getGlyphHeight(){return this.glyphHeight}prepare(){let t=this.atlasColumns*this.glyphWidth,e=this.atlasColumns*this.glyphHeight;this.atlasCanvas=document.createElement("canvas"),this.atlasCanvas.width=t,this.atlasCanvas.height=e,this.atlasCtx=this.atlasCanvas.getContext("2d",{alpha:!0,willReadFrequently:!0}),this.atlasCtx&&(this.atlasCtx.imageSmoothingEnabled=!1,this.atlasCtx.clearRect(0,0,t,e)),this.isLoaded=!0}async loadBlock(t,e){return(!this.atlasCanvas||!this.atlasCtx)&&this.prepare(),new Promise((i,s)=>{let r=new Uint8Array(e),a=new Blob([r],{type:"image/png"}),n=URL.createObjectURL(a),o=new Image;o.onload=()=>{URL.revokeObjectURL(n);let l=Math.sqrt(this.atlasBlocks),h=t%l,d=Math.floor(t/l),c=h*16*this.glyphWidth,u=d*16*this.glyphHeight;this.atlasCtx.drawImage(o,c,u),this.colorCache.clear(),i()},o.onerror=()=>{URL.revokeObjectURL(n),s(new Error(`Failed to load PNG for block ${t}`))},o.src=n})}async loadFromPNG(t){return new Promise((e,i)=>{let s=new Uint8Array(t),r=new Blob([s],{type:"image/png"}),a=URL.createObjectURL(r),n=new Image;n.onload=()=>{URL.revokeObjectURL(a);let o=this.atlasColumns*this.glyphWidth,l=this.atlasColumns*this.glyphHeight;if((n.width!==o||n.height!==l)&&U.create("render:atlas").warn(`Image size ${n.width}\xD7${n.height} doesn't match expected ${o}\xD7${l} for ${this.atlasBlocks} block(s) with ${this.glyphWidth}\xD7${this.glyphHeight} glyphs`),this.atlasCanvas=document.createElement("canvas"),this.atlasCanvas.width=n.width,this.atlasCanvas.height=n.height,this.atlasCtx=this.atlasCanvas.getContext("2d",{alpha:!0,willReadFrequently:!0}),!this.atlasCtx){i(new Error("Failed to create 2D context for atlas"));return}this.atlasCtx.imageSmoothingEnabled=!1,this.atlasCtx.drawImage(n,0,0),this.atlasImage=n,this.isLoaded=!0,e()},n.onerror=()=>{URL.revokeObjectURL(a),i(new Error("Failed to load PNG image for atlas"))},n.src=a})}isReady(){return this.isLoaded}getGlyphPosition(t){if(t<0||t>this.maxCharCode)return null;let{col:e,row:i}=Qe(t,this.atlasBlocks);return{x:e*this.glyphWidth,y:i*this.glyphHeight}}getCharUV(t){if(t<0||t>this.maxCharCode)return null;let{col:e,row:i}=Qe(t,this.atlasBlocks),s=e/this.atlasColumns,r=i/this.atlasColumns,a=(e+1)/this.atlasColumns,n=(i+1)/this.atlasColumns;return{u1:s,v1:r,u2:a,v2:n}}drawChar(t,e,i,s,r,a,n){if(!this.isLoaded||!this.atlasCanvas)return;let o=this.getGlyphPosition(e);if(!o)return;let l=`${e}:${n}`,h=this.colorCache.get(l);if(h)h.lastUsed=performance.now();else{let d=this.createColoredGlyph(e,n,o);if(!d)return;h={canvas:d,lastUsed:performance.now()},this.colorCache.set(l,h),this.colorCache.size>this.MAX_CACHE_SIZE&&this.evictLRU()}if(t.imageSmoothingEnabled=!1,r===this.cellWidth&&a===this.cellHeight){let d=Math.floor((this.cellWidth-this.glyphWidth)/2),c=Math.floor((this.cellHeight-this.glyphHeight)/2);t.drawImage(h.canvas,Math.floor(i)+d,Math.floor(s)+c)}else{let d=r/this.cellWidth,c=a/this.cellHeight,u=Math.floor((this.cellWidth-this.glyphWidth)/2*d),f=Math.floor((this.cellHeight-this.glyphHeight)/2*c),p=Math.ceil(this.glyphWidth*d),m=Math.ceil(this.glyphHeight*c);t.drawImage(h.canvas,Math.floor(i)+u,Math.floor(s)+f,p,m)}}createColoredGlyph(t,e,i){if(!this.atlasCtx)return null;let s=this.atlasCtx.getImageData(i.x,i.y,this.glyphWidth,this.glyphHeight),r=s.data,a=this.parseColor(e);for(let l=0;l<r.length;l+=4)r[l+3]>0&&(r[l]=r[l]*a.r/255,r[l+1]=r[l+1]*a.g/255,r[l+2]=r[l+2]*a.b/255);let n=document.createElement("canvas");n.width=this.glyphWidth,n.height=this.glyphHeight;let o=n.getContext("2d",{alpha:!0});return o?(o.putImageData(s,0,0),n):null}parseColor(t){if(t.startsWith("#")){let i=t.slice(1);return i.length===3&&(i=i[0]+i[0]+i[1]+i[1]+i[2]+i[2]),{r:parseInt(i.slice(0,2),16),g:parseInt(i.slice(2,4),16),b:parseInt(i.slice(4,6),16)}}let e=/rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(t);return e?{r:parseInt(e[1],10),g:parseInt(e[2],10),b:parseInt(e[3],10)}:{r:255,g:255,b:255}}evictLRU(){let t=null,e=1/0;for(let[i,s]of this.colorCache)s.lastUsed<e&&(e=s.lastUsed,t=i);if(t){let i=this.colorCache.get(t);i&&(i.canvas.width=0,i.canvas.height=0),this.colorCache.delete(t)}}getAtlasCanvas(){return this.atlasCanvas}getAtlasImage(){return this.atlasImage}getConfig(){return{glyphWidth:this.glyphWidth,glyphHeight:this.glyphHeight,cellWidth:this.cellWidth,cellHeight:this.cellHeight,atlasBlocks:this.atlasBlocks}}getGlyphDimensions(){return{width:this.glyphWidth,height:this.glyphHeight}}getCellDimensions(){return{width:this.cellWidth,height:this.cellHeight}}getAtlasDimensions(){return{width:this.atlasColumns*this.glyphWidth,height:this.atlasColumns*this.glyphHeight}}getAtlasColumns(){return this.atlasColumns}getMaxCharCode(){return this.maxCharCode}isValidCharCode(t){return t>=0&&t<=this.maxCharCode}clearCache(){for(let t of this.colorCache.values())t.canvas.width=0,t.canvas.height=0;this.colorCache.clear()}getCacheStats(){return{size:this.colorCache.size,maxSize:this.MAX_CACHE_SIZE}}destroy(){this.clearCache(),this.atlasCanvas&&(this.atlasCanvas.width=0,this.atlasCanvas.height=0,this.atlasCanvas=null),this.atlasCtx=null,this.atlasImage=null,this.isLoaded=!1}},Ue=U.create("render:2d"),qe=class{containerDiv;canvas;ctx;parentElement;cells;cols=0;rows=0;defaultFgColor;defaultBgColor;canvasBgColor;cellWidth;cellHeight;offsetX=0;offsetY=0;imageAtlas;showDebugGrid;debugGridColor;gridOverlay;fixedGridMode;fixedCols;fixedRows;cellAspectRatio;resizeObserver;paletteCache;scalingMode=T.None;currentScale=1;customCellSize=!1;constructor(t,e={}){if(!t)throw new Error("Render: parent element is required");this.parentElement=t,this.fixedGridMode=!!(e.fixedCols&&e.fixedRows),this.fixedCols=e.fixedCols,this.fixedRows=e.fixedRows,this.cellAspectRatio=e.cellAspectRatio??1,this.cellWidth=e.cellWidth??8,this.cellHeight=e.cellHeight??8,this.defaultFgColor=e.defaultFgColor??"#ffffff",this.defaultBgColor=e.defaultBgColor??"#000000",this.canvasBgColor=e.canvasBgColor!==void 0?e.canvasBgColor:null,this.showDebugGrid=e.showDebugGrid??!1,this.debugGridColor=e.debugGridColor??"rgba(144, 24, 24, 1)",this.scalingMode=e.scalingMode??T.None,window.getComputedStyle(this.parentElement).position==="static"&&(this.parentElement.style.position="relative"),this.containerDiv=document.createElement("div"),this.containerDiv.className="terminal2d-container",this.containerDiv.style.cssText=`
|
|
53
|
+
position: absolute !important;
|
|
54
|
+
top: 0 !important;
|
|
55
|
+
left: 0 !important;
|
|
56
|
+
right: 0 !important;
|
|
57
|
+
bottom: 0 !important;
|
|
58
|
+
width: 100% !important;
|
|
59
|
+
height: 100% !important;
|
|
60
|
+
overflow: visible !important;
|
|
61
|
+
contain: layout style !important;
|
|
62
|
+
display: flex !important;
|
|
63
|
+
justify-content: center !important;
|
|
64
|
+
align-items: center !important;
|
|
65
|
+
isolation: isolate !important;
|
|
66
|
+
pointer-events: none !important;
|
|
67
|
+
`,this.canvas=document.createElement("canvas"),this.canvas.className="terminal2d-canvas",e.className&&(this.canvas.className+=" "+e.className),e.style&&Object.assign(this.canvas.style,e.style),this.canvas.style.imageRendering="pixelated",this.canvas.style.imageRendering="crisp-edges",this.containerDiv.appendChild(this.canvas),this.parentElement.appendChild(this.containerDiv);let i=this.canvas.getContext("2d",{alpha:!0,desynchronized:!1});if(!i)throw new Error("Render: Failed to obtain 2D canvas context");this.ctx=i,this.ctx.imageSmoothingEnabled=!1,this.calculateGridSize(),this.cells=this.createEmptyGrid(),this.showDebugGrid&&(this.gridOverlay=new Se(this.parentElement,{strokeColor:this.debugGridColor,lineWidth:1,zIndex:10})),this.enableAutoResize(),this.render()}calculateGridSize(){let t=this.parentElement.clientWidth||800,e=this.parentElement.clientHeight||600;if(!this.customCellSize){let l,h;if(this.imageAtlas){let d=this.imageAtlas.getCellDimensions();l=d.width,h=d.height}else l=this.cellWidth,h=this.cellHeight;this.cellWidth=Math.round(l),this.cellHeight=Math.round(h)}this.scalingMode===T.Responsive?(this.cols=Math.floor(t/this.cellWidth)||1,this.rows=Math.floor(e/this.cellHeight)||1):this.fixedGridMode&&this.fixedCols&&this.fixedRows?(this.cols=this.fixedCols,this.rows=this.fixedRows):(this.cols=Math.floor(t/this.cellWidth)||1,this.rows=Math.floor(e/this.cellHeight)||1);let i=this.cols*this.cellWidth,s=this.rows*this.cellHeight,r=t/i,a=e/s,n=Math.min(r,a),o;switch(this.scalingMode){case T.Integer:o=Math.max(1,Math.floor(n));break;case T.Half:o=Math.max(.5,Math.floor(n*2)/2);break;case T.Quarter:o=Math.max(.25,Math.floor(n*4)/4);break;case T.Eighth:o=Math.max(.125,Math.floor(n*8)/8);break;case T.Responsive:o=1;break;case T.None:default:o=Math.max(.1,n);break}this.currentScale=o,this.canvas.width=i,this.canvas.height=s,this.ctx.imageSmoothingEnabled=!1,this.canvas.style.cssText=`
|
|
68
|
+
flex-shrink: 0 !important;
|
|
69
|
+
flex-grow: 0 !important;
|
|
70
|
+
width: ${i}px !important;
|
|
71
|
+
height: ${s}px !important;
|
|
72
|
+
image-rendering: pixelated !important;
|
|
73
|
+
image-rendering: crisp-edges !important;
|
|
74
|
+
-ms-interpolation-mode: nearest-neighbor !important;
|
|
75
|
+
transform-origin: center center !important;
|
|
76
|
+
transform: scale(${o}) !important;
|
|
77
|
+
will-change: transform !important;
|
|
78
|
+
backface-visibility: hidden !important;
|
|
79
|
+
pointer-events: auto !important;
|
|
80
|
+
touch-action: manipulation !important;
|
|
81
|
+
`,this.offsetX=0,this.offsetY=0}createEmptyGrid(){let t=[];for(let e=0;e<this.rows;e++){let i=[];for(let s=0;s<this.cols;s++)i.push({char:" ",fgColor:this.defaultFgColor,bgColor:this.defaultBgColor});t.push(i)}return t}enableAutoResize(){this.resizeObserver=new ResizeObserver(()=>{let t=this.cols,e=this.rows;if(this.calculateGridSize(),this.cols!==t||this.rows!==e){let i=this.cells;this.cells=this.createEmptyGrid();let s=Math.min(t,this.cols),r=Math.min(e,this.rows);for(let a=0;a<r;a++)for(let n=0;n<s;n++)this.cells[a][n]=i[a][n]}this.render()}),this.resizeObserver.observe(this.parentElement)}setCell(t,e,i,s,r){if(e<0||e>=this.rows||t<0||t>=this.cols)return;let a=i&&typeof i=="string"?i.charAt(0):" ";this.cells[e][t]={char:a,fgColor:s??this.defaultFgColor,bgColor:r??this.defaultBgColor}}getCell(t,e){return e<0||e>=this.rows||t<0||t>=this.cols?null:this.cells[e][t]}write(t,e,i,s,r){for(let a=0;a<i.length;a++)this.setCell(t+a,e,i[a],s,r)}fillRect(t,e,i,s,r=" ",a,n){for(let o=e;o<e+s;o++)for(let l=t;l<t+i;l++)this.setCell(l,o,r,a,n)}clear(){this.cells=this.createEmptyGrid()}setFromArray(t){let e=t.width*t.height;if(t.cells.length!==e)throw new Error(`Invalid array length: expected ${e} (${t.width}\xD7${t.height}), got ${t.cells.length}`);let i=0;for(let s=0;s<t.height;s++)for(let r=0;r<t.width;r++){let a=t.cells[i];s<this.rows&&r<this.cols&&this.setCell(r,s,a.char,a.fgColor,a.bgColor),i++}}render(t=!0){this.renderClassic(t)}renderClassic(t=!0){t&&(this.canvasBgColor!==null?(this.ctx.fillStyle=this.canvasBgColor,this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height)):this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height)),this.ctx.imageSmoothingEnabled=!1,this.canvas.style.imageRendering="pixelated",this.canvas.style.imageRendering="crisp-edges";for(let e=0;e<this.rows;e++)for(let i=0;i<this.cols;i++){let s=this.cells[e][i],r=Math.floor(this.offsetX+i*this.cellWidth),a=Math.floor(this.offsetY+e*this.cellHeight),n=Math.floor(this.offsetX+(i+1)*this.cellWidth),o=Math.floor(this.offsetY+(e+1)*this.cellHeight),l=n-r,h=o-a;if((this.canvasBgColor!==null||s.bgColor!==this.defaultBgColor)&&(this.ctx.fillStyle=s.bgColor,this.ctx.fillRect(r,a,l,h)),s.char!==" "&&this.imageAtlas){let d=s.char.charCodeAt(0);this.imageAtlas.drawChar(this.ctx,d,r,a,l,h,s.fgColor)}}this.showDebugGrid&&this.drawDebugGrid()}drawDebugGrid(){if(!this.gridOverlay)return;let t=this.parentElement.clientWidth||800,e=this.parentElement.clientHeight||600;this.gridOverlay.update(this.cols,this.rows,this.cellWidth,this.cellHeight,t,e,this.offsetX,this.offsetY)}getCanvas(){return this.canvas}getContext(){return this.ctx}getDimensions(){return{cols:this.cols,rows:this.rows}}getCellDimensions(){return{cellWidth:this.cellWidth,cellHeight:this.cellHeight}}getCellWidth(){return this.cellWidth}getCellHeight(){return this.cellHeight}getCurrentScale(){return this.currentScale}getScalingMode(){return this.scalingMode}getOffsets(){return{offsetX:this.offsetX,offsetY:this.offsetY}}setDebugGrid(t){this.showDebugGrid=t,t&&!this.gridOverlay?(this.gridOverlay=new Se(this.parentElement,{strokeColor:this.debugGridColor,lineWidth:1,zIndex:10}),this.drawDebugGrid()):!t&&this.gridOverlay?(this.gridOverlay.destroy(),this.gridOverlay=void 0):t&&this.gridOverlay&&this.gridOverlay.setVisible(!0)}setCanvasBackgroundColor(t){this.canvasBgColor=t}getCanvasBackgroundColor(){return this.canvasBgColor}setFixedGrid(t,e,i){this.fixedGridMode=!0,this.fixedCols=t,this.fixedRows=e,i!==void 0&&(this.cellAspectRatio=i);let s=this.cols,r=this.rows,a=this.cells;if(this.calculateGridSize(),this.cols!==s||this.rows!==r){this.cells=this.createEmptyGrid();let n=Math.min(s,this.cols),o=Math.min(r,this.rows);for(let l=0;l<o;l++)for(let h=0;h<n;h++)this.cells[l][h]=a[l][h]}this.render()}setAdaptiveGrid(t,e){this.fixedGridMode=!1,this.fixedCols=void 0,this.fixedRows=void 0,t!==void 0&&(this.cellWidth=t),e!==void 0&&(this.cellHeight=e);let i=this.cols,s=this.rows,r=this.cells;if(this.calculateGridSize(),this.cols!==i||this.rows!==s){this.cells=this.createEmptyGrid();let a=Math.min(i,this.cols),n=Math.min(s,this.rows);for(let o=0;o<n;o++)for(let l=0;l<a;l++)this.cells[o][l]=r[o][l]}this.render()}isFixedGridMode(){return this.fixedGridMode}setDebugGridColor(t){this.debugGridColor=t}isDebugGridEnabled(){return this.showDebugGrid}async setImageFont(t,e,i,s,r,a){this.imageAtlas=new Ut({glyphWidth:e,glyphHeight:i,cellWidth:s,cellHeight:r,atlasBlocks:a}),await this.imageAtlas.loadFromPNG(t),this.cellWidth=s,this.cellHeight=r,this.calculateGridSize(),this.fixedGridMode||(this.calculateGridSize(),this.cells=this.createEmptyGrid()),this.render()}async setImageFontStructure(t,e,i,s,r){let a=this.imageAtlas;if(this.imageAtlas=new Ut({glyphWidth:t,glyphHeight:e,cellWidth:i,cellHeight:s,atlasBlocks:r}),this.imageAtlas.prepare(),a){let n=a.getCanvas();if(n&&a.getGlyphWidth()===t&&a.getGlyphHeight()===e){let o=this.imageAtlas.getCanvas()?.getContext("2d");if(o){let l=16*t,h=16*e;n.width>=l&&n.height>=h&&o.drawImage(n,0,0,l,h,0,0,l,h)}}}this.cellWidth=i,this.cellHeight=s,this.fixedGridMode||(this.calculateGridSize(),this.cells=this.createEmptyGrid())}async setImageFontBlock(t,e){if(!this.imageAtlas){Ue.warn("Cannot load block: no atlas initialized");return}await this.imageAtlas.loadBlock(t,e),this.render()}setPalette(t){this.paletteCache=t}convertColor(t,e){if(t==null||isNaN(t))return this.defaultFgColor;if(t===255)return"rgba(0, 0, 0, 0)";if(t<0||t>=e.length)return this.defaultFgColor;let i=e[t];return!i||typeof i.r!="number"?this.defaultFgColor:`rgba(${i.r}, ${i.g}, ${i.b}, ${i.a/255})`}renderDirect(t,e,i,s,r){for(let a=0;a<e&&a<this.rows;a++)for(let n=0;n<t&&n<this.cols;n++){let o=a*t+n;if(o>=i.length)break;let l=i[o];if(!l)continue;let h=this.convertColor(l.fgColorIndex,s),d=this.convertColor(l.bgColorIndex,s);this.setCell(n,a,l.char??" ",h,d)}this.render(r)}renderDisplayData(t){if(!t||!t.cells||t.cells.length===0){Ue.warn("Empty display data");return}if(t.width===0||t.height===0){Ue.warn("Invalid display dimensions",{width:t.width,height:t.height});return}(t.width!==this.cols||t.height!==this.rows)&&this.setFixedGrid(t.width,t.height,this.cellAspectRatio);let e=this.paletteCache??t.palette;if(!e||e.length===0){Ue.error("No palette available (neither cached nor in display)");return}if(t.passes&&t.passes.length>0)for(let i=0;i<t.passes.length;i++){let s=t.passes[i];this.renderDirect(t.width,t.height,s.cells,e,i===0)}else this.renderDirect(t.width,t.height,t.cells,e,!0)}isReady(){return!0}getCols(){return this.cols}getRows(){return this.rows}resize(t,e){this.setFixedGrid(t,e)}setScalingMode(t){if(this.scalingMode===t)return;let e=this.cols,i=this.rows;if(this.scalingMode=t,this.calculateGridSize(),this.cols!==e||this.rows!==i){let s=this.cells;if(this.cells=this.createEmptyGrid(),s&&s.length>0){let r=Math.min(e,this.cols),a=Math.min(i,this.rows);for(let n=0;n<a;n++)for(let o=0;o<r;o++)s[n]&&s[n][o]&&(this.cells[n][o]=s[n][o])}}this.render()}setCellSize(t,e){let i=Math.max(1,Math.min(255,Math.round(t))),s=Math.max(1,Math.min(255,Math.round(e)));if(this.cellWidth===i&&this.cellHeight===s)return;let r=this.cols,a=this.rows;if(this.cellWidth=i,this.cellHeight=s,this.customCellSize=!0,this.calculateGridSize(),this.cols!==r||this.rows!==a){let n=this.cells;if(this.cells=this.createEmptyGrid(),n&&n.length>0){let o=Math.min(r,this.cols),l=Math.min(a,this.rows);for(let h=0;h<l;h++)for(let d=0;d<o;d++)n[h]&&n[h][d]&&(this.cells[h][d]=n[h][d])}}this.render()}getCellSize(){return{cellWidth:this.cellWidth,cellHeight:this.cellHeight}}getAvailableSize(){return{width:this.parentElement.clientWidth,height:this.parentElement.clientHeight}}getMaxCells(){return 65536}destroy(){this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=void 0),this.gridOverlay&&(this.gridOverlay.destroy(),this.gridOverlay=void 0),this.containerDiv.parentElement&&this.containerDiv.parentElement.removeChild(this.containerDiv)}},V=U.create("render:gl"),Re=class St{static checkCompatibility(){let e={webgl1:!1,uint32Indices:!1,maxTextureSize:0,maxViewportDims:[0,0],maxCellsUint16:0,maxCellsUint32:0,recommendedMaxCells:0,warnings:[],errors:[]},i=document.createElement("canvas"),s=i.getContext("webgl")||i.getContext("experimental-webgl");if(!s||!(s instanceof WebGLRenderingContext))return e.errors.push("\u274C WebGL 1.0 not supported by this browser/device"),e;let r=s;e.webgl1=!0;try{e.maxTextureSize=r.getParameter(r.MAX_TEXTURE_SIZE);let o=r.getParameter(r.MAX_VIEWPORT_DIMS);e.maxViewportDims=[o[0],o[1]]}catch(o){return e.errors.push(`\u274C Failed to query WebGL parameters: ${o}`),e}let a=r.getExtension("OES_element_index_uint");e.uint32Indices=!!a;let n=8;if(e.maxCellsUint16=Math.floor(65535/n),e.uint32Indices){let o=Math.floor(e.maxTextureSize*e.maxTextureSize/64);e.maxCellsUint32=Math.min(o,262144)}else e.maxCellsUint32=e.maxCellsUint16,e.warnings.push(`\u26A0\uFE0F OES_element_index_uint not supported - limited to ${e.maxCellsUint16} cells (e.g., 90\xD790 or 127\xD764)`);return e.recommendedMaxCells=Math.floor((e.uint32Indices?e.maxCellsUint32:e.maxCellsUint16)*.8),e.maxTextureSize<256?e.errors.push(`\u274C MAX_TEXTURE_SIZE too small: ${e.maxTextureSize} (minimum 256 required for font atlas)`):e.maxTextureSize<2048&&e.warnings.push(`\u26A0\uFE0F Small MAX_TEXTURE_SIZE: ${e.maxTextureSize} (may limit font atlas)`),(e.maxViewportDims[0]<1024||e.maxViewportDims[1]<768)&&e.warnings.push(`\u26A0\uFE0F Small MAX_VIEWPORT_DIMS: ${e.maxViewportDims[0]}\xD7${e.maxViewportDims[1]}`),r.getExtension("WEBGL_lose_context")||e.warnings.push("\u26A0\uFE0F WEBGL_lose_context not supported - may cause memory leaks"),e}canvas;gl;parentElement;containerDiv;cols;rows;charWidth;charHeight;cellWidth=8;cellHeight=8;glyphOffsetX=0;glyphOffsetY=0;canvasBgColor;showGrid;supportsUint32Indices=!1;useUint16Indices=!1;gridOverlay;bitmapFont;atlasTexture=null;atlasCanvas;atlasColumns=0;fontLoaded=!1;paletteTexture=null;program=null;positionBuffer=null;texCoordBuffer=null;colorIndexBuffer=null;indexBuffer=null;aPosition;aTexCoord;aColorIndex;uResolution=null;uTexture=null;uPalette=null;resizeObserver;boundWindowResize;charCodeToAtlasIndex=new Uint16Array(65536).fill(65535);atlasUVs=new Float32Array(0);cachedAtlasWidth=0;cachedAtlasHeight=0;paletteFloat=new Float32Array(256*4);maxCells=0;renderPositions=new Float32Array(0);renderTexCoords=new Float32Array(0);renderColorIndices=new Float32Array(0);renderIndices=new Uint32Array(0);cachedResolution=[0,0];cachedTextureUnit=-1;cachedPaletteUnit=-1;cachedTextureUniform=!1;cachedPaletteUniform=!1;paletteHash=0;currentScale=1;scalingMode=T.None;ambientEffectEnabled=!1;ambientEffectCanvas=null;ambientEffectCtx=null;ambientEffectBlur=$.ambientEffect.blur;ambientEffectScale=$.ambientEffect.scale;ambientEffectOpacity=.7;onResizeCallback;staticPositionsInitialized=!1;vaoExtension=null;vao=null;instancedExtension=null;useInstancing=!1;instanceDataBuffer=null;instanceData=new Float32Array(0);templateQuadPositions=new Float32Array(0);templateQuadIndices=new Uint16Array(0);aInstanceOffset=-1;aInstanceUVs=-1;aInstanceColors=-1;uCellSize=null;constructor(e,i){if(!e)throw new Error("TerminalGL: Parent element is required");if(!Number.isInteger(i.cols)||i.cols<=0)throw new Error(`TerminalGL: Invalid cols: ${i.cols}. Must be a positive integer.`);if(!Number.isInteger(i.rows)||i.rows<=0)throw new Error(`TerminalGL: Invalid rows: ${i.rows}. Must be a positive integer.`);let s=i.cols*i.rows,r=St.checkCompatibility();if(r.errors.length>0)throw new Error(`TerminalGL: WebGL incompatible - ${r.errors.join(", ")}`);let a=i.forceUint16??!1;if(a&&s>r.maxCellsUint16)throw new Error(`TerminalGL: Terminal size ${i.cols}\xD7${i.rows} (${s} cells) exceeds Uint16 limit of ${r.maxCellsUint16} cells. Maximum size with Uint16: ${Math.floor(Math.sqrt(r.maxCellsUint16))}\xD7${Math.floor(Math.sqrt(r.maxCellsUint16))} (or smaller rectangles like 127\xD764)`);if(!r.uint32Indices&&s>r.maxCellsUint16)throw new Error(`TerminalGL: Terminal size ${i.cols}\xD7${i.rows} (${s} cells) exceeds device limit of ${r.maxCellsUint16} cells (OES_element_index_uint not supported). Maximum size: ${Math.floor(Math.sqrt(r.maxCellsUint16))}\xD7${Math.floor(Math.sqrt(r.maxCellsUint16))}`);let n=i.charWidth??8,o=i.charHeight??8;if(!Number.isFinite(n)||n<=0)throw new Error(`TerminalGL: Invalid charWidth: ${n}. Must be a positive number.`);if(!Number.isFinite(o)||o<=0)throw new Error(`TerminalGL: Invalid charHeight: ${o}. Must be a positive number.`);for(this.parentElement=e,this.cols=i.cols,this.rows=i.rows,this.charWidth=n,this.charHeight=o,this.canvasBgColor=i.canvasBgColor!==void 0?i.canvasBgColor:null,this.showGrid=i.showGrid??!1,this.scalingMode=i.scalingMode??T.None,i.ambientEffect&&(this.ambientEffectEnabled=!0,typeof i.ambientEffect=="object"&&(this.ambientEffectBlur=i.ambientEffect.blur??$.ambientEffect.blur,this.ambientEffectScale=i.ambientEffect.scale??$.ambientEffect.scale,this.ambientEffectOpacity=i.ambientEffect.opacity??.7));this.parentElement.firstChild;)this.parentElement.removeChild(this.parentElement.firstChild);let l=window.getComputedStyle(this.parentElement).position;l!=="relative"&&l!=="absolute"&&l!=="fixed"&&(this.parentElement.style.position="relative"),this.containerDiv=document.createElement("div"),this.containerDiv.className="terminalgl-container",this.containerDiv.style.cssText=`
|
|
82
|
+
position: absolute !important;
|
|
83
|
+
top: 0 !important;
|
|
84
|
+
left: 0 !important;
|
|
85
|
+
right: 0 !important;
|
|
86
|
+
bottom: 0 !important;
|
|
87
|
+
width: 100% !important;
|
|
88
|
+
height: 100% !important;
|
|
89
|
+
overflow: visible !important;
|
|
90
|
+
contain: layout style !important;
|
|
91
|
+
display: flex !important;
|
|
92
|
+
justify-content: center !important;
|
|
93
|
+
align-items: center !important;
|
|
94
|
+
isolation: isolate !important;
|
|
95
|
+
pointer-events: none !important;
|
|
96
|
+
`,this.canvas=document.createElement("canvas"),this.canvas.className="terminalgl-webgl-canvas",this.canvas.width=this.cols*this.cellWidth,this.canvas.height=this.rows*this.cellHeight,this.canvas.style.cssText=`
|
|
97
|
+
flex-shrink: 0 !important;
|
|
98
|
+
width: ${this.canvas.width}px !important;
|
|
99
|
+
height: ${this.canvas.height}px !important;
|
|
100
|
+
image-rendering: pixelated !important;
|
|
101
|
+
image-rendering: crisp-edges !important;
|
|
102
|
+
-ms-interpolation-mode: nearest-neighbor !important;
|
|
103
|
+
transform-origin: center center !important;
|
|
104
|
+
transform: scale(1) !important;
|
|
105
|
+
will-change: transform !important;
|
|
106
|
+
backface-visibility: hidden !important;
|
|
107
|
+
position: relative !important;
|
|
108
|
+
z-index: 1 !important;
|
|
109
|
+
pointer-events: auto !important;
|
|
110
|
+
touch-action: manipulation !important;
|
|
111
|
+
`;let h=this.canvas.getContext("webgl",{alpha:this.canvasBgColor===null,premultipliedAlpha:!1});if(!h)throw new Error("TerminalGL: WebGL not supported");this.gl=h,this.supportsUint32Indices=!!h.getExtension("OES_element_index_uint"),this.useUint16Indices=a||!this.supportsUint32Indices,this.vaoExtension=h.getExtension("OES_vertex_array_object"),this.instancedExtension=h.getExtension("ANGLE_instanced_arrays"),this.instancedExtension&&(this.useInstancing=!0),this.containerDiv.appendChild(this.canvas),this.ambientEffectEnabled&&this.createAmbientEffectCanvas(),this.parentElement.appendChild(this.containerDiv),this.initRenderBuffers();try{this.initWebGL()}catch(d){throw V.error("Failed to initialize WebGL",d),d}this.showGrid&&this.initGridOverlay(),this.setupResizeObserver()}initInstancedBuffers(){let e=this.gl;this.templateQuadPositions=new Float32Array([0,0,this.cellWidth,0,0,this.cellHeight,this.cellWidth,this.cellHeight]),this.templateQuadIndices=new Uint16Array([0,1,2,2,1,3]),e.bindBuffer(e.ARRAY_BUFFER,this.positionBuffer),e.bufferData(e.ARRAY_BUFFER,this.templateQuadPositions,e.STATIC_DRAW),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,this.templateQuadIndices,e.STATIC_DRAW),this.instanceData=new Float32Array(this.maxCells*8),e.bindBuffer(e.ARRAY_BUFFER,this.instanceDataBuffer),e.bufferData(e.ARRAY_BUFFER,this.instanceData.byteLength,e.DYNAMIC_DRAW)}initRenderBuffers(){let e=this.cols*this.rows*2;this.maxCells=Math.ceil(e*2),this.renderPositions=new Float32Array(this.maxCells*4*2),this.renderTexCoords=new Float32Array(this.maxCells*4*2),this.renderColorIndices=new Float32Array(this.maxCells*4),this.useUint16Indices?this.renderIndices=new Uint16Array(this.maxCells*6):this.renderIndices=new Uint32Array(this.maxCells*6),this.staticPositionsInitialized=!1}precomputeStaticPositions(){let e=this.cellWidth,i=this.cellHeight,s=this.glyphOffsetX,r=this.glyphOffsetY,a=this.charWidth,n=this.charHeight,o=0,l=0,h=0;for(let c=0;c<this.rows;c++){let u=Math.round(c*i),f=Math.round(u+i);for(let p=0;p<this.cols;p++){let m=Math.round(p*e),y=Math.round(m+e);this.renderPositions[o++]=m,this.renderPositions[o++]=u,this.renderPositions[o++]=y,this.renderPositions[o++]=u,this.renderPositions[o++]=m,this.renderPositions[o++]=f,this.renderPositions[o++]=y,this.renderPositions[o++]=f,this.renderIndices[l++]=h,this.renderIndices[l++]=h+1,this.renderIndices[l++]=h+2,this.renderIndices[l++]=h+2,this.renderIndices[l++]=h+1,this.renderIndices[l++]=h+3,h+=4;let C=Math.round(m+s),v=Math.round(u+r),x=Math.round(C+a),E=Math.round(v+n);this.renderPositions[o++]=C,this.renderPositions[o++]=v,this.renderPositions[o++]=x,this.renderPositions[o++]=v,this.renderPositions[o++]=C,this.renderPositions[o++]=E,this.renderPositions[o++]=x,this.renderPositions[o++]=E,this.renderIndices[l++]=h,this.renderIndices[l++]=h+1,this.renderIndices[l++]=h+2,this.renderIndices[l++]=h+2,this.renderIndices[l++]=h+1,this.renderIndices[l++]=h+3,h+=4}}let d=this.gl;d.bindBuffer(d.ARRAY_BUFFER,this.positionBuffer),d.bufferSubData(d.ARRAY_BUFFER,0,this.renderPositions),d.bindBuffer(d.ELEMENT_ARRAY_BUFFER,this.indexBuffer),d.bufferSubData(d.ELEMENT_ARRAY_BUFFER,0,this.renderIndices),this.staticPositionsInitialized=!0}initWebGL(){let e=this.gl,i;this.useInstancing?i=`
|
|
112
|
+
// Per-vertex attributes (template quad)
|
|
113
|
+
attribute vec2 aPosition; // Local quad position (0,0 to cellW,cellH)
|
|
114
|
+
|
|
115
|
+
// Per-instance attributes (different for each cell)
|
|
116
|
+
attribute vec2 aInstanceOffset; // Cell grid position (col, row)
|
|
117
|
+
attribute vec4 aInstanceUVs; // Atlas UVs (u1, v1, u2, v2)
|
|
118
|
+
attribute vec2 aInstanceColors; // (bgColorIdx, fgColorIdx)
|
|
119
|
+
|
|
120
|
+
uniform vec2 uResolution;
|
|
121
|
+
uniform vec2 uCellSize; // (cellWidth, cellHeight)
|
|
122
|
+
uniform sampler2D uPalette;
|
|
123
|
+
|
|
124
|
+
varying vec2 vTexCoord;
|
|
125
|
+
varying vec4 vColor;
|
|
126
|
+
|
|
127
|
+
void main() {
|
|
128
|
+
// Compute world position: instance offset + local quad position
|
|
129
|
+
vec2 worldPos = aInstanceOffset * uCellSize + aPosition;
|
|
130
|
+
vec2 clipSpace = (worldPos / uResolution) * 2.0 - 1.0;
|
|
131
|
+
gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);
|
|
132
|
+
|
|
133
|
+
// Interpolate UVs based on local position
|
|
134
|
+
vec2 localUV = aPosition / uCellSize; // (0,0) to (1,1)
|
|
135
|
+
vTexCoord = mix(
|
|
136
|
+
aInstanceUVs.xy, // top-left (u1, v1)
|
|
137
|
+
aInstanceUVs.zw, // bottom-right (u2, v2)
|
|
138
|
+
localUV
|
|
139
|
+
);
|
|
140
|
+
|
|
141
|
+
// Choose background or foreground color based on instance UVs
|
|
142
|
+
// If instance UVs are all (0,0), it's a background quad
|
|
143
|
+
float isBg = step(length(aInstanceUVs), 0.001);
|
|
144
|
+
float colorIndex = mix(aInstanceColors.y, aInstanceColors.x, isBg);
|
|
145
|
+
|
|
146
|
+
// Lookup color in palette
|
|
147
|
+
float paletteU = (colorIndex + 0.5) / 256.0;
|
|
148
|
+
vColor = texture2D(uPalette, vec2(paletteU, 0.5));
|
|
149
|
+
}
|
|
150
|
+
`:i=`
|
|
151
|
+
attribute vec2 aPosition;
|
|
152
|
+
attribute vec2 aTexCoord;
|
|
153
|
+
attribute float aColorIndex; // \u{1F680} Index dans palette (0-255)
|
|
154
|
+
|
|
155
|
+
uniform vec2 uResolution;
|
|
156
|
+
uniform sampler2D uPalette; // \u{1F680} Texture palette 256\xD71 RGBA
|
|
157
|
+
|
|
158
|
+
varying vec2 vTexCoord;
|
|
159
|
+
varying vec4 vColor;
|
|
160
|
+
|
|
161
|
+
void main() {
|
|
162
|
+
// Convert from pixels to clip space (-1 to 1)
|
|
163
|
+
vec2 clipSpace = (aPosition / uResolution) * 2.0 - 1.0;
|
|
164
|
+
gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);
|
|
165
|
+
|
|
166
|
+
vTexCoord = aTexCoord;
|
|
167
|
+
|
|
168
|
+
// \u{1F680} Lookup couleur dans la palette texture (GPU-side)
|
|
169
|
+
float paletteU = (aColorIndex + 0.5) / 256.0;
|
|
170
|
+
vColor = texture2D(uPalette, vec2(paletteU, 0.5));
|
|
171
|
+
}
|
|
172
|
+
`;let s=`
|
|
173
|
+
precision mediump float;
|
|
174
|
+
|
|
175
|
+
uniform sampler2D uTexture;
|
|
176
|
+
|
|
177
|
+
varying vec2 vTexCoord;
|
|
178
|
+
varying vec4 vColor;
|
|
179
|
+
|
|
180
|
+
void main() {
|
|
181
|
+
// If texCoord is (0, 0), it's a background without texture
|
|
182
|
+
if (vTexCoord.x == 0.0 && vTexCoord.y == 0.0) {
|
|
183
|
+
gl_FragColor = vColor;
|
|
184
|
+
} else {
|
|
185
|
+
// Textured character: multiply atlas color by uniform color
|
|
186
|
+
// - White glyph (1,1,1) \u2192 uniform color applied normally
|
|
187
|
+
// - Colored glyph \u2192 atlas color \xD7 uniform color (multiply blend)
|
|
188
|
+
vec4 texColor = texture2D(uTexture, vTexCoord);
|
|
189
|
+
gl_FragColor = vec4(texColor.rgb * vColor.rgb, texColor.a);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
`,r=this.compileShader(e.VERTEX_SHADER,i),a=this.compileShader(e.FRAGMENT_SHADER,s);if(!r||!a)throw new Error("Shader compilation error");let n=e.createProgram();if(!n)throw new Error("Unable to create WebGL program");if(e.attachShader(n,r),e.attachShader(n,a),e.linkProgram(n),!e.getProgramParameter(n,e.LINK_STATUS)){let o=e.getProgramInfoLog(n);throw new Error("Program linking error: "+o)}this.program=n,this.cachedTextureUniform=!1,this.cachedPaletteUniform=!1,this.aPosition=e.getAttribLocation(n,"aPosition"),this.useInstancing?(this.aInstanceOffset=e.getAttribLocation(n,"aInstanceOffset"),this.aInstanceUVs=e.getAttribLocation(n,"aInstanceUVs"),this.aInstanceColors=e.getAttribLocation(n,"aInstanceColors"),this.uCellSize=e.getUniformLocation(n,"uCellSize"),this.instanceDataBuffer=e.createBuffer(),this.aTexCoord=this.aInstanceOffset,this.aColorIndex=this.aInstanceUVs):(this.aTexCoord=e.getAttribLocation(n,"aTexCoord"),this.aColorIndex=e.getAttribLocation(n,"aColorIndex")),this.uResolution=e.getUniformLocation(n,"uResolution"),this.uTexture=e.getUniformLocation(n,"uTexture"),this.uPalette=e.getUniformLocation(n,"uPalette"),this.positionBuffer=e.createBuffer(),this.texCoordBuffer=e.createBuffer(),this.colorIndexBuffer=e.createBuffer(),this.indexBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.positionBuffer),e.bufferData(e.ARRAY_BUFFER,this.renderPositions.byteLength,e.DYNAMIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,this.texCoordBuffer),e.bufferData(e.ARRAY_BUFFER,this.renderTexCoords.byteLength,e.DYNAMIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,this.colorIndexBuffer),e.bufferData(e.ARRAY_BUFFER,this.renderColorIndices.byteLength,e.DYNAMIC_DRAW),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,this.renderIndices.byteLength,e.DYNAMIC_DRAW),this.vaoExtension&&(this.vao=this.vaoExtension.createVertexArrayOES(),this.vao&&(this.vaoExtension.bindVertexArrayOES(this.vao),e.bindBuffer(e.ARRAY_BUFFER,this.positionBuffer),e.enableVertexAttribArray(this.aPosition),e.vertexAttribPointer(this.aPosition,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this.texCoordBuffer),e.enableVertexAttribArray(this.aTexCoord),e.vertexAttribPointer(this.aTexCoord,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this.colorIndexBuffer),e.enableVertexAttribArray(this.aColorIndex),e.vertexAttribPointer(this.aColorIndex,1,e.FLOAT,!1,0,0),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer),this.vaoExtension.bindVertexArrayOES(null))),e.enable(e.BLEND),e.blendFunc(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA),e.viewport(0,0,this.canvas.width,this.canvas.height)}compileShader(e,i){let s=this.gl,r=s.createShader(e);return r?(s.shaderSource(r,i),s.compileShader(r),s.getShaderParameter(r,s.COMPILE_STATUS)?r:(V.error("Shader compilation error",s.getShaderInfoLog(r)),s.deleteShader(r),null)):null}initGridOverlay(){this.gridOverlay=new Se(this.containerDiv,{strokeColor:"rgba(144, 24, 24, 1)",lineWidth:1,zIndex:10}),this.updateGridOverlay()}updateGridOverlay(){if(!this.gridOverlay)return;let e=this.cols*this.cellWidth,i=this.rows*this.cellHeight,s=this.canvas.getBoundingClientRect(),r=this.containerDiv.getBoundingClientRect();this.gridOverlay.setDimensions(this.cols,this.rows,this.cellWidth,this.cellHeight,0,0),this.gridOverlay.setTransform(this.currentScale,e,i,s,r),this.gridOverlay.render()}setBitmapFont(e,i,s,r=i,a=s){this.bitmapFont=e,this.fontLoaded=!0,this.charWidth=i,this.charHeight=s,this.cellWidth=r,this.cellHeight=a,this.glyphOffsetX=Math.round((this.cellWidth-this.charWidth)/2),this.glyphOffsetY=Math.round((this.cellHeight-this.charHeight)/2),this.useInstancing&&this.initInstancedBuffers(),this.generateAtlas(),this.updateCanvasSize()}generateAtlas(){if(!this.bitmapFont)return;this.atlasColumns=16;let e=256,i=this.atlasColumns*this.charWidth,s=Math.ceil(e/this.atlasColumns)*this.charHeight;this.atlasCanvas=document.createElement("canvas"),this.atlasCanvas.width=i,this.atlasCanvas.height=s;let r=this.atlasCanvas.getContext("2d",{willReadFrequently:!0});if(!r)return;r.clearRect(0,0,i,s);let a=Array.from(this.bitmapFont.keys());for(let n of a){let o=this.bitmapFont.get(n);if(!o)continue;let l=n%this.atlasColumns,h=Math.floor(n/this.atlasColumns),d=l*this.charWidth,c=h*this.charHeight;for(let u=0;u<this.charHeight&&!(u>=o.length);u++){let f=o[u];for(let p=0;p<this.charWidth;p++){let m=1<<7-p;f&m&&(r.fillStyle="#FFFFFF",r.fillRect(d+p,c+u,1,1))}}}this.cachedAtlasWidth=i,this.cachedAtlasHeight=s,this.createAtlasTexture(),this.charCodeToAtlasIndex.fill(65535);for(let n=0;n<e;n++)this.charCodeToAtlasIndex[n]=n}async setImageFontStructure(e,i,s,r,a){let n=this.atlasCanvas&&this.fontLoaded&&this.charWidth===Math.round(e)&&this.charHeight===Math.round(i),o=this.atlasCanvas;this.fontLoaded=!0,this.charWidth=Math.round(e),this.charHeight=Math.round(i),this.cellWidth=Math.round(s),this.cellHeight=Math.round(r),this.atlasColumns=Me(a);let l=Xe(a);this.glyphOffsetX=Math.round((this.cellWidth-this.charWidth)/2),this.glyphOffsetY=Math.round((this.cellHeight-this.charHeight)/2),this.useInstancing&&this.initInstancedBuffers();let h=Me(a);if(this.cachedAtlasWidth=h*this.charWidth,this.cachedAtlasHeight=h*this.charHeight,this.allocateAtlasTexture(this.cachedAtlasWidth,this.cachedAtlasHeight),n&&o){let d=this.gl;d.bindTexture(d.TEXTURE_2D,this.atlasTexture),d.texSubImage2D(d.TEXTURE_2D,0,0,0,d.RGBA,d.UNSIGNED_BYTE,o)}this.charCodeToAtlasIndex.fill(65535);for(let d=0;d<=l;d++)this.charCodeToAtlasIndex[d]=d;this.precomputeImageFontUVs(a),this.canvas.width=this.cols*this.cellWidth,this.canvas.height=this.rows*this.cellHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.useInstancing||this.precomputeStaticPositions()}async setImageFontBlock(e,i){let s=this.gl;if(!this.atlasTexture)return;let r=new Blob([i],{type:"image/png"}),a=await createImageBitmap(r),n=this.atlasColumns/16,o=e%n,l=Math.floor(e/n),h=o*16*this.charWidth,d=l*16*this.charHeight;s.bindTexture(s.TEXTURE_2D,this.atlasTexture),s.texSubImage2D(s.TEXTURE_2D,0,h,d,s.RGBA,s.UNSIGNED_BYTE,a),a.close()}async setImageFont(e,i,s,r,a,n){this.fontLoaded=!0,this.charWidth=Math.round(i),this.charHeight=Math.round(s),this.cellWidth=Math.round(r),this.cellHeight=Math.round(a),this.atlasColumns=Me(n);let o=Xe(n);this.glyphOffsetX=Math.round((this.cellWidth-this.charWidth)/2),this.glyphOffsetY=Math.round((this.cellHeight-this.charHeight)/2),this.useInstancing&&this.initInstancedBuffers(),await this.loadImageFontAtlas(e),this.charCodeToAtlasIndex.fill(65535);for(let l=0;l<=o;l++)this.charCodeToAtlasIndex[l]=l;this.precomputeImageFontUVs(n),this.canvas.width=this.cols*this.cellWidth,this.canvas.height=this.rows*this.cellHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.useInstancing||this.precomputeStaticPositions(),this.showGrid&&this.gridOverlay&&this.updateGridOverlay()}async loadImageFontAtlas(e){return new Promise((i,s)=>{let r=new Uint8Array(e),a=new Blob([r],{type:"image/png"}),n=URL.createObjectURL(a),o=new Image;o.onload=()=>{URL.revokeObjectURL(n),this.atlasCanvas=document.createElement("canvas"),this.atlasCanvas.width=o.width,this.atlasCanvas.height=o.height;let l=this.atlasCanvas.getContext("2d");if(!l){s(new Error("Failed to create 2D context for atlas"));return}l.drawImage(o,0,0),this.cachedAtlasWidth=o.width,this.cachedAtlasHeight=o.height,this.createAtlasTexture(),i()},o.onerror=()=>{URL.revokeObjectURL(n),s(new Error("Failed to load PNG image for ImageFont atlas"))},o.src=n})}precomputeImageFontUVs(e){let i=e*256;this.atlasUVs=new Float32Array(i*4);let s=this.cachedAtlasWidth,r=this.cachedAtlasHeight,a=.5/s,n=.5/r;for(let o=0;o<i;o++){let{col:l,row:h}=Qe(o,e),d=(l*this.charWidth+a)/s,c=(h*this.charHeight+n)/r,u=((l+1)*this.charWidth-a)/s,f=((h+1)*this.charHeight-n)/r,p=o*4;this.atlasUVs[p]=d,this.atlasUVs[p+1]=c,this.atlasUVs[p+2]=u,this.atlasUVs[p+3]=f}}allocateAtlasTexture(e,i){try{let s=this.gl,r=s.createTexture();if(!r)throw new Error("Unable to create texture");s.bindTexture(s.TEXTURE_2D,r),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,e,i,0,s.RGBA,s.UNSIGNED_BYTE,null),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),this.atlasTexture=r}catch(s){throw V.error("Failed to create atlas texture",s),s}}createAtlasTexture(){if(this.atlasCanvas)try{let e=this.gl,i=e.createTexture();if(!i)throw new Error("Unable to create texture");e.bindTexture(e.TEXTURE_2D,i),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,this.atlasCanvas),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),this.atlasTexture=i}catch(e){throw V.error("Failed to create atlas texture",e),e}}clear(){let e=this.gl;e&&e.clear(e.COLOR_BUFFER_BIT)}parseColor(e){if(e.startsWith("#")){let i=e.slice(1),s=0,r=0,a=0;return i.length===3?(s=parseInt(i[0]+i[0],16),r=parseInt(i[1]+i[1],16),a=parseInt(i[2]+i[2],16)):i.length===6&&(s=parseInt(i.slice(0,2),16),r=parseInt(i.slice(2,4),16),a=parseInt(i.slice(4,6),16)),[s/255,r/255,a/255,1]}if(e.startsWith("rgb")){let i=e.match(/rgba?\(([^)]+)\)/);if(i){let s=i[1].split(",").map(r=>parseFloat(r.trim()));return[s[0]/255,s[1]/255,s[2]/255,s[3]!==void 0?s[3]:1]}}return[1,1,1,1]}setupResizeObserver(){if(!(typeof ResizeObserver>"u")){try{this.resizeObserver=new ResizeObserver(()=>{try{this.updateCanvasSize()}catch(e){V.error("Error in resize callback",e)}}),this.resizeObserver.observe(this.parentElement),this.updateCanvasSize()}catch(e){V.error("Failed to setup ResizeObserver",e)}this.boundWindowResize=()=>{try{this.updateCanvasSize()}catch(e){V.error("Error in window resize callback",e)}},window.addEventListener("resize",this.boundWindowResize)}}updateCanvasSize(){let e=this.parentElement.clientWidth,i=this.parentElement.clientHeight;if(e===0||i===0)return;let s=this.cols*this.cellWidth,r=this.rows*this.cellHeight;if(s===0||r===0)return;let a=e/s,n=i/r,o=Math.min(a,n),l;switch(this.scalingMode){case T.Integer:l=Math.max(1,Math.floor(o));break;case T.Half:l=Math.max(1,Math.floor(o*2)/2);break;case T.Quarter:l=Math.max(1,Math.floor(o*4)/4);break;case T.Eighth:l=Math.max(1,Math.floor(o*8)/8);break;case T.Responsive:l=1;break;case T.None:default:l=Math.max(.1,o);break}if(this.canvas.style.transform=`scale(${l})`,this.ambientEffectEnabled&&this.ambientEffectCanvas){let h=l*this.ambientEffectScale;this.ambientEffectCanvas.style.transform=`scale(${h})`}this.currentScale=l,this.onResizeCallback&&this.onResizeCallback(),this.showGrid&&this.gridOverlay&&this.updateGridOverlay()}updateAmbientEffect(){!this.ambientEffectCanvas||!this.ambientEffectCtx||this.ambientEffectCtx.drawImage(this.canvas,0,0)}setPalette(e){let i=0,s=Math.min(e.length,256);for(let a=0;a<s;a++){let n=e[a];i=(i<<5)-i+n.r,i=(i<<5)-i+n.g,i=(i<<5)-i+n.b,i=(i<<5)-i+n.a,i=i|0}if(i===this.paletteHash)return;this.paletteHash=i,this.paletteFloat.fill(0);let r=15*4;this.paletteFloat[r]=1,this.paletteFloat[r+1]=1,this.paletteFloat[r+2]=1,this.paletteFloat[r+3]=1;for(let a=0;a<s;a++){let n=e[a],o=a*4;this.paletteFloat[o]=n.r/255,this.paletteFloat[o+1]=n.g/255,this.paletteFloat[o+2]=n.b/255,this.paletteFloat[o+3]=n.a/255}this.updatePaletteTexture()}updatePaletteTexture(){try{let e=this.gl;this.paletteTexture||(this.paletteTexture=e.createTexture()),e.bindTexture(e.TEXTURE_2D,this.paletteTexture);let i=new Uint8Array(256*4);for(let s=0;s<256;s++){let r=s*4;i[r]=this.paletteFloat[r]*255,i[r+1]=this.paletteFloat[r+1]*255,i[r+2]=this.paletteFloat[r+2]*255,i[r+3]=this.paletteFloat[r+3]*255}e.texImage2D(e.TEXTURE_2D,0,e.RGBA,256,1,0,e.RGBA,e.UNSIGNED_BYTE,i),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null)}catch(e){throw V.error("Failed to update palette texture",e),e}}renderDisplayData(e){try{if(!this.isReady())return;(e.width!==this.cols||e.height!==this.rows)&&this.resize(e.width,e.height),e.passes&&e.passes.length>0?this.renderMultiPass(e,e.passes):this.renderDirect(e),this.ambientEffectEnabled&&this.ambientEffectCanvas&&this.ambientEffectCtx&&this.updateAmbientEffect()}catch(i){V.error("Error rendering display data",i)}}renderMultiPass(e,i){for(let s=0;s<i.length;s++){let r=i[s],a={id:e.id,width:e.width,height:e.height,palette:e.palette,cells:r.cells};this.renderDirect(a,s===0)}}renderDirect(e,i=!0){let s=this.gl;if(!this.staticPositionsInitialized&&!this.useInstancing&&this.precomputeStaticPositions(),i){if(this.canvasBgColor!==null){let r=this.parseColor(this.canvasBgColor);s.clearColor(r[0],r[1],r[2],r[3])}else s.clearColor(0,0,0,0);s.clear(s.COLOR_BUFFER_BIT)}this.useInstancing?this.renderInstanced(e):this.renderDirectBuffers(e)}renderInstanced(e){let i=this.gl,s=this.instancedExtension;if(!this.instanceData||this.instanceData.length===0){this.renderDirectBuffers(e);return}let r=0,a=this.instanceData.length/8,n=e.width*e.height*2;if(n>a){V.error(`Instance buffer too small! Need ${n}, have ${a}. Display size: ${e.width}\xD7${e.height}, buffer was sized for smaller terminal.`),this.renderDirectBuffers(e);return}for(let l=0;l<e.height;l++)for(let h=0;h<e.width;h++){let d=e.cells[l*e.width+h],c=d.bgColorIndex,u=d.fgColorIndex,f=this.canvasBgColor!==null&&c===255,p=d.char===" "||u===255;if(!f){if(r>=a){V.error(`Instance buffer overflow! instanceIdx=${r}, max=${a}`);break}let m=r*8;this.instanceData[m]=h,this.instanceData[m+1]=l,this.instanceData[m+2]=0,this.instanceData[m+3]=0,this.instanceData[m+4]=0,this.instanceData[m+5]=0,this.instanceData[m+6]=c,this.instanceData[m+7]=0,r++}if(!p){let m=d.char.charCodeAt(0),y=this.charCodeToAtlasIndex[m];if(y!==65535){if(r>=a){V.error(`Instance buffer overflow! instanceIdx=${r}, max=${a}`);break}let C=y*4,v=r*8;this.instanceData[v]=h,this.instanceData[v+1]=l,this.instanceData[v+2]=this.atlasUVs[C],this.instanceData[v+3]=this.atlasUVs[C+1],this.instanceData[v+4]=this.atlasUVs[C+2],this.instanceData[v+5]=this.atlasUVs[C+3],this.instanceData[v+6]=0,this.instanceData[v+7]=u,r++}}}if(r===0)return;i.bindBuffer(i.ARRAY_BUFFER,this.instanceDataBuffer),i.bufferSubData(i.ARRAY_BUFFER,0,this.instanceData.subarray(0,r*8)),i.useProgram(this.program),i.bindBuffer(i.ARRAY_BUFFER,this.positionBuffer),i.enableVertexAttribArray(this.aPosition),i.vertexAttribPointer(this.aPosition,2,i.FLOAT,!1,0,0),s.vertexAttribDivisorANGLE(this.aPosition,0),i.bindBuffer(i.ARRAY_BUFFER,this.instanceDataBuffer);let o=8*Float32Array.BYTES_PER_ELEMENT;i.enableVertexAttribArray(this.aInstanceOffset),i.vertexAttribPointer(this.aInstanceOffset,2,i.FLOAT,!1,o,0),s.vertexAttribDivisorANGLE(this.aInstanceOffset,1),i.enableVertexAttribArray(this.aInstanceUVs),i.vertexAttribPointer(this.aInstanceUVs,4,i.FLOAT,!1,o,2*Float32Array.BYTES_PER_ELEMENT),s.vertexAttribDivisorANGLE(this.aInstanceUVs,1),i.enableVertexAttribArray(this.aInstanceColors),i.vertexAttribPointer(this.aInstanceColors,2,i.FLOAT,!1,o,6*Float32Array.BYTES_PER_ELEMENT),s.vertexAttribDivisorANGLE(this.aInstanceColors,1),i.uniform2f(this.uResolution,this.canvas.width,this.canvas.height),i.uniform2f(this.uCellSize,this.cellWidth,this.cellHeight),i.activeTexture(i.TEXTURE0),i.bindTexture(i.TEXTURE_2D,this.atlasTexture),i.uniform1i(this.uTexture,0),i.activeTexture(i.TEXTURE1),i.bindTexture(i.TEXTURE_2D,this.paletteTexture),i.uniform1i(this.uPalette,1),i.bindBuffer(i.ELEMENT_ARRAY_BUFFER,this.indexBuffer),s.drawElementsInstancedANGLE(i.TRIANGLES,6,i.UNSIGNED_SHORT,0,r),s.vertexAttribDivisorANGLE(this.aPosition,0),s.vertexAttribDivisorANGLE(this.aInstanceOffset,0),s.vertexAttribDivisorANGLE(this.aInstanceUVs,0),s.vertexAttribDivisorANGLE(this.aInstanceColors,0)}renderDirectBuffers(e){let i=this.gl,s=e.width*e.height,r=s*2;if(r>this.maxCells){V.error(`Buffer overflow detected! Trying to render ${r} quads but buffer capacity is ${this.maxCells}. This should not happen - resize() should have reallocated.`);return}let a=0,n=0,o=e.cells,l=s;for(let f=0;f<l;f++){let p=o[f],m=p.bgColorIndex,y=this.canvasBgColor!==null&&m===255?255:m,C=0;for(let E=0;E<4;E++)this.renderTexCoords[a++]=C,this.renderTexCoords[a++]=C,this.renderColorIndices[n++]=y;let v=p.fgColorIndex,x=p.char;if(x===" "||x==="\0"||v===255)for(let E=0;E<4;E++)this.renderTexCoords[a++]=0,this.renderTexCoords[a++]=0,this.renderColorIndices[n++]=255;else{let E=x.charCodeAt(0),P=this.charCodeToAtlasIndex[E];if(P!==65535){let L=P*4,z=this.atlasUVs[L],O=this.atlasUVs[L+1],W=this.atlasUVs[L+2],q=this.atlasUVs[L+3];this.renderTexCoords[a++]=z,this.renderTexCoords[a++]=O,this.renderColorIndices[n++]=v,this.renderTexCoords[a++]=W,this.renderTexCoords[a++]=O,this.renderColorIndices[n++]=v,this.renderTexCoords[a++]=z,this.renderTexCoords[a++]=q,this.renderColorIndices[n++]=v,this.renderTexCoords[a++]=W,this.renderTexCoords[a++]=q,this.renderColorIndices[n++]=v}else for(let L=0;L<4;L++)this.renderTexCoords[a++]=0,this.renderTexCoords[a++]=0,this.renderColorIndices[n++]=255}}(a!==l*2*4*2||n!==l*2*4)&&V.error("Buffer index mismatch!",{texIdx:a,colorIdx:n,expected:l*2*4}),i.useProgram(this.program),this.vao&&this.vaoExtension?(this.vaoExtension.bindVertexArrayOES(this.vao),i.bindBuffer(i.ARRAY_BUFFER,this.texCoordBuffer),i.bufferSubData(i.ARRAY_BUFFER,0,this.renderTexCoords.subarray(0,a)),i.bindBuffer(i.ARRAY_BUFFER,this.colorIndexBuffer),i.bufferSubData(i.ARRAY_BUFFER,0,this.renderColorIndices.subarray(0,n))):(i.bindBuffer(i.ARRAY_BUFFER,this.positionBuffer),i.enableVertexAttribArray(this.aPosition),i.vertexAttribPointer(this.aPosition,2,i.FLOAT,!1,0,0),i.bindBuffer(i.ARRAY_BUFFER,this.texCoordBuffer),i.bufferSubData(i.ARRAY_BUFFER,0,this.renderTexCoords.subarray(0,a)),i.enableVertexAttribArray(this.aTexCoord),i.vertexAttribPointer(this.aTexCoord,2,i.FLOAT,!1,0,0),i.bindBuffer(i.ARRAY_BUFFER,this.colorIndexBuffer),i.bufferSubData(i.ARRAY_BUFFER,0,this.renderColorIndices.subarray(0,n)),i.enableVertexAttribArray(this.aColorIndex),i.vertexAttribPointer(this.aColorIndex,1,i.FLOAT,!1,0,0));let h=this.canvas.width,d=this.canvas.height;(this.cachedResolution[0]!==h||this.cachedResolution[1]!==d)&&(i.uniform2f(this.uResolution,h,d),this.cachedResolution[0]=h,this.cachedResolution[1]=d),this.cachedTextureUnit!==0&&(i.activeTexture(i.TEXTURE0),this.cachedTextureUnit=0),i.bindTexture(i.TEXTURE_2D,this.atlasTexture),this.cachedTextureUniform||(i.uniform1i(this.uTexture,0),this.cachedTextureUniform=!0),this.cachedPaletteUnit!==1&&(i.activeTexture(i.TEXTURE1),this.cachedPaletteUnit=1),i.bindTexture(i.TEXTURE_2D,this.paletteTexture),this.cachedPaletteUniform||(i.uniform1i(this.uPalette,1),this.cachedPaletteUniform=!0),i.bindBuffer(i.ELEMENT_ARRAY_BUFFER,this.indexBuffer);let c=e.width*e.height*2*6,u=this.useUint16Indices?i.UNSIGNED_SHORT:i.UNSIGNED_INT;i.drawElements(i.TRIANGLES,c,u,0)}resize(e,i){if(!Number.isInteger(e)||e<=0){V.error(`Invalid cols: ${e}. Must be positive integer.`);return}if(!Number.isInteger(i)||i<=0){V.error(`Invalid rows: ${i}. Must be positive integer.`);return}if(e===this.cols&&i===this.rows)return;let s=e*i,r=this.useInstancing?262144:this.useUint16Indices?8191:262144;if(s>r){let h=Math.floor(Math.sqrt(r));V.error(`Cannot resize to ${e}\xD7${i} (${s} cells). Device limit: ${r} cells (max ~${h}\xD7${h}). ${!this.useInstancing&&this.useUint16Indices?"Device lacks OES_element_index_uint extension.":""}`);return}this.cols=e,this.rows=i,this.staticPositionsInitialized=!1;let a=this.cols*this.rows*2,n=Math.ceil(a*1.5),o=a>this.maxCells,l=this.maxCells>n*4;if(o||l){if(this.maxCells=n,this.renderPositions=new Float32Array(this.maxCells*4*2),this.renderTexCoords=new Float32Array(this.maxCells*4*2),this.renderColorIndices=new Float32Array(this.maxCells*4),this.useUint16Indices?this.renderIndices=new Uint16Array(this.maxCells*6):this.renderIndices=new Uint32Array(this.maxCells*6),this.useInstancing&&this.instanceDataBuffer){this.instanceData=new Float32Array(this.maxCells*8);let d=this.gl;d.bindBuffer(d.ARRAY_BUFFER,this.instanceDataBuffer),d.bufferData(d.ARRAY_BUFFER,this.instanceData.byteLength,d.DYNAMIC_DRAW)}let h=this.gl;this.useInstancing||(h.bindBuffer(h.ARRAY_BUFFER,this.positionBuffer),h.bufferData(h.ARRAY_BUFFER,this.renderPositions.byteLength,h.DYNAMIC_DRAW)),h.bindBuffer(h.ARRAY_BUFFER,this.texCoordBuffer),h.bufferData(h.ARRAY_BUFFER,this.renderTexCoords.byteLength,h.DYNAMIC_DRAW),h.bindBuffer(h.ARRAY_BUFFER,this.colorIndexBuffer),h.bufferData(h.ARRAY_BUFFER,this.renderColorIndices.byteLength,h.DYNAMIC_DRAW),this.useInstancing||(h.bindBuffer(h.ELEMENT_ARRAY_BUFFER,this.indexBuffer),h.bufferData(h.ELEMENT_ARRAY_BUFFER,this.renderIndices.byteLength,h.DYNAMIC_DRAW)),this.vaoExtension&&this.vao&&(this.vaoExtension.deleteVertexArrayOES(this.vao),this.vao=this.vaoExtension.createVertexArrayOES(),this.vao&&(this.vaoExtension.bindVertexArrayOES(this.vao),h.bindBuffer(h.ARRAY_BUFFER,this.positionBuffer),h.enableVertexAttribArray(this.aPosition),h.vertexAttribPointer(this.aPosition,2,h.FLOAT,!1,0,0),h.bindBuffer(h.ARRAY_BUFFER,this.texCoordBuffer),h.enableVertexAttribArray(this.aTexCoord),h.vertexAttribPointer(this.aTexCoord,2,h.FLOAT,!1,0,0),h.bindBuffer(h.ARRAY_BUFFER,this.colorIndexBuffer),h.enableVertexAttribArray(this.aColorIndex),h.vertexAttribPointer(this.aColorIndex,1,h.FLOAT,!1,0,0),h.bindBuffer(h.ELEMENT_ARRAY_BUFFER,this.indexBuffer),this.vaoExtension.bindVertexArrayOES(null)))}this.canvas.width=this.cols*this.cellWidth,this.canvas.height=this.rows*this.cellHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.canvas.style.width=`${this.canvas.width}px`,this.canvas.style.height=`${this.canvas.height}px`,this.ambientEffectEnabled&&this.ambientEffectCanvas&&(this.ambientEffectCanvas.width=this.canvas.width,this.ambientEffectCanvas.height=this.canvas.height,this.ambientEffectCanvas.style.width=`${this.canvas.width}px`,this.ambientEffectCanvas.style.height=`${this.canvas.height}px`),this.showGrid&&this.gridOverlay&&this.updateGridOverlay(),this.updateCanvasSize()}getCanvas(){return this.canvas}getGridSize(){return{cols:this.cols,rows:this.rows}}getCellWidth(){return this.cellWidth}getCellHeight(){return this.cellHeight}getCurrentScale(){return this.currentScale}getBaseDimensions(){return{width:this.cols*this.cellWidth,height:this.rows*this.cellHeight}}setOnResizeCallback(e){this.onResizeCallback=e}clearOnResizeCallback(){this.onResizeCallback=void 0}getAvailableSize(){return{width:this.parentElement.clientWidth,height:this.parentElement.clientHeight}}setScalingMode(e){this.scalingMode!==e&&(this.scalingMode=e,this.updateCanvasSize())}getScalingMode(){return this.scalingMode}setCellSize(e,i){let s=Math.max(1,Math.min(255,Math.round(e))),r=Math.max(1,Math.min(255,Math.round(i)));this.cellWidth===s&&this.cellHeight===r||(this.cellWidth=s,this.cellHeight=r,this.charWidth=s,this.charHeight=r,this.glyphOffsetX=Math.round((this.cellWidth-this.charWidth)/2),this.glyphOffsetY=Math.round((this.cellHeight-this.charHeight)/2),this.useInstancing&&this.initInstancedBuffers(),this.updateCanvasSize())}getCellSize(){return{cellWidth:this.cellWidth,cellHeight:this.cellHeight}}getMaxCells(){return this.useInstancing?262144:this.useUint16Indices?8191:262144}setGrid(e){e.enabled?(this.gridOverlay?this.gridOverlay.setStyle({strokeColor:e.color,lineWidth:e.lineWidth}):this.gridOverlay=new Se(this.containerDiv,{strokeColor:e.color??"rgba(144, 24, 24, 1)",lineWidth:e.lineWidth??1,zIndex:10}),this.showGrid=!0,this.gridOverlay.setVisible(!0),this.updateGridOverlay()):(this.showGrid=!1,this.gridOverlay&&this.gridOverlay.setVisible(!1))}isGridEnabled(){return this.showGrid}setAmbientEffect(e){typeof e=="boolean"?this.ambientEffectEnabled=e:(this.ambientEffectEnabled=!0,e.blur!==void 0&&(this.ambientEffectBlur=e.blur),e.scale!==void 0&&(this.ambientEffectScale=e.scale)),this.ambientEffectEnabled&&!this.ambientEffectCanvas&&this.createAmbientEffectCanvas(),this.ambientEffectCanvas&&(this.ambientEffectEnabled?(this.ambientEffectCanvas.style.display="block",this.ambientEffectCanvas.style.filter=`blur(${this.ambientEffectBlur}px)`,this.ambientEffectCanvas.style.transform=`scale(${this.ambientEffectScale})`,this.updateAmbientEffect()):this.ambientEffectCanvas.style.display="none")}createAmbientEffectCanvas(){this.ambientEffectCanvas||(this.ambientEffectCanvas=document.createElement("canvas"),this.ambientEffectCanvas.className="terminalgl-ambient-effect-canvas",this.ambientEffectCanvas.width=this.canvas.width,this.ambientEffectCanvas.height=this.canvas.height,this.ambientEffectCanvas.style.cssText=`
|
|
193
|
+
display: block !important;
|
|
194
|
+
position: absolute !important;
|
|
195
|
+
width: ${this.canvas.width}px !important;
|
|
196
|
+
height: ${this.canvas.height}px !important;
|
|
197
|
+
filter: blur(${this.ambientEffectBlur}px) !important;
|
|
198
|
+
opacity: ${this.ambientEffectOpacity} !important;
|
|
199
|
+
transform-origin: center center !important;
|
|
200
|
+
transform: scale(${this.ambientEffectScale}) !important;
|
|
201
|
+
pointer-events: none !important;
|
|
202
|
+
z-index: 0 !important;
|
|
203
|
+
`,this.ambientEffectCtx=this.ambientEffectCanvas.getContext("2d",{alpha:!0}),this.containerDiv.insertBefore(this.ambientEffectCanvas,this.canvas))}isAmbientEffectEnabled(){return this.ambientEffectEnabled}getAmbientEffectConfig(){return{enabled:this.ambientEffectEnabled,blur:this.ambientEffectBlur,scale:this.ambientEffectScale}}getCols(){return this.cols}getRows(){return this.rows}isReady(){return!!(this.fontLoaded&&this.atlasTexture&&this.program)}destroy(){this.dispose()}dispose(){this.resizeObserver&&this.resizeObserver.disconnect(),this.boundWindowResize&&(window.removeEventListener("resize",this.boundWindowResize),this.boundWindowResize=void 0);let e=this.gl;this.program&&e.deleteProgram(this.program),this.positionBuffer&&e.deleteBuffer(this.positionBuffer),this.texCoordBuffer&&e.deleteBuffer(this.texCoordBuffer),this.colorIndexBuffer&&e.deleteBuffer(this.colorIndexBuffer),this.indexBuffer&&e.deleteBuffer(this.indexBuffer),this.instanceDataBuffer&&e.deleteBuffer(this.instanceDataBuffer),this.atlasTexture&&e.deleteTexture(this.atlasTexture),this.paletteTexture&&e.deleteTexture(this.paletteTexture),this.vao&&this.vaoExtension&&this.vaoExtension.deleteVertexArrayOES(this.vao);let i=e.getExtension("WEBGL_lose_context");i&&i.loseContext(),this.atlasCanvas&&(this.atlasCanvas.width=0,this.atlasCanvas.height=0,this.atlasCanvas=void 0),this.containerDiv.parentElement&&this.containerDiv.parentElement.removeChild(this.containerDiv),this.canvas.width=0,this.canvas.height=0,this.ambientEffectCanvas&&(this.ambientEffectCanvas.width=0,this.ambientEffectCanvas.height=0,this.ambientEffectCanvas=null),this.gridOverlay&&(this.gridOverlay.destroy(),this.gridOverlay=void 0),this.renderPositions=new Float32Array(0),this.renderTexCoords=new Float32Array(0),this.renderColorIndices=new Float32Array(0),this.renderIndices=new Uint32Array(0),this.paletteFloat=new Float32Array(0),this.atlasUVs=new Float32Array(0),this.instanceData=new Float32Array(0),this.templateQuadPositions=new Float32Array(0),this.templateQuadIndices=new Uint16Array(0)}};var ue=class Bt{width;height;size;data;constructor(e,i){this.width=e,this.height=i,this.size=e*i,this.data=new Uint32Array(this.size)}clear(){this.data.fill(255<<24|255<<16|0)}fill(e,i,s){let r=s<<24|i<<16|e;this.data.fill(r)}setSafe(e,i,s,r,a){e<0||e>=this.width||i<0||i>=this.height||(this.data[i*this.width+e]=a<<24|r<<16|s)}set(e,i,s,r){this.data[e]=r<<24|s<<16|i}setPacked(e,i){this.data[e]=i}get(e){return this.data[e]}unpack(e){let i=this.data[e];return{char:i&65535,fg:i>>>16&255,bg:i>>>24&255}}clone(){let e=new Bt(this.width,this.height);return e.data.set(this.data),e}},Ri=class{static pack(t,e,i){return i<<24|e<<16|t}static getChar(t){return t&65535}static getFg(t){return t>>>16&255}static getBg(t){return t>>>24&255}},Ai=class{rasterize(t,e,i){for(let s of e)this.executeOrder(t,s,i)}executeOrder(t,e,i){switch(e.type){case g.Char:this.drawChar(t,e);break;case g.Text:this.drawText(t,e);break;case g.TextMultiline:this.drawTextMultiline(t,e);break;case g.SubFrame:this.drawSubFrame(t,e);break;case g.SubFrameMulti:this.drawSubFrameMulti(t,e);break;case g.FullFrame:this.drawFullFrame(t,e);break;case g.FullFrameMulti:this.drawFullFrameMulti(t,e);break;case g.ColorMap:this.drawColorMap(t,e);break;case g.DotCloud:this.drawDotCloud(t,e);break;case g.DotCloudMulti:this.drawDotCloudMulti(t,e);break;case g.SpriteCloud:this.drawSpriteCloud(t,e,i);break;case g.SpriteCloudMulti:this.drawSpriteCloudMulti(t,e,i);break;case g.SpriteCloudVaried:this.drawSpriteCloudVaried(t,e,i);break;case g.SpriteCloudVariedMulti:this.drawSpriteCloudVariedMulti(t,e,i);break;case g.Bitmask:this.drawBitmask(t,e);break;case g.Bitmask4:this.drawBitmask4(t,e);break;case g.Bitmask16:this.drawBitmask16(t,e);break;case g.Polyline:this.drawPolyline(t,e);break;case g.Fill:this.drawFill(t,e);break;case g.FillChar:this.drawFillChar(t,e);break;case g.FillSprite:this.drawFillSprite(t,e,i);break;case g.FillSpriteMulti:this.drawFillSpriteMulti(t,e,i);break;case g.Sprite:this.drawSprite(t,e,i);break;case g.SpriteMulti:this.drawSpriteMulti(t,e,i);break;case g.Shape:this.drawShape(t,e);break}}drawChar(t,e){let{x:i,y:s,char:r,fg:a,bg:n}=e;t.setSafe(i,s,r,a,n)}drawText(t,e){let{x:i,y:s,text:r,fg:a,bg:n}=e;if(typeof r=="string")for(let o=0;o<r.length;o++){let l=r.charCodeAt(o);t.setSafe(i+o,s,l,a,n)}}drawTextMultiline(t,e){let{x:i,y:s,text:r,fg:a,bg:n}=e;if(typeof r!="string")return;let o=r.split(`
|
|
204
|
+
`);for(let l=0;l<o.length;l++){let h=o[l];for(let d=0;d<h.length;d++){let c=h.charCodeAt(d);t.setSafe(i+d,s+l,c,a,n)}}}drawSubFrame(t,e){let{x:i,y:s,width:r,height:a,frame:n,fg:o,bg:l}=e;for(let h=0;h<a;h++)for(let d=0;d<r;d++){let c=h*r+d;c<n.length&&t.setSafe(i+d,s+h,n[c],o,l)}}drawSubFrameMulti(t,e){let{x:i,y:s,width:r,height:a,frame:n}=e;for(let o=0;o<a;o++)for(let l=0;l<r;l++){let h=o*r+l;if(h<n.length){let d=n[h];t.setSafe(i+l,s+o,d.char,d.fg,d.bg)}}}drawFullFrame(t,e){let{frame:i,fg:s,bg:r}=e,a=t.width,n=t.height,o=0;for(let l=0;l<n;l++)for(let h=0;h<a;h++){if(o>=i.length)return;t.setSafe(h,l,i[o],s,r),o++}}drawFullFrameMulti(t,e){let{frame:i}=e,s=t.width,r=t.height,a=0;for(let n=0;n<r;n++)for(let o=0;o<s;o++){if(a>=i.length)return;let l=i[a];t.setSafe(o,n,l.char,l.fg,l.bg),a++}}drawColorMap(t,e){let{x:i,y:s,width:r,height:a,data:n}=e;for(let o=0;o<a;o++)for(let l=0;l<r;l++){let h=o*r+l;if(h<n.length){let d=n[h];if(i+l>=0&&i+l<t.width&&s+o>=0&&s+o<t.height){let c=(s+o)*t.width+(i+l),u=t.data[c]&65535;t.data[c]=d.bg<<24|d.fg<<16|u}}}}drawFill(t,e){let{char:i,fg:s,bg:r,x:a,y:n,width:o,height:l}=e,h=a??0,d=n??0,c=o??t.width,u=l??t.height;if(h===0&&d===0&&c===t.width&&u===t.height){let f=r<<24|s<<16|i&65535;t.data.fill(f);return}for(let f=d;f<d+u;f++)for(let p=h;p<h+c;p++)t.setSafe(p,f,i,s,r)}drawFillChar(t,e){let{patternWidth:i,patternHeight:s,pattern:r,fg:a,bg:n}=e;if(!(i<=0||s<=0))for(let o=0;o<t.height;o++)for(let l=0;l<t.width;l++){let h=l%i,d=o%s,c=r[d*i+h];t.setSafe(l,o,c,a,n)}}drawFillSprite(t,e,i){if(!i)return;let s=i.getUnicolorSprite(e.spriteId);if(s)for(let r=0;r<t.height;r+=s.height)for(let a=0;a<t.width;a+=s.width)for(let n=0;n<s.height;n++)for(let o=0;o<s.width;o++){let l=s.data[n*s.width+o];t.setSafe(a+o,r+n,l,e.fg,e.bg)}}drawFillSpriteMulti(t,e,i){if(!i)return;let s=i.getMulticolorSprite(e.spriteId);if(s)for(let r=0;r<t.height;r+=s.height)for(let a=0;a<t.width;a+=s.width)for(let n=0;n<s.height;n++)for(let o=0;o<s.width;o++){let l=s.data[n*s.width+o],h=a+o,d=r+n;h>=0&&h<t.width&&d>=0&&d<t.height&&(t.data[d*t.width+h]=l)}}drawSprite(t,e,i){if(!i)return;let{x:s,y:r,spriteId:a,fg:n,bg:o}=e,l=i.getUnicolorSprite(a);if(l)for(let h=0;h<l.height;h++)for(let d=0;d<l.width;d++){let c=l.data[h*l.width+d];t.setSafe(s+d,r+h,c,n,o)}}drawSpriteMulti(t,e,i){if(!i)return;let{x:s,y:r,spriteId:a}=e,n=i.getMulticolorSprite(a);if(n)for(let o=0;o<n.height;o++)for(let l=0;l<n.width;l++){let h=n.data[o*n.width+l],d=s+l,c=r+o;d>=0&&d<t.width&&c>=0&&c<t.height&&(t.data[c*t.width+d]=h)}}drawDotCloud(t,e){let{positions:i,char:s,fg:r,bg:a}=e;for(let n of i)t.setSafe(n.x,n.y,s,r,a)}drawDotCloudMulti(t,e){for(let i of e.dots)t.setSafe(i.x,i.y,i.char,i.fg,i.bg)}drawSpriteCloud(t,e,i){if(!i)return;let s=i.getUnicolorSprite(e.spriteId);if(s)for(let r of e.positions)for(let a=0;a<s.height;a++)for(let n=0;n<s.width;n++){let o=s.data[a*s.width+n];t.setSafe(r.x+n,r.y+a,o,e.fg,e.bg)}}drawSpriteCloudMulti(t,e,i){if(!i)return;let s=i.getMulticolorSprite(e.spriteId);if(s)for(let r of e.positions)for(let a=0;a<s.height;a++)for(let n=0;n<s.width;n++){let o=s.data[a*s.width+n],l=r.x+n,h=r.y+a;l>=0&&l<t.width&&h>=0&&h<t.height&&(t.data[h*t.width+l]=o)}}drawSpriteCloudVaried(t,e,i){if(i)for(let s of e.sprites){let r=i.getUnicolorSprite(s.spriteId);if(r)for(let a=0;a<r.height;a++)for(let n=0;n<r.width;n++){let o=r.data[a*r.width+n];t.setSafe(s.x+n,s.y+a,o,s.fg,s.bg)}}}drawSpriteCloudVariedMulti(t,e,i){if(i)for(let s of e.sprites){let r=i.getMulticolorSprite(s.spriteId);if(r)for(let a=0;a<r.height;a++)for(let n=0;n<r.width;n++){let o=r.data[a*r.width+n],l=s.x+n,h=s.y+a;l>=0&&l<t.width&&h>=0&&h<t.height&&(t.data[h*t.width+l]=o)}}}drawBitmask(t,e){let{x:i,y:s,width:r,height:a,mask:n,char:o,fg:l,bg:h,override:d}=e;for(let c=0;c<a;c++)for(let u=0;u<r;u++){let f=c*r+u,p=f>>3,m=f&7;n[p]&1<<m?t.setSafe(i+u,s+c,o,l,h):d&&t.setSafe(i+u,s+c,0,255,255)}}drawBitmask4(t,e){let{x:i,y:s,width:r,height:a,mask:n,variants:o,override:l}=e;for(let h=0;h<a;h++)for(let d=0;d<r;d++){let c=h*r+d,u=c>>2,f=(c&3)*2,p=n[u]>>f&3;if(p>0){let m=o[p-1];m&&t.setSafe(i+d,s+h,m.char,m.fg,m.bg)}else l&&t.setSafe(i+d,s+h,0,255,255)}}drawBitmask16(t,e){let{x:i,y:s,width:r,height:a,mask:n,variants:o,override:l}=e;for(let h=0;h<a;h++)for(let d=0;d<r;d++){let c=h*r+d,u=c>>1,f=(c&1)*4,p=n[u]>>f&15;if(p>0){let m=o[p-1];m&&t.setSafe(i+d,s+h,m.char,m.fg,m.bg)}else l&&t.setSafe(i+d,s+h,0,255,255)}}drawPolyline(t,e){let{points:i,char:s,fg:r,bg:a}=e;if(!(i.length<2))for(let n=0;n<i.length-1;n++){let o=i[n],l=i[n+1];this.drawLineBresenham(t,o.x,o.y,l.x,l.y,s,r,a)}}drawLineBresenham(t,e,i,s,r,a,n,o){let l=Math.abs(s-e),h=Math.abs(r-i),d=e<s?1:-1,c=i<r?1:-1,u=l-h;for(;t.setSafe(e,i,a,n,o),!(e===s&&i===r);){let f=2*u;f>-h&&(u-=h,e+=d),f<l&&(u+=l,i+=c)}}drawShape(t,e){switch(e.shapeType){case B.Rectangle:this.drawRectangle(t,e);break;case B.Circle:this.drawCircle(t,e);break;case B.Line:e.x1!==void 0&&e.y1!==void 0&&e.x2!==void 0&&e.y2!==void 0&&this.drawLineBresenham(t,e.x1,e.y1,e.x2,e.y2,e.char,e.fg,e.bg);break;case B.Ellipse:this.drawEllipse(t,e);break;case B.Triangle:this.drawTriangle(t,e);break}}drawRectangle(t,e){let{char:i,fg:s,bg:r,filled:a}=e,n=e.x??0,o=e.y??0,l=e.width??0,h=e.height??0;if(a)for(let d=o;d<o+h;d++)for(let c=n;c<n+l;c++)t.setSafe(c,d,i,s,r);else{for(let d=n;d<n+l;d++)t.setSafe(d,o,i,s,r),t.setSafe(d,o+h-1,i,s,r);for(let d=o+1;d<o+h-1;d++)t.setSafe(n,d,i,s,r),t.setSafe(n+l-1,d,i,s,r)}}drawCircle(t,e){let{char:i,fg:s,bg:r,filled:a}=e,n=e.x??0,o=e.y??0,l=e.radius??0;if(l<=0)return;let h=l,d=0,c=0;for(;h>=d;){if(a){for(let u=n-h;u<=n+h;u++)t.setSafe(u,o+d,i,s,r);for(let u=n-h;u<=n+h;u++)t.setSafe(u,o-d,i,s,r);for(let u=n-d;u<=n+d;u++)t.setSafe(u,o+h,i,s,r);for(let u=n-d;u<=n+d;u++)t.setSafe(u,o-h,i,s,r)}else t.setSafe(n+h,o+d,i,s,r),t.setSafe(n+d,o+h,i,s,r),t.setSafe(n-d,o+h,i,s,r),t.setSafe(n-h,o+d,i,s,r),t.setSafe(n-h,o-d,i,s,r),t.setSafe(n-d,o-h,i,s,r),t.setSafe(n+d,o-h,i,s,r),t.setSafe(n+h,o-d,i,s,r);c<=0&&(d+=1,c+=2*d+1),c>0&&(h-=1,c-=2*h+1)}}drawEllipse(t,e){let{char:i,fg:s,bg:r,filled:a}=e,n=e.x??0,o=e.y??0,l=e.radiusX??e.radius??0,h=e.radiusY??e.radius??0;if(l<=0||h<=0)return;let d=0,c=h,u=h*h-l*l*h+.25*l*l,f=2*h*h*d,p=2*l*l*c;for(;f<p;){if(a)for(let y=n-d;y<=n+d;y++)t.setSafe(y,o+c,i,s,r),t.setSafe(y,o-c,i,s,r);else t.setSafe(n+d,o+c,i,s,r),t.setSafe(n-d,o+c,i,s,r),t.setSafe(n+d,o-c,i,s,r),t.setSafe(n-d,o-c,i,s,r);u<0?(d++,f+=2*h*h,u+=f+h*h):(d++,c--,f+=2*h*h,p-=2*l*l,u+=f-p+h*h)}let m=h*h*((d+.5)*(d+.5))+l*l*((c-1)*(c-1))-l*l*h*h;for(;c>=0;){if(a)for(let y=n-d;y<=n+d;y++)t.setSafe(y,o+c,i,s,r),t.setSafe(y,o-c,i,s,r);else t.setSafe(n+d,o+c,i,s,r),t.setSafe(n-d,o+c,i,s,r),t.setSafe(n+d,o-c,i,s,r),t.setSafe(n-d,o-c,i,s,r);m>0?(c--,p-=2*l*l,m+=l*l-p):(c--,d++,f+=2*h*h,p-=2*l*l,m+=f-p+l*l)}}drawTriangle(t,e){let{char:i,fg:s,bg:r,filled:a}=e,n=e.x1??0,o=e.y1??0,l=e.x2??0,h=e.y2??0,d=e.x3??0,c=e.y3??0;if(!a){this.drawLineBresenham(t,n,o,l,h,i,s,r),this.drawLineBresenham(t,l,h,d,c,i,s,r),this.drawLineBresenham(t,d,c,n,o,i,s,r);return}let u=n,f=o,p=l,m=h,y=d,C=c;if(f>m){let x=u;u=p,p=x,x=f,f=m,m=x}if(f>C){let x=u;u=y,y=x,x=f,f=C,C=x}if(m>C){let x=p;p=y,y=x,x=m,m=C,C=x}let v=C-f;if(v!==0)for(let x=0;x<v;x++){let E=x>m-f||m===f,P=E?C-m:m-f,L=x/v,z=(x-(E?m-f:0))/P,O=Math.floor(u+(y-u)*L),W;if(E?W=Math.floor(p+(y-p)*z):W=Math.floor(u+(p-u)*z),O>W){let q=O;O=W,W=q}for(let q=O;q<=W;q++)t.setSafe(q,f+x,i,s,r)}}},et=class Ft{id=0;grid;x=0;y=0;origin;zIndex=0;visible=!0;opacity=1;name;isMacroLayer;width;height;mustBeReliable=!1;spriteRegistry;charCodeMode;is16bit;pendingOrders=[];enabled=!0;needsCommit=!1;static rasterizer=new Ai;constructor(e,i,s,r,a){s<1||s>256||r<1||r>256;let n={};typeof a=="boolean"?n={mustBeReliable:a}:a&&(n=a),this.origin=e,this.x=e.x,this.y=e.y,this.zIndex=i,this.name=n.name,this.width=s,this.height=r,this.mustBeReliable=n.mustBeReliable??!1,this.isMacroLayer=n.isMacroLayer??!1,this.charCodeMode=n.charCodeMode??"8bit",this.is16bit=this.charCodeMode==="16bit",this.grid=new ue(s,r),this.grid.clear()}setId(e){this.id=e}setSpriteRegistry(e){this.spriteRegistry=e}resize(e,i){this.grid=new ue(e,i),this.width=e,this.height=i}getMustBeReliable(){return this.mustBeReliable}getName(){return this.name}getIsMacroLayer(){return this.isMacroLayer}getWidth(){return this.width}getHeight(){return this.height}getOrigin(){return this.origin}setOrders(e){this.pendingOrders=e,this.grid.clear(),Ft.rasterizer.rasterize(this.grid,e,this.spriteRegistry),this.needsCommit=!0}getPendingOrders(){return this.pendingOrders}clearPendingOrders(){this.pendingOrders.length=0}commit(){this.needsCommit=!0}getNeedsCommit(){return this.needsCommit}clearCommit(){this.needsCommit=!1}isEnabled(){return this.enabled}},tt=class{id;x=0;y=0;width;height;cellWidth=8;cellHeight=8;postProcess={};scalingMode=T.None;activePaletteSlot=0;renderPasses;constructor(t,e,i){this.id=t,this.width=e,this.height=i}teleport(t,e){this.x=t,this.y=e}resize(t,e){this.width=t,this.height=e}setCellSize(t,e){this.cellWidth=Math.max(1,Math.min(255,Math.round(t))),this.cellHeight=Math.max(1,Math.min(255,Math.round(e)))}getCellSize(){return{cellWidth:this.cellWidth,cellHeight:this.cellHeight}}setScalingMode(t){this.scalingMode=t}setAmbientEffect(t){this.postProcess.ambientEffect||(this.postProcess.ambientEffect={enabled:!1,blur:30,scale:1.3}),typeof t=="boolean"?this.postProcess.ambientEffect.enabled=t:this.postProcess.ambientEffect={...this.postProcess.ambientEffect,...t,enabled:!0}}setPostProcess(t){if(t===null){this.postProcess={};return}this.postProcess={...this.postProcess,...t}}setOrigin(t){this.x=t.x,this.y=t.y}switchPalette(t){this.activePaletteSlot=t}setRenderPasses(t){if(!t||t.length===0){this.renderPasses=void 0;return}if(t.length>4)throw new Error(`Display.setRenderPasses: max 4 passes, got ${t.length}`);this.renderPasses=t.map(e=>this.normalizePass(e))}getRenderPasses(){return this.renderPasses}normalizePass(t){let e=Math.max(0,Math.min(255,t.zMin)),i=Math.max(0,Math.min(255,t.zMax));if(e>i){let s=e;e=i,i=s}return{id:t.id,zMin:e,zMax:i,enabled:t.enabled!==!1}}},Dt=class{axes=new Map;buttons=new Map;touchZones=new Map;axisNameToId=new Map;buttonNameToId=new Map;touchZoneNameToId=new Map;version=1;n=null;s=null;o=null;defineAxis(t,e,i=[],s=-1,r=1,a=0){if(t<0||t>255)throw new Error(`Axis bindingId must be between 0 and 255, got ${t}`);if(this.axes.has(t))throw new Error(`Axis bindingId ${t} is already defined`);if(this.axisNameToId.has(e))throw new Error(`Axis name "${e}" is already defined`);let n={bindingId:t,name:e,min:s,max:r,defaultValue:a,sources:i};this.axes.set(t,n),this.axisNameToId.set(e,t),this.n=null,this.version++}defineButton(t,e,i=[],s=!1){if(t<0||t>255)throw new Error(`Button bindingId must be between 0 and 255, got ${t}`);if(this.buttons.has(t))throw new Error(`Button bindingId ${t} is already defined`);if(this.buttonNameToId.has(e))throw new Error(`Button name "${e}" is already defined`);let r={bindingId:t,name:e,defaultValue:s,sources:i};this.buttons.set(t,r),this.buttonNameToId.set(e,t),this.s=null,this.version++}defineTouchZone(t,e,i,s,r,a){if(t<0||t>31)throw new Error(`Touch zone zoneId must be between 0 and 31, got ${t}`);if(this.touchZones.has(t))throw new Error(`Touch zone zoneId ${t} is already defined`);if(this.touchZoneNameToId.has(e))throw new Error(`Touch zone name "${e}" is already defined`);let n={zoneId:t,name:e,x:i,y:s,width:r,height:a};this.touchZones.set(t,n),this.touchZoneNameToId.set(e,t),this.o=null,this.version++}evaluateAxis(t,e){let i=this.axes.get(t);if(!i)return 0;let s=0;for(let r of i.sources){let a=e.get(r.sourceId)??0,n=r.deadzone??0;Math.abs(a)<n?a=0:a=(a>0?1:-1)*((Math.abs(a)-n)/(1-n)),a*=(r.scale??1)*(r.sensitivity??1),r.invert&&(a=-a),s+=a}return Math.max(i.min,Math.min(i.max,s))}evaluateButton(t,e){let i=this.buttons.get(t);if(!i)return!1;for(let s of i.sources)if(e.get(s.sourceId)===!0)return!0;return i.defaultValue}toLoadPacket(){return{type:"input-binding",version:this.version,axes:Array.from(this.axes.values()),buttons:Array.from(this.buttons.values()),touchZones:this.touchZones.size>0?Array.from(this.touchZones.values()):void 0}}getAllAxes(){return this.n||(this.n=Array.from(this.axes.values()).sort((t,e)=>t.bindingId-e.bindingId)),this.n}getAllButtons(){return this.s||(this.s=Array.from(this.buttons.values()).sort((t,e)=>t.bindingId-e.bindingId)),this.s}getAllTouchZones(){return this.o||(this.o=Array.from(this.touchZones.values()).sort((t,e)=>t.zoneId-e.zoneId)),this.o}getAxisCount(){return this.axes.size}getButtonCount(){return this.buttons.size}getAxisId(t){return this.axisNameToId.get(t)??null}getButtonId(t){return this.buttonNameToId.get(t)??null}clear(){this.axes.clear(),this.buttons.clear(),this.touchZones.clear(),this.axisNameToId.clear(),this.buttonNameToId.clear(),this.touchZoneNameToId.clear(),this.n=null,this.s=null,this.o=null,this.version++}},it=class{id;name;data={};bridgeInbox=[];d=new Map;u=new Map;e=new Map;isTabHidden=!1;layers=new Map;displays=new Map;nextLayerId=1;t=null;i=null;spriteRegistry;macroRegistry=null;commandQueue=[];l=[];nextSoundInstanceId=1;axes=new Map;buttons=new Map;justPressed=new Set;justReleased=new Set;mouseX=0;mouseY=0;activeDisplay=0;mouseOver=!1;constructor(t,e){this.id=t,this.name=e}setSpriteRegistry(t){this.spriteRegistry=t;for(let e of this.layers.values())e.setSpriteRegistry(t)}addLayer(t,e){let i=this.nextLayerId++;t.setId(i),this.layers.set(t.id,t),this.t=null,this.spriteRegistry&&t.setSpriteRegistry(this.spriteRegistry)}addDisplay(t){this.displays.set(t.id,t),this.i=null}getMouseDisplayInfo(){return this.mouseOver?{localX:this.mouseX,localY:this.mouseY,displayId:this.activeDisplay}:null}inputRegistry=new Dt;getInputBindingRegistry(){return this.inputRegistry}applyInput(t,e){this.mouseX=t.mouseX,this.mouseY=t.mouseY,this.mouseOver=t.mouseOverDisplay,this.activeDisplay=t.displayId;for(let i of e.getAllAxes()){let s=t.axes.get(i.bindingId)??i.defaultValue;this.axes.set(i.name,s)}for(let i of e.getAllButtons()){let s=t.buttons.get(i.bindingId)??i.defaultValue,r=this.buttons.get(i.name)??!1;s&&!r?this.justPressed.add(i.name):!s&&r&&this.justReleased.add(i.name),this.buttons.set(i.name,s)}}poll(){this.justPressed.clear(),this.justReleased.clear(),this.commandQueue.length=0}playSound(t,e){let i=this.nextSoundInstanceId++,s={type:g.Audio,sound:t,instanceId:i,...e};return this.commandQueue.push(s),i}stopSound(t){let e={type:g.Audio,sound:t,stop:!0};this.commandQueue.push(e)}stopAllSounds(){let t={type:g.Audio,sound:"all",stop:!0};this.commandQueue.push(t)}fadeOutSound(t,e){let i={type:g.Audio,sound:t,fadeOut:e};this.commandQueue.push(i)}fadeOutAllSounds(t){let e={type:g.Audio,sound:"all",fadeOut:t};this.commandQueue.push(e)}pauseSound(t){let e={type:g.Audio,sound:t,pause:!0};this.commandQueue.push(e)}pauseAllSounds(){let t={type:g.Audio,sound:"all",pause:!0};this.commandQueue.push(t)}resumeSound(t){let e={type:g.Audio,sound:t,resume:!0};this.commandQueue.push(e)}resumeAllSounds(){let t={type:g.Audio,sound:"all",resume:!0};this.commandQueue.push(t)}setSoundEffects(t,e){let i={type:g.Audio,sound:t,...e};this.commandQueue.push(i)}setListenerPosition(t,e){let i={type:g.Audio,sound:"__listener_position__",x:t,y:e};this.commandQueue.push(i)}configureSpatialAudio(t){let e={type:g.Audio,sound:"__configure_spatial__",...t};this.commandQueue.push(e)}sendSounds(){this.m=!0}m=!1;vibrate(t){let e={type:g.Vibration,pattern:t};this.commandQueue.push(e)}vibrateGamepad(t){let e={type:g.Vibration,target:"gamepad",gamepadIndex:t.gamepadIndex??0,duration:t.duration,strongMagnitude:t.strongMagnitude??1,weakMagnitude:t.weakMagnitude??1,startDelay:t.startDelay??0};this.commandQueue.push(e)}setPostProcess(t,e){let i=this.displays.get(t);i&&i.setPostProcess(e)}setAmbientEffect(t,e){let i=this.displays.get(t);i&&i.setAmbientEffect(e)}setScalingMode(t,e){let i=this.displays.get(t);i&&i.setScalingMode(e)}switchPalette(t,e){let i=this.displays.get(t);i&&i.switchPalette(e)}setOrigin(t,e){let i=this.displays.get(t);i&&i.setOrigin(e)}flushCommands(){let t=this.commandQueue;return this.commandQueue=this.l,this.l=t,this.commandQueue.length=0,t}getAxis(t){return this.axes.get(t)??0}getButton(t){return this.buttons.get(t)??!1}isJustPressed(t){return this.justPressed.has(t)}isJustReleased(t){return this.justReleased.has(t)}createLayer(t,e,i){if(this.layers.has(t))throw new Error(`Layer ${t} already exists`);let s=new et(new N(0,0),0,e,i);return s.setId(t),this.layers.set(t,s),this.t=null,s}getLayer(t){return this.layers.get(t)}removeLayer(t){let e=this.layers.delete(t);return e&&(this.t=null),e}getLayers(){return this.t===null&&(this.t=Array.from(this.layers.values())),this.t}createDisplay(t,e,i){if(this.displays.has(t))throw new Error(`Display ${t} already exists`);let s=new tt(t,e,i);return this.displays.set(t,s),this.i=null,s}getDisplay(t){return this.displays.get(t)}removeDisplay(t){let e=this.displays.delete(t);return e&&(this.i=null),e}getDisplays(){return this.i===null&&(this.i=Array.from(this.displays.values())),this.i}defineButton(t,e,i,s=!1){this.inputRegistry.defineButton(t,e,i,s)}defineAxis(t,e,i,s=-1,r=1,a=0){this.inputRegistry.defineAxis(t,e,i,s,r,a)}handleAudioAck(t){switch(t.type){case"sound-loaded":this.d.set(t.soundId,{name:t.name,loadedAt:Date.now()}),this.u.delete(t.soundId);break;case"sound-error":this.u.set(t.soundId,{name:t.name,error:t.error,at:Date.now()});break;case"playback-started":this.e.set(t.instanceId,{soundId:t.soundId,startedAt:Date.now()});break;case"playback-ended":this.e.delete(t.instanceId);break;case"playback-error":t.instanceId!=null&&this.e.delete(t.instanceId);break}}isSoundLoaded(t){return this.d.has(t)}getLoadedSounds(){return this.d}getSoundLoadError(t){return this.u.get(t)?.error}getSoundLoadErrors(){return this.u}isSoundPlaying(t){return this.e.has(t)}getPlayingSounds(){return this.e}getPlayingSoundCount(){return this.e.size}setMacroRegistry(t){this.macroRegistry=t}getMacroRegistry(){return this.macroRegistry}loadMacro(t,e){if(!this.macroRegistry)throw new Error("MacroRegistry not set");return this.macroRegistry.registerTemplate(t,e)}createMacroInstance(t){if(!this.macroRegistry)throw new Error("MacroRegistry not set");return this.macroRegistry.createInstance(t)}updateMacroInstance(t,e){this.macroRegistry?.updateInstance(t,e)}removeMacroInstance(t){this.macroRegistry?.removeInstance(t)}pauseMacroInstance(t){this.macroRegistry?.pauseInstance(t)}resumeMacroInstance(t){this.macroRegistry?.resumeInstance(t)}onMacroEvent(t,e,i){this.macroRegistry?.onEvent(t,e,i)}handleMacroFeedback(t){this.macroRegistry?.handleFeedback(t)}},Zs=U.create("core:update-builder");var Qs=U.create("core:update-parser");var $s=new TextDecoder;function Pt(t){let e=Array.from(t.axes.entries()).sort((p,m)=>p[0]-m[0]),i=Array.from(t.buttons.entries()).sort((p,m)=>p[0]-m[0]),s=mt(i.length),r=new TextEncoder,a=t.textInputs.map(p=>r.encode(p)),n=1+a.reduce((p,m)=>p+1+m.length,0),o=1+t.displayViewports.length*5,l=1+t.touchPositions.length*4,h=2+e.length+s+4+n+o+l,d=new Uint8Array(h),c=new DataView(d.buffer),u=0;d[u++]=e.length&255,d[u++]=i.length&255;for(let[,p]of e)d[u++]=pt(p)+256&255;for(let p=0;p<s;p++){let m=0;for(let y=0;y<8;y++){let C=p*8+y;C<i.length&&i[C][1]&&(m|=1<<y)}d[u++]=m}d[u++]=t.displayId&255,d[u++]=t.mouseX&255,d[u++]=t.mouseY&255;let f=0;t.mouseOverDisplay&&(f|=1),t.isTabHidden&&(f|=2),d[u++]=f,d[u++]=Math.min(a.length,255);for(let p of a){let m=Math.min(p.length,255);d[u++]=m,d.set(p.slice(0,m),u),u+=m}d[u++]=Math.min(t.displayViewports.length,255);for(let p of t.displayViewports)d[u++]=p.displayId&255,c.setUint16(u,p.pixelWidth,!1),u+=2,c.setUint16(u,p.pixelHeight,!1),u+=2;d[u++]=Math.min(t.touchPositions.length,255);for(let p of t.touchPositions)d[u++]=p.id&15,d[u++]=p.x&255,d[u++]=p.y&255,d[u++]=p.over?1:0;return d}var Lt=[[0,0],[9786,1],[9787,2],[9829,3],[9830,4],[9827,5],[9824,6],[8226,7],[9688,8],[9675,9],[9689,10],[9794,11],[9792,12],[9834,13],[9835,14],[9788,15],[9658,16],[9668,17],[8597,18],[8252,19],[182,20],[167,21],[9644,22],[8616,23],[8593,24],[8595,25],[8594,26],[8592,27],[8735,28],[8596,29],[9650,30],[9660,31],[8962,127],[199,128],[252,129],[233,130],[226,131],[228,132],[224,133],[229,134],[231,135],[234,136],[235,137],[232,138],[239,139],[238,140],[236,141],[196,142],[197,143],[201,144],[230,145],[198,146],[244,147],[246,148],[242,149],[251,150],[249,151],[255,152],[214,153],[220,154],[162,155],[163,156],[165,157],[8359,158],[402,159],[225,160],[237,161],[243,162],[250,163],[241,164],[209,165],[170,166],[186,167],[191,168],[8976,169],[172,170],[189,171],[188,172],[161,173],[171,174],[187,175],[9617,176],[9618,177],[9619,178],[9474,179],[9508,180],[9569,181],[9570,182],[9558,183],[9557,184],[9571,185],[9553,186],[9559,187],[9565,188],[9564,189],[9563,190],[9488,191],[9492,192],[9524,193],[9516,194],[9500,195],[9472,196],[9532,197],[9566,198],[9567,199],[9562,200],[9556,201],[9577,202],[9574,203],[9568,204],[9552,205],[9580,206],[9575,207],[9576,208],[9572,209],[9573,210],[9561,211],[9560,212],[9554,213],[9555,214],[9579,215],[9578,216],[9496,217],[9484,218],[9608,219],[9604,220],[9612,221],[9616,222],[9600,223],[945,224],[223,225],[915,226],[960,227],[931,228],[963,229],[181,230],[964,231],[934,232],[920,233],[937,234],[948,235],[8734,236],[966,237],[949,238],[8745,239],[8801,240],[177,241],[8805,242],[8804,243],[8992,244],[8993,245],[247,246],[8776,247],[176,248],[8729,249],[183,250],[8730,251],[8319,252],[178,253],[9632,254],[160,255]],Ti=new Map(Lt),js=new Map(Lt.map(([t,e])=>[e,t]));function $e(t){if(t<128)return t;let e=Ti.get(t);return e!==void 0?e:t&255}var Bi=class{unicolorSprites=new Map;multicolorSprites=new Map;loadUnicolorSprites(t){for(let e of t){let{spriteId:i,width:s,height:r,data:a}=e,n=new Uint16Array(s*r);if(typeof a=="string"){let l=a.replace(/\n/g,"");for(let h=0;h<Math.min(l.length,s*r);h++)n[h]=$e(l.charCodeAt(h))}else if(Array.isArray(a)&&a.length>0&&typeof a[0]=="string"){let l=a;for(let h=0;h<Math.min(l.length,r);h++){let d=l[h];if(d)for(let c=0;c<Math.min(d.length,s);c++)n[h*s+c]=$e(d.charCodeAt(c))}}else{let l=a;for(let h=0;h<Math.min(l.length,s*r);h++)n[h]=l[h]}let o={id:i,width:s,height:r,data:n};this.unicolorSprites.set(o.id,o)}}loadMulticolorSprites(t){for(let e of t){let{spriteId:i,width:s,height:r,data:a}=e,n=new Uint32Array(s*r);for(let l=0;l<Math.min(a.length,s*r);l++){let h=a[l],d=0;typeof h.charCode=="string"?d=$e(h.charCode.charCodeAt(0)):d=h.charCode||0;let c=h.fgColorId||0,u=h.bgColorId||0;n[l]=Ri.pack(d,c,u)}let o={id:i,width:s,height:r,data:n};this.multicolorSprites.set(o.id,o)}}getUnicolorSprite(t){return this.unicolorSprites.get(t)}getMulticolorSprite(t){return this.multicolorSprites.get(t)}hasUnicolorSprite(t){return this.unicolorSprites.has(t)}hasMulticolorSprite(t){return this.multicolorSprites.has(t)}clearAll(){this.unicolorSprites.clear(),this.multicolorSprites.clear()}},Fi=(t=>(t.Bitmap="bitmap",t.Image="image",t))(Fi||{});function Di(t){return Math.sqrt(t)*16}function Pi(t){return t*256-1}var Li=class{constructor(t,e){this.fontId=t,this.config=e,this.atlasColumns=Di(e.atlasBlocks),this.maxCharCode=Pi(e.atlasBlocks)}atlasColumns;maxCharCode;blocks=new Map;addBlock(t,e){if(t<0||t>=this.config.atlasBlocks)throw new Error(`Invalid block index ${t} for font with ${this.config.atlasBlocks} blocks`);this.blocks.set(t,e)}getBlock(t){return this.blocks.get(t)}getFontId(){return this.fontId}getConfig(){return{glyphWidth:this.config.glyphWidth,glyphHeight:this.config.glyphHeight,cellWidth:this.config.cellWidth,cellHeight:this.config.cellHeight,atlasBlocks:this.config.atlasBlocks}}getGlyphWidth(){return this.config.glyphWidth}getGlyphHeight(){return this.config.glyphHeight}getCellWidth(){return this.config.cellWidth??this.config.glyphWidth}getCellHeight(){return this.config.cellHeight??this.config.glyphHeight}getAtlasBlocks(){return this.config.atlasBlocks}getAtlasColumns(){return this.atlasColumns}getMaxCharCode(){return this.maxCharCode}getAtlasDimensions(){return{width:this.atlasColumns*this.config.glyphWidth,height:this.atlasColumns*this.config.glyphHeight}}getCharUV(t){if(t<0||t>this.maxCharCode)return null;let e=t%this.atlasColumns,i=Math.floor(t/this.atlasColumns),s=e/this.atlasColumns,r=i/this.atlasColumns,a=(e+1)/this.atlasColumns,n=(i+1)/this.atlasColumns;return{u1:s,v1:r,u2:a,v2:n}}isValidCharCode(t){return t>=0&&t<=this.maxCharCode}},Oi=class{fonts=new Map;nameToId=new Map;nextId=0;allocateId(t){if(this.nextId>255)throw new Error(`Cannot register font "${t}": maximum 256 fonts reached`);return this.nextId++}registerFont(t,e){if(this.nameToId.has(t))throw new Error(`ImageFont with name "${t}" already exists`);let i=this.allocateId(t),s={glyphWidth:e.glyphWidth,glyphHeight:e.glyphHeight,cellWidth:e.cellWidth,cellHeight:e.cellHeight,atlasBlocks:e.atlasBlocks??1},r=new Li(i,s);return this.fonts.set(i,r),this.nameToId.set(t,i),i}unregisterFont(t){let e=this.nameToId.get(t);e!==void 0&&(this.fonts.delete(e),this.nameToId.delete(t))}hasFont(t){return this.nameToId.has(t)}addBlock(t,e,i){let s=this.fonts.get(t);if(!s)throw new Error(`ImageFont with ID ${t} not found`);s.addBlock(e,i)}getFont(t){return this.fonts.get(t)}getFontByName(t){let e=this.nameToId.get(t);if(e!==void 0)return this.fonts.get(e)}getFontId(t){return this.nameToId.get(t)}getAllFonts(){return Array.from(this.fonts.values())}getFontName(t){for(let[e,i]of this.nameToId)if(i===t)return e}},Vi=class{sounds=new Map;nameToId=new Map;nextId=0;registerFile(t,e,i){let s=this.allocateId(t),r={soundId:s,name:t,loadType:"file",format:e,data:i};return this.addEntry(r),s}registerExternal(t,e,i,s,r){let a=this.allocateId(t),n={soundId:a,name:t,loadType:"external",format:e,url:i,size:s,checksum:r};return this.addEntry(n),a}get(t){if(typeof t=="number")return this.sounds.get(t);let e=this.nameToId.get(t);return e!==void 0?this.sounds.get(e):void 0}has(t){return this.get(t)!==void 0}toLoadPackets(){let t=[],e=Array.from(this.sounds.values()),i=e.length,s=e.filter(a=>a.loadType==="file");s.length>0&&t.push({type:"sound",mode:"file",sounds:s.map(a=>({soundId:a.soundId,name:a.name,format:a.format,data:a.data})),totalSounds:i});let r=e.filter(a=>a.loadType==="external");return r.length>0&&t.push({type:"sound",mode:"external",sounds:r.map(a=>({soundId:a.soundId,name:a.name,format:a.format,url:a.url,size:a.size,checksum:a.checksum})),totalSounds:i}),t}allocateId(t){if(this.nameToId.has(t))throw new Error(`Sound with name "${t}" 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++}addEntry(t){this.sounds.set(t.soundId,t),this.nameToId.set(t.name,t.soundId)}},kt=U.create("core:macro-registry"),Hi=class{templates=new Map;templateNameToId=new Map;nextTemplateId=0;instances=new Map;instanceNameToId=new Map;nextInstanceId=1;pendingDefines=[];pendingOrders=[];feedbackHandlers=new Map;registerTemplate(t,e){if(this.templateNameToId.has(t))return this.templateNameToId.get(t);let i=this.nextTemplateId++;if(i>65535)throw new Error("Max 65535 macro templates");return this.templates.set(i,e),this.templateNameToId.set(t,i),this.pendingDefines.push({templateId:i,template:e}),kt.debug(`Template registered: "${t}" \u2192 id=${i}`),i}getTemplate(t){if(typeof t=="string"){let e=this.templateNameToId.get(t);return e!==void 0?this.templates.get(e):void 0}return this.templates.get(t)}getTemplateId(t){return this.templateNameToId.get(t)}createInstance(t){let e=this.templateNameToId.get(t.macro);if(e===void 0)throw new Error(`Unknown macro template: "${t.macro}"`);let i=this.nextInstanceId++;if(i>65535)throw new Error("Max 65535 macro instances");let s={instanceId:i,templateId:e,layerId:t.layer,x:t.x,y:t.y,zIndex:t.zIndex??0,params:t.params??{},state:"running"};return this.instances.set(i,s),t.name&&this.instanceNameToId.set(t.name,i),this.pendingOrders.push({cmd:1,instanceId:i,templateId:e,layerId:t.layer,x:t.x,y:t.y,zIndex:t.zIndex??0,params:t.params??{}}),kt.debug(`Instance created: id=${i} macro="${t.macro}" layer=${t.layer}`),i}updateInstance(t,e){let i=this.resolveInstanceId(t);if(i===void 0)return;let s=this.instances.get(i);s&&(Object.assign(s.params,e),this.pendingOrders.push({cmd:2,instanceId:i,params:e}))}removeInstance(t){let e=this.resolveInstanceId(t);if(e!==void 0){this.instances.delete(e);for(let[i,s]of this.instanceNameToId)if(s===e){this.instanceNameToId.delete(i);break}this.feedbackHandlers.delete(e),this.pendingOrders.push({cmd:3,instanceId:e})}}pauseInstance(t){let e=this.resolveInstanceId(t);if(e===void 0)return;let i=this.instances.get(e);i&&(i.state="paused"),this.pendingOrders.push({cmd:4,instanceId:e})}resumeInstance(t){let e=this.resolveInstanceId(t);if(e===void 0)return;let i=this.instances.get(e);i&&(i.state="running"),this.pendingOrders.push({cmd:5,instanceId:e})}getPendingDefines(){return this.pendingDefines}getPendingOrders(){return this.pendingOrders}clearPendingDefines(){this.pendingDefines.length=0}clearPendingOrders(){this.pendingOrders.length=0}getAllDefines(){let t=[];for(let[e,i]of this.templates)t.push({templateId:e,template:i});return t}getActiveInstanceOrders(){let t=[];for(let e of this.instances.values())t.push({cmd:1,instanceId:e.instanceId,templateId:e.templateId,layerId:e.layerId,x:e.x,y:e.y,zIndex:e.zIndex,params:e.params});return t}onEvent(t,e,i){let s=this.resolveInstanceId(t);if(s===void 0)return;let r=this.feedbackHandlers.get(s);r||(r=new Map,this.feedbackHandlers.set(s,r));let a=r.get(e);a||(a=[],r.set(e,a)),a.push(i)}handleFeedback(t){let e=this.feedbackHandlers.get(t.instanceId);if(!e)return;let i,s;switch(t.cmd){case 1:i="click",s=void 0;break;case 2:i="change",s=t.value;break;case 3:i="submit",s=t.text;break;case 4:i="select",s=t.index;break;case 5:i="custom",s=t.data;break;default:return}let r=e.get(i);if(r)for(let a of r)a(s)}resolveInstanceId(t){return typeof t=="number"?t:this.instanceNameToId.get(t)}},Ot=class{buffer;view;offset=0;constructor(t=4096){this.buffer=new Uint8Array(t),this.view=new DataView(this.buffer.buffer)}reset(){this.offset=0}ensure(t){if(this.offset+t>this.buffer.length){let e=this.buffer.length*2;for(;e<this.offset+t;)e*=2;let i=new Uint8Array(e);i.set(this.buffer),this.buffer=i,this.view=new DataView(this.buffer.buffer)}}ensureAndGetBuffer(t){return this.ensure(t),this.buffer}writeU8(t){this.ensure(1),this.buffer[this.offset++]=t&255}writeI8(t){this.ensure(1),this.view.setInt8(this.offset,t),this.offset+=1}writeU16BE(t){this.ensure(2),this.view.setUint16(this.offset,t,!1),this.offset+=2}writeI16BE(t){this.ensure(2),this.view.setInt16(this.offset,t,!1),this.offset+=2}writeU16LE(t){this.ensure(2),this.view.setUint16(this.offset,t,!0),this.offset+=2}writeBytes(t){this.ensure(t.length),this.buffer.set(t,this.offset),this.offset+=t.length}toUint8Array(){return this.buffer.slice(0,this.offset)}getView(){return this.buffer.subarray(0,this.offset)}},Rt=new TextEncoder;function F(t,e,i){i?t.writeU16LE(e):t.writeU8(e&255)}var Wi=class M{static p=new Ot(4096);static encode(e,i=!1){let s=M.p;s.reset();for(let r of e)M.encodeOne(s,r,i);return s.toUint8Array()}static encodeInto(e,i,s=!1){for(let r of i)M.encodeOne(e,r,s)}static encodeOne(e,i,s){switch(i.type){case g.Char:M.encodeChar(e,i,s);break;case g.Text:M.encodeText(e,i);break;case g.TextMultiline:M.encodeTextMultiline(e,i);break;case g.SubFrame:M.encodeSubFrame(e,i,s);break;case g.SubFrameMulti:M.encodeSubFrameMulti(e,i,s);break;case g.FullFrame:M.encodeFullFrame(e,i,s);break;case g.FullFrameMulti:M.encodeFullFrameMulti(e,i,s);break;case g.Sprite:M.encodeSprite(e,i);break;case g.SpriteMulti:M.encodeSpriteMulti(e,i);break;case g.ColorMap:M.encodeColorMap(e,i);break;case g.Shape:M.encodeShape(e,i,s);break;case g.Polyline:M.encodePolyline(e,i,s);break;case g.DotCloud:M.encodeDotCloud(e,i,s);break;case g.DotCloudMulti:M.encodeDotCloudMulti(e,i,s);break;case g.SpriteCloud:M.encodeSpriteCloud(e,i);break;case g.SpriteCloudMulti:M.encodeSpriteCloudMulti(e,i);break;case g.SpriteCloudVaried:M.encodeSpriteCloudVaried(e,i);break;case g.SpriteCloudVariedMulti:M.encodeSpriteCloudVariedMulti(e,i);break;case g.Bitmask:M.encodeBitmask(e,i,s);break;case g.Bitmask4:M.encodeBitmask4(e,i,s);break;case g.Bitmask16:M.encodeBitmask16(e,i,s);break;case g.Fill:M.encodeFill(e,i,s);break;case g.FillChar:M.encodeFillChar(e,i,s);break;case g.FillSprite:M.encodeFillSprite(e,i);break;case g.FillSpriteMulti:M.encodeFillSpriteMulti(e,i);break;default:break}}static encodeChar(e,i,s){e.writeU8(g.Char),e.writeU8(i.x),e.writeU8(i.y),F(e,i.char,s),e.writeU8(i.bg),e.writeU8(i.fg)}static encodeText(e,i){e.writeU8(g.Text),e.writeU8(i.x),e.writeU8(i.y);let s=i.text.length*3,r=e.ensureAndGetBuffer(1+s),a=e.offset;e.offset++;let{written:n}=Rt.encodeInto(i.text,r.subarray(e.offset,e.offset+s));r[a]=n,e.offset+=n,e.writeU8(i.bg),e.writeU8(i.fg)}static encodeTextMultiline(e,i){e.writeU8(g.TextMultiline),e.writeU8(i.x),e.writeU8(i.y);let s=i.text.length*3,r=e.ensureAndGetBuffer(1+s),a=e.offset;e.offset++;let{written:n}=Rt.encodeInto(i.text,r.subarray(e.offset,e.offset+s));r[a]=n,e.offset+=n,e.writeU8(i.bg),e.writeU8(i.fg)}static encodeSubFrame(e,i,s){e.writeU8(g.SubFrame),e.writeU8(i.x),e.writeU8(i.y),e.writeU8(i.width-1),e.writeU8(i.height-1),e.writeU8(i.bg),e.writeU8(i.fg);for(let r of i.frame)F(e,r,s)}static encodeSubFrameMulti(e,i,s){e.writeU8(g.SubFrameMulti),e.writeU8(i.x),e.writeU8(i.y),e.writeU8(i.width-1),e.writeU8(i.height-1);for(let r of i.frame)F(e,r.char,s),e.writeU8(r.bg),e.writeU8(r.fg)}static encodeFullFrame(e,i,s){e.writeU8(g.FullFrame),e.writeU8(i.bg),e.writeU8(i.fg);for(let r of i.frame)F(e,r,s)}static encodeFullFrameMulti(e,i,s){e.writeU8(g.FullFrameMulti);for(let r of i.frame)F(e,r.char,s),e.writeU8(r.bg),e.writeU8(r.fg)}static encodeSprite(e,i){e.writeU8(g.Sprite),e.writeU8(i.x),e.writeU8(i.y),e.writeU8(i.spriteId),e.writeU8(i.bg),e.writeU8(i.fg)}static encodeSpriteMulti(e,i){e.writeU8(g.SpriteMulti),e.writeU8(i.x),e.writeU8(i.y),e.writeU8(i.spriteId)}static encodeColorMap(e,i){e.writeU8(g.ColorMap),e.writeU8(i.x),e.writeU8(i.y),e.writeU8(i.width-1),e.writeU8(i.height-1);for(let s of i.data)e.writeU8(s.bg),e.writeU8(s.fg)}static encodeShape(e,i,s){switch(e.writeU8(g.Shape),e.writeU8(i.shapeType),i.shapeType){case B.Rectangle:e.writeU8(i.x??0),e.writeU8(i.y??0),e.writeU8((i.width??1)-1),e.writeU8((i.height??1)-1),e.writeU8(i.filled?1:0),F(e,i.char,s),e.writeU8(i.bg),e.writeU8(i.fg);break;case B.Circle:e.writeU8(i.x??0),e.writeU8(i.y??0),e.writeU8((i.radius??1)-1),e.writeU8(i.filled?1:0),F(e,i.char,s),e.writeU8(i.bg),e.writeU8(i.fg);break;case B.Line:e.writeU8(i.x1??0),e.writeU8(i.y1??0),e.writeU8(i.x2??0),e.writeU8(i.y2??0),F(e,i.char,s),e.writeU8(i.bg),e.writeU8(i.fg);break;case B.Ellipse:e.writeU8(i.x??0),e.writeU8(i.y??0),e.writeU8((i.radiusX??1)-1),e.writeU8((i.radiusY??1)-1),e.writeU8(i.filled?1:0),F(e,i.char,s),e.writeU8(i.bg),e.writeU8(i.fg);break;case B.Triangle:e.writeU8(i.x1??0),e.writeU8(i.y1??0),e.writeU8(i.x2??0),e.writeU8(i.y2??0),e.writeU8(i.x3??0),e.writeU8(i.y3??0),e.writeU8(i.filled?1:0),F(e,i.char,s),e.writeU8(i.bg),e.writeU8(i.fg);break}}static encodePolyline(e,i,s){e.writeU8(g.Polyline),F(e,i.char,s),e.writeU8(i.fg),e.writeU8(i.bg),e.writeU8(i.points.length);for(let r of i.points)e.writeU8(r.x),e.writeU8(r.y)}static encodeDotCloud(e,i,s){e.writeU8(g.DotCloud),F(e,i.char,s),e.writeU8(i.bg),e.writeU8(i.fg),e.writeU16BE(i.positions.length);for(let r of i.positions)e.writeU8(r.x),e.writeU8(r.y)}static encodeDotCloudMulti(e,i,s){e.writeU8(g.DotCloudMulti),e.writeU16BE(i.dots.length);for(let r of i.dots)F(e,r.char,s),e.writeU8(r.bg),e.writeU8(r.fg),e.writeU8(r.x),e.writeU8(r.y)}static encodeSpriteCloud(e,i){e.writeU8(g.SpriteCloud),e.writeU8(i.spriteId),e.writeU8(i.bg),e.writeU8(i.fg),e.writeU16BE(i.positions.length);for(let s of i.positions)e.writeU8(s.x),e.writeU8(s.y)}static encodeSpriteCloudMulti(e,i){e.writeU8(g.SpriteCloudMulti),e.writeU8(i.spriteId),e.writeU16BE(i.positions.length);for(let s of i.positions)e.writeU8(s.x),e.writeU8(s.y)}static encodeSpriteCloudVaried(e,i){e.writeU8(g.SpriteCloudVaried),e.writeU16BE(i.sprites.length);for(let s of i.sprites)e.writeU8(s.spriteId),e.writeU8(s.bg),e.writeU8(s.fg),e.writeU8(s.x),e.writeU8(s.y)}static encodeSpriteCloudVariedMulti(e,i){e.writeU8(g.SpriteCloudVariedMulti),e.writeU16BE(i.sprites.length);for(let s of i.sprites)e.writeU8(s.spriteId),e.writeU8(s.x),e.writeU8(s.y)}static encodeBitmask(e,i,s){e.writeU8(g.Bitmask),e.writeU8(i.x),e.writeU8(i.y),e.writeU8(i.width-1),e.writeU8(i.height-1),F(e,i.char,s),e.writeU8(i.bg),e.writeU8(i.fg),e.writeU8(i.override?1:0),e.writeBytes(i.mask)}static encodeBitmask4(e,i,s){e.writeU8(g.Bitmask4),e.writeU8(i.x),e.writeU8(i.y),e.writeU8(i.width-1),e.writeU8(i.height-1),e.writeU8(i.override?1:0);for(let r of i.variants)F(e,r.char,s),e.writeU8(r.bg),e.writeU8(r.fg);e.writeBytes(i.mask)}static encodeBitmask16(e,i,s){e.writeU8(g.Bitmask16),e.writeU8(i.x),e.writeU8(i.y),e.writeU8(i.width-1),e.writeU8(i.height-1),e.writeU8(i.override?1:0),e.writeU8(i.variants.length);for(let r of i.variants)F(e,r.char,s),e.writeU8(r.bg),e.writeU8(r.fg);e.writeBytes(i.mask)}static encodeFill(e,i,s){e.writeU8(g.Fill),F(e,i.char,s),e.writeU8(i.bg),e.writeU8(i.fg)}static encodeFillChar(e,i,s){e.writeU8(g.FillChar),e.writeU8(i.patternWidth-1),e.writeU8(i.patternHeight-1),e.writeU8(i.bg),e.writeU8(i.fg);for(let r of i.pattern)F(e,r,s)}static encodeFillSprite(e,i){e.writeU8(g.FillSprite),e.writeU8(i.spriteId),e.writeU8(i.bg),e.writeU8(i.fg)}static encodeFillSpriteMulti(e,i){e.writeU8(g.FillSpriteMulti),e.writeU8(i.spriteId)}},Ae=new TextEncoder,Gi=32,Yi=64,je=[],Je=[],de=[],ce=[],zi=[],Ki=[],Ni=new Ot(8192),_e={reliable:new Uint8Array(0),volatile:new Uint8Array(0)},At=class Z{static encode(e){let i=e.getDisplays(),s=e.getLayers(),r=e.flushCommands();je.length=0,Je.length=0;for(let d of s)d.getNeedsCommit()&&(d.getMustBeReliable()?je.push(d):Je.push(d));de.length=0,ce.length=0;for(let d of r)switch(d.type){case g.Audio:de.push(d);break;case g.Vibration:ce.push(d);break}let a=e.getMacroRegistry(),n=a?.getPendingOrders()??[],o=a?.getPendingDefines()??[],l=Z.encodePacket(i,je,de,ce,void 0,n,o),h=Z.encodePacket(i,Je,zi,Ki);return a?.clearPendingOrders(),a?.clearPendingDefines(),_e.reliable=l,_e.volatile=h,_e}static encodeFull(e,i){let s=e.getDisplays(),r=e.getLayers(),a=e.flushCommands();de.length=0,ce.length=0;for(let d of a)switch(d.type){case g.Audio:de.push(d);break;case g.Vibration:ce.push(d);break}let n;if(i){n=new Map;for(let d of s){let c=d.activePaletteSlot;i.has(c)&&!n.has(c)&&n.set(c,i.get(c))}}let o=e.getMacroRegistry(),l=o?.getAllDefines()??[],h=o?.getActiveInstanceOrders()??[];return Z.encodePacket(s,r,de,ce,n,h,l)}static encodePacket(e,i,s,r,a,n,o){let l=Ni;l.reset(),l.writeU8(e.length);for(let c of e){l.writeU8(c.id),l.writeI16BE(c.x),l.writeI16BE(c.y),l.writeU16BE(c.width),l.writeU16BE(c.height),l.writeU8(c.activePaletteSlot),l.writeU8(c.scalingMode),l.writeU8(c.cellWidth),l.writeU8(c.cellHeight);let u=c.renderPasses;if(u&&u.length>0){l.writeU8(u.length);for(let f of u)l.writeU8(f.id),l.writeU8(Math.max(0,Math.min(255,f.zMin))),l.writeU8(Math.max(0,Math.min(255,f.zMax))),l.writeU8(f.enabled!==!1?1:0)}else l.writeU8(0)}if(a&&a.size>0){l.writeU8(a.size);for(let[c,u]of a){l.writeU8(c);for(let f=0;f<256;f++){let p=u[f];p?(l.writeU8(p.r??0),l.writeU8(p.g??0),l.writeU8(p.b??0),l.writeU8(p.a??0)):(l.writeU8(0),l.writeU8(0),l.writeU8(0),l.writeU8(0))}}}else l.writeU8(0);l.writeU16BE(i.length);for(let c of i){l.writeU16BE(c.id);let u=0;c.getIsMacroLayer()&&(u|=Gi);let f=c.is16bit;f&&(u|=Yi),l.writeU8(u),l.writeI8(c.zIndex);let p=c.getOrigin();l.writeI16BE(p.x),l.writeI16BE(p.y),l.writeU16BE(c.getWidth()),l.writeU16BE(c.getHeight());let m=c.getPendingOrders();l.writeU16BE(m.length),m.length>0&&Wi.encodeInto(l,m,f)}l.writeU8(Math.min(s.length,255));for(let c=0;c<Math.min(s.length,255);c++)Z.encodeAudioOrder(l,s[c]);l.writeU8(Math.min(r.length,255));for(let c=0;c<Math.min(r.length,255);c++)Z.encodeVibrationOrder(l,r[c]);let h=o??[];l.writeU16BE(h.length);for(let c of h)Z.encodeMacroDefine(l,c);let d=n??[];l.writeU16BE(d.length);for(let c of d)Z.encodeMacroOrder(l,c);return l.writeU8(0),l.toUint8Array()}static encodeAudioOrder(e,i){if(i.stop){e.writeU8(2),Z.encodeSoundTarget(e,i.sound);return}if(i.fadeOut!==void 0){e.writeU8(3),Z.encodeSoundTarget(e,i.sound),e.writeU16BE(Math.round(i.fadeOut*1e3));return}if(i.pause){e.writeU8(4),Z.encodeSoundTarget(e,i.sound);return}if(i.resume){e.writeU8(5),Z.encodeSoundTarget(e,i.sound);return}if(i.sound==="__listener_position__"){e.writeU8(7),e.writeI16BE(i.x??0),e.writeI16BE(i.y??0);return}if(i.sound==="__configure_spatial__"){e.writeU8(8),e.writeU16BE(i.maxDistance??100),e.writeU16BE(i.referenceDistance??1),e.writeU8(i.rolloffFactor??1),e.writeU8(i.panSpread??0);return}if(i.instanceId===void 0&&typeof i.sound=="number"&&(i.lowpass!==void 0||i.highpass!==void 0||i.reverb!==void 0||i.pitch!==void 0||i.volume!==void 0)){e.writeU8(6),e.writeU16BE(i.sound);let r=0;i.lowpass!==void 0&&(r|=1),i.highpass!==void 0&&(r|=2),i.reverb!==void 0&&(r|=4),i.pitch!==void 0&&(r|=8),i.volume!==void 0&&(r|=16),e.writeU8(r),i.lowpass!==void 0&&e.writeU16BE(Math.round(i.lowpass)),i.highpass!==void 0&&e.writeU16BE(Math.round(i.highpass)),i.reverb!==void 0&&e.writeU8(Math.round(i.reverb*255)),i.pitch!==void 0&&e.writeU8(Math.round(i.pitch*100)),i.volume!==void 0&&e.writeU8(Math.round(i.volume*255));return}e.writeU8(1),Z.encodeSoundTarget(e,i.sound),e.writeU16BE(i.instanceId??0);let s=0;i.volume!==void 0&&(s|=1),i.pitch!==void 0&&(s|=2),i.fadeIn!==void 0&&(s|=4),i.x!==void 0&&i.y!==void 0&&(s|=8),i.lowpass!==void 0&&(s|=16),i.highpass!==void 0&&(s|=32),i.reverb!==void 0&&(s|=64),i.loop&&(s|=128),e.writeU8(s),i.volume!==void 0&&e.writeU8(Math.round(i.volume*255)),i.pitch!==void 0&&e.writeU8(Math.round(i.pitch*100)),i.fadeIn!==void 0&&e.writeU16BE(Math.round(i.fadeIn*1e3)),i.x!==void 0&&i.y!==void 0&&(e.writeI16BE(i.x),e.writeI16BE(i.y)),i.lowpass!==void 0&&e.writeU16BE(Math.round(i.lowpass)),i.highpass!==void 0&&e.writeU16BE(Math.round(i.highpass)),i.reverb!==void 0&&e.writeU8(Math.round(i.reverb*255))}static encodeSoundTarget(e,i){if(typeof i=="number")e.writeU8(0),e.writeU16BE(i);else if(i==="all")e.writeU8(1);else{e.writeU8(2);let s=Ae.encode(i);e.writeU8(s.length),e.writeBytes(s)}}static encodeVibrationOrder(e,i){if("target"in i&&i.target==="gamepad")e.writeU8(1),e.writeU8(i.gamepadIndex),e.writeU16BE(i.duration),e.writeU8(Math.round(i.strongMagnitude*255)),e.writeU8(Math.round(i.weakMagnitude*255)),e.writeU16BE(i.startDelay);else{e.writeU8(0);let s=i.pattern;if(typeof s=="number")e.writeU8(1),e.writeU16BE(s);else{e.writeU8(s.length);for(let r of s)e.writeU16BE(r)}}}static encodeMacroDefine(e,i){e.writeU16BE(i.templateId);let s=Ae.encode(JSON.stringify(i.template));e.writeU16BE(s.length),e.writeBytes(s)}static encodeMacroOrder(e,i){switch(e.writeU8(i.cmd),e.writeU16BE(i.instanceId),i.cmd){case 1:{let s=i;if(e.writeU16BE(s.templateId),e.writeU16BE(s.layerId),e.writeI16BE(s.x),e.writeI16BE(s.y),e.writeU8(s.zIndex),s.params!==void 0){let r=Ae.encode(JSON.stringify(s.params));e.writeU16BE(r.length),e.writeBytes(r)}else e.writeU16BE(0);break}case 2:{let s=i,r=Ae.encode(JSON.stringify(s.params));e.writeU16BE(r.length),e.writeBytes(r);break}default:break}}},Zi=class{samples;head=0;count=0;windowSize;totalTicks=0;c=0;constructor(t=120){this.windowSize=t,this.samples=new Array(t);for(let e=0;e<t;e++)this.samples[e]={durationMs:0,bytes:0,layers:0,orders:0,cells:0,displays:0}}beginTick(){this.c=performance.now()}endTick(t){let e=performance.now()-this.c;this.totalTicks++;let i=this.samples[this.head];i.durationMs=e,i.bytes=t.bytes,i.layers=t.layers,i.orders=t.orders,i.cells=t.cells,i.displays=t.displays,this.head=(this.head+1)%this.windowSize,this.count<this.windowSize&&this.count++}getSnapshot(){if(this.count===0)return{totalTicks:0,lastTickDurationMs:0,avgTickDurationMs:0,peakTickDurationMs:0,lastTickBytes:0,avgTickBytes:0,lastLayerCount:0,lastOrderCount:0,lastCellCount:0,lastDisplayCount:0};let t=(this.head-1+this.windowSize)%this.windowSize,e=this.samples[t],i=0,s=0,r=0,a=this.count<this.windowSize?0:this.head;for(let n=0;n<this.count;n++){let o=this.samples[(a+n)%this.windowSize];i+=o.durationMs,r+=o.bytes,o.durationMs>s&&(s=o.durationMs)}return{totalTicks:this.totalTicks,lastTickDurationMs:e.durationMs,avgTickDurationMs:i/this.count,peakTickDurationMs:s,lastTickBytes:e.bytes,avgTickBytes:r/this.count,lastLayerCount:e.layers,lastOrderCount:e.orders,lastCellCount:e.cells,lastDisplayCount:e.displays}}reset(){this.head=0,this.count=0,this.totalTicks=0;for(let t=0;t<this.windowSize;t++){let e=this.samples[t];e.durationMs=0,e.bytes=0,e.layers=0,e.orders=0,e.cells=0,e.displays=0}}},st=class Be{static VGA_COLORS=[{colorId:0,r:0,g:0,b:0,a:255},{colorId:1,r:170,g:0,b:0,a:255},{colorId:2,r:0,g:170,b:0,a:255},{colorId:3,r:170,g:85,b:0,a:255},{colorId:4,r:0,g:0,b:170,a:255},{colorId:5,r:170,g:0,b:170,a:255},{colorId:6,r:0,g:170,b:170,a:255},{colorId:7,r:170,g:170,b:170,a:255},{colorId:8,r:85,g:85,b:85,a:255},{colorId:9,r:255,g:85,b:85,a:255},{colorId:10,r:85,g:255,b:85,a:255},{colorId:11,r:255,g:255,b:85,a:255},{colorId:12,r:85,g:85,b:255,a:255},{colorId:13,r:255,g:85,b:255,a:255},{colorId:14,r:85,g:255,b:255,a:255},{colorId:15,r:255,g:255,b:255,a:255}];static SYSTEM_COLORS=[{colorId:240,r:0,g:0,b:0,a:255},{colorId:241,r:60,g:60,b:75,a:255},{colorId:242,r:160,g:160,b:180,a:255},{colorId:243,r:255,g:255,b:255,a:255},{colorId:244,r:230,g:50,b:80,a:255},{colorId:245,r:255,g:120,b:50,a:255},{colorId:246,r:255,g:210,b:60,a:255},{colorId:247,r:130,g:220,b:50,a:255},{colorId:248,r:35,g:100,b:55,a:255},{colorId:249,r:40,g:200,b:220,a:255},{colorId:250,r:60,g:120,b:240,a:255},{colorId:251,r:35,g:55,b:125,a:255},{colorId:252,r:150,g:70,b:210,a:255},{colorId:253,r:130,g:80,b:50,a:255},{colorId:254,r:240,g:210,b:170,a:255}];mode;sessions=new Map;spriteRegistry=new Bi;fontRegistry=new Oi;soundRegistry=new Vi;inputBindings=new Dt;macroRegistry=new Hi;stats=new Zi;getSpriteRegistry(){return this.spriteRegistry}resourceLoader=null;onFontAllocatedCallback=null;onFontBlockAddedCallback=null;constructor(e){this.mode=e.mode,this.initializeDefaultPalette(),this.loadFont(8,8,1,8,8)}setResourceLoader(e){this.resourceLoader=e}createUser(e,i){let s=String(e),r=i??`Player ${e}`,a=new it(s,r);return this.spriteRegistry&&a.setSpriteRegistry(this.spriteRegistry),a.setMacroRegistry(this.macroRegistry),this.sessions.set(s,a),a}removeUser(e){return this.sessions.delete(String(e))}getUser(e){return this.sessions.get(String(e))}endTick(e){this.stats.beginTick();let i=At.encode(e),s=e.getLayers(),r=0,a=0;for(let o of s)a+=o.getWidth()*o.getHeight(),o.getNeedsCommit()&&(r+=o.getPendingOrders().length,o.clearPendingOrders(),o.clearCommit());let n=e.getDisplays();return this.stats.endTick({bytes:i.reliable.byteLength+i.volatile.byteLength,layers:s.length,orders:r,cells:a,displays:n.length}),i}getEngineStats(){return this.stats.getSnapshot()}encodeInitialState(e){return At.encodeFull(e,this.palettes)}onFontAllocated(e){this.onFontAllocatedCallback=e}onFontBlockAdded(e){this.onFontBlockAddedCallback=e}loadFont(e,i,s,r,a){let n="__default__";this.fontRegistry.getFontId(n)!==void 0&&this.fontRegistry.unregisterFont(n),this.fontRegistry.registerFont(n,{glyphWidth:e,glyphHeight:i,cellWidth:r,cellHeight:a,atlasBlocks:s}),this.onFontAllocatedCallback&&this.onFontAllocatedCallback()}async loadFontBlock(e,i){let s;if(typeof i=="string"){if(!this.resourceLoader)throw new Error("[Engine] No resource loader set. The runtime must call engine.setResourceLoader() before loading font blocks.");s=await this.resourceLoader.load(i)}else s=i;let r=this.fontRegistry.getFontId("__default__");if(r===void 0)throw new Error("[Engine] No font allocated. Call loadFont() first.");this.fontRegistry.addBlock(r,e,s),this.onFontBlockAddedCallback&&this.onFontBlockAddedCallback(e)}async loadFontBlocks(e){await Promise.all(Object.entries(e).map(([i,s])=>this.loadFontBlock(Number(i),s)))}getFontConfig(){return this.fontRegistry.getFontByName("__default__")?.getConfig()}getFontBlock(e){return this.fontRegistry.getFontByName("__default__")?.getBlock(e)}palettes=new Map;detectSoundFormat(e){let i=e.split(".").pop()?.toLowerCase();return{mp3:"mp3",wav:"wav",ogg:"ogg",webm:"webm",aac:"aac",m4a:"aac"}[i||""]||"mp3"}async loadSound(e,i){if(!this.resourceLoader)throw new Error("[Engine] No resource loader set. The runtime must call engine.setResourceLoader() before loading sounds.");let s=this.detectSoundFormat(i),r=await this.resourceLoader.load(i);return this.soundRegistry.registerFile(e,s,r)}async loadSounds(e){let i=Object.entries(e),s=await Promise.all(i.map(([a,n])=>this.loadSound(a,n))),r={};return i.forEach(([a],n)=>{r[a]=s[n]}),r}initializeDefaultPalette(){let e=new Array(256);for(let i=0;i<256;i++)e[i]={colorId:i,r:0,g:0,b:0,a:0};for(let i of Be.VGA_COLORS)e[i.colorId]={...i};for(let i of Be.SYSTEM_COLORS)e[i.colorId]={...i};e[255]={colorId:255,r:0,g:0,b:0,a:0},this.palettes.set(0,e)}loadPaletteToSlot(e,i){let s=new Array(256);for(let r=0;r<256;r++)s[r]={colorId:r,r:0,g:0,b:0,a:0};for(let r of i){let a=r.colorId;a>=0&&a<240&&(s[a]={colorId:a,r:r.r??0,g:r.g??0,b:r.b??0,a:r.a??255})}for(let r of Be.SYSTEM_COLORS)s[r.colorId]={...r};s[255]={colorId:255,r:0,g:0,b:0,a:0},this.palettes.set(e,s)}getPalette(e){return this.palettes.get(e)}},rt=class{composite(t,e,i){let s=t.renderPasses;!s||s.length===0?this.compositeSinglePass(t,e,i):this.compositeMultiPass(t,e,s,i)}compositeSinglePass(t,e,i){let s=[...e].sort((a,n)=>n.zIndex-a.zIndex);i.clear();let r=new Uint8Array(i.size);for(let a of s)a.visible&&this.compositeLayer(t,a,i,r)}compositeMultiPass(t,e,i,s){let r=i.filter(n=>n.enabled!==!1);if(r.length===0){this.compositeSinglePass(t,e,s);return}let a=[...e].filter(n=>n.visible).sort((n,o)=>o.zIndex-n.zIndex);s.clear();for(let n of r){let o=a.filter(d=>d.zIndex>=n.zMin&&d.zIndex<=n.zMax);if(o.length===0)continue;let l=new ue(t.width,t.height);l.clear();let h=new Uint8Array(l.size);for(let d of o)this.compositeLayer(t,d,l,h);this.overlayPass(l,s)}}overlayPass(t,e){let i=t.size;for(let s=0;s<i;s++){let r=t.data[s];(r>>>24&255)!==255&&(e.data[s]=r)}}compositeLayer(t,e,i,s){let r=Math.max(t.x,e.x),a=Math.min(t.x+t.width,e.x+e.grid.width),n=Math.max(t.y,e.y),o=Math.min(t.y+t.height,e.y+e.grid.height);if(r>=a||n>=o)return;let l=a-r,h=o-n,d=t.width,c=e.grid.width,u=(n-t.y)*d+(r-t.x),f=(n-e.y)*c+(r-e.x);for(let p=0;p<h;p++){let m=u,y=f;for(let C=0;C<l;C++){if(!s[m]){let v=e.grid.data[y],x=v>>>24&255,E=v>>>16&255,P=v&65535,L=i.data[m],z=L>>>24&255,O=L>>>16&255,W=L&65535;P!==0&&(W===0||W===32)&&(W=P),E!==255&&O===255&&(O=E),x!==255&&(z===255&&(z=x),s[m]=1),i.data[m]=z<<24|O<<16|W}m++,y++}u+=d,f+=c}}};var Xi=class{view;data;offset;constructor(t,e=0){this.data=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.offset=e}get remaining(){return this.data.length-this.offset}readU8(){return this.data[this.offset++]}readI8(){let t=this.view.getInt8(this.offset);return this.offset+=1,t}readU16BE(){let t=this.view.getUint16(this.offset,!1);return this.offset+=2,t}readI16BE(){let t=this.view.getInt16(this.offset,!1);return this.offset+=2,t}readU16LE(){let t=this.view.getUint16(this.offset,!0);return this.offset+=2,t}readBytes(t){let e=this.data.slice(this.offset,this.offset+t);return this.offset+=t,e}},Tt=new TextDecoder;function D(t,e){return e?t.readU16LE():t.readU8()}var Qi=class k{static decode(e,i=!1,s=0,r=0){let a=new Xi(e),n=[];for(;a.remaining>0;){let o=a.readU8(),l=k.decodeOne(a,o,i,s,r);l&&n.push(l)}return n}static decodeOne(e,i,s,r,a){switch(i){case g.Char:return k.decodeChar(e,s);case g.Text:return k.decodeText(e);case g.TextMultiline:return k.decodeTextMultiline(e);case g.SubFrame:return k.decodeSubFrame(e,s);case g.SubFrameMulti:return k.decodeSubFrameMulti(e,s);case g.FullFrame:return k.decodeFullFrame(e,s,r,a);case g.FullFrameMulti:return k.decodeFullFrameMulti(e,s,r,a);case g.Sprite:return k.decodeSprite(e);case g.SpriteMulti:return k.decodeSpriteMulti(e);case g.ColorMap:return k.decodeColorMap(e);case g.Shape:return k.decodeShape(e,s);case g.Polyline:return k.decodePolyline(e,s);case g.DotCloud:return k.decodeDotCloud(e,s);case g.DotCloudMulti:return k.decodeDotCloudMulti(e,s);case g.SpriteCloud:return k.decodeSpriteCloud(e);case g.SpriteCloudMulti:return k.decodeSpriteCloudMulti(e);case g.SpriteCloudVaried:return k.decodeSpriteCloudVaried(e);case g.SpriteCloudVariedMulti:return k.decodeSpriteCloudVariedMulti(e);case g.Bitmask:return k.decodeBitmask(e,s);case g.Bitmask4:return k.decodeBitmask4(e,s);case g.Bitmask16:return k.decodeBitmask16(e,s);case g.Fill:return k.decodeFill(e,s);case g.FillChar:return k.decodeFillChar(e,s);case g.FillSprite:return k.decodeFillSprite(e);case g.FillSpriteMulti:return k.decodeFillSpriteMulti(e);default:return null}}static decodeChar(e,i){let s=e.readU8(),r=e.readU8(),a=D(e,i),n=e.readU8(),o=e.readU8();return{type:g.Char,x:s,y:r,char:a,fg:o,bg:n}}static decodeText(e){let i=e.readU8(),s=e.readU8(),r=e.readU8(),a=e.readBytes(r),n=Tt.decode(a),o=e.readU8(),l=e.readU8();return{type:g.Text,x:i,y:s,text:n,fg:l,bg:o}}static decodeTextMultiline(e){let i=e.readU8(),s=e.readU8(),r=e.readU8(),a=e.readBytes(r),n=Tt.decode(a),o=e.readU8(),l=e.readU8();return{type:g.TextMultiline,x:i,y:s,text:n,fg:l,bg:o}}static decodeSubFrame(e,i){let s=e.readU8(),r=e.readU8(),a=e.readU8()+1,n=e.readU8()+1,o=e.readU8(),l=e.readU8(),h=a*n,d=new Array(h);for(let c=0;c<h;c++)d[c]=D(e,i);return{type:g.SubFrame,x:s,y:r,width:a,height:n,frame:d,fg:l,bg:o}}static decodeSubFrameMulti(e,i){let s=e.readU8(),r=e.readU8(),a=e.readU8()+1,n=e.readU8()+1,o=a*n,l=new Array(o);for(let h=0;h<o;h++){let d=D(e,i),c=e.readU8(),u=e.readU8();l[h]={char:d,fg:u,bg:c}}return{type:g.SubFrameMulti,x:s,y:r,width:a,height:n,frame:l}}static decodeFullFrame(e,i,s,r){let a=e.readU8(),n=e.readU8(),o=s*r,l=new Array(o);for(let h=0;h<o;h++)l[h]=D(e,i);return{type:g.FullFrame,frame:l,fg:n,bg:a}}static decodeFullFrameMulti(e,i,s,r){let a=s*r,n=new Array(a);for(let o=0;o<a;o++){let l=D(e,i),h=e.readU8(),d=e.readU8();n[o]={char:l,fg:d,bg:h}}return{type:g.FullFrameMulti,frame:n}}static decodeSprite(e){let i=e.readU8(),s=e.readU8(),r=e.readU8(),a=e.readU8(),n=e.readU8();return{type:g.Sprite,x:i,y:s,spriteId:r,fg:n,bg:a}}static decodeSpriteMulti(e){let i=e.readU8(),s=e.readU8(),r=e.readU8();return{type:g.SpriteMulti,x:i,y:s,spriteId:r}}static decodeColorMap(e){let i=e.readU8(),s=e.readU8(),r=e.readU8()+1,a=e.readU8()+1,n=r*a,o=new Array(n);for(let l=0;l<n;l++){let h=e.readU8(),d=e.readU8();o[l]={fg:d,bg:h}}return{type:g.ColorMap,x:i,y:s,width:r,height:a,data:o}}static decodeShape(e,i){let s=e.readU8(),r={type:g.Shape,shapeType:s,filled:!1,char:0,fg:0,bg:0};switch(s){case B.Rectangle:{let a=e.readU8(),n=e.readU8(),o=e.readU8()+1,l=e.readU8()+1,h=e.readU8()!==0,d=D(e,i),c=e.readU8(),u=e.readU8();return{...r,x:a,y:n,width:o,height:l,filled:h,char:d,fg:u,bg:c}}case B.Circle:{let a=e.readU8(),n=e.readU8(),o=e.readU8()+1,l=e.readU8()!==0,h=D(e,i),d=e.readU8(),c=e.readU8();return{...r,x:a,y:n,radius:o,filled:l,char:h,fg:c,bg:d}}case B.Line:{let a=e.readU8(),n=e.readU8(),o=e.readU8(),l=e.readU8(),h=D(e,i),d=e.readU8(),c=e.readU8();return{...r,x1:a,y1:n,x2:o,y2:l,filled:!1,char:h,fg:c,bg:d}}case B.Ellipse:{let a=e.readU8(),n=e.readU8(),o=e.readU8()+1,l=e.readU8()+1,h=e.readU8()!==0,d=D(e,i),c=e.readU8(),u=e.readU8();return{...r,x:a,y:n,radiusX:o,radiusY:l,filled:h,char:d,fg:u,bg:c}}case B.Triangle:{let a=e.readU8(),n=e.readU8(),o=e.readU8(),l=e.readU8(),h=e.readU8(),d=e.readU8(),c=e.readU8()!==0,u=D(e,i),f=e.readU8(),p=e.readU8();return{...r,x1:a,y1:n,x2:o,y2:l,x3:h,y3:d,filled:c,char:u,fg:p,bg:f}}default:return r}}static decodePolyline(e,i){let s=D(e,i),r=e.readU8(),a=e.readU8(),n=e.readU8(),o=new Array(n);for(let l=0;l<n;l++)o[l]={x:e.readU8(),y:e.readU8()};return{type:g.Polyline,points:o,char:s,fg:r,bg:a}}static decodeDotCloud(e,i){let s=D(e,i),r=e.readU8(),a=e.readU8(),n=e.readU16BE(),o=new Array(n);for(let l=0;l<n;l++)o[l]={x:e.readU8(),y:e.readU8()};return{type:g.DotCloud,positions:o,char:s,fg:a,bg:r}}static decodeDotCloudMulti(e,i){let s=e.readU16BE(),r=new Array(s);for(let a=0;a<s;a++){let n=D(e,i),o=e.readU8(),l=e.readU8(),h=e.readU8(),d=e.readU8();r[a]={x:h,y:d,char:n,fg:l,bg:o}}return{type:g.DotCloudMulti,dots:r}}static decodeSpriteCloud(e){let i=e.readU8(),s=e.readU8(),r=e.readU8(),a=e.readU16BE(),n=new Array(a);for(let o=0;o<a;o++)n[o]={x:e.readU8(),y:e.readU8()};return{type:g.SpriteCloud,positions:n,spriteId:i,fg:r,bg:s}}static decodeSpriteCloudMulti(e){let i=e.readU8(),s=e.readU16BE(),r=new Array(s);for(let a=0;a<s;a++)r[a]={x:e.readU8(),y:e.readU8()};return{type:g.SpriteCloudMulti,positions:r,spriteId:i}}static decodeSpriteCloudVaried(e){let i=e.readU16BE(),s=new Array(i);for(let r=0;r<i;r++){let a=e.readU8(),n=e.readU8(),o=e.readU8(),l=e.readU8(),h=e.readU8();s[r]={x:l,y:h,spriteId:a,fg:o,bg:n}}return{type:g.SpriteCloudVaried,sprites:s}}static decodeSpriteCloudVariedMulti(e){let i=e.readU16BE(),s=new Array(i);for(let r=0;r<i;r++){let a=e.readU8(),n=e.readU8(),o=e.readU8();s[r]={x:n,y:o,spriteId:a}}return{type:g.SpriteCloudVariedMulti,sprites:s}}static decodeBitmask(e,i){let s=e.readU8(),r=e.readU8(),a=e.readU8()+1,n=e.readU8()+1,o=D(e,i),l=e.readU8(),h=e.readU8(),d=e.readU8()!==0,c=Math.ceil(a*n/8),u=e.readBytes(c);return{type:g.Bitmask,x:s,y:r,width:a,height:n,mask:u,char:o,fg:h,bg:l,override:d}}static decodeBitmask4(e,i){let s=e.readU8(),r=e.readU8(),a=e.readU8()+1,n=e.readU8()+1,o=e.readU8()!==0,l=[{char:0,fg:0,bg:0},{char:0,fg:0,bg:0},{char:0,fg:0,bg:0}];for(let c=0;c<3;c++)l[c].char=D(e,i),l[c].bg=e.readU8(),l[c].fg=e.readU8();let h=Math.ceil(a*n*2/8),d=e.readBytes(h);return{type:g.Bitmask4,x:s,y:r,width:a,height:n,mask:d,variants:l,override:o}}static decodeBitmask16(e,i){let s=e.readU8(),r=e.readU8(),a=e.readU8()+1,n=e.readU8()+1,o=e.readU8()!==0,l=e.readU8(),h=new Array(l);for(let u=0;u<l;u++){let f=D(e,i),p=e.readU8(),m=e.readU8();h[u]={char:f,fg:m,bg:p}}let d=Math.ceil(a*n*4/8),c=e.readBytes(d);return{type:g.Bitmask16,x:s,y:r,width:a,height:n,mask:c,variants:h,override:o}}static decodeFill(e,i){let s=D(e,i),r=e.readU8(),a=e.readU8();return{type:g.Fill,char:s,fg:a,bg:r}}static decodeFillChar(e,i){let s=e.readU8()+1,r=e.readU8()+1,a=e.readU8(),n=e.readU8(),o=s*r,l=new Array(o);for(let h=0;h<o;h++)l[h]=D(e,i);return{type:g.FillChar,patternWidth:s,patternHeight:r,pattern:l,fg:n,bg:a}}static decodeFillSprite(e){let i=e.readU8(),s=e.readU8(),r=e.readU8();return{type:g.FillSprite,spriteId:i,fg:r,bg:s}}static decodeFillSpriteMulti(e){let i=e.readU8();return{type:g.FillSpriteMulti,spriteId:i}}},qi=32,$i=64,ji=class{view;buf;offset;constructor(t,e=0){this.buf=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.offset=e}get remaining(){return this.buf.length-this.offset}get rawBuffer(){return this.buf}readU8(){return this.buf[this.offset++]}readI8(){let t=this.view.getInt8(this.offset);return this.offset+=1,t}readU16BE(){let t=this.view.getUint16(this.offset,!1);return this.offset+=2,t}readI16BE(){let t=this.view.getInt16(this.offset,!1);return this.offset+=2,t}readBytes(t){let e=this.buf.slice(this.offset,this.offset+t);return this.offset+=t,e}},Te=new TextDecoder,Vt=class X{static decode(e){let i=new ji(e),s=i.offset,r=i.readU8(),a=new Array(r);for(let A=0;A<r;A++){let K=i.readU8(),ae=i.readI16BE(),J=i.readI16BE(),He=i.readU16BE(),Ce=i.readU16BE(),We=i.readU8(),Ge=i.readU8(),Ye=i.readU8(),ve=i.readU8(),ne=i.readU8(),oe;if(ne>0){oe=new Array(ne);for(let le=0;le<ne;le++)oe[le]={id:i.readU8(),zMin:i.readU8(),zMax:i.readU8(),enabled:(i.readU8()&1)!==0}}a[A]={id:K,originX:ae,originY:J,width:He,height:Ce,paletteSlot:We,scalingMode:Ge,cellWidth:Ye,cellHeight:ve,renderPasses:oe}}let n=i.offset-s,o=i.offset,l=i.readU8(),h=new Array(l);for(let A=0;A<l;A++){let K=i.readU8(),ae=new Array(256);for(let J=0;J<256;J++)ae[J]={colorId:J,r:i.readU8(),g:i.readU8(),b:i.readU8(),a:i.readU8()};h[A]={slot:K,colors:ae}}let d=i.offset-o,c=i.offset,u=i.readU16BE(),f=new Array(u);for(let A=0;A<u;A++){let K=i.offset,ae=i.readU16BE(),J=i.readU8(),He=(J&qi)!==0,Ce=(J&$i)!==0,We=i.readI8(),Ge=i.readI16BE(),Ye=i.readI16BE(),ve=i.readU16BE(),ne=i.readU16BE(),oe=i.readU16BE(),le=[];oe>0&&(le=X.decodeOrders(i,oe,Ce,ve,ne));let si=i.offset-K;f[A]={id:ae,isMacro:He,is16bit:Ce,zIndex:We,originX:Ge,originY:Ye,width:ve,height:ne,orders:le,byteSize:si}}let p=i.offset-c,m=i.offset,y=i.readU8(),C=new Array(y);for(let A=0;A<y;A++)C[A]=X.decodeAudioOrder(i);let v=i.offset-m,x=i.offset,E=i.readU8(),P=new Array(E);for(let A=0;A<E;A++)P[A]=X.decodeVibrationOrder(i);let L=i.offset-x,z=i.offset,O=[];if(i.remaining>=2){let A=i.readU16BE();O=new Array(A);for(let K=0;K<A;K++)O[K]=X.decodeMacroDefine(i)}let W=i.offset-z,q=i.offset,Ve=[];if(i.remaining>=2){let A=i.readU16BE();Ve=new Array(A);for(let K=0;K<A;K++)Ve[K]=X.decodeMacroOrder(i)}let ti=i.offset-q;i.remaining>0&&i.readU8();let ii={displays:n,palettes:d,layers:p,audio:v,vibration:L,macroDefines:W,macroOrders:ti,total:e.byteLength};return{displays:a,palettes:h,layers:f,audioOrders:C,vibrationOrders:P,macroDefines:O,macroOrders:Ve,sectionSizes:ii}}static decodeOrders(e,i,s,r,a){let n=e.offset;for(let h=0;h<i;h++)X.skipOneOrder(e,s,r,a);let o=e.offset-n,l=new Uint8Array(e.rawBuffer.buffer,e.rawBuffer.byteOffset+n,o);return Qi.decode(l,s,r,a)}static skipOneOrder(e,i,s,r){let a=e.readU8(),n=i?2:1;switch(a){case 1:e.offset+=2+n+2;break;case 2:case 23:{e.offset+=2;let o=e.readU8();e.offset+=o+2;break}case 3:{e.offset+=2;let o=e.readU8()+1,l=e.readU8()+1;e.offset+=2,e.offset+=o*l*n;break}case 4:{e.offset+=2;let o=e.readU8()+1,l=e.readU8()+1;e.offset+=o*l*(n+2);break}case 5:{e.offset+=2,e.offset+=s*r*n;break}case 6:e.offset+=s*r*(n+2);break;case 7:e.offset+=5;break;case 8:e.offset+=3;break;case 9:{e.offset+=2;let o=e.readU8()+1,l=e.readU8()+1;e.offset+=o*l*2;break}case 10:{switch(e.readU8()){case 1:e.offset+=5+n+2;break;case 2:e.offset+=4+n+2;break;case 3:e.offset+=4+n+2;break;case 4:e.offset+=5+n+2;break;case 5:e.offset+=7+n+2;break}break}case 25:{e.offset+=n+2;let o=e.readU8();e.offset+=o*2;break}case 11:{e.offset+=n+2;let o=e.readU16BE();e.offset+=o*2;break}case 12:{let o=e.readU16BE();e.offset+=o*(n+2+2);break}case 13:{e.offset+=3;let o=e.readU16BE();e.offset+=o*2;break}case 14:{e.offset+=1;let o=e.readU16BE();e.offset+=o*2;break}case 15:{let o=e.readU16BE();e.offset+=o*5;break}case 16:{let o=e.readU16BE();e.offset+=o*3;break}case 17:{e.offset+=2;let o=e.readU8()+1,l=e.readU8()+1;e.offset+=n+2+1,e.offset+=Math.ceil(o*l/8);break}case 18:{e.offset+=2;let o=e.readU8()+1,l=e.readU8()+1;e.offset+=1,e.offset+=3*(n+2),e.offset+=Math.ceil(o*l*2/8);break}case 24:{e.offset+=2;let o=e.readU8()+1,l=e.readU8()+1;e.offset+=1;let h=e.readU8();e.offset+=h*(n+2),e.offset+=Math.ceil(o*l*4/8);break}case 19:e.offset+=n+2;break;case 20:{let o=e.readU8()+1,l=e.readU8()+1;e.offset+=2,e.offset+=o*l*n;break}case 21:e.offset+=3;break;case 22:e.offset+=1;break;default:break}}static decodeAudioOrder(e){switch(e.readU8()){case 1:{let i=X.decodeSoundTarget(e),s=e.readU16BE(),r=e.readU8(),a={type:g.Audio,sound:i,instanceId:s};return r&1&&(a.volume=e.readU8()/255),r&2&&(a.pitch=e.readU8()/100),r&4&&(a.fadeIn=e.readU16BE()/1e3),r&8&&(a.x=e.readI16BE(),a.y=e.readI16BE()),r&16&&(a.lowpass=e.readU16BE()),r&32&&(a.highpass=e.readU16BE()),r&64&&(a.reverb=e.readU8()/255),r&128&&(a.loop=!0),a}case 2:{let i=X.decodeSoundTarget(e);return{type:g.Audio,sound:i,stop:!0}}case 3:{let i=X.decodeSoundTarget(e),s=e.readU16BE();return{type:g.Audio,sound:i,fadeOut:s/1e3}}case 4:{let i=X.decodeSoundTarget(e);return{type:g.Audio,sound:i,pause:!0}}case 5:{let i=X.decodeSoundTarget(e);return{type:g.Audio,sound:i,resume:!0}}case 6:{let i=e.readU16BE(),s=e.readU8(),r={type:g.Audio,sound:i};return s&1&&(r.lowpass=e.readU16BE()),s&2&&(r.highpass=e.readU16BE()),s&4&&(r.reverb=e.readU8()/255),s&8&&(r.pitch=e.readU8()/100),s&16&&(r.volume=e.readU8()/255),r}case 7:{let i=e.readI16BE(),s=e.readI16BE();return{type:g.Audio,sound:"__listener_position__",x:i,y:s}}case 8:{let i=e.readU16BE(),s=e.readU16BE(),r=e.readU8(),a=e.readU8();return{type:g.Audio,sound:"__configure_spatial__",maxDistance:i,referenceDistance:s,rolloffFactor:r,panSpread:a}}default:return{type:g.Audio,sound:0}}}static decodeSoundTarget(e){switch(e.readU8()){case 0:return e.readU16BE();case 1:return"all";case 2:{let i=e.readU8(),s=e.readBytes(i);return Te.decode(s)}default:return 0}}static decodeVibrationOrder(e){if(e.readU8()===1){let r=e.readU8(),a=e.readU16BE(),n=e.readU8()/255,o=e.readU8()/255,l=e.readU16BE();return{type:g.Vibration,target:"gamepad",gamepadIndex:r,duration:a,strongMagnitude:n,weakMagnitude:o,startDelay:l}}let i=e.readU8();if(i===1)return{type:g.Vibration,pattern:e.readU16BE()};let s=new Array(i);for(let r=0;r<i;r++)s[r]=e.readU16BE();return{type:g.Vibration,pattern:s}}static decodeMacroDefine(e){let i=e.readU16BE(),s=e.readU16BE(),r=e.readBytes(s),a=JSON.parse(Te.decode(r));return{templateId:i,template:a}}static decodeMacroOrder(e){let i=e.readU8(),s=e.readU16BE();switch(i){case 1:{let r=e.readU16BE(),a=e.readU16BE(),n=e.readI16BE(),o=e.readI16BE(),l=e.readU8(),h=e.readU16BE(),d;if(h>0){let c=e.readBytes(h);d=JSON.parse(Te.decode(c))}return{cmd:i,instanceId:s,templateId:r,layerId:a,x:n,y:o,zIndex:l,params:d??{}}}case 2:{let r=e.readU16BE(),a=e.readBytes(r),n=JSON.parse(Te.decode(a));return{cmd:i,instanceId:s,params:n}}case 3:return{cmd:i,instanceId:s};case 4:return{cmd:i,instanceId:s};case 5:return{cmd:i,instanceId:s};default:return{cmd:i,instanceId:s}}}};var w={HandshakeRequest:1,HandshakeResponse:2,HandshakeStateClient:3,HandshakeStateServer:4,Ping:5,Pong:6,LoadBundle:16,LoadBundleFrag:17,UpdateReliable:32,UpdateReliableFrag:33,UpdateVolatile:34,UpdateVolatileFrag:35,EmptyUpdate:36,InputReliable:48,InputReliableFrag:49,InputVolatile:50,InputVolatileFrag:51,AudioOrder:64,HapticOrder:65,PostProcessOrder:66,MacroOrder:67,BridgeToServer:80,BridgeToServerFrag:81,BridgeToClient:82,BridgeToClientFrag:83,ClientCallback:96,ClientCallbackFrag:97};function Gt(t){return t===w.LoadBundleFrag||t===w.UpdateReliableFrag||t===w.UpdateVolatileFrag||t===w.InputReliableFrag||t===w.InputVolatileFrag||t===w.BridgeToServerFrag||t===w.BridgeToClientFrag||t===w.ClientCallbackFrag}function Ji(t){switch(t){case w.LoadBundle:return w.LoadBundleFrag;case w.UpdateReliable:return w.UpdateReliableFrag;case w.UpdateVolatile:return w.UpdateVolatileFrag;case w.InputReliable:return w.InputReliableFrag;case w.InputVolatile:return w.InputVolatileFrag;case w.BridgeToServer:return w.BridgeToServerFrag;case w.BridgeToClient:return w.BridgeToClientFrag;case w.ClientCallback:return w.ClientCallbackFrag;default:return t}}function Ht(t){return t<=15||t===w.LoadBundle||t===w.LoadBundleFrag||t===w.UpdateReliable||t===w.UpdateReliableFrag||t===w.InputReliable||t===w.InputReliableFrag||t>=80}var re=(t=>(t[t.OK=0]="OK",t[t.VersionMismatch=1]="VersionMismatch",t[t.ServerFull=2]="ServerFull",t[t.AuthFailed=3]="AuthFailed",t))(re||{}),S=(t=>(t[t.Connected=0]="Connected",t[t.WaitingForResponse=1]="WaitingForResponse",t[t.Authenticating=2]="Authenticating",t[t.LoadingAssets=3]="LoadingAssets",t[t.Ready=4]="Ready",t[t.InSimulation=5]="InSimulation",t[t.Disconnected=255]="Disconnected",t))(S||{}),te=class ge{high;low;constructor(e,i){this.high=e>>>0,this.low=i>>>0}static ZERO=new ge(0,0);static from(e){let i=Number(e>>32n&0xffffffffn),s=Number(e&0xffffffffn);return new ge(i,s)}static fromNumber(e){if(e<0)throw new Error("Tick must be positive");let i=Math.floor(e/4294967296),s=e>>>0;return new ge(i,s)}static fromBuffer(e,i=0){let s=(e[i]<<24|e[i+1]<<16|e[i+2]<<8|e[i+3])>>>0,r=(e[i+4]<<24|e[i+5]<<16|e[i+6]<<8|e[i+7])>>>0;return new ge(s,r)}toBigInt(){return BigInt(this.high)<<32n|BigInt(this.low)}toNumber(){return this.high*4294967296+this.low}toBuffer(){let e=new Uint8Array(8);return this.writeToBuffer(e,0),e}writeToBuffer(e,i=0){e[i]=this.high>>>24&255,e[i+1]=this.high>>>16&255,e[i+2]=this.high>>>8&255,e[i+3]=this.high&255,e[i+4]=this.low>>>24&255,e[i+5]=this.low>>>16&255,e[i+6]=this.low>>>8&255,e[i+7]=this.low&255}increment(){let e=this.low+1,i=this.high;return e>4294967295&&(e=0,i++),new ge(i,e)}compare(e){return this.high!==e.high?this.high-e.high:this.low-e.low}equals(e){return this.high===e.high&&this.low===e.low}isZero(){return this.high===0&&this.low===0}toString(){return`Tick(${this.toBigInt()})`}getHigh(){return this.high}getLow(){return this.low}};function _i(t,e,i){let s=t.fragInfo!==void 0;return e[i]=t.marker,s&&t.fragInfo?(e[i+1]=t.fragInfo.totalChunks>>>8&255,e[i+2]=t.fragInfo.totalChunks&255,e[i+3]=t.fragInfo.chunkIndex>>>8&255,e[i+4]=t.fragInfo.chunkIndex&255,t.tick.writeToBuffer(e,i+5),13):(t.tick.writeToBuffer(e,i+1),9)}function es(t){if(t.length<9)throw new Error(`Buffer too small for header: ${t.length} < 9`);let e=t[0];if(Gt(e)){if(t.length<13)throw new Error(`Buffer too small for frag header: ${t.length} < 13`);let s=t[1]<<8|t[2],r=t[3]<<8|t[4],a=te.fromBuffer(t,5);return{header:{marker:e,tick:a,fragInfo:{totalChunks:s,chunkIndex:r}},payloadOffset:13}}let i=te.fromBuffer(t,1);return{header:{marker:e,tick:i},payloadOffset:9}}function we(t,e){let i=t.fragInfo!==void 0?13:9,s=e?e.length:0,r=new Uint8Array(i+s);return _i(t,r,0),s>0&&r.set(e,i),r}function Wt(t,e,i,s){let r=s?.mtu??1200,a=r-13;if(i.length+9<=r)return[we({marker:t,tick:e},i)];let n=Ji(t);if(n===t)throw new Error(`Packet with marker 0x${t.toString(16)} exceeds MTU (${r}) but has no fragmentation variant.`);let o=Math.ceil(i.length/a),l=[];for(let h=0;h<o;h++){let d=h*a,c=Math.min(d+a,i.length),u=i.subarray(d,c),f={marker:n,tick:e,fragInfo:{totalChunks:o,chunkIndex:h}};l.push(we(f,u))}return l}function ts(t,e){return`${t}:${e.getHigh()}:${e.getLow()}`}var Yt=class{buckets=new Map;ttlMs;constructor(t){this.ttlMs=t?.ttlMs??1e4}receive(t){let{header:e,payloadOffset:i}=es(t),s=t.subarray(i);return!Gt(e.marker)||!e.fragInfo?{marker:e.marker,tick:e.tick,payload:s}:this.handleFragment(e,s)}handleFragment(t,e){let{marker:i,tick:s,fragInfo:r}=t;if(!r)return null;let a=ts(i,s),n=this.buckets.get(a);if(n||(n={marker:i,tick:s,totalChunks:r.totalChunks,receivedCount:0,chunks:new Array(r.totalChunks).fill(null),createdAt:Date.now()},this.buckets.set(a,n)),r.chunkIndex>=n.totalChunks)return null;if(n.chunks[r.chunkIndex]===null&&(n.chunks[r.chunkIndex]=e,n.receivedCount++),n.receivedCount===n.totalChunks){let o=0;for(let d=0;d<n.chunks.length;d++)n.chunks[d]&&(o+=n.chunks[d].length);let l=new Uint8Array(o),h=0;for(let d of n.chunks)d&&(l.set(d,h),h+=d.length);return this.buckets.delete(a),{marker:i,tick:s,payload:l}}return null}cleanup(){let t=Date.now(),e=0;for(let[i,s]of this.buckets)t-s.createdAt>this.ttlMs&&(this.buckets.delete(i),e++);return e}getPendingCount(){return this.buckets.size}clearTick(t){for(let[e,i]of this.buckets)i.tick.equals(t)&&this.buckets.delete(e)}destroy(){this.buckets.clear()}},zt=class{transport;backgroundQueue=[];immediateQueue=[];bgCursor=0;imCursor=0;options;constructor(t,e={}){this.transport=t,this.options={fragmentsPerTick:e.fragmentsPerTick??5,bufferedThreshold:e.bufferedThreshold??16384}}enqueue(t,e,i){let s=Ht(t),r=Wt(t,e,i);for(let a of r)this.backgroundQueue.push({data:a,reliable:s})}enqueueImmediate(t,e,i){let s=Ht(t),r=Wt(t,e,i);for(let a of r)this.immediateQueue.push({data:a,reliable:s})}enqueueRawImmediate(t,e){this.immediateQueue.push({data:t,reliable:e})}flush(){if(!this.transport.isReady())return;for(;this.imCursor<this.immediateQueue.length;){let i=this.immediateQueue[this.imCursor++];this.transport.send(i.data,i.reliable)}this.imCursor>0&&(this.immediateQueue.length=0,this.imCursor=0);let t=0,e=this.options.fragmentsPerTick;for(;this.bgCursor<this.backgroundQueue.length&&t<e&&this.transport.getBufferedAmount()<this.options.bufferedThreshold;){let i=this.backgroundQueue[this.bgCursor++];this.transport.send(i.data,i.reliable),t++}this.bgCursor>0&&this.bgCursor>=this.backgroundQueue.length?(this.backgroundQueue.length=0,this.bgCursor=0):this.bgCursor>256&&(this.backgroundQueue.splice(0,this.bgCursor),this.bgCursor=0)}clear(){this.backgroundQueue.length=0,this.immediateQueue.length=0,this.bgCursor=0,this.imCursor=0}getPendingCount(){return this.backgroundQueue.length-this.bgCursor}hasImmediatePending(){return this.imCursor<this.immediateQueue.length}},Fe={AudioAck:1,MacroFeedback:2},is=1,ss=2,rs=3,as=4,ns=5,fe=new TextEncoder,wr=new TextDecoder;function at(t){let e=[];if(t.audioAcks.length>0&&e.push({type:Fe.AudioAck,payload:os(t.audioAcks)}),t.macroFeedbacks.length>0&&e.push({type:Fe.MacroFeedback,payload:ls(t.macroFeedbacks)}),e.length===0)return new Uint8Array(0);let i=1;for(let a of e)i+=2+a.payload.byteLength;let s=new Uint8Array(i),r=0;s[r++]=e.length;for(let a of e)s[r++]=a.type,a.type===Fe.AudioAck?s[r++]=t.audioAcks.length:a.type===Fe.MacroFeedback?s[r++]=t.macroFeedbacks.length:s[r++]=0,s.set(a.payload,r),r+=a.payload.byteLength;return s}function os(t){let e=0,i=[];for(let n of t)switch(n.type){case"sound-loaded":{let o=fe.encode(n.name);i.push({name:o}),e+=4+o.byteLength;break}case"sound-error":{let o=fe.encode(n.name),l=fe.encode(n.error);i.push({name:o,error:l}),e+=4+o.byteLength+1+l.byteLength;break}case"playback-started":i.push({}),e+=7;break;case"playback-ended":i.push({}),e+=7;break;case"playback-error":{let o=fe.encode(n.error);i.push({error:o}),e+=2+(n.instanceId!=null?4:0)+2+1+o.byteLength;break}}let s=new Uint8Array(e),r=new DataView(s.buffer),a=0;for(let n=0;n<t.length;n++){let o=t[n],l=i[n];switch(o.type){case"sound-loaded":s[a++]=is,r.setUint16(a,o.soundId,!1),a+=2,s[a++]=l.name.byteLength,s.set(l.name,a),a+=l.name.byteLength;break;case"sound-error":s[a++]=ss,r.setUint16(a,o.soundId,!1),a+=2,s[a++]=l.name.byteLength,s.set(l.name,a),a+=l.name.byteLength,s[a++]=l.error.byteLength,s.set(l.error,a),a+=l.error.byteLength;break;case"playback-started":s[a++]=rs,r.setUint32(a,o.instanceId,!1),a+=4,r.setUint16(a,o.soundId,!1),a+=2;break;case"playback-ended":s[a++]=as,r.setUint32(a,o.instanceId,!1),a+=4,r.setUint16(a,o.soundId,!1),a+=2;break;case"playback-error":{s[a++]=ns;let h=o.instanceId!=null?1:0;s[a++]=h,h&&(r.setUint32(a,o.instanceId,!1),a+=4);let d=typeof o.sound=="number"?o.sound:0;r.setUint16(a,d,!1),a+=2,s[a++]=l.error.byteLength,s.set(l.error,a),a+=l.error.byteLength;break}}}return s}function ls(t){let e=0,i=[];for(let n of t)switch(e+=3,n.cmd){case 1:i.push(null);break;case 2:i.push(null),e+=1+(n.valueType==="number"?2:1);break;case 3:{let o=fe.encode(n.text);i.push(o),e+=2+o.byteLength;break}case 4:i.push(null),e+=2;break;case 5:{let o=fe.encode(n.data);i.push(o),e+=2+o.byteLength;break}}let s=new Uint8Array(e),r=new DataView(s.buffer),a=0;for(let n=0;n<t.length;n++){let o=t[n];switch(s[a++]=o.cmd,r.setUint16(a,o.instanceId,!1),a+=2,o.cmd){case 1:break;case 2:o.valueType==="number"?(s[a++]=0,r.setUint16(a,o.value,!1),a+=2):(s[a++]=1,s[a++]=o.value?1:0);break;case 3:{let l=i[n];r.setUint16(a,l.byteLength,!1),a+=2,s.set(l,a),a+=l.byteLength;break}case 4:r.setUint16(a,o.index,!1),a+=2;break;case 5:{let l=i[n];r.setUint16(a,l.byteLength,!1),a+=2,s.set(l,a),a+=l.byteLength;break}}}return s}var I=(t=>(t[t.Connecting=0]="Connecting",t[t.Open=1]="Open",t[t.Closing=2]="Closing",t[t.Closed=3]="Closed",t))(I||{}),Kt=class{onMessage=null;onStateChange=null;onError=null;send(t,e){this.onMessage?.(t)}getState(){return 1}getBufferedAmount(){return 0}isReady(){return!0}close(t,e){}},Nt="reliable",Zt="unreliable";var hs=class{state=S.Connected;transport=null;serverConfig=null;callbacks;constructor(t={}){this.callbacks=t}bind(t){this.transport=t}getState(){return this.state}getServerConfig(){return this.serverConfig}sendRequest(t){if(!this.transport)throw new Error("Transport not bound");if(this.state!==S.Connected){this.callbacks.onError?.(`Cannot send HandshakeRequest in state ${this.state}`);return}let e=new Uint8Array(3);e[0]=t.major,e[1]=t.minor,e[2]=t.patch;let i={marker:w.HandshakeRequest,tick:te.ZERO};this.transport.send(we(i,e),!0),this.setState(S.WaitingForResponse)}sendAuth(t,e){if(!this.transport)throw new Error("Transport not bound");if(this.state!==S.Authenticating){this.callbacks.onError?.(`Cannot send Auth in state ${this.state}`);return}let i=new TextEncoder().encode(t),s=new TextEncoder().encode(e),r=new Uint8Array(2+i.length+s.length);r[0]=i.length,r.set(i,1),r[1+i.length]=s.length,r.set(s,2+i.length),this.sendState(S.Authenticating,r)}sendLoadingProgress(t){if(this.state!==S.LoadingAssets)return;let e=new Uint8Array([Math.min(100,Math.max(0,t))]);this.sendState(S.LoadingAssets,e)}sendReady(){if(this.state!==S.LoadingAssets){this.callbacks.onError?.(`Cannot send Ready in state ${this.state}`);return}this.sendState(S.Ready)}handleResponse(t){if(this.state!==S.WaitingForResponse){this.callbacks.onError?.(`Unexpected HandshakeResponse in state ${this.state}`);return}if(t.length<14){this.callbacks.onError?.("Invalid HandshakeResponse: too short");return}let e=t[0],i=t[1],s=t[2],r=te.fromBuffer(t,3),a=t[11]<<8|t[12],n=t[13];if(this.serverConfig={status:e,serverVersion:{major:i,minor:s},startTick:r,clientId:a,tickRate:n},this.callbacks.onServerConfig?.(this.serverConfig),e!==re.OK){let o={[re.OK]:"",[re.VersionMismatch]:"Version mismatch",[re.ServerFull]:"Server full",[re.AuthFailed]:"Authentication failed"};this.callbacks.onError?.(o[e]||"Unknown error"),this.setState(S.Disconnected);return}this.setState(S.Authenticating)}handleServerState(t){if(t.length<1)return;let e=t[0];switch(e){case S.LoadingAssets:if(this.state!==S.Authenticating){this.callbacks.onError?.(`Unexpected LoadingAssets from server in state ${this.state}`);return}this.setState(S.LoadingAssets);break;case S.Ready:if(this.state!==S.LoadingAssets){this.callbacks.onError?.(`Unexpected Ready from server in state ${this.state}`);return}this.setState(S.Ready);break;case S.InSimulation:if(this.state!==S.Ready&&this.state!==S.LoadingAssets){this.callbacks.onError?.(`Unexpected InSimulation from server in state ${this.state}`);return}this.setState(S.InSimulation),this.callbacks.onReady?.();break;case S.Disconnected:if(t.length>2){let i=t[1],s=new TextDecoder().decode(t.slice(2,2+i));this.callbacks.onError?.(s)}this.setState(S.Disconnected);break;default:this.callbacks.onError?.(`Unknown server state: 0x${e.toString(16)}`);break}}sendState(t,e){if(!this.transport)throw new Error("Transport not bound");let i=new Uint8Array(1+(e?.length??0));i[0]=t,e&&i.set(e,1);let s={marker:w.HandshakeStateClient,tick:te.ZERO};this.transport.send(we(s,i),!0)}setState(t){this.state=t,this.callbacks.onStateChange?.(t)}isComplete(){return this.state===S.InSimulation}},De=class{transport=null;assembler;interleaving=null;handshake;callbacks;options;currentTick=te.ZERO;t=0;n=0;constructor(t,e={}){this.options=t,this.callbacks=e,this.assembler=new Yt,this.handshake=new hs({onStateChange:i=>this.callbacks.onHandshakeState?.(i),onServerConfig:i=>{this.currentTick=i.startTick,this.callbacks.onServerConfig?.(i)},onError:i=>this.callbacks.onError?.(i),onReady:()=>this.callbacks.onSimulationStart?.()})}async connect(t,e){this.transport=t,this.interleaving=new zt(t),t.onMessage=i=>this.handleMessage(i),t.onStateChange=i=>{i===I.Closed&&this.callbacks.onDisconnect?.("Transport closed")},t.onError=i=>this.callbacks.onError?.(i.message),await t.connect(e),this.handshake.bind(t),this.handshake.sendRequest(this.options.version)}flush(){this.interleaving?.flush()}handleMessage(t){let e=this.assembler.receive(t);e&&this.processPacket(e)}processPacket(t){let{marker:e,tick:i,payload:s}=t;switch(e){case w.HandshakeResponse:this.handshake.handleResponse(s),this.handshake.getState()===S.Authenticating&&this.handshake.sendAuth(this.options.username,this.options.token??"");break;case w.HandshakeStateServer:this.handshake.handleServerState(s);break;case w.Ping:this.sendPong(s);break;case w.Pong:this.t>0&&(this.n=Date.now()-this.t,this.t=0);break;case w.UpdateReliable:case w.UpdateReliableFrag:this.currentTick=i,this.callbacks.onUpdate?.(i,s,!0);break;case w.UpdateVolatile:case w.UpdateVolatileFrag:case w.EmptyUpdate:this.currentTick=i,this.callbacks.onUpdate?.(i,s,!1);break;case w.LoadBundle:case w.LoadBundleFrag:this.callbacks.onLoadBundle?.(i,s);break;case w.BridgeToClient:case w.BridgeToClientFrag:this.callbacks.onBridgeMessage?.(s);break}}sendInput(t,e=!1){if(!this.interleaving)return;let i=e?w.InputReliable:w.InputVolatile;this.interleaving.enqueueImmediate(i,this.currentTick,t)}sendPing(){this.interleaving&&(this.t=Date.now(),this.interleaving.enqueueImmediate(w.Ping,this.currentTick,new Uint8Array(0)))}sendPong(t){this.interleaving&&this.interleaving.enqueueImmediate(w.Pong,this.currentTick,t)}sendBridgeMessage(t){this.interleaving&&this.interleaving.enqueue(w.BridgeToServer,this.currentTick,t)}sendClientCallback(t){!this.interleaving||t.byteLength===0||this.interleaving.enqueue(w.ClientCallback,this.currentTick,t)}getRtt(){return this.n}getHandshakeState(){return this.handshake.getState()}getServerConfig(){return this.handshake.getServerConfig()}getCurrentTick(){return this.currentTick}sendLoadingProgress(t){this.handshake.sendLoadingProgress(t)}sendReady(){this.handshake.sendReady()}disconnect(t){this.transport?.close(1e3,t),this.assembler.destroy()}isInSimulation(){return this.handshake.isComplete()}},nt=U.create("network:ws-client"),Pe=class{socket=null;e=I.Closed;onMessage=null;onStateChange=null;onError=null;async connect(t){return new Promise((e,i)=>{try{this.socket=new WebSocket(t),this.socket.binaryType="arraybuffer",this.e=I.Connecting,this.onStateChange?.(I.Connecting),this.socket.onopen=()=>{this.e=I.Open,this.onStateChange?.(I.Open),e()},this.socket.onmessage=s=>{this.onMessage&&s.data instanceof ArrayBuffer&&(nt.trace(()=>`onmessage size=${s.data.byteLength}, readyState=${this.socket?.readyState}`),this.onMessage(new Uint8Array(s.data)))},this.socket.onerror=()=>{nt.warn("WebSocket error fired");let s=new Error("WebSocket error");this.onError?.(s),this.e===I.Connecting&&i(s)},this.socket.onclose=s=>{nt.info("Connection closed",{code:s.code,reason:s.reason,wasClean:s.wasClean}),this.e=I.Closed,this.onStateChange?.(I.Closed)}}catch(s){this.e=I.Closed,i(s)}})}send(t,e){!this.socket||this.socket.readyState!==WebSocket.OPEN||this.socket.send(t)}close(t,e){this.socket&&(this.e=I.Closing,this.onStateChange?.(I.Closing),this.socket.close(t,e))}getState(){return this.e}getBufferedAmount(){return this.socket?.bufferedAmount??0}isReady(){return this.e===I.Open}},Xt=class{constructor(t={mode:"full"}){this.config=t}signalingWs=null;pc=null;reliableDc=null;unreliableDc=null;e=I.Closed;onMessage=null;onStateChange=null;onError=null;async connect(t){let e=t??this.config.signalingUrl;if(!e)throw new Error("WebRTCClient.connect(): no URL provided and config.signalingUrl is not set");return new Promise((i,s)=>{this.e=I.Connecting,this.onStateChange?.(I.Connecting);try{this.signalingWs=new WebSocket(e)}catch(h){this.e=I.Closed,s(h);return}let r=!1,a=!1,n=!1,o=()=>{r&&a&&!n&&(n=!0,this.e=I.Open,this.onStateChange?.(I.Open),i())},l=h=>{n||(n=!0,this.teardown(),s(h))};this.signalingWs.onopen=async()=>{try{let h={};this.config.mode==="full"&&this.config.stunServers?.length&&(h.iceServers=this.config.stunServers.map(f=>({urls:f}))),this.pc=new RTCPeerConnection(h),this.reliableDc=this.pc.createDataChannel(Nt,{ordered:!0}),this.reliableDc.binaryType="arraybuffer",this.unreliableDc=this.pc.createDataChannel(Zt,{ordered:!1,maxRetransmits:0}),this.unreliableDc.binaryType="arraybuffer",this.reliableDc.onopen=()=>{r=!0,o()},this.unreliableDc.onopen=()=>{a=!0,o()};let d=f=>{this.onMessage&&f.data instanceof ArrayBuffer&&this.onMessage(new Uint8Array(f.data))};this.reliableDc.onmessage=d,this.unreliableDc.onmessage=d;let c=()=>{this.e===I.Open&&(this.e=I.Closed,this.onStateChange?.(I.Closed))};this.reliableDc.onclose=c,this.unreliableDc.onclose=c,this.reliableDc.onerror=()=>this.onError?.(new Error("Reliable DC error")),this.unreliableDc.onerror=()=>this.onError?.(new Error("Unreliable DC error")),this.pc.onicecandidate=f=>{f.candidate&&this.sendSignaling({type:"rtc-candidate",candidate:f.candidate.candidate,mid:f.candidate.sdpMid??"0"})},this.pc.onconnectionstatechange=()=>{let f=this.pc?.connectionState;(f==="failed"||f==="disconnected")&&l(new Error(`WebRTC connection ${f}`))};let u=await this.pc.createOffer();await this.pc.setLocalDescription(u),this.sendSignaling({type:"rtc-offer",sdp:u.sdp})}catch(h){l(h)}},this.signalingWs.onmessage=async h=>{if(typeof h.data=="string")try{let d=JSON.parse(h.data);switch(d.type){case"rtc-answer":await this.pc.setRemoteDescription({type:"answer",sdp:d.sdp});break;case"rtc-candidate":await this.pc.addIceCandidate({candidate:d.candidate,sdpMid:d.mid});break;case"rtc-error":l(new Error(`Server signaling error: ${d.message}`));break}}catch(d){l(d)}},this.signalingWs.onerror=()=>{l(new Error("Signaling WebSocket error"))},this.signalingWs.onclose=()=>{n?this.e===I.Open&&(this.e=I.Closed,this.onStateChange?.(I.Closed),this.teardown()):l(new Error("Signaling WebSocket closed before WebRTC established"))}})}send(t,e){let i=e?this.reliableDc:this.unreliableDc;if(!i||i.readyState!=="open")return;let s=t.buffer;t.byteOffset===0&&t.byteLength===s.byteLength?i.send(s):i.send(t.slice().buffer)}close(t,e){this.e=I.Closing,this.onStateChange?.(I.Closing),this.teardown(t,e)}getState(){return this.e}getBufferedAmount(){let t=this.reliableDc?.bufferedAmount??0,e=this.unreliableDc?.bufferedAmount??0;return t+e}isReady(){return this.e===I.Open}sendSignaling(t){this.signalingWs&&this.signalingWs.readyState===WebSocket.OPEN&&this.signalingWs.send(JSON.stringify(t))}teardown(t,e){try{this.reliableDc?.close()}catch{}try{this.unreliableDc?.close()}catch{}try{this.pc?.close()}catch{}try{this.signalingWs?.close(t??1e3,e)}catch{}this.reliableDc=null,this.unreliableDc=null,this.pc=null,this.signalingWs=null,this.e=I.Closed}};var Qt=U.create("audio:soundbank"),ds=class{sounds=new Map;nameToId=new Map;audioContext;constructor(t){this.audioContext=t}async loadFromData(t,e,i){try{let s=await this.audioContext.decodeAudioData(i.buffer);this.store(t,e,s)}catch(s){throw Qt.error(`Failed to decode sound "${e}" (${t})`,s),s}}async loadFromUrl(t,e,i){try{let s=await(await fetch(i)).arrayBuffer(),r=await this.audioContext.decodeAudioData(s);this.store(t,e,r)}catch(s){throw Qt.error(`Failed to load sound "${e}" from URL ${i}`,s),s}}store(t,e,i){this.sounds.set(t,i),this.nameToId.set(e,t)}get(t){if(typeof t=="number")return this.sounds.get(t);let e=this.nameToId.get(t);return e!==void 0?this.sounds.get(e):void 0}has(t){return this.get(t)!==void 0}clear(){this.sounds.clear(),this.nameToId.clear()}getAll(){let t=[],e=new Map;for(let[i,s]of this.nameToId)e.set(s,i);for(let[i,s]of this.sounds)t.push({soundId:i,name:e.get(i)??`Sound ${i}`,duration:s.duration});return t}},cs=class{instanceId;soundId;name;source;gainNode;pannerNode;lowpassNode;highpassNode;reverbSend;audioContext;destination;t=!1;i=!1;e=1;n=1;position;onEnded;constructor(t,e,i,s,r,a={}){this.audioContext=t,this.instanceId=e,this.soundId=i,this.name=a.name??"",this.destination=r,this.e=a.volume??1,this.position=a.position,this.source=t.createBufferSource(),this.source.buffer=s,this.source.loop=a.loop??!1,this.source.playbackRate.value=a.pitch??1,this.gainNode=t.createGain();let n=a.fadeIn??0;n>0?(this.gainNode.gain.setValueAtTime(0,t.currentTime),this.gainNode.gain.linearRampToValueAtTime(this.e,t.currentTime+n)):this.gainNode.gain.value=this.e,a.position&&(this.pannerNode=t.createStereoPanner()),this.source.connect(this.gainNode),this.pannerNode?(this.gainNode.connect(this.pannerNode),this.pannerNode.connect(this.destination)):this.gainNode.connect(this.destination),a.reverbNode&&(this.reverbSend=t.createGain(),this.reverbSend.gain.value=a.reverb??0,this.gainNode.connect(this.reverbSend),this.reverbSend.connect(a.reverbNode)),a.lowpass&&this.setLowpass(a.lowpass),a.highpass&&this.setHighpass(a.highpass),this.source.onended=()=>{this.i||(this.t=!0,this.onEnded?.())}}start(t=0){this.source.start(0,t)}stop(t=0){this.t||(t>0?(this.gainNode.gain.linearRampToValueAtTime(0,this.audioContext.currentTime+t),setTimeout(()=>this.internalStop(),t*1e3)):this.internalStop())}internalStop(){try{this.source.stop()}catch{}this.t=!0,this.onEnded?.()}setVolume(t,e=0){this.e=t,this.updateTotalVolume(e)}setSpatialVolume(t){this.n=t,this.updateTotalVolume()}updateTotalVolume(t=0){let e=this.e*this.n;t>0?this.gainNode.gain.linearRampToValueAtTime(e,this.audioContext.currentTime+t):this.gainNode.gain.setValueAtTime(e,this.audioContext.currentTime)}setPan(t){this.pannerNode&&this.pannerNode.pan.setValueAtTime(t,this.audioContext.currentTime)}setPitch(t){this.source.playbackRate.setValueAtTime(t,this.audioContext.currentTime)}setLowpass(t){t<=0?this.lowpassNode=void 0:(this.lowpassNode||(this.lowpassNode=this.audioContext.createBiquadFilter(),this.lowpassNode.type="lowpass"),this.lowpassNode.frequency.setValueAtTime(t,this.audioContext.currentTime)),this.updateChain()}setHighpass(t){t<=0?this.highpassNode=void 0:(this.highpassNode||(this.highpassNode=this.audioContext.createBiquadFilter(),this.highpassNode.type="highpass"),this.highpassNode.frequency.setValueAtTime(t,this.audioContext.currentTime)),this.updateChain()}updateChain(){this.source.disconnect(),this.lowpassNode&&this.lowpassNode.disconnect(),this.highpassNode&&this.highpassNode.disconnect();let t=this.source;this.lowpassNode&&(t.connect(this.lowpassNode),t=this.lowpassNode),this.highpassNode&&(t.connect(this.highpassNode),t=this.highpassNode),t.connect(this.gainNode),this.reverbSend&&this.gainNode.connect(this.reverbSend)}setReverb(t){this.reverbSend&&this.reverbSend.gain.setTargetAtTime(t,this.audioContext.currentTime,.1)}isPlaying(){return!this.t&&!this.i}},us=class{config={listenerX:0,listenerY:0,maxDistance:200,referenceDistance:20,rolloffFactor:1,panSpread:1};configure(t){t.maxDistance!==void 0&&(this.config.maxDistance=t.maxDistance),t.referenceDistance!==void 0&&(this.config.referenceDistance=t.referenceDistance),t.rolloffFactor!==void 0&&(this.config.rolloffFactor=t.rolloffFactor),t.panSpread!==void 0&&(this.config.panSpread=t.panSpread)}setListenerPosition(t,e){this.config.listenerX=t,this.config.listenerY=e}getConfig(){return this.config}calculate2D(t,e){let{listenerX:i,listenerY:s,maxDistance:r,referenceDistance:a,panSpread:n}=this.config,o=t-i,l=e-s,h=Math.sqrt(o*o+l*l),d;h<=a?d=1:h>=r?d=0:d=1-(h-a)/(r-a);let c=0;return r>0&&n>0&&(c=o/r*n,c=Math.max(-1,Math.min(1,c))),{pan:c,distanceVolume:d}}},gs=class{static playStartSound(t,e){let i=t.currentTime,s=[261.63,329.63,392,523.25],r=.06,a=.07;s.forEach((n,o)=>{let l=i+o*a,h=t.createOscillator(),d=t.createGain();h.type="square",h.frequency.setValueAtTime(n,l),d.gain.setValueAtTime(0,l),d.gain.linearRampToValueAtTime(.2,l+.005),d.gain.setValueAtTime(.2,l+r-.01),d.gain.linearRampToValueAtTime(0,l+r),h.connect(d),d.connect(e),h.start(l),h.stop(l+r)})}static noteToFrequency(t){let e=/^([A-G])([#b]?)(\d)$/i,i=t.match(e);if(!i)return null;let[,s,r,a]=i,n=parseInt(a,10),o={C:0,D:2,E:4,F:5,G:7,A:9,B:11}[s.toUpperCase()];r==="#"?o+=1:r==="b"&&(o-=1);let l=o+(n+1)*12;return 440*Math.pow(2,(l-49)/12)}},fs=U.create("audio:engine"),Le=class{ctx=null;masterGain=null;reverbBus=null;soundBank=null;spatial=new us;instances=new Map;nextInstanceId=1;onAudioEvent=null;initialize(){if(this.ctx)return!0;try{return this.ctx=new(window.AudioContext||window.webkitAudioContext),this.masterGain=this.ctx.createGain(),this.masterGain.connect(this.ctx.destination),this.ctx.state==="suspended"&&this.ctx.resume(),this.reverbBus=this.ctx.createConvolver(),this.reverbBus.buffer=this.createImpulseResponse(2,2),this.reverbBus.connect(this.masterGain),this.soundBank=new ds(this.ctx),!0}catch(t){return fs.error("Failed to initialize",t),!1}}createImpulseResponse(t,e){if(!this.ctx)throw new Error("Context not initialized");let i=this.ctx.sampleRate,s=i*t,r=this.ctx.createBuffer(2,s,i);for(let a=0;a<2;a++){let n=r.getChannelData(a);for(let o=0;o<s;o++){let l=Math.pow(1-o/s,e);n[o]=(Math.random()*2-1)*l}}return r}getLoader(){return this.soundBank}setMasterVolume(t){this.masterGain&&(this.masterGain.gain.value=Math.max(0,Math.min(1,t)))}getMasterVolume(){return this.masterGain?.gain.value??1}play(t,e={}){if(!this.ctx||!this.masterGain||!this.soundBank)return null;let i=this.soundBank.get(t);if(!i)return null;let s=e.instanceId??this.nextInstanceId++,r=typeof t=="number"?t:-1,a=new cs(this.ctx,s,r,i,this.masterGain,{...e,name:e.name??(typeof t=="string"?t:""),reverbNode:this.reverbBus||void 0});if(e.position){let{pan:n,distanceVolume:o}=this.spatial.calculate2D(e.position.x,e.position.y);a.setSpatialVolume(o),a.setPan(n)}return a.onEnded=()=>{this.onAudioEvent?.({type:"playback-ended",instanceId:s,soundId:r}),this.instances.delete(s)},this.instances.set(s,a),a.start(),this.onAudioEvent?.({type:"playback-started",instanceId:s,soundId:r}),{instanceId:s}}stop(t){if(typeof t=="number"){let e=this.instances.get(t);if(e)return e.stop(),1}else{let e=0;for(let i of this.instances.values())(t==="all"||i.name===t)&&(i.stop(),e++);return e}return 0}stopAll(){let t=this.instances.size;return this.instances.forEach(e=>e.stop()),this.instances.clear(),t}fadeOut(t,e){if(t==="all"){let i=this.instances.size;return this.instances.forEach(s=>s.stop(e)),i}if(typeof t=="number"){let i=this.instances.get(t);if(i)return i.stop(e),1}return 0}pause(t){return 0}resume(t){return 0}setListenerPosition(t,e){this.spatial.setListenerPosition(t,e);for(let i of this.instances.values())if(i.position){let{pan:s,distanceVolume:r}=this.spatial.calculate2D(i.position.x,i.position.y);i.setPan(s),i.setSpatialVolume(r)}}configureSpatial(t){this.spatial.configure(t)}setEffects(t,e){let i=this.instances.get(t);i&&(e.lowpass!==void 0&&i.setLowpass(e.lowpass),e.highpass!==void 0&&i.setHighpass(e.highpass),e.reverb!==void 0&&i.setReverb(e.reverb),e.pitch!==void 0&&i.setPitch(e.pitch),e.volume!==void 0&&i.setVolume(e.volume))}stopBySoundId(t){let e=0;for(let i of this.instances.values())i.soundId===t&&(i.stop(),e++);return e}fadeOutBySoundId(t,e){let i=0;for(let s of this.instances.values())s.soundId===t&&(s.stop(e),i++);return i}pauseBySoundId(t){return 0}resumeBySoundId(t){return 0}playTone(t,e,i={}){if(!this.ctx||!this.masterGain)return;let{type:s="sine",volume:r=.3,attack:a=.01,release:n=.1}=i,o=this.ctx.currentTime,l=this.ctx.createOscillator();l.type=s,l.frequency.setValueAtTime(t,o);let h=this.ctx.createGain();h.gain.setValueAtTime(0,o),h.gain.linearRampToValueAtTime(r,o+a),h.gain.setValueAtTime(r,o+e-n),h.gain.linearRampToValueAtTime(0,o+e),l.connect(h),h.connect(this.masterGain),l.start(o),l.stop(o+e)}playStartSound(){this.ctx&&this.masterGain&&gs.playStartSound(this.ctx,this.masterGain)}};var ps=class{instanceId;templateId;layerId;position;zIndex;params;state="running";executorState=null;createdAt;constructor(t,e,i,s,r,a,n){this.instanceId=t,this.templateId=e,this.layerId=i,this.position={x:s,y:r},this.zIndex=a,this.params={...n},this.createdAt=typeof performance<"u"?performance.now():Date.now()}elapsed(){return((typeof performance<"u"?performance.now():Date.now())-this.createdAt)/1e3}};function qt(t,e){if(typeof t=="string"&&t.startsWith("$")){let i=t.slice(1);return e[i]??t}return t}function ee(t,e,i=Math.random){if(typeof t=="string"){let s=qt(t,e);return typeof s=="number"?s:0}if(Array.isArray(t)){let[s,r]=t;return s+i()*(r-s)}return t}var pe=U.create("macro:engine"),ot=class{executors=new Map;templates=new Map;instances=new Map;feedbackQueue=[];register(t,e){this.executors.set(t,e),pe.debug(`Executor registered: "${t}"`)}loadTemplate(t,e){this.templates.set(t,e),pe.debug(`Template loaded: id=${t} type="${e.type}"`)}loadDefines(t){for(let e of t)this.loadTemplate(e.templateId,e.template)}applyOrder(t){switch(t.cmd){case 1:this.handleCreate(t);break;case 2:this.handleUpdate(t);break;case 3:this.handleRemove(t);break;case 4:this.handlePause(t);break;case 5:this.handleResume(t);break}}applyOrders(t){for(let e of t)this.applyOrder(e)}handleCreate(t){let e=this.templates.get(t.templateId);if(!e){pe.warn(`Create failed: unknown templateId=${t.templateId}`);return}let i=this.executors.get(e.type);if(!i){pe.warn(`Create failed: no executor for type="${e.type}"`);return}let s=new ps(t.instanceId,t.templateId,t.layerId,t.x,t.y,t.zIndex,t.params),r=this.buildContext(s,e,{mouseX:0,mouseY:0,mouseDown:!1,keysPressed:[],keysHeld:[]});s.executorState=i.init(r,e,t.params),this.instances.set(t.instanceId,s),pe.debug(`Instance started: id=${t.instanceId} type="${e.type}"`)}handleUpdate(t){let e=this.instances.get(t.instanceId);if(!e)return;Object.assign(e.params,t.params);let i=this.templates.get(e.templateId),s=i?this.executors.get(i.type):void 0;if(s?.onParamUpdate&&i){let r=this.buildContext(e,i,{mouseX:0,mouseY:0,mouseDown:!1,keysPressed:[],keysHeld:[]});s.onParamUpdate(r,e.executorState,t.params)}}handleRemove(t){let e=this.instances.get(t.instanceId);if(!e)return;let i=this.templates.get(e.templateId),s=i?this.executors.get(i.type):void 0;if(s&&i){let r=this.buildContext(e,i,{mouseX:0,mouseY:0,mouseDown:!1,keysPressed:[],keysHeld:[]});s.destroy(r,e.executorState)}this.instances.delete(t.instanceId),pe.debug(`Instance removed: id=${t.instanceId}`)}handlePause(t){let e=this.instances.get(t.instanceId);if(!e)return;e.state="paused";let i=this.templates.get(e.templateId),s=i?this.executors.get(i.type):void 0;if(s?.onPause&&i){let r=this.buildContext(e,i,{mouseX:0,mouseY:0,mouseDown:!1,keysPressed:[],keysHeld:[]});s.onPause(r,e.executorState)}}handleResume(t){let e=this.instances.get(t.instanceId);if(!e)return;e.state="running";let i=this.templates.get(e.templateId),s=i?this.executors.get(i.type):void 0;if(s?.onResume&&i){let r=this.buildContext(e,i,{mouseX:0,mouseY:0,mouseDown:!1,keysPressed:[],keysHeld:[]});s.onResume(r,e.executorState)}}tick(t,e,i){let s=new Map;for(let r of this.instances.values()){if(r.state==="paused")continue;let a=s.get(r.layerId);a||(a=[],s.set(r.layerId,a)),a.push(r)}for(let[r,a]of s){let n=e.get(r);if(!n||!n.getIsMacroLayer())continue;a.sort((l,h)=>l.zIndex-h.zIndex);let o=[];for(let l of a){let h=this.templates.get(l.templateId);if(!h)continue;let d=this.executors.get(h.type);if(!d)continue;let c=this.buildContext(l,h,i,n),u=d.tick(c,h,l.executorState,t);o.push(...u)}n.setOrders(o)}}getFeedbackQueue(){return this.feedbackQueue}clearFeedbackQueue(){this.feedbackQueue=[]}getActiveInstances(){return this.instances}getInstanceCount(){return this.instances.size}buildContext(t,e,i,s){let r=this.feedbackQueue,a=t.instanceId;return{instanceId:a,position:t.position,layerWidth:s?.getWidth()??0,layerHeight:s?.getHeight()??0,input:i,sendFeedback(n,o){switch(n){case"click":r.push({cmd:1,instanceId:a});break;case"change":r.push({cmd:2,instanceId:a,valueType:typeof o=="boolean"?"boolean":"number",value:o});break;case"submit":r.push({cmd:3,instanceId:a,text:o});break;case"select":r.push({cmd:4,instanceId:a,index:o});break;case"custom":r.push({cmd:5,instanceId:a,data:o});break}},elapsed:()=>t.elapsed(),random:Math.random,resolveValue(n,o){return qt(n,o)},resolveNumber(n,o){return ee(n,o)}}}},lt=class{type="particle";init(t,e,i){return{particles:[],timeSinceEmit:0,emitDone:!1}}tick(t,e,i,s){let r=e,a=r.emitter,n=r.particle,o={};if(!i.emitDone){if(a.once&&a.burst){let c=a.burst;for(let u=0;u<c&&!(a.limit&&i.particles.length>=a.limit);u++)i.particles.push(this.spawnParticle(t,a,n,o));i.emitDone=!0}else if(a.rate){i.timeSinceEmit+=s;let c=1/a.rate;for(;i.timeSinceEmit>=c&&(i.timeSinceEmit-=c,!(a.limit&&i.particles.length>=a.limit));)i.particles.push(this.spawnParticle(t,a,n,o))}}let l=n.gravity?.x??0,h=n.gravity?.y??0;for(let c of i.particles)c.vx+=l*s,c.vy+=h*s,c.x+=c.vx*s,c.y+=c.vy*s,c.lifetime-=s;i.particles=i.particles.filter(c=>c.lifetime>0);let d=[];for(let c of i.particles){let u=Math.round(c.x),f=Math.round(c.y);u<0||f<0||u>=t.layerWidth||f>=t.layerHeight||d.push({type:g.Char,x:u,y:f,char:c.char,fg:c.fg,bg:c.bg??0})}return d}destroy(t,e){}spawnParticle(t,e,i,s){let r=e.zone,a,n;switch(e.spawnArea??"zone"){case"top-edge":a=r.x+Math.random()*r.w,n=r.y;break;case"bottom-edge":a=r.x+Math.random()*r.w,n=r.y+r.h-1;break;case"left-edge":a=r.x,n=r.y+Math.random()*r.h;break;case"right-edge":a=r.x+r.w-1,n=r.y+Math.random()*r.h;break;default:a=r.x+Math.random()*r.w,n=r.y+Math.random()*r.h;break}a+=t.position.x,n+=t.position.y;let o=i.chars[Math.floor(Math.random()*i.chars.length)],l=typeof o=="string"?o.charCodeAt(0):o,h=ee(i.fg,s),d=i.bg,c=ee(i.velocity.x,s),u=ee(i.velocity.y,s),f=ee(i.lifetime,s);return{x:a,y:n,vx:c,vy:u,char:l,fg:Math.round(h),bg:d,lifetime:f,maxLifetime:f}}},ht=class{type="effect";init(t,e,i){let s=e;return{elapsed:0,duration:s.transform.duration,decay:s.transform.decay??1,offsetX:s.transform.offsetX??0,offsetY:s.transform.offsetY??0}}tick(t,e,i,s){if(i.elapsed+=s,i.elapsed>=i.duration)return t.position.x=0,t.position.y=0,[];let r=i.elapsed/i.duration,a=Math.pow(1-r,i.decay),n={},o=ee(i.offsetX,n)*a,l=ee(i.offsetY,n)*a;return t.position.x=Math.round(o),t.position.y=Math.round(l),[]}destroy(t,e){}},dt=class{type="reveal";init(t,e,i){let s=e,r=this.buildCells(s),a=this.buildRevealOrder(s.pattern,r.length,t.layerWidth);return{cells:r,revealOrder:a,revealedCount:s.direction==="hide"?r.length:0,elapsed:0,delay:s.delay??0,cursorBlink:!0,cursorTimer:0,width:t.layerWidth||80}}tick(t,e,i,s){let r=e;if(i.elapsed+=s,i.elapsed<i.delay)return[];let a=i.elapsed-i.delay,n=Math.min(Math.floor(a*r.speed),i.cells.length);if(r.direction==="reveal")for(;i.revealedCount<n;){let d=i.revealOrder[i.revealedCount];d!==void 0&&(i.cells[d].revealed=!0),i.revealedCount++}else for(;i.revealedCount>i.cells.length-n;){i.revealedCount--;let d=i.revealOrder[i.revealedCount];d!==void 0&&(i.cells[d].revealed=!1)}if(r.cursor?.blink){i.cursorTimer+=s;let d=r.cursor.blinkRate??2;i.cursorTimer>=1/d&&(i.cursorTimer-=1/d,i.cursorBlink=!i.cursorBlink)}let o=[],l=t.position.x,h=t.position.y;for(let d=0;d<i.cells.length;d++){let c=i.cells[d];if(!c.revealed)continue;let u=l+d%i.width,f=h+Math.floor(d/i.width);o.push({type:g.Char,x:u,y:f,char:c.char,fg:c.fg,bg:c.bg})}if(r.cursor&&i.cursorBlink&&i.revealedCount<i.cells.length){let d=i.revealOrder[i.revealedCount];if(d!==void 0){let c=l+d%i.width,u=h+Math.floor(d/i.width),f=typeof r.cursor.char=="string"?r.cursor.char.charCodeAt(0):r.cursor.char;o.push({type:g.Char,x:c,y:u,char:f,fg:r.cursor.fg,bg:0})}}return o}destroy(t,e){}buildCells(t){let e=[];if(t.content==="text"&&typeof t.data=="string")for(let i of t.data)e.push({char:i.charCodeAt(0),fg:15,bg:0,revealed:!1});else if(t.content==="cells"&&Array.isArray(t.data))for(let i of t.data)e.push({char:i.char,fg:i.fg,bg:i.bg??0,revealed:!1});else if(t.content==="sprite"&&Array.isArray(t.data))for(let i of t.data)e.push({char:i,fg:15,bg:0,revealed:!1});return e}buildRevealOrder(t,e,i){let s=[],r=i||1,a=Math.ceil(e/r);switch(t){case"typewriter":case"ltr":for(let n=0;n<e;n++)s.push(n);break;case"rtl":for(let n=e-1;n>=0;n--)s.push(n);break;case"ttb":for(let n=0;n<r;n++)for(let o=0;o<a;o++){let l=o*r+n;l<e&&s.push(l)}break;case"btt":for(let n=0;n<r;n++)for(let o=a-1;o>=0;o--){let l=o*r+n;l<e&&s.push(l)}break;case"random":{let n=Array.from({length:e},(o,l)=>l);for(let o=n.length-1;o>0;o--){let l=Math.floor(Math.random()*(o+1));[n[o],n[l]]=[n[l],n[o]]}s.push(...n);break}case"center-out":{let n=Math.floor(r/2),o=Math.floor(a/2),l=Array.from({length:e},(h,d)=>d);l.sort((h,d)=>{let c=h%r,u=Math.floor(h/r),f=d%r,p=Math.floor(d/r),m=Math.abs(c-n)+Math.abs(u-o),y=Math.abs(f-n)+Math.abs(p-o);return m-y}),s.push(...l);break}case"edges-in":{let n=Math.floor(r/2),o=Math.floor(a/2),l=Array.from({length:e},(h,d)=>d);l.sort((h,d)=>{let c=h%r,u=Math.floor(h/r),f=d%r,p=Math.floor(d/r),m=Math.abs(c-n)+Math.abs(u-o);return Math.abs(f-n)+Math.abs(p-o)-m}),s.push(...l);break}case"spiral":{let n=new Set,o=0,l=a-1,h=0,d=r-1;for(;o<=l&&h<=d;){for(let c=h;c<=d;c++){let u=o*r+c;u<e&&!n.has(u)&&(s.push(u),n.add(u))}o++;for(let c=o;c<=l;c++){let u=c*r+d;u<e&&!n.has(u)&&(s.push(u),n.add(u))}d--;for(let c=d;c>=h;c--){let u=l*r+c;u<e&&!n.has(u)&&(s.push(u),n.add(u))}l--;for(let c=l;c>=o;c--){let u=c*r+h;u<e&&!n.has(u)&&(s.push(u),n.add(u))}h++}break}default:for(let n=0;n<e;n++)s.push(n);break}return s}},ct=class{type="line";init(t,e,i){let s=e,r=s.char,a=typeof r=="string"?r.charCodeAt(0):r;return{points:i.points??[],maxPoints:s.maxPoints??1e3,char:a,fg:s.fg,bg:s.bg??0,fadeOut:s.fadeOut??!1,fadeLength:s.fadeLength??5,closed:s.closed??!1}}tick(t,e,i,s){if(i.points.length<2)return[];let r=[],a=t.position.x,n=t.position.y,o=i.points.length;for(let l=0;l<o-1;l++){let h=i.points[l],d=i.points[l+1];this.rasterizeLine(r,a,n,h,d,i,l,o,t)}if(i.closed&&o>=3){let l=i.points[o-1],h=i.points[0];this.rasterizeLine(r,a,n,l,h,i,o-1,o,t)}return r}destroy(t,e){}onParamUpdate(t,e,i){i.points&&Array.isArray(i.points)&&(e.points=i.points,e.points.length>e.maxPoints&&(e.points=e.points.slice(-e.maxPoints)))}rasterizeLine(t,e,i,s,r,a,n,o,l){let h=s.x,d=s.y,c=r.x,u=r.y,f=Math.abs(c-h),p=Math.abs(u-d),m=h<c?1:-1,y=d<u?1:-1,C=f-p,v=a.fg;if(a.fadeOut){let x=o-1-n;if(x<a.fadeLength){let E=x/a.fadeLength;v=Math.round(a.fg*E)}}for(;;){let x=e+h,E=i+d;if(x>=0&&E>=0&&x<l.layerWidth&&E<l.layerHeight&&t.push({type:g.Char,x,y:E,char:a.char,fg:v,bg:a.bg}),h===c&&d===u)break;let P=2*C;P>-p&&(C-=p,h+=m),P<f&&(C+=f,d+=y)}}},ut=class{type="ui";init(t,e,i){let s=e;return{hovered:!1,active:!1,focused:!1,disabled:i.disabled===!0,text:i.text??"",cursorPos:0,cursorBlink:!0,cursorTimer:0,value:i.value??s.min??0,dragging:!1}}tick(t,e,i,s){let r=e,a={},n=typeof r.width=="number"?r.width:ee(r.width,a),o=typeof r.height=="number"?r.height??1:r.height?ee(r.height,a):1,l=t.position.x,h=t.position.y,d=t.input.mouseX,c=t.input.mouseY;i.hovered=!i.disabled&&d>=l&&d<l+n&&c>=h&&c<h+o;let u=i.active;if(i.active=i.hovered&&t.input.mouseDown,i.active&&!u&&i.hovered)switch(r.subtype){case"button":t.sendFeedback("click");break;case"text-input":i.focused=!0;break;case"slider":i.dragging=!0;break}!t.input.mouseDown&&u&&(i.active=!1,r.subtype==="slider"&&(i.dragging=!1)),r.subtype==="text-input"&&i.focused&&this.handleTextInput(t,r,i,s),r.subtype==="slider"&&i.dragging&&this.handleSliderDrag(t,r,i,n,l),i.focused&&(i.cursorTimer+=s,i.cursorTimer>=.5&&(i.cursorTimer-=.5,i.cursorBlink=!i.cursorBlink));let f=this.resolveStyle(r,i);return this.renderUI(r,i,f,l,h,n,o,t)}destroy(t,e){}onParamUpdate(t,e,i){i.disabled!==void 0&&(e.disabled=i.disabled),i.text!==void 0&&(e.text=i.text),i.value!==void 0&&(e.value=i.value)}handleTextInput(t,e,i,s){for(let r of t.input.keysPressed)if(r==="Backspace")i.cursorPos>0&&(i.text=i.text.slice(0,i.cursorPos-1)+i.text.slice(i.cursorPos),i.cursorPos--);else if(r==="Delete")i.cursorPos<i.text.length&&(i.text=i.text.slice(0,i.cursorPos)+i.text.slice(i.cursorPos+1));else if(r==="ArrowLeft")i.cursorPos=Math.max(0,i.cursorPos-1);else if(r==="ArrowRight")i.cursorPos=Math.min(i.text.length,i.cursorPos+1);else if(r==="Home")i.cursorPos=0;else if(r==="End")i.cursorPos=i.text.length;else if(r==="Enter")t.sendFeedback("submit",i.text),i.focused=!1;else if(r==="Escape")i.focused=!1;else if(r.length===1){let a=e.maxLength??256;i.text.length<a&&(i.text=i.text.slice(0,i.cursorPos)+r+i.text.slice(i.cursorPos),i.cursorPos++)}}handleSliderDrag(t,e,i,s,r){let a=e.min??0,n=e.max??100,o=e.step??1,l=t.input.mouseX-r,h=Math.max(0,Math.min(1,l/(s-1))),d=a+h*(n-a);d=Math.round(d/o)*o,d=Math.max(a,Math.min(n,d)),d!==i.value&&(i.value=d,t.sendFeedback("change",d))}resolveStyle(t,e){return e.disabled&&t.states.disabled?{...t.states.normal,...t.states.disabled}:e.focused&&t.states.focused?{...t.states.normal,...t.states.focused}:e.active&&t.states.active?{...t.states.normal,...t.states.active}:e.hovered&&t.states.hover?{...t.states.normal,...t.states.hover}:t.states.normal}renderUI(t,e,i,s,r,a,n,o){let l=[],h=i.fg??15,d=i.bg??0;if(l.push({type:g.Fill,x:s,y:r,width:a,height:n,bg:d}),i.borderStyle&&i.borderStyle!=="none"){let c=this.getBorderChars(i.borderStyle),u=i.borderFg??h,f=i.borderBg??d;l.push({type:g.Char,x:s,y:r,char:c.tl,fg:u,bg:f});for(let p=1;p<a-1;p++)l.push({type:g.Char,x:s+p,y:r,char:c.h,fg:u,bg:f});if(l.push({type:g.Char,x:s+a-1,y:r,char:c.tr,fg:u,bg:f}),n>1){l.push({type:g.Char,x:s,y:r+n-1,char:c.bl,fg:u,bg:f});for(let p=1;p<a-1;p++)l.push({type:g.Char,x:s+p,y:r+n-1,char:c.h,fg:u,bg:f});l.push({type:g.Char,x:s+a-1,y:r+n-1,char:c.br,fg:u,bg:f})}for(let p=1;p<n-1;p++)l.push({type:g.Char,x:s,y:r+p,char:c.v,fg:u,bg:f}),l.push({type:g.Char,x:s+a-1,y:r+p,char:c.v,fg:u,bg:f})}switch(t.subtype){case"button":this.renderButton(l,t,e,i,s,r,a,n,h,d);break;case"text-input":this.renderTextInput(l,t,e,i,s,r,a,n,h,d);break;case"slider":this.renderSlider(l,t,e,i,s,r,a,n,h,d);break}return l}renderButton(t,e,i,s,r,a,n,o,l,h){let d=e.label??"",c=s.borderStyle&&s.borderStyle!=="none",u=c?r+1:r,f=c?n-2:n,p=a+Math.floor(o/2),m=u+Math.max(0,Math.floor((f-d.length)/2));for(let y=0;y<d.length&&y<f;y++)t.push({type:g.Char,x:m+y,y:p,char:d.charCodeAt(y),fg:l,bg:h})}renderTextInput(t,e,i,s,r,a,n,o,l,h){let d=s.borderStyle&&s.borderStyle!=="none",c=d?r+1:r,u=d?n-2:n,f=d?a+1:a,p=i.text||(i.focused?"":e.placeholder??""),m=i.text?l:Math.floor(l/2);for(let y=0;y<u&&y<p.length;y++)t.push({type:g.Char,x:c+y,y:f,char:p.charCodeAt(y),fg:m,bg:h});if(i.focused&&i.cursorBlink){let y=c+i.cursorPos;y<c+u&&t.push({type:g.Char,x:y,y:f,char:9608,fg:l,bg:h})}}renderSlider(t,e,i,s,r,a,n,o,l,h){let d=s.borderStyle&&s.borderStyle!=="none",c=d?r+1:r,u=d?n-2:n,f=a+Math.floor(o/2),p=e.min??0,m=e.max??100,y=m>p?(i.value-p)/(m-p):0,C=c+Math.round(y*(u-1));for(let v=c;v<c+u;v++)t.push({type:g.Char,x:v,y:f,char:9472,fg:Math.floor(l/2),bg:h});t.push({type:g.Char,x:C,y:f,char:9679,fg:l,bg:h})}getBorderChars(t){switch(t){case"double":return{tl:9556,tr:9559,bl:9562,br:9565,h:9552,v:9553};case"rounded":return{tl:9581,tr:9582,bl:9584,br:9583,h:9472,v:9474};default:return{tl:9484,tr:9488,bl:9492,br:9496,h:9472,v:9474}}}};var me=class{isActive=!1;targetElement;config;constructor(t=window,e={}){this.targetElement=t,this.config={enabled:!0,preventDefault:!1,stopPropagation:!1,debug:!1,...e}}isListening(){return this.isActive}destroy(){this.stop()}getTargetElement(){return this.targetElement}enable(){this.config.enabled=!0,this.isActive||this.start()}disable(){this.config.enabled=!1,this.isActive&&this.stop()}isEnabled(){return this.config.enabled??!0}},ms=class extends me{keys={};textInputsThisFrame=[];keyboardCallbacks={};boundHandlers;constructor(t=window,e={}){super(t,e),this.boundHandlers={keyDown:this.handleKeyDown.bind(this),keyUp:this.handleKeyUp.bind(this),blur:this.handleBlur.bind(this)}}start(){this.isActive||(this.targetElement.addEventListener("keydown",this.boundHandlers.keyDown),this.targetElement.addEventListener("keyup",this.boundHandlers.keyUp),window.addEventListener("blur",this.boundHandlers.blur),this.isActive=!0)}stop(){this.isActive&&(this.targetElement.removeEventListener("keydown",this.boundHandlers.keyDown),this.targetElement.removeEventListener("keyup",this.boundHandlers.keyUp),window.removeEventListener("blur",this.boundHandlers.blur),this.isActive=!1)}reset(){this.keys={},this.textInputsThisFrame=[]}resetDelta(){}poll(){for(let t in this.keys)this.keys[t].justPressed=!1,this.keys[t].justReleased=!1;this.textInputsThisFrame=[]}setCallbacks(t){this.keyboardCallbacks={...this.keyboardCallbacks,...t}}getTextInputs(){return this.textInputsThisFrame}isKeyPressed(t){return this.keys[t]?.pressed||!1}isKeyJustPressed(t){return this.keys[t]?.justPressed||!1}isKeyJustReleased(t){return this.keys[t]?.justReleased||!1}getKeysJustPressed(){let t=[];for(let e in this.keys)this.keys[e].justPressed&&t.push(e);return t}getKeysHeld(){let t=[];for(let e in this.keys)this.keys[e].pressed&&t.push(e);return t}shouldAllowDefault(t,e){let i=/^F([1-9]|1[0-2])$/.test(t),s=(e.ctrlKey||e.metaKey)&&(t==="KeyT"||t==="KeyW"||t==="KeyR"||t==="KeyN"||t==="Tab");return i||s}handleKeyDown(t){let e=t.code,i=this.shouldAllowDefault(e,t);this.config.preventDefault&&!i&&t.preventDefault(),this.config.stopPropagation&&!i&&t.stopPropagation(),this.keys[e]||(this.keys[e]={pressed:!1,justPressed:!1,justReleased:!1}),this.keys[e].pressed||(this.keys[e].justPressed=!0,this.keyboardCallbacks.onKeyDown?.(e,t)),this.keys[e].pressed=!0,this.keys[e].justReleased=!1;let s=t.key;s.length===1&&!t.ctrlKey&&!t.metaKey&&this.textInputsThisFrame.push(s)}handleKeyUp(t){let e=t.code,i=this.shouldAllowDefault(e,t);this.config.preventDefault&&!i&&t.preventDefault(),this.config.stopPropagation&&!i&&t.stopPropagation(),this.keys[e]||(this.keys[e]={pressed:!1,justPressed:!1,justReleased:!1}),this.keys[e].pressed&&(this.keys[e].justReleased=!0,this.keyboardCallbacks.onKeyUp?.(e,t)),this.keys[e].pressed=!1,this.keys[e].justPressed=!1}handleBlur(){this.reset()}},ys=class gt extends me{mouseButtons={left:{pressed:!1,justPressed:!1,justReleased:!1},middle:{pressed:!1,justPressed:!1,justReleased:!1},right:{pressed:!1,justPressed:!1,justReleased:!1}};mousePosition=new N(0,0);mouseDelta=new N(0,0);wheelDelta=0;boundHandlers;constructor(e=window,i={}){super(e,i),this.boundHandlers={mouseDown:this.handleMouseDown.bind(this),mouseUp:this.handleMouseUp.bind(this),mouseMove:this.handleMouseMove.bind(this),wheel:this.handleWheel.bind(this),contextMenu:this.handleContextMenu.bind(this),blur:this.handleBlur.bind(this)}}start(){this.isActive||(this.targetElement.addEventListener("mousedown",this.boundHandlers.mouseDown),this.targetElement.addEventListener("mouseup",this.boundHandlers.mouseUp),this.targetElement.addEventListener("mousemove",this.boundHandlers.mouseMove),this.targetElement.addEventListener("wheel",this.boundHandlers.wheel),this.targetElement.addEventListener("contextmenu",this.boundHandlers.contextMenu),window.addEventListener("blur",this.boundHandlers.blur),this.isActive=!0)}stop(){this.isActive&&(this.targetElement.removeEventListener("mousedown",this.boundHandlers.mouseDown),this.targetElement.removeEventListener("mouseup",this.boundHandlers.mouseUp),this.targetElement.removeEventListener("mousemove",this.boundHandlers.mouseMove),this.targetElement.removeEventListener("wheel",this.boundHandlers.wheel),this.targetElement.removeEventListener("contextmenu",this.boundHandlers.contextMenu),window.removeEventListener("blur",this.boundHandlers.blur),this.isActive=!1)}reset(){this.mouseButtons={left:{pressed:!1,justPressed:!1,justReleased:!1},middle:{pressed:!1,justPressed:!1,justReleased:!1},right:{pressed:!1,justPressed:!1,justReleased:!1}},this.mousePosition=new N(0,0),this.mouseDelta=new N(0,0),this.wheelDelta=0}poll(){this.mouseButtons.left.justPressed=!1,this.mouseButtons.left.justReleased=!1,this.mouseButtons.middle.justPressed=!1,this.mouseButtons.middle.justReleased=!1,this.mouseButtons.right.justPressed=!1,this.mouseButtons.right.justReleased=!1,this.resetDelta()}resetDelta(){this.mouseDelta=new N(0,0),this.wheelDelta=0}isLeftMousePressed(){return this.mouseButtons.left.pressed}isLeftMouseJustPressed(){return this.mouseButtons.left.justPressed}isLeftMouseJustReleased(){return this.mouseButtons.left.justReleased}isRightMousePressed(){return this.mouseButtons.right.pressed}isRightMouseJustPressed(){return this.mouseButtons.right.justPressed}isRightMouseJustReleased(){return this.mouseButtons.right.justReleased}isMiddleMousePressed(){return this.mouseButtons.middle.pressed}getMousePosition(){return this.mousePosition.clone()}getMouseDelta(){return this.mouseDelta.clone()}getWheelDelta(){return this.wheelDelta}static BUTTON_NAMES=["left","middle","right"];handleMouseDown(e){this.config.preventDefault&&this.isInteractiveSurfaceEvent(e)&&e.preventDefault();let i=gt.BUTTON_NAMES[e.button];if(i){let s=this.mouseButtons[i];s.pressed||(s.justPressed=!0),s.pressed=!0,s.justReleased=!1}}handleMouseUp(e){this.config.preventDefault&&this.isInteractiveSurfaceEvent(e)&&e.preventDefault();let i=gt.BUTTON_NAMES[e.button];if(i){let s=this.mouseButtons[i];s.pressed&&(s.justReleased=!0),s.pressed=!1,s.justPressed=!1}}handleMouseMove(e){let i=new N(e.clientX,e.clientY);this.mouseDelta=i.subtract(this.mousePosition),this.mousePosition=i}handleWheel(e){this.config.preventDefault&&this.isInteractiveSurfaceEvent(e)&&e.preventDefault(),this.wheelDelta=e.deltaY}handleContextMenu(e){this.isInteractiveSurfaceEvent(e)&&e.preventDefault()}handleBlur(){this.reset()}isInteractiveSurfaceEvent(e){let i=e.target;return i?(i.tagName||"").toLowerCase()==="canvas"||(i.getAttribute?.("data-primitiv-input-surface")??"").toLowerCase()==="true"?!0:!!i.closest?.('canvas, [data-primitiv-input-surface="true"]'):!1}},bs=class extends me{gamepads=new Map;previousGameState=new Map;rafId=null;boundHandlers;constructor(t=window,e={}){super(t,e),this.boundHandlers={connected:this.handleGamepadConnected.bind(this),disconnected:this.handleGamepadDisconnected.bind(this)}}start(){this.isActive||(window.addEventListener("gamepadconnected",this.boundHandlers.connected),window.addEventListener("gamepaddisconnected",this.boundHandlers.disconnected),this.startPolling(),this.isActive=!0)}stop(){this.isActive&&(window.removeEventListener("gamepadconnected",this.boundHandlers.connected),window.removeEventListener("gamepaddisconnected",this.boundHandlers.disconnected),this.stopPolling(),this.isActive=!1)}startPolling(){let t=()=>{this.poll(),this.rafId=requestAnimationFrame(t)};this.rafId=requestAnimationFrame(t)}stopPolling(){this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null)}poll(){let t=navigator.getGamepads();for(let e=0;e<t.length;e++){let i=t[e];i&&this.updateGamepadState(i)}}reset(){this.gamepads.clear(),this.previousGameState.clear()}resetDelta(){this.previousGameState.clear();for(let[t,e]of this.gamepads)this.previousGameState.set(t,this.cloneState(e))}updateGamepadState(t){let e=this.gamepads.get(t.index),i=t.buttons.map((s,r)=>{let a=e?.buttons[r],n=s.pressed,o=a?.pressed??!1;return{pressed:n,justPressed:n&&!o,justReleased:!n&&o,value:s.value,touched:s.touched}});this.gamepads.set(t.index,{id:t.id,index:t.index,connected:t.connected,buttons:i,axes:[...t.axes],timestamp:t.timestamp,mapping:t.mapping})}isButtonPressed(t,e){return this.gamepads.get(t)?.buttons[e]?.pressed??!1}isButtonJustPressed(t,e){return this.gamepads.get(t)?.buttons[e]?.justPressed??!1}isButtonJustReleased(t,e){return this.gamepads.get(t)?.buttons[e]?.justReleased??!1}getAxis(t,e){return this.gamepads.get(t)?.axes[e]??0}vibrationPresets={tap:{duration:50,strongMagnitude:.3,weakMagnitude:.5},impact:{duration:100,strongMagnitude:.7,weakMagnitude:.3},heavy:{duration:200,strongMagnitude:1,weakMagnitude:.2},success:{duration:150,strongMagnitude:.4,weakMagnitude:.6},error:{duration:300,strongMagnitude:.8,weakMagnitude:.4},explosion:{duration:400,strongMagnitude:1,weakMagnitude:.8}};async vibrate(t,e){let i=navigator.getGamepads()[t];if(!i||!i.vibrationActuator)return!1;try{return await i.vibrationActuator.playEffect("dual-rumble",{startDelay:e.startDelay??0,duration:e.duration,strongMagnitude:e.strongMagnitude??1,weakMagnitude:e.weakMagnitude??1}),!0}catch{return!1}}async vibratePreset(t,e){return this.vibrate(t,this.vibrationPresets[e])}async vibrateAll(t){let e=Array.from(this.gamepads.keys()).map(i=>this.vibrate(i,t));await Promise.all(e)}async stopVibration(t){let e=navigator.getGamepads()[t];if(e&&e.vibrationActuator)try{await e.vibrationActuator.reset()}catch{}}handleGamepadConnected(t){this.updateGamepadState(t.gamepad)}handleGamepadDisconnected(t){this.gamepads.delete(t.gamepad.index),this.previousGameState.delete(t.gamepad.index)}cloneState(t){return{...t,buttons:t.buttons.map(e=>({...e})),axes:[...t.axes]}}},ws=class extends me{touches=new Map;nativeToInternal=new Map;maxTouches=10;boundHandlers;constructor(t=window,e={}){super(t,e),this.boundHandlers={touchStart:this.handleTouchStart.bind(this),touchEnd:this.handleTouchEnd.bind(this),touchMove:this.handleTouchMove.bind(this),touchCancel:this.handleTouchCancel.bind(this),visibilityChange:this.handleVisibilityChange.bind(this)}}start(){if(this.isActive)return;let t={passive:!this.config.preventDefault};this.targetElement.addEventListener("touchstart",this.boundHandlers.touchStart,t),this.targetElement.addEventListener("touchend",this.boundHandlers.touchEnd,t),this.targetElement.addEventListener("touchmove",this.boundHandlers.touchMove,t),this.targetElement.addEventListener("touchcancel",this.boundHandlers.touchCancel,t),document.addEventListener("visibilitychange",this.boundHandlers.visibilityChange),this.isActive=!0}stop(){this.isActive&&(this.targetElement.removeEventListener("touchstart",this.boundHandlers.touchStart),this.targetElement.removeEventListener("touchend",this.boundHandlers.touchEnd),this.targetElement.removeEventListener("touchmove",this.boundHandlers.touchMove),this.targetElement.removeEventListener("touchcancel",this.boundHandlers.touchCancel),document.removeEventListener("visibilitychange",this.boundHandlers.visibilityChange),this.isActive=!1)}poll(){let t=[];for(let[e,i]of this.touches)i.justReleased?t.push(e):(i.justPressed=!1,i.justReleased=!1);for(let e of t){let i=this.touches.get(e);i&&(this.nativeToInternal.delete(i.nativeId),this.touches.delete(e))}}reset(){this.touches.clear(),this.nativeToInternal.clear()}resetDelta(){}isTouchActive(t){return this.touches.get(t)?.active??!1}isTouchJustPressed(t){return this.touches.get(t)?.justPressed??!1}isTouchJustReleased(t){return this.touches.get(t)?.justReleased??!1}getTouchPosition(t){let e=this.touches.get(t);return e?{x:e.x,y:e.y}:null}getAllTouches(){return Array.from(this.touches.values()).filter(t=>t.active)}updateTouches(t){let e=new Set;for(let i=0;i<t.touches.length;i++){let s=t.touches[i],r=s.identifier;e.add(r);let a=this.nativeToInternal.get(r),n;if(a===void 0){if(this.touches.size>=this.maxTouches)continue;for(let h=0;h<this.maxTouches;h++)if(!this.touches.has(h)){a=h;break}if(a===void 0)continue;this.nativeToInternal.set(r,a),n=void 0}else n=this.touches.get(a);let o=!0,l=n?.active??!1;this.touches.set(a,{id:a,nativeId:r,active:o,justPressed:o&&!l,justReleased:!1,x:s.clientX,y:s.clientY,startX:n?.startX??s.clientX,startY:n?.startY??s.clientY})}for(let[i,s]of this.nativeToInternal)if(!e.has(i)){let r=this.touches.get(s);r&&r.active&&(r.active=!1,r.justReleased=!0)}}handleTouchStart(t){this.config.preventDefault&&t.preventDefault(),this.updateTouches(t)}handleTouchEnd(t){this.config.preventDefault&&t.preventDefault(),this.updateTouches(t)}handleTouchMove(t){this.config.preventDefault&&t.preventDefault(),this.updateTouches(t)}handleTouchCancel(t){this.handleTouchEnd(t)}handleVisibilityChange(){document.visibilityState==="hidden"&&this.reset()}},Cs=class extends me{constructor(t,e){super(e.targetElement,e),this.touch=t,this.gridWidth=e.gridWidth,this.gridHeight=e.gridHeight,e.zones&&this.setZones(e.zones)}zones=[];zoneStates=new Map;gridWidth;gridHeight;start(){this.isActive=!0}stop(){this.isActive=!1}reset(){this.zoneStates.clear()}resetDelta(){}setZones(t){this.zones=t;for(let e of t)this.zoneStates.has(e.id)||this.zoneStates.set(e.id,{pressed:!1,justPressed:!1,justReleased:!1,lastX:0,lastY:0})}updateFromTouches(){let t=this.targetElement.getBoundingClientRect(),e=t.width/this.gridWidth,i=t.height/this.gridHeight,s=this.touch.getAllTouches(),r=new Set;for(let a of s){let n=Math.floor((a.x-t.left)/e),o=Math.floor((a.y-t.top)/i);for(let l of this.zones)if(n>=l.x&&n<l.x+l.width&&o>=l.y&&o<l.y+l.height){r.add(l.id);let h=this.zoneStates.get(l.id);h.lastX=n,h.lastY=o}}for(let[a,n]of this.zoneStates){let o=r.has(a);o&&!n.pressed&&(n.justPressed=!0),!o&&n.pressed&&(n.justReleased=!0),n.pressed=o}}poll(){for(let t of this.zoneStates.values())t.justPressed=!1,t.justReleased=!1}isZonePressed(t){return this.zoneStates.get(t)?.pressed??!1}isZoneJustPressed(t){return this.zoneStates.get(t)?.justPressed??!1}isZoneJustReleased(t){return this.zoneStates.get(t)?.justReleased??!1}getZoneAxis(t,e){let i=this.zoneStates.get(t);if(!i||!i.pressed)return 0;let s=this.zones.find(r=>r.id===t);if(!s)return 0;if(e==="x"){let r=(s.width-1)/2,a=s.x+r;return r>0?(i.lastX-a)/r:0}else{let r=(s.height-1)/2,a=s.y+r;return r>0?(i.lastY-a)/r:0}}getZonePosition(t){let e=this.zoneStates.get(t);return e?{x:e.lastX,y:e.lastY}:null}},vs=class extends me{accelerometer={x:0,y:0,z:0,includesGravity:!1};gyroscope={alpha:0,beta:0,gamma:0};orientation={alpha:null,beta:null,gamma:null,absolute:!1};prevAccelerometer={x:0,y:0,z:0,includesGravity:!1};prevGyroscope={alpha:0,beta:0,gamma:0};motionCallbacks={};motionConfig;permissionGranted=!1;boundHandlers;constructor(t=window,e={}){super(t,e),this.motionConfig={targetElement:t,includeGravity:e.includeGravity??!1,threshold:e.threshold??.1,autoRequestPermission:e.autoRequestPermission??!1,enabled:e.enabled??!0,debug:e.debug??!1,preventDefault:e.preventDefault??!1,stopPropagation:e.stopPropagation??!1},this.boundHandlers={devicemotion:this.handleDeviceMotion.bind(this),deviceorientation:this.handleDeviceOrientation.bind(this)}}async requestPermission(){if(typeof DeviceMotionEvent.requestPermission=="function")try{let t=await DeviceMotionEvent.requestPermission();return this.permissionGranted=t==="granted",this.permissionGranted}catch{return!1}return this.permissionGranted=!0,!0}start(){this.isActive||(window.addEventListener("devicemotion",this.boundHandlers.devicemotion),window.addEventListener("deviceorientation",this.boundHandlers.deviceorientation),this.isActive=!0)}stop(){this.isActive&&(window.removeEventListener("devicemotion",this.boundHandlers.devicemotion),window.removeEventListener("deviceorientation",this.boundHandlers.deviceorientation),this.isActive=!1)}setCallbacks(t){this.motionCallbacks={...this.motionCallbacks,...t}}poll(){}reset(){this.accelerometer={x:0,y:0,z:0,includesGravity:!1},this.gyroscope={alpha:0,beta:0,gamma:0},this.orientation={alpha:null,beta:null,gamma:null,absolute:!1}}resetDelta(){this.prevAccelerometer={...this.accelerometer},this.prevGyroscope={...this.gyroscope}}getAccelerometer(){return{...this.accelerometer}}getGyroscope(){return{...this.gyroscope}}getOrientation(){return{...this.orientation}}getNormalizedTilt(){return new N(Math.max(-1,Math.min(1,this.accelerometer.x/9.81)),Math.max(-1,Math.min(1,this.accelerometer.y/9.81)))}handleDeviceMotion(t){let e=this.motionConfig.includeGravity?t.accelerationIncludingGravity:t.acceleration;if(e){let s={x:e.x??0,y:e.y??0,z:e.z??0,includesGravity:this.motionConfig.includeGravity};this.hasSignificantChange(this.prevAccelerometer,s)&&(this.accelerometer=s,this.motionCallbacks.onAccelerometer?.(s))}let i=t.rotationRate;if(i){let s={alpha:i.alpha??0,beta:i.beta??0,gamma:i.gamma??0};this.hasSignificantGyroChange(this.prevGyroscope,s)&&(this.gyroscope=s,this.motionCallbacks.onGyroscope?.(s))}}handleDeviceOrientation(t){this.orientation={alpha:t.alpha,beta:t.beta,gamma:t.gamma,absolute:t.absolute},this.motionCallbacks.onOrientation?.(this.orientation)}hasSignificantChange(t,e){let i=this.motionConfig.threshold;return Math.abs(e.x-t.x)>i||Math.abs(e.y-t.y)>i||Math.abs(e.z-t.z)>i}hasSignificantGyroChange(t,e){let i=this.motionConfig.threshold;return Math.abs(e.alpha-t.alpha)>i||Math.abs(e.beta-t.beta)>i||Math.abs(e.gamma-t.gamma)>i}},$t=class{keyboard=null;mouse=null;gamepad=null;touch=null;touchZone=null;motion=null;config;constructor(t={}){this.config={enableKeyboardMouse:t.enableKeyboardMouse??!0,enableGamepad:t.enableGamepad??!0,enableTouch:t.enableTouch??!0,targetElement:t.targetElement??window,gridWidth:t.gridWidth??80,gridHeight:t.gridHeight??25,debug:t.debug??!1},this.initialize()}initialize(){let t=this.config.targetElement;if(this.config.enableKeyboardMouse&&(this.keyboard=new ms(t),this.mouse=new ys(t)),this.config.enableGamepad&&(this.gamepad=new bs(t)),this.config.enableTouch){this.touch=new ws(t);let e=t instanceof Window?document.body:t;this.touchZone=new Cs(this.touch,{targetElement:e,gridWidth:this.config.gridWidth,gridHeight:this.config.gridHeight}),this.motion=new vs(t)}this.start()}getButton(t,e){switch(t){case b.Keyboard:return this.keyboard?.isKeyPressed(ye[e])??!1;case b.Mouse:return this.getMouseButton(e);case b.Gamepad:return this.gamepad?.isButtonPressed(0,e)??!1;case b.Touch:return this.touch?.isTouchActive(e)??!1;case b.TouchZone:return this.touchZone?.isZonePressed(e)??!1;default:return!1}}getButtonJustPressed(t,e){switch(t){case b.Keyboard:return this.keyboard?.isKeyJustPressed(ye[e])??!1;case b.Mouse:return this.getMouseButtonJustPressed(e);case b.Gamepad:return this.gamepad?.isButtonJustPressed(0,e)??!1;case b.Touch:return this.touch?.isTouchJustPressed?.(e)??!1;case b.TouchZone:return this.touchZone?.isZoneJustPressed(e)??!1;default:return!1}}getButtonJustReleased(t,e){switch(t){case b.Keyboard:return this.keyboard?.isKeyJustReleased(ye[e])??!1;case b.Mouse:return this.getMouseButtonJustReleased(e);case b.Gamepad:return this.gamepad?.isButtonJustReleased(0,e)??!1;case b.Touch:return this.touch?.isTouchJustReleased?.(e)??!1;case b.TouchZone:return this.touchZone?.isZoneJustReleased(e)??!1;default:return!1}}getAxis(t,e){switch(t){case b.Mouse:return this.getMouseAxis(e);case b.Gamepad:return this.gamepad?.getAxis(0,e-100)??0;case b.Touch:return this.getTouchAxis(e);case b.TouchZone:return this.getTouchZoneAxis(e);default:return 0}}isLeftMousePressed(){return this.mouse?.isLeftMousePressed()??!1}getTextInputs(){return this.keyboard?.getTextInputs()??[]}getMouseButton(t){return this.mouse?t===Y.LeftButton?this.mouse.isLeftMousePressed():t===Y.RightButton?this.mouse.isRightMousePressed():t===Y.MiddleButton?this.mouse.isMiddleMousePressed():!1:!1}getMouseButtonJustPressed(t){return this.mouse?t===Y.LeftButton?this.mouse.isLeftMouseJustPressed():t===Y.RightButton?this.mouse.isRightMouseJustPressed():!1:!1}getMouseButtonJustReleased(t){return this.mouse?t===Y.LeftButton?this.mouse.isLeftMouseJustReleased():t===Y.RightButton?this.mouse.isRightMouseJustReleased():!1:!1}getMouseAxis(t){return this.mouse?t===Y.PositionX?this.mouse.getMousePosition().x:t===Y.PositionY?this.mouse.getMousePosition().y:t===Y.DeltaX?this.mouse.getMouseDelta().x:t===Y.DeltaY?this.mouse.getMouseDelta().y:t===Y.WheelDeltaY?this.mouse.getWheelDelta():0:0}getTouchAxis(t){if(!this.touch)return 0;if(t>=100&&t<200){let e=Math.floor((t-100)/2),i=(t-100)%2===1,s=this.touch.getTouchPosition(e);return s?i?s.y:s.x:0}return 0}getTouchZoneAxis(t){if(!this.touchZone)return 0;if(t>=100&&t<200){let e=Math.floor((t-100)/2),i=(t-100)%2===1;return this.touchZone.getZoneAxis(e,i?"y":"x")}return 0}getMouseGridX(){if(!this.mouse)return 0;let t=this.mouse.getMousePosition().x,e=this.config.targetElement,i,s;if(e instanceof Window)i=e.innerWidth,s=0;else{let r=e.getBoundingClientRect();i=r.width,s=r.left}return i===0?0:Math.floor((t-s)/i*this.config.gridWidth)}getMouseGridY(){if(!this.mouse)return 0;let t=this.mouse.getMousePosition().y,e=this.config.targetElement,i,s;if(e instanceof Window)i=e.innerHeight,s=0;else{let r=e.getBoundingClientRect();i=r.height,s=r.top}return i===0?0:Math.floor((t-s)/i*this.config.gridHeight)}isMouseButtonDown(t){return this.mouse?t===0?this.mouse.isLeftMousePressed():t===1?this.mouse.isMiddleMousePressed():t===2?this.mouse.isRightMousePressed():!1:!1}getKeysPressed(){return this.keyboard?.getKeysJustPressed()??[]}getKeysHeld(){return this.keyboard?.getKeysHeld()??[]}start(){this.keyboard?.start(),this.mouse?.start(),this.gamepad?.start(),this.touch?.start(),this.touchZone?.start(),this.motion?.start()}stop(){this.keyboard?.stop(),this.mouse?.stop(),this.gamepad?.stop(),this.touch?.stop(),this.touchZone?.stop(),this.motion?.stop()}reset(){this.keyboard?.reset(),this.mouse?.reset(),this.gamepad?.reset(),this.touch?.reset(),this.touchZone?.reset(),this.motion?.reset()}poll(){this.keyboard?.poll(),this.mouse?.poll(),this.gamepad?.poll(),this.touch?.poll(),this.touchZone?.updateFromTouches(),this.touchZone?.poll(),this.motion?.poll()}resetDelta(){this.keyboard?.resetDelta(),this.mouse?.resetDelta(),this.gamepad?.resetDelta(),this.touch?.resetDelta(),this.touchZone?.resetDelta(),this.motion?.resetDelta()}destroy(){this.stop(),this.keyboard?.destroy(),this.mouse?.destroy(),this.gamepad?.destroy(),this.touch?.destroy(),this.touchZone?.destroy(),this.motion?.destroy()}},Oe=class ft{static calculateRenderMetrics(e,i){let s=e.getBoundingClientRect(),r=e.width/e.height,a=s.width/s.height,n,o,l,h;r>a?(n=s.width,o=s.width/r,l=0,h=(s.height-o)/2):(n=s.height*r,o=s.height,l=(s.width-n)/2,h=0);let d=i?.offsetX||0,c=i?.offsetY||0;return l+=d,h+=c,n-=d*2,o-=c*2,{renderWidth:n,renderHeight:o,offsetX:l,offsetY:h,rect:s}}static collectAxisSources(e,i){let s=new Map;for(let r of e)for(let a of r.sources){if(s.has(a.sourceId))continue;let n=0,o=!1;if(a.type===b.Keyboard&&a.negativeKey!==void 0&&a.positiveKey!==void 0){let l=i.getButton(b.Keyboard,a.negativeKey);i.getButton(b.Keyboard,a.positiveKey)&&(n+=1),l&&(n-=1),o=!0}else if(a.type===b.Mouse&&a.mouseAxis!==void 0)n=i.getAxis(b.Mouse,a.mouseAxis),o=!0;else if(a.type===b.Gamepad&&a.axis!==void 0)n=i.getAxis(b.Gamepad,a.axis),o=!0;else if(a.type===b.Touch&&a.touchId!==void 0&&a.touchAxis!==void 0){let l=100+a.touchId*2,h=a.touchAxis==="x"?l:l+1;n=i.getAxis(b.Touch,h),o=!0}else if(a.type===b.TouchZone&&a.touchZoneId!==void 0&&a.touchZoneAxis!==void 0){let l=100+a.touchZoneId*2,h=a.touchZoneAxis==="x"?l:l+1;n=i.getAxis(b.TouchZone,h),o=!0}o&&s.set(a.sourceId,n)}return s}static collectButtonSources(e,i){let s=new Map;for(let r of e)for(let a of r.sources){if(s.has(a.sourceId))continue;let n=!1,o=!1;a.type===b.Keyboard&&a.key!==void 0?(n=i.getButton(b.Keyboard,a.key),o=!0):a.type===b.Mouse&&a.mouseButton!==void 0?(n=i.getButton(b.Mouse,a.mouseButton),o=!0):a.type===b.Gamepad&&a.button!==void 0?(n=i.getButton(b.Gamepad,a.button),o=!0):a.type===b.Touch&&a.touchButton!==void 0?(n=i.getButton(b.Touch,a.touchButton),o=!0):a.type===b.TouchZone&&a.touchZoneId!==void 0&&(n=i.getButton(b.TouchZone,a.touchZoneId),o=!0),o&&s.set(a.sourceId,n)}return s}static collectButtonSourcesWithTransitions(e,i){let s=new Map;for(let r of e)for(let a of r.sources){if(s.has(a.sourceId))continue;let n=!1,o=!1,l=!1,h=!1;a.type===b.Keyboard&&a.key!==void 0?(n=i.getButton(b.Keyboard,a.key),o=i.getButtonJustPressed(b.Keyboard,a.key),l=i.getButtonJustReleased(b.Keyboard,a.key),h=!0):a.type===b.Mouse&&a.mouseButton!==void 0?(n=i.getButton(b.Mouse,a.mouseButton),o=i.getButtonJustPressed(b.Mouse,a.mouseButton),l=i.getButtonJustReleased(b.Mouse,a.mouseButton),h=!0):a.type===b.Gamepad&&a.button!==void 0?(n=i.getButton(b.Gamepad,a.button),o=i.getButtonJustPressed(b.Gamepad,a.button),l=i.getButtonJustReleased(b.Gamepad,a.button),h=!0):a.type===b.Touch&&a.touchButton!==void 0?(n=i.getButton(b.Touch,a.touchButton),o=i.getButtonJustPressed(b.Touch,a.touchButton),l=i.getButtonJustReleased(b.Touch,a.touchButton),h=!0):a.type===b.TouchZone&&a.touchZoneId!==void 0&&(n=i.getButton(b.TouchZone,a.touchZoneId),o=i.getButtonJustPressed(b.TouchZone,a.touchZoneId),l=i.getButtonJustReleased(b.TouchZone,a.touchZoneId),h=!0),h&&s.set(a.sourceId,{pressed:n,justPressed:o,justReleased:l})}return s}static collectMousePosition(e,i,s,r,a){let n=e.getAxis(b.Mouse,100),o=e.getAxis(b.Mouse,101),l=e.getButton(b.Mouse,0),{renderWidth:h,renderHeight:d,offsetX:c,offsetY:u,rect:f}=ft.calculateRenderMetrics(i,a),p=n-f.left-c,m=o-f.top-u,y=h/s,C=d/r,v=Math.floor(p/y),x=Math.floor(m/C),E=p>=0&&p<h&&m>=0&&m<d;return{x:Math.max(0,Math.min(s-1,v)),y:Math.max(0,Math.min(r-1,x)),over:E,isLeftDown:l}}static collectTouchPositions(e,i,s,r,a=10,n){let o=[],{renderWidth:l,renderHeight:h,offsetX:d,offsetY:c,rect:u}=ft.calculateRenderMetrics(i,n),f=l/s,p=h/r;for(let m=0;m<a;m++)if(e.getButton(b.Touch,m)){let y=100+m*2,C=100+m*2+1,v=e.getAxis(b.Touch,y),x=e.getAxis(b.Touch,C),E=v-u.left-d,P=x-u.top-c,L=Math.floor(E/f),z=Math.floor(P/p),O=E>=0&&E<l&&P>=0&&P<h;o.push({id:m,x:Math.max(0,Math.min(s-1,L)),y:Math.max(0,Math.min(r-1,z)),over:O})}return o}static collectTextInputs(e){return typeof e.getTextInputs=="function"?e.getTextInputs():[]}};var xs=class{data;head=0;count=0;windowSize;totalFrames=0;s=0;p=0;u=0;f=0;m=0;n=0;constructor(t=120){this.windowSize=t,this.data=new Float64Array(t*4)}beginFrame(){this.s=performance.now()}beginUpdate(){this.p=performance.now()}endUpdate(){this.u=performance.now()}beginRender(){this.f=performance.now()}endRender(){this.m=performance.now()}endFrame(){let t=performance.now(),e=t-this.s,i=this.u-this.p,s=this.m-this.f,r=this.n>0?Math.max(0,this.s-this.n):0;this.n=t,this.totalFrames++;let a=this.head*4;this.data[a+0]=e,this.data[a+1]=i,this.data[a+2]=s,this.data[a+3]=r,this.head=(this.head+1)%this.windowSize,this.count<this.windowSize&&this.count++}getSnapshot(){if(this.count===0)return{fps:0,lastFrameMs:0,avgFrameMs:0,peakFrameMs:0,lastUpdateMs:0,avgUpdateMs:0,lastRenderMs:0,avgRenderMs:0,lastIdleMs:0,totalFrames:0};let t=(this.head-1+this.windowSize)%this.windowSize*4,e=0,i=0,s=0,r=0,a=this.count<this.windowSize?0:this.head;for(let o=0;o<this.count;o++){let l=(a+o)%this.windowSize*4,h=this.data[l+0];e+=h,h>i&&(i=h),s+=this.data[l+1],r+=this.data[l+2]}let n=e/this.count;return{fps:n>0?1e3/n:0,lastFrameMs:this.data[t+0],avgFrameMs:n,peakFrameMs:i,lastUpdateMs:this.data[t+1],avgUpdateMs:s/this.count,lastRenderMs:this.data[t+2],avgRenderMs:r/this.count,lastIdleMs:this.data[t+3],totalFrames:this.totalFrames}}reset(){this.head=0,this.count=0,this.totalFrames=0,this.data.fill(0),this.n=0}},Is="iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAAR8ElEQVR4Ae3BC3JbW5AkwUgOFy6uPCe6rcas5tgFBFDQ74nu4R9XcUfEHRV3RPzB3nlQxRKxVCwRo0JRhSIOVcSFihFxoYr4CSqWiCViqThULBGjYom4oUIRqlCEKhRVEapQhKo3HlChDFQxKg4VqhgVo2KpUMWhYqk4VKjihg5uyOBQ5VAxoh4iDhEXKpSBKi5U3FBxiCoOVfTGH6BiqVgiloilYqk4VIyKQ8SI+AkqFPGTVByiilFF6I2fLOJCxIhYIpYKRajiL9LBEjEi1IEifoHwoIolYqlYIpaKEXGhirihirihirihQhGjYkSoYkSoYolQhSKWiiVCFYo4VChiqThELBVLxKiiCkVV/ge/UBXxCRUj4lAxIh5UcUfEHRV3RBVLxFJxIUIVS8SFCkWMKkIVilAV/nEVd0TcUXFHxIMqFPGLhL9ExSHiyw8JSxVxRxVxoUIRS4UiVKEIVdwQVShiVCjiQRWKuFChiCdVKOKOCkU8qYp4oTdGxYMqDhWj4kEVihgRS4Q6UAYPqhgVh4pRMfodqGJU3FAxKg4dXKj4jg5u6GB5QxVPqhgVh4oXqVCEKp5QcagYFYeKB1QcKg4Vh4oHVIweGBWj4kHvKKp4QsSIUIUiHhR18EkVFyIUoQpFjIobqqjiQlTxk0UVijhUHKoIVSwVyv9gqSLuqCKWigsRT6hQVKEIVYyIpeJChCouRBV3RKhiiRgVS8SFiiVCFRcilirihgpFHCqWCIUXqVgiRoUiVKGIpUJRxRKhCkWMigsRo2KJeFKFIg4VirijQhEvVqGICxWKGOGFKhTxQhVLxCdUKOLL/3rnCRWKWCoUdUQsFYoqFHGoUMQh4oaKEfFJFYpYKhTxH/LGH6KD0cGFDkaFIlTxCRWKOESo4tDB6ODQwW/Wgd74BSpGxahQhSKUBWWgCkW8UIUibohQxRKhDhTxB6pQhMITKhTxpApFFYoYFYeIpUIRh4oR8aQKRdxRoQhV3BFVXIh4QMWFiCdUKGKEJ1Qo4gkVN0QsVVShCFUo4lChqEJRFfGACkXcUaGIpWKJOFQo4herUMQSfpEKRRWKUMWFCFUoQhWKUIUiVKGIJ1Qo4kKFIpYKRahCEUuFIi5UKOITKhSxVCjiEJ5QoYgnVSiqUMRSoYg7KhQxKkZUoYgnVChiqVDET1KhiE+oUMSXv0sHv1gYFUvEoUIRh4olYqlYIi5UKGJUXIhYKkbEqLgQMSqWiKViifgJKhTxhApFXKhYIhRUoQhVKGJUjIilQhGqUIQqFKEKRSwVI2JUKOKGCkV8R4UiVKEIVShCFYpQhSJeqEIRn1ChiKVCEapQ9M6h4kJUcSHijojvqPiOihExKhTxHRWKeLEKRVyoUMShQhGHigsRS9QRMSJGhSIUVHEhYqlQxA0VijhUjIhRoahCETdUKEIVh4hDhSIOFUvEUnGIWCoUcaFCEUuFIl6gQhFLhSJGUMWIKhSxVCjiQoUi7qhQhCouRFyoUIQqFKEKRYwKRRwqFKEKRVyoUMSLVCjiUHEh4lChiEOFIsY7S8QnVSjiUKGICxGjQhGjQhG/WYUiDhWKuFChiEPUEbFEPKBCERciDmFULBGj4kKEKi5EjIol4kKFIpaKJWKpWCKWCkVcqFgilooRcaFCERcqFHFDhSKeUKGIGyoU8eXX6uAPE0bFErFULBGj4hCxVCwRo2KJWCouRKjiQsSoWCJGhSJUoQhVXIgYFYcIVShCFYpQhSIuVChiVCiqUIQqFDEqlgi9oQploIpRoQxUcchAFaNCGajiEKGKCzlwyIFRoQxU8aAMRgZLBiPiQoUinlShiidUKANV6I1DxU+WwYUIVfwkGfxiFYr4pIobKp70zoWo4lBxR8WIeLGKEXGoGBEXKkbEUvGTRXxSVEUVFyqe8MaFigsZ3JCBKl4sCxeycEPEDRn8RBU/IOKGiCe9ccjCT9LBhQpF/CU6+I4IVfwkEU94R1EHI+JJFSNiRB2MiEOFIi5ULBEPiDoYEQ+qWCoUoagDRdwQdUQsFUvEC0QdjIgvX4IqDhFLxRIxKg4RS8USMSouRKhCEapQhCoUoQpFqEIRo0JRhSJUoQhVKEIVilDFhYhRsUQ8oWKJOFQo4kFvLBmoYlQoA1UcMlDFqFAGqhgZjAz+EjlwRwZLB3dkcEPFqHjQG79BBn+ICHWgiE+oUMSDIlTxCRXKQBUPeGPpQBFP6kARI0Jd+E0qLkSMiCVCHSjiUKGIJ0Wo4kkZjAwe8MaShRuqiAsRN2RBFb9YhSoOFaPiEDEiDhWK+KQIVfwib3xCFXEhQhWjg58kQh0o4kLEoUIZqOJBFYr4QRGq+AXeeUDUEXVEPCDqYEQ8KOpgRCxRhSIuRCiqeLGKJeJQoYgbIg4Vn1Dx5cstYVQo4kkViniBCkU8oWJEPKhCEXdUKOKGCkWMCkXcUDEifpE3RoQq/kIVilDFi2VwRwZPivgN3lmijoilYok4VIyIpWKJWCruqFgibog4VBwilooRsVSMiAsVI+KGCkU8oEIRqlCEKg4RS8USoTcOGRyyoIpDBqoYFcpAFaNCGRwqlIEqRsXoYKlQBjdkoIol4jsivqNCEU/qYFQsGahiVCgDVeidB1W8SMQnVFyIKhTxh6pQxCdEVVTxAu88oEIRqvgBFYp4QsQnRB38RlFHxB/gjQdEqIMbOlDEiFAHihgR6uAQoS48KQufUDEqlg4eEKGKpWJU3BDxpAh1oAiFf0TFEvFCFSPiLxH+EBWK+A+rGBFLhSKWihFxoUIRo4q4440vv0yFMnhQBqo4VCiqUMWhg+UdVRwilopDhCoUVShiqThEqGJUKGJUKEIVilCFIlShCFUoYlQoqlCEKhShCkWoQhGquBDxi0QoqlDEqBhVhN5YMlDFqFAGN1QRqhgVyoERMTL4SSoOEepAEQ/KwogYHSjikyLUwYhYMhgVhwq98UIRymBEqAt/mIgR8QkVilgyUMUnVSiDF3hnqRgRI+rgkyJGR8SFCkU8IOpgRBwqVHGoGFXEiDq4oUIRf5gIVShiBFUo4gEVilCFIi5UHCIOFSNiqThELBWKOFQoqlCEKhShCkVcqFCEKi5EHCpGxFKhiKViRHxCxRKhoApFPKBCEf+IiiXiPyCMiiViVChCFYo4VCjiUKGIpUIRqlDEqFDEDRWK+IQKRSwVilCFIkaFIg4VilCFIpYKRRwqFHGoUIQqFLFUKGLrYHTwpA4OHYwOntTBhYpR8YQORgdP6uBJHYwODh18QsWoGEEVirhQoQhVKGJULBFLxRKxVCwRS8USsVQsEUvFErFULBFLxRKxVCwRhwpFvFjFErFULBH/Twc3dDA6GB2MDm7o4IYObujghg5GBzd0MDoYHYwORgejg0MHN3RwQweHDkYHo4PRgd65UKGIJ1TcUHFHxR0Vd1T8oIo7Ku6o+I0q7qg4vKOogxHxpIgLFYpQxVKhCFUsFYpQxVKhCFUsUQcj4hBxR8QdEb9RhCouRKhivDEiRsQSoQ4OEerCEqEODhHq4BChDg4R6uBCxIhYItSFJUJdWCLUhb9NB/9RHXz5/7wzIlShiCdUXIgYFYpYKhShCkWMCkXcUKGIJ1QoQhWKUIUiVKEIVShCFYp4QsWIGBWKUIUiVHGIuFAx8j9YKhTxhApFFYoYFYpQhSKeUKGIpUIRqlDEUqGI36BCEYcKRRWKUIUiVKEIVShCFYpYKhRVKKjiQoQqFFWMCFUoqlDEUrFELBVLxFKxRLxIhSJUoYhRsUSMCkWoQhGj4hAxKhRxoWKJGBWHiEOFIsb/Qd+Eoo+F8TEqFH0bH/om9E2Mb+NDFYo+9G18CFUo+tC38SFUoehD38aHUPVNH0LVN30IVd/0IVR904fQN6EPoW9CH0IVij70bXwIfRP6EPom9CFUoehjYVSMb+NDjIrDN30IfROKPkb1IUbF+KYPoXeWihExKpaKC1GFIv4SUQe/QVShiEOEKhRxR8UhqlDEeGeJOFQoqlDEf0zEqHihqIMl4gEVS4UiDhWjirgjqOJChCpGVDGiCkUVS4QqloilYolYKpaIpeIQMSoOEaNiiVgqloilYok4VChiqbgQsVQoYqlQhCoUVSiqUMQIX/6TKhRVjIglHCoUcaFCERcqFHGhQhFLhaIKRYwKRRWKWCpGxKFiRBwqFPFCFYq4UKGIOyoU8SJhqVDEhQpFXKhQxIUKRSwViioUMSoUVSjihgpFjApFFYr4ySpGxKFiRPxib4yKUXEhgwsVo+JCBocMlMENEao4dPBJHbxQxIUKRVyoOHRwoQN1oA7UwfLOiBgdEUuFIpYKRagjQhWKUIUiVHGIOFQRFyoUVTypQhFLxQ1RxQ0RFyruqHhChaIKRSjqiDoi9M6o+M0i1BFxqLgQdXAh6kARo0IRN0RciDhU3FChiAsVilgqRhWhCkUViliijqgjekcVilDFHyiquCHijogHVCjiBSJUoYglQhWKeFDUEXVEjApFFYpQGBWHiKVCEYeKJWKpOESoQhGqUIQqFKEKRYyKQ8SoOESMiiXihSoUcaHiELFUKOJQoahCUYWiCkWM8OWnq1BUMSIuVCjiV6lYKlSxVCwVqlCFKg4d3NDBDR1c6EAdvFAH6mDpQB08oQN1sHSgDg4dPOGtQhGqUIQiVKEIVSiqoiqqooovf7S3CFUoQhWqUIQqFKEqqqIqqiK+/NHeqwxUZaAIVRmoyqiiKqqiKuKOijsqDlWEKu6ouCGquBChiqVCEQ+ouBChiqVCEaq4oeJCFaGKQ8SpYqlQxVKxVKhCFao4dHBDBzd04dCBOlg6UAeHLhw6UAdLB+pg6UAd/GIdLG8VilCFIhShCkWoQlEVVVEVVfwEET9RxD/iLUIVilCFKhShCkWoiqqoiqqIL3+0twpFqEIRilCFIlShqIqqqIoqvvzR3iNGxQ1RhTIYEYpQhCKeEPFJUUfEkyoUVShiRIyIJ0WMiEOFogpFPKhCUYUivuONL/+0N/6DunBHxT8uLBUvFjEqXixiVBwiVKGoYkSo4kKEKn6CCFX8Bu8sET+gQhF3RHxChSLuiHhAxIh4QFShiAdVKKpQxCGqUMSDKhRVKOI73vnyR6u4I+KOijve+fJHi/gBEXe88eWfFkaFogpFvFCFIg4ViioU8UIVijhUKKpQxFKhiAdV3BFxR8UScUfFE9748k9748s/7b1iqRgVPyjiUDEiloobKg4RqjhEFYeKGypGxRMq/jLhRSoUVSjiF6lQVKGIpUIRhwpFFYp4QoUiRsULRdxRsUTc8c53VNwR8aCKQ8SDKg4Rd1QcKkbEP+yd74gYFYr4hIgXiHhQxKhQxJf/9caXf1p4QMUhYlRciHhAxYWIX6hCEYeKJWKpWCIOFSPikyoUsVQsEaNiiVB4QIUiVKEIVShCFYp4QIUifoOKCxGqUIQqFKEKRahCEaNCET+gQhFLhSIOFYpQhaJ3VLFEFYp4UsRScUNGR8SFigtRhSJUoQhVXIgqFFUo6oh4gagjYqlQVDEiVHGoIlShiCe9VSgDVVzoQBEPihgRI2JEqOJQoQxGxAMyGBk8qYNPqBgVo0JRhSLUgSJGhCqWHnjAO0+IUEfEi1Qo4g8VoYol6mBEjApFqCPihSKe9BahDhTxC1Uo4gd0oIgHRKhiVCjiARXKQBUPiFCFogploIpRoQhFqOJJ7yjiEHGhQhEvVrFEKOpgRBwiPiFCFYpYog5GxIOiDkbEiFgiLkTcEHUwIhSxRDyjgz9UB/9BHfwk4QkVijhUKOKOCkVcqBgRS4UiXqxiRPwkFUtUoahCEaNiiXiRoIoLEUuFIi5UKOJChSIuVCiqUMSoUMSFCkUsFSOqUIQqFFUo4ieoUMRSoahCEYcKRbzAO4q4o2KpUMQSdUQsFYr4SSIOFYo6UMRfpkIRh4ol4gHvqOJChCJUoYgLFYo4RB0R3xHxoIoLGYyIC1EHirhQoYhfrEIRL/SOIn5QhSJuiDoiXiTijooRVShiRPygCkWMihHxCRWjQhEvEFRxIeIXqlDEqFBUoYgLFYoYFYoqRsQvUqGoQhEvVLFEPCA8oOJChCouRKjiQsRSoYhRoahCEX+ZiiXiDxD+IBWKWCpGxF+qYkT8Af4vDu0nt4v6zWEAAAAASUVORK5CYII=",j={glyphWidth:8,glyphHeight:8,cellWidth:8,cellHeight:8,atlasBlocks:1,atlasWidth:128,atlasHeight:128};function jt(){if(typeof atob=="function"){let t=atob(Is),e=new Uint8Array(t.length);for(let i=0;i<t.length;i++)e[i]=t.charCodeAt(i);return e}throw new Error("[Primitiv] decodeDefaultAtlas: atob() is not available in this environment")}var Jt=class{async load(t){let e=await fetch(t);if(!e.ok)throw new Error(`[FetchResourceLoader] Failed to load resource: ${t} (${e.status})`);return new Uint8Array(await e.arrayBuffer())}},R=U.create("client"),_t=class H{options;renderer=null;engine=null;inputRouter=null;postProcessOverlay=null;autoplayOverlay=null;audioEngine=null;audioInitialized=!1;macroEngine=null;lastPostProcessHash="";running=!1;lastFrameTime=0;frameId=null;tickRate=60;loopback=null;networkClient=null;networkTransport=null;e=!1;bridgeHandlers=new Map;onBridgeMessage=null;o=!1;l={width:0,height:0};i=null;localDisplays=new Map;localLayers=new Map;h=new Map;d=new Map;c=new Map;perfMonitor=new xs;pendingAudioAcks=[];t=new Map;constructor(e){let i={renderer:Q.TerminalGL,renderMode:"continuous",autoplay:!0,debug:!1};if(this.options={...i,...e},e.logLevel&&U.setLevel(e.logLevel),e.logFilter)for(let[s,r]of Object.entries(e.logFilter))U.setLevel(s,r);R.info(`Initializing ClientRuntime in ${this.options.mode} mode`),this.initRenderer(),this.options.autoplay?this.start():this.showAutoplayOverlay()}initRenderer(){let{container:e,renderer:i}=this.options;if(!e)throw new Error("[ClientRuntime] Container element is required");let s={cols:this.options.width||80,rows:this.options.height||24,charWidth:8,charHeight:8};switch(i){case Q.TerminalGL:this.renderer=new Re(e,s),R.info("Renderer: WebGL");break;case Q.Terminal2D:this.renderer=new qe(e,{fixedCols:s.cols,fixedRows:s.rows,cellWidth:s.charWidth,cellHeight:s.charHeight}),R.info("Renderer: Canvas2D");break;default:this.renderer=new Re(e,s),R.info("Renderer: WebGL (default)")}}showAutoplayOverlay(){this.options.container&&(this.audioEngine=new Le,this.audioEngine.onAudioEvent=e=>this.pendingAudioAcks.push(e),this.autoplayOverlay=new Mt(this.options.container,{...this.options.autoplayOptions,onStart:()=>{this.audioEngine.initialize(),this.audioEngine.playStartSound(),this.autoplayOverlay?.destroy(),this.autoplayOverlay=null,this.start()}}))}starting=!1;async start(){if(!(this.running||this.starting)){if(this.starting=!0,this.renderer&&"setImageFont"in this.renderer){let e=jt();await this.renderer.setImageFont(e,j.glyphWidth,j.glyphHeight,j.cellWidth,j.cellHeight,j.atlasBlocks)}if(this.running=!0,this.starting=!1,this.options.mode==="standalone"&&this.options.standalone){R.info("Starting in standalone mode"),this.engine=new st({mode:"standalone"}),this.engine.setResourceLoader(new Jt),this.macroEngine=new ot,this.macroEngine.register("particle",new lt),this.macroEngine.register("effect",new ht),this.macroEngine.register("reveal",new dt),this.macroEngine.register("line",new ct),this.macroEngine.register("ui",new ut),this.wireFontCallbacks(),await this.options.standalone.application.init(this,this.engine),R.info("Application initialized");let e=this.options.standalone.userId||"user-1",i=new it(e,this.options.standalone.username||"Player");if(this.engine.sessions.set(e,i),i.setSpriteRegistry(this.engine.spriteRegistry),this.options.standalone.application.initUser(this,this.engine,i,{username:this.options.standalone.username||"Player"}),this.audioEngine||(this.audioEngine=new Le,this.audioEngine.onAudioEvent=s=>this.pendingAudioAcks.push(s)),await this.loadSoundsFromRegistry(),this.options.container&&(this.postProcessOverlay=new ke(this.options.container)),this.inputRouter=new $t({enableKeyboardMouse:!0,enableGamepad:!0,enableTouch:!0,targetElement:window,gridWidth:this.options.width||80,gridHeight:this.options.height||24,debug:this.options.debug}),this.loopback=new Kt,this.loopback.onMessage=s=>{this.applyUpdate(s)},this.options.displaySlots)for(let s of this.options.displaySlots)this.addDisplaySlot(s)}else if((this.options.mode==="client"||this.options.mode==="socketio"||this.options.mode==="webrtc")&&(await this.initConnectedMode(),this.options.displaySlots))for(let e of this.options.displaySlots)this.addDisplaySlot(e);this.lastFrameTime=performance.now(),this.options.mode==="standalone"&&this.loop()}}async initConnectedMode(){let e=this.options,i=e.url;if(!i)throw new Error("[ClientRuntime] Connected mode requires a url");this.engine=new st({mode:"client"}),this.engine.setResourceLoader(new Jt),this.macroEngine=new ot,this.macroEngine.register("particle",new lt),this.macroEngine.register("effect",new ht),this.macroEngine.register("reveal",new dt),this.macroEngine.register("line",new ct),this.macroEngine.register("ui",new ut),this.wireFontCallbacks(),this.audioEngine||(this.audioEngine=new Le,this.audioEngine.onAudioEvent=r=>this.pendingAudioAcks.push(r)),this.options.container&&(this.postProcessOverlay=new ke(this.options.container));let s=()=>({network:this.networkClient,engine:this.engine,connected:this.e,latency:this.networkClient?.getRtt()??0,sendInput:(r,a)=>{this.networkClient?.sendInput(r,a)},sendBridgeMessage:r=>{this.networkClient?.sendBridgeMessage(r)}});this.networkClient=new De({version:{major:0,minor:0,patch:0},username:"Player"},{onSimulationStart:()=>{this.e=!0,R.info("Simulation started \u2014 receiving server updates"),this.startInputTracking(),e.application?.onConnect?.(s())},onUpdate:(r,a,n)=>{this.applyUpdate(a),this.flushPendingAudioAcks(),this.flushPendingMacroFeedback(),this.sendClientInput(),e.application?.onUpdate?.(s(),r,a)},onLoadBundle:(r,a)=>{R.info(`LoadBundle received: ${a.byteLength} bytes`),this.applyUpdate(a),this.flushPendingAudioAcks(),this.flushPendingMacroFeedback(),this.networkClient&&(this.networkClient.sendLoadingProgress(100),this.networkClient.sendReady())},onBridgeMessage:r=>{this.handleIncomingBridge(r),e.application?.onBridgeMessage?.(s(),r)},onError:r=>{R.error("Network error",r),e.application?.onError?.(s(),r)},onDisconnect:r=>{this.e=!1,R.warn(`Disconnected: ${r}`),e.application?.onDisconnect?.(s(),r)},onHandshakeState:r=>{R.debug(`Handshake state: ${r}`)},onServerConfig:r=>{R.info(`Server config: tickRate=${r.tickRate}`),this.tickRate=r.tickRate}}),e.mode==="webrtc"?(this.networkTransport=new Xt(e.webrtc??{mode:"full"}),R.info("Transport: WebRTC")):(this.networkTransport=new Pe,R.info("Transport: WebSocket"));try{await this.networkClient.connect(this.networkTransport,i),R.info(`Connected to ${i}`)}catch(r){R.error("Failed to connect",r),e.application?.onError?.(s(),String(r))}}stop(){R.info("Stopping client runtime"),this.running=!1,this.starting=!1,this.frameId!==null&&(cancelAnimationFrame(this.frameId),this.frameId=null),this.inputRouter&&(this.inputRouter.destroy(),this.inputRouter=null),this.postProcessOverlay&&(this.postProcessOverlay.destroy(),this.postProcessOverlay=null),this.autoplayOverlay&&(this.autoplayOverlay.destroy(),this.autoplayOverlay=null),this.audioEngine&&(this.audioEngine.stopAll(),this.audioEngine=null,this.audioInitialized=!1),this.macroEngine=null,this.loopback&&(this.loopback.close(),this.loopback=null),this.stopInputTracking(),this.networkClient&&(this.networkClient.disconnect("client_stop"),this.networkClient=null),this.networkTransport&&(this.networkTransport=null),this.e=!1,this.localDisplays.clear(),this.localLayers.clear(),this.lastPostProcessHash="";for(let e of this.t.values())e.renderer.destroy(),e.postProcess?.destroy();this.t.clear()}loop=()=>{if(this.running){this.perfMonitor.beginFrame();try{let e=performance.now(),i=(e-this.lastFrameTime)/1e3;if(this.lastFrameTime=e,this.collectAndApplyInput(),this.perfMonitor.beginUpdate(),this.update(i),this.perfMonitor.endUpdate(),this.flushPendingAudioAcks(),this.macroEngine&&this.engine){let s=this.collectMacroInput();this.macroEngine.tick(i,this.localLayers,s)}this.flushPendingMacroFeedback(),this.perfMonitor.beginRender(),this.render(),this.perfMonitor.endRender(),this.inputRouter?.poll(),this.options.mode==="standalone"&&this.options.standalone.application.onCommit?.(this,{},i)}catch(e){R.error("Error in loop",e)}this.perfMonitor.endFrame(),this.options.renderMode==="continuous"&&this.options.mode==="standalone"&&(this.frameId=requestAnimationFrame(this.loop))}};scheduleConnectedRender(){this.o||!this.running||(this.o=!0,R.trace("scheduleConnectedRender \u2014 scheduling RAF"),requestAnimationFrame(()=>{if(this.o=!1,!!this.running){this.perfMonitor.beginFrame(),this.perfMonitor.beginUpdate(),this.perfMonitor.endUpdate();try{if(this.macroEngine){let e=this.collectMacroInput();this.macroEngine.tick(1/this.tickRate,this.localLayers,e)}this.perfMonitor.beginRender(),this.render(),this.perfMonitor.endRender()}catch(e){R.error("Error in connected render",e)}this.perfMonitor.endFrame()}}))}update(e){if(this.options.mode==="standalone"&&this.options.standalone&&this.engine){this.options.standalone.application.update?.(this,this.engine,e);for(let i of this.engine.sessions.values()){this.options.standalone.application.updateUser(this,this.engine,i,e),i.C&&(i.C=!1,this.loadSoundsFromRegistry());let{reliable:s,volatile:r}=this.engine.endTick(i);this.loopback&&(s.byteLength>0&&this.loopback.send(s,!0),r.byteLength>0&&this.loopback.send(r,!1)),i.poll()}}}collectAndApplyInput(){if(!this.inputRouter||!this.renderer||!this.engine)return;let e=this.renderer.getCanvas();if(!e)return;let i=this.renderer.getOffsets?.()??{offsetX:0,offsetY:0};for(let s of this.engine.sessions.values()){let r=s.getDisplay(s.activeDisplay);if(!r)continue;let a=r.width,n=r.height,o=Oe.collectMousePosition(this.inputRouter,e,a,n,i),l=s.getInputBindingRegistry(),h=l.getAllButtons(),d=l.getAllAxes(),c=Oe.collectButtonSources(h,this.inputRouter),u=Oe.collectAxisSources(d,this.inputRouter),f=new Map;for(let y of h)f.set(y.bindingId,l.evaluateButton(y.bindingId,c));let p=new Map;for(let y of d)p.set(y.bindingId,l.evaluateAxis(y.bindingId,u));let m={axes:p,buttons:f,displayId:s.activeDisplay,mouseX:o.x,mouseY:o.y,mouseOverDisplay:o.over,isTabHidden:document.hidden,textInputs:this.inputRouter.getTextInputs()??[],displayViewports:[],touchPositions:[]};s.applyInput(m,l)}}render(){if(!this.renderer||!this.running||!this.renderer.isReady())return;let e=null,i=[],s=[];if(this.options.mode==="standalone"&&this.options.standalone&&this.engine){let c=Array.from(this.engine.sessions.values());if(c.length===0)return;let u=c[0];if(e=u.getDisplay(u.activeDisplay)??null,!e)return;i=u.getLayers(),s=this.engine.getPalette(e.activePaletteSlot)||[]}else if(this.options.mode==="client"&&this.engine){let c=this.options.renderDisplayId??0;if(!this.localDisplays.has(c)||(e=this.localDisplays.get(c)??null,!e))return;i=Array.from(this.localLayers.values()),s=this.engine.getPalette(e.activePaletteSlot)||[]}if(!e)return;if("setScalingMode"in this.renderer){let c=this.renderer;c.getScalingMode()!==e.scalingMode&&c.setScalingMode(e.scalingMode)}if("setCellSize"in this.renderer){let c=this.renderer,u=c.getCellSize?.()??{cellWidth:c.getCellWidth?.()??8,cellHeight:c.getCellHeight?.()??8};(u.cellWidth!==e.cellWidth||u.cellHeight!==e.cellHeight)&&c.setCellSize(e.cellWidth,e.cellHeight)}if(e.scalingMode===T.Responsive&&"getAvailableSize"in this.renderer){let c=this.renderer,u=c.getAvailableSize(),f=c.getCellWidth(),p=c.getCellHeight();if(u.width>0&&u.height>0&&f>0&&p>0){let m=Math.floor(u.width/f),y=Math.floor(u.height/p);m=Math.min(256,Math.max(1,m)),y=Math.min(256,Math.max(1,y));let C="getMaxCells"in c?Math.min(256*256,c.getMaxCells()):256*256;if(m*y>C){let v=Math.sqrt(C/(m*y));m=Math.max(1,Math.floor(m*v)),y=Math.max(1,Math.floor(y*v))}(e.width!==m||e.height!==y)&&(e.resize(m,y),this.renderer.resize(m,y)),this.options.mode==="client"&&this.networkClient&&(u.width!==this.l.width||u.height!==this.l.height)&&(this.l={width:u.width,height:u.height},this.sendViewportResize(0,u.width,u.height),this.networkClient.flush())}}this.syncPostProcess(e.postProcess);let r=new rt,a=new ue(e.width,e.height);r.composite(e,i,a),this.renderer.setPalette(s);let n=e.width,o=e.height,l=n*o,h=new Array(l);for(let c=0;c<l;c++){let u=a.data[c],f=u&65535,p=u>>>16&255,m=u>>>24&255;h[c]={char:f===0?" ":String.fromCharCode(f),fgColorIndex:p,bgColorIndex:m,fgEmission:0,bgEmission:0}}let d={id:e.id,width:n,height:o,cells:h,palette:s.map(c=>({r:c.r,g:c.g,b:c.b,a:c.a}))};this.renderer.renderDisplayData(d),this.renderExtraSlots(i,s)}renderExtraSlots(e,i){if(this.t.size!==0)for(let s of this.t.values()){if(!s.renderer.isReady())continue;let r=null,a=i;if(this.options.mode==="standalone"&&this.engine){let u=Array.from(this.engine.sessions.values());if(u.length===0)continue;r=u[0].getDisplay(s.displayId)??null,r&&(a=this.engine.getPalette(r.activePaletteSlot)||i)}else this.engine&&(r=this.localDisplays.get(s.displayId)??null,r&&(a=this.engine.getPalette(r.activePaletteSlot)||i));if(!r)continue;if("setCellSize"in s.renderer){let u=s.renderer,f=u.getCellSize?.()??{cellWidth:8,cellHeight:8};(f.cellWidth!==r.cellWidth||f.cellHeight!==r.cellHeight)&&u.setCellSize(r.cellWidth,r.cellHeight)}if("setScalingMode"in s.renderer){let u=s.renderer;u.getScalingMode()!==r.scalingMode&&u.setScalingMode(r.scalingMode)}if(r.scalingMode===T.Responsive&&"getAvailableSize"in s.renderer){let u=s.renderer,f=u.getAvailableSize(),p=u.getCellWidth(),m=u.getCellHeight();if(f.width>0&&f.height>0&&p>0&&m>0){let y=Math.min(256,Math.max(1,Math.floor(f.width/p))),C=Math.min(256,Math.max(1,Math.floor(f.height/m))),v="getMaxCells"in u?Math.min(256*256,u.getMaxCells()):256*256;if(y*C>v){let x=Math.sqrt(v/(y*C));y=Math.max(1,Math.floor(y*x)),C=Math.max(1,Math.floor(C*x))}(r.width!==y||r.height!==C)&&(r.resize(y,C),s.renderer.resize(y,C))}}if(s.postProcess){let u=JSON.stringify(r.postProcess);u!==s.lastPostProcessHash&&(s.lastPostProcessHash=u,s.postProcess.setConfig(r.postProcess))}let n=new rt,o=new ue(r.width,r.height);n.composite(r,e,o),s.renderer.setPalette(a);let l=r.width,h=r.height,d=l*h,c=new Array(d);for(let u=0;u<d;u++){let f=o.data[u];c[u]={char:f&65535?String.fromCharCode(f&65535):" ",fgColorIndex:f>>>16&255,bgColorIndex:f>>>24&255,fgEmission:0,bgEmission:0}}s.renderer.renderDisplayData({id:r.id,width:l,height:h,cells:c,palette:a.map(u=>({r:u.r,g:u.g,b:u.b,a:u.a}))})}}syncPostProcess(e){let i=JSON.stringify(e);if(i!==this.lastPostProcessHash&&(this.lastPostProcessHash=i,this.postProcessOverlay&&this.postProcessOverlay.setConfig(e),this.renderer&&"setAmbientEffect"in this.renderer)){let s=this.renderer,r=e.ambientEffect;r&&r.enabled?s.setAmbientEffect({blur:r.blur,scale:r.scale}):s.isAmbientEffectEnabled?.()&&s.setAmbientEffect(!1)}}sendClientInput(){if(!this.networkClient||!this.e)return;let e=Ke();e.isTabHidden=document.hidden;let i=Pt(e);this.networkClient.sendInput(i,!0)}startInputTracking(){this.i||(this.i=()=>{this.sendClientInput()},document.addEventListener("visibilitychange",this.i),R.debug("Input tracking started (visibility \u2192 input packet)"))}stopInputTracking(){this.i&&(document.removeEventListener("visibilitychange",this.i),this.i=null)}sendViewportResize(e,i,s){if(!this.networkClient)return;let r=new Uint8Array(5),a=new DataView(r.buffer);r[0]=e,a.setUint16(1,Math.min(i,65535),!1),a.setUint16(3,Math.min(s,65535),!1),this.networkClient.sendInput(r,!0)}applyUpdate(e){if(!this.engine||e.byteLength===0)return;R.trace(()=>`applyUpdate payload size=${e.byteLength}, connected=${this.e}`);let i=Vt.decode(e),s=this.options.mode==="standalone",r=null;if(s){let a=Array.from(this.engine.sessions.values());if(a.length===0)return;r=a[0]}if(!s)for(let a of i.displays){let n=this.localDisplays.get(a.id);n||(n=new tt(a.id,a.width,a.height),this.localDisplays.set(a.id,n)),(n.width!==a.width||n.height!==a.height)&&n.resize(a.width,a.height),n.switchPalette(a.paletteSlot),n.setScalingMode(a.scalingMode),n.setCellSize(a.cellWidth,a.cellHeight),a.renderPasses&&a.renderPasses.length>0?n.setRenderPasses(a.renderPasses):n.renderPasses&&n.setRenderPasses(void 0)}if(i.palettes.length>0&&this.engine)for(let a of i.palettes)this.engine.loadPaletteToSlot(a.slot,a.colors);for(let a of i.layers){let n;r?n=r.getLayer(a.id):n=this.localLayers.get(a.id),n||(n=new et(new N(a.originX,a.originY),a.zIndex,a.width,a.height,{mustBeReliable:!1,isMacroLayer:a.isMacro,charCodeMode:a.is16bit?"16bit":"8bit"}),n.setId(a.id),this.engine.spriteRegistry&&n.setSpriteRegistry(this.engine.spriteRegistry),r?r.layers?.set(a.id,n):this.localLayers.set(a.id,n)),n.zIndex=a.zIndex;let o=n.getOrigin();o.x=a.originX,o.y=a.originY,n.x=a.originX,n.y=a.originY,a.orders.length>0&&n.setOrders(a.orders),n.clearPendingOrders(),n.clearCommit()}i.audioOrders.length>0&&this.processDecodedAudioCommands(i.audioOrders);for(let a of i.vibrationOrders)"target"in a&&a.target==="gamepad"?this.dispatchGamepadVibration(a):"pattern"in a&&typeof navigator<"u"&&"vibrate"in navigator&&navigator.vibrate(a.pattern);i.macroDefines.length>0&&this.macroEngine?.loadDefines(i.macroDefines),i.macroOrders.length>0&&this.macroEngine?.applyOrders(i.macroOrders),this.accumulateTrafficStats(i),this.options.mode==="client"&&this.scheduleConnectedRender()}processDecodedAudioCommands(e){if(this.audioEngine){this.ensureAudioInitialized();for(let i of e){if(i.sound==="__listener_position__"){this.audioEngine.setListenerPosition(i.x??0,i.y??0);continue}if(i.sound==="__configure_spatial__"){this.audioEngine.configureSpatial(i);continue}if(i.stop){i.sound==="all"?this.audioEngine.stopAll():this.audioEngine.stop(i.sound);continue}if(i.fadeOut!==void 0){this.audioEngine.fadeOut(i.sound,i.fadeOut);continue}if(i.pause){this.audioEngine.pause(i.sound);continue}if(i.resume){this.audioEngine.resume(i.sound);continue}if((i.lowpass!==void 0||i.highpass!==void 0||i.reverb!==void 0||i.pitch!==void 0||i.volume!==void 0)&&i.instanceId===void 0&&typeof i.sound=="number"){this.audioEngine.setEffects(i.sound,{lowpass:i.lowpass,highpass:i.highpass,reverb:i.reverb,pitch:i.pitch,volume:i.volume});continue}if(i.instanceId!==void 0){let s=i.sound,r=s;if(typeof s=="string"&&this.engine){let a=this.engine.soundRegistry.get(s);a&&(r=a.soundId)}this.audioEngine.play(r,{instanceId:i.instanceId,volume:i.volume,pitch:i.pitch,loop:i.loop,fadeIn:i.fadeIn,position:i.x!==void 0&&i.y!==void 0?{x:i.x,y:i.y}:void 0,name:typeof s=="string"?s:void 0,lowpass:i.lowpass,highpass:i.highpass,reverb:i.reverb})||this.pendingAudioAcks.push({type:"playback-error",sound:r,error:"sound not found or not loaded"})}}}}flushPendingAudioAcks(){if(this.pendingAudioAcks.length===0)return;let e=this.pendingAudioAcks;if(this.pendingAudioAcks=[],this.networkClient&&this.options.mode!=="standalone"){let i=at({audioAcks:e,macroFeedbacks:[]});this.networkClient.sendClientCallback(i)}else if(this.engine)for(let i of this.engine.sessions.values())for(let s of e)i.handleAudioAck(s)}flushPendingMacroFeedback(){if(!this.macroEngine)return;let e=this.macroEngine.getFeedbackQueue();if(e.length!==0){if(this.macroEngine.clearFeedbackQueue(),this.networkClient&&this.options.mode!=="standalone"){let i=at({audioAcks:[],macroFeedbacks:e});this.networkClient.sendClientCallback(i)}else if(this.engine)for(let i of this.engine.sessions.values())for(let s of e)i.handleMacroFeedback(s)}}collectMacroInput(){let e=this.inputRouter;return{mouseX:e?.getMouseGridX()??0,mouseY:e?.getMouseGridY()??0,mouseDown:e?.isMouseButtonDown(0)??!1,keysPressed:e?.getKeysPressed()??[],keysHeld:e?.getKeysHeld()??[]}}ensureAudioInitialized(){return this.audioInitialized?!0:this.audioEngine?(this.audioInitialized=this.audioEngine.initialize(),this.audioInitialized):!1}wireFontCallbacks(){if(!this.engine||!this.renderer)return;let e=this.renderer,i=this.engine;i.onFontAllocated(()=>{let s=i.getFontConfig();s&&typeof e.setImageFontStructure=="function"&&e.setImageFontStructure(s.glyphWidth,s.glyphHeight,s.cellWidth??s.glyphWidth,s.cellHeight??s.glyphHeight,s.atlasBlocks)}),i.onFontBlockAdded(s=>{let r=i.getFontBlock(s);r&&typeof e.setImageFontBlock=="function"&&e.setImageFontBlock(s,r)})}async loadSoundsFromRegistry(){if(!this.audioEngine||!this.engine)return;this.ensureAudioInitialized();let e=this.audioEngine.getLoader();if(!e)return;let i=this.engine.soundRegistry.toLoadPackets();for(let s of i)if(s.mode==="file"){for(let r of s.sounds)if(!e.has(r.soundId))try{await e.loadFromData(r.soundId,r.name,r.data),this.pendingAudioAcks.push({type:"sound-loaded",soundId:r.soundId,name:r.name})}catch(a){R.warn(`Failed to decode sound "${r.name}"`,a),this.pendingAudioAcks.push({type:"sound-error",soundId:r.soundId,name:r.name,error:String(a)})}}else if(s.mode==="external"){for(let r of s.sounds)if(!e.has(r.soundId))try{await e.loadFromUrl(r.soundId,r.name,r.url),this.pendingAudioAcks.push({type:"sound-loaded",soundId:r.soundId,name:r.name})}catch(a){R.warn(`Failed to load external sound "${r.name}"`,a),this.pendingAudioAcks.push({type:"sound-error",soundId:r.soundId,name:r.name,error:String(a)})}}}getMode(){return this.options.mode==="socketio"||this.options.mode==="webrtc"?"client":this.options.mode||"client"}isRunning(){return this.running}getTickRate(){return this.tickRate}setTickRate(e){this.tickRate=e}disconnectUser(e,i){return this.options.mode==="client"?(this.stop(),!0):!1}getStats(){let e=this.perfMonitor.getSnapshot();return{mode:this.options.mode==="standalone"?"standalone":"client",uptime:performance.now(),fps:e.fps,avgFrameMs:e.avgFrameMs,peakFrameMs:e.peakFrameMs,lastUpdateMs:e.lastUpdateMs,avgUpdateMs:e.avgUpdateMs,lastRenderMs:e.lastRenderMs,avgRenderMs:e.avgRenderMs,lastIdleMs:e.lastIdleMs,totalFrames:e.totalFrames,latencyMs:this.networkClient?.getRtt()??0}}getPerformanceStats(){return this.perfMonitor.getSnapshot()}addDisplaySlot(e){this.removeDisplaySlot(e.displayId);let i=e.renderer??this.options.renderer??Q.TerminalGL,s=e.width??this.options.width??80,r=e.height??this.options.height??24,a;switch(i){case Q.Terminal2D:a=new qe(e.container,{fixedCols:s,fixedRows:r,cellWidth:8,cellHeight:8});break;case Q.TerminalGL:default:a=new Re(e.container,{cols:s,rows:r,charWidth:8,charHeight:8});break}if("setImageFont"in a){let l=jt();a.setImageFont(l,j.glyphWidth,j.glyphHeight,j.cellWidth,j.cellHeight,j.atlasBlocks).catch(()=>{})}let n=new ke(e.container),o={displayId:e.displayId,container:e.container,renderer:a,postProcess:n,lastPostProcessHash:""};this.t.set(e.displayId,o),R.info(`Display slot added: displayId=${e.displayId}`)}removeDisplaySlot(e){let i=this.t.get(e);return i?(i.renderer.destroy(),i.postProcess?.destroy(),this.t.delete(e),R.info(`Display slot removed: displayId=${e}`),!0):!1}getDisplaySlotIds(){return Array.from(this.t.keys())}async destroy(){this.stop(),this.bridgeHandlers.clear(),this.renderer?.destroy(),this.renderer=null}getAudioEngine(){return this.audioEngine}getAudioManager(){return this.audioEngine}getEngine(){return this.engine}getCore(){return this.engine}static BRIDGE_FORMAT_JSON=0;static BRIDGE_FORMAT_BINARY=1;static textEncoder=new TextEncoder;static textDecoder=new TextDecoder;static encodeBridgeWire(e,i,s){let r=H.textEncoder.encode(e);if(r.length>255)throw new RangeError(`Bridge channel name exceeds 255 bytes: '${e}'`);let a=i==="json"?H.BRIDGE_FORMAT_JSON:H.BRIDGE_FORMAT_BINARY,n;i==="json"?n=H.textEncoder.encode(JSON.stringify(s)):n=s;let o=2+r.length+n.length,l=new Uint8Array(o);return l[0]=a,l[1]=r.length,l.set(r,2),l.set(n,2+r.length),l}sendBridge(...e){let i,s;e.length===3?[,i,s]=e:[i,s]=e;let r=H.encodeBridgeWire(i,"json",s);this.options.mode==="standalone"&&this.loopback?(this.dispatchBridge(i,s),this.onBridgeMessage?.({channel:i,type:"json",data:s})):this.networkClient&&(this.networkClient.sendBridgeMessage(r),this.networkClient.flush())}sendBridgeBinary(...e){let i,s;e.length===3?[,i,s]=e:[i,s]=e;let r=H.encodeBridgeWire(i,"binary",s);this.options.mode==="standalone"&&this.loopback?(this.dispatchBridge(i,s),this.onBridgeMessage?.({channel:i,type:"binary",data:s})):this.networkClient&&(this.networkClient.sendBridgeMessage(r),this.networkClient.flush())}broadcastBridge(e,i){this.sendBridge(e,i)}broadcastBridgeBinary(e,i){this.sendBridgeBinary(e,i)}onBridge(e,i){this.bridgeHandlers.has(e)||this.bridgeHandlers.set(e,new Set),this.bridgeHandlers.get(e).add(i)}offBridge(e,i){let s=this.bridgeHandlers.get(e);s&&(s.delete(i),s.size===0&&this.bridgeHandlers.delete(e))}removeAllBridgeHandlers(e){e?this.bridgeHandlers.delete(e):this.bridgeHandlers.clear()}dispatchBridge(e,i){let s=this.bridgeHandlers.get(e);if(s)for(let r of s)try{r(i)}catch(a){R.error(`Bridge handler error on channel '${e}'`,a)}}handleIncomingBridge(e){if(e.length>=3){let i=e[0];if(i===H.BRIDGE_FORMAT_JSON||i===H.BRIDGE_FORMAT_BINARY){let s=e[1];if(e.length>=2+s){let r=H.textDecoder.decode(e.subarray(2,2+s)),a=e.subarray(2+s);if(i===H.BRIDGE_FORMAT_JSON)try{let n=JSON.parse(H.textDecoder.decode(a));this.dispatchBridge(r,n),this.onBridgeMessage?.({channel:r,type:"json",data:n});return}catch{}else{let n=new Uint8Array(a);this.dispatchBridge(r,n),this.onBridgeMessage?.({channel:r,type:"binary",data:n});return}}}}try{let i=H.textDecoder.decode(e),s=JSON.parse(i);s&&typeof s.channel=="string"&&(this.dispatchBridge(s.channel,s.data),this.onBridgeMessage?.({channel:s.channel,type:"json",data:s.data}))}catch{}}static TRAFFIC_WINDOW_MS=1e3;accumulateTrafficStats(e){let i=performance.now(),s=H.TRAFFIC_WINDOW_MS;for(let r of e.layers){let a=this.h.get(r.id);a||(a={total:0,bytesPerSec1s:0,windowBytes:[],windowTs:[]},this.h.set(r.id,a)),a.total+=r.byteSize,a.windowBytes.push(r.byteSize),a.windowTs.push(i),H.pruneAndComputeBps(a,i,s)}if(e.sectionSizes.audio>1&&this.accumulateMiscEntry("update.audioOrders",e.sectionSizes.audio,i,s),e.sectionSizes.vibration>1&&this.accumulateMiscEntry("update.vibrationOrders",e.sectionSizes.vibration,i,s),e.displays.length>0){let r=Math.ceil(e.sectionSizes.displays/e.displays.length);for(let a of e.displays){let n=this.c.get(a.id);n||(n={total:0,bytesPerSec1s:0,windowBytes:[],windowTs:[]},this.c.set(a.id,n)),n.total+=r,n.windowBytes.push(r),n.windowTs.push(i),H.pruneAndComputeBps(n,i,s)}}}accumulateMiscEntry(e,i,s,r){let a=this.d.get(e);a||(a={total:0,bytesPerSec1s:0,windowBytes:[],windowTs:[]},this.d.set(e,a)),a.total+=i,a.windowBytes.push(i),a.windowTs.push(s),H.pruneAndComputeBps(a,s,r)}static pruneAndComputeBps(e,i,s){for(;e.windowTs.length>0&&i-e.windowTs[0]>s;)e.windowTs.shift(),e.windowBytes.shift();let r=0;for(let n=0;n<e.windowBytes.length;n++)r+=e.windowBytes[n];let a=e.windowTs.length>0?Math.max(1,i-e.windowTs[0]):s;e.bytesPerSec1s=Math.round(r/a*1e3)}getLayerTrafficStats(){let e={};for(let[i,s]of this.h)e[i]={total:s.total,bytesPerSec1s:s.bytesPerSec1s};return e}getMiscTrafficStats(){let e={};for(let[i,s]of this.d)e[i]={total:s.total,bytesPerSec1s:s.bytesPerSec1s};return e}getDisplayTrafficStats(){let e={};for(let[i,s]of this.c)e[i]={total:s.total,bytesPerSec1s:s.bytesPerSec1s};return e}dispatchGamepadVibration(e){if(typeof navigator>"u"||!navigator.getGamepads)return;let i=navigator.getGamepads()[e.gamepadIndex];!i||!i.vibrationActuator||i.vibrationActuator.playEffect("dual-rumble",{startDelay:e.startDelay,duration:e.duration,strongMagnitude:e.strongMagnitude,weakMagnitude:e.weakMagnitude}).catch(()=>{})}},ie=U.create("client:wrapper"),ei=class{options;transport;networkClient;e=!1;reconnectTimer=null;engine=null;constructor(t){if(this.options={autoReconnect:!0,reconnectInterval:1e3,debug:!1,...t},t.logLevel&&U.setLevel(t.logLevel),t.logFilter)for(let[e,i]of Object.entries(t.logFilter))U.setLevel(e,i);this.transport=new Pe,this.networkClient=new De({version:{major:0,minor:0,patch:0},username:"User"},{onSimulationStart:()=>{ie.info("Connected to server (simulation started)"),this.e=!0,this.options.application.onConnect?.(this)},onDisconnect:e=>{ie.warn(`Disconnected: ${e}`),this.e=!1,this.options.application.onDisconnect?.(this,e),this.options.autoReconnect&&this.scheduleReconnect()},onUpdate:(e,i)=>{this.options.application.onUpdate?.(this,e,i)},onBridgeMessage:e=>{ie.debug(`Bridge message: ${e.length} bytes`),this.options.application.onBridgeMessage?.(this,e)},onError:e=>{ie.error(`Network error: ${e}`),this.options.application.onError?.(this,e)}})}get network(){return this.networkClient}get connected(){return this.e}get latency(){return this.networkClient.getRtt()??-1}sendInput(t,e=!1){this.networkClient.sendInput(t,e)}sendBridgeMessage(t){this.networkClient.sendBridgeMessage(t)}async connect(){ie.info(`Connecting to ${this.options.url}...`);try{await this.networkClient.connect(this.transport,this.options.url)}catch(t){throw ie.error("Connection failed",t),this.options.autoReconnect&&this.scheduleReconnect(),t}}disconnect(){ie.info("Disconnecting..."),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.networkClient.disconnect()}scheduleReconnect(){this.reconnectTimer||(ie.info(`Reconnecting in ${this.options.reconnectInterval}ms...`),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect().catch(()=>{})},this.options.reconnectInterval))}};
|