/*!
* Copyright (c) 2025 Gig Game Corp.
*
* Author: Jason Bramble
*
* All rights reserved. This file or any portion thereof
* may only be used within the Gig Game service and may not be
* reproduced, altered, decompiled, or used with any other services
* without the express written permission of the author,
* except for the use of brief quotations in a review.
*
* For permission requests, write to the author at the email address below:
* - Email: support@sparkinnovationscorp.com
*/
(n=>{let c=!1,o=null,y="https://cdn.gig.game",r=null,u=null,f=null,l="R2K7DPRD56EFS3J8AWWN4O9GCB7K5Z8Y",i=!0,a=!1,s="DEMO1",e="en",v=!1;class p{constructor(){}async fetchApi(n,t){i&&console.warn("API",n,t);try{const i=await fetch(n,t);if(!i.ok)throw new Error(`HTTP error! status: ${i.status}`);return await i.json()}catch(r){console.error("Error:",r);throw r;}}getCommonHeaders(){return new Headers({"Content-Type":"application/json","api-key":l,"game-key":r})}}class w{constructor(){this.connection=null;this.isConnected=!1;this.hasConnected=!1;this.registeredEvents={};this.messageQueue=[];this.messageQueueProcessing=!1;this.loadingShow();var n=this;window.addEventListener("message",function(t){t.data&&t.data.event==="GgPlayerImageUpload"&&(n.messageQueue.push({fn:"invokeAction",p:{id:"",actionName:"GgHudMediaShare",options:{imageUrl:t.data.imageUrl}}}),n.checkQueue())});window.addEventListener("beforeunload",()=>{window.serverhud&&!window.serverhud.closed&&window.serverhud.close()})}loadingShow(){const n=document.createElement("div");n.id="loadingOverlay";n.style.position="fixed";n.style.top="0";n.style.left="0";n.style.width="100vw";n.style.height="100vh";n.style.background="black";n.style.zIndex="1000";n.style.display="flex";n.style.justifyContent="center";n.style.alignItems="center";const t=document.createElement("img");t.src="https://launch.gig.game/api/1.0.1/img/loading.png";t.alt="Loading...";n.appendChild(t);document.body.appendChild(n)}loadingHide(){const n=document.getElementById("loadingOverlay");n&&n.parentNode.removeChild(n)}getSandbox(){return a}getMode(){return f?"controller":v?"hud":"host"}getUserKey(){return f??u}getGameKey(){return r}getGameCode(){return s}getGameQrCode(){return s=="DEMO1"?"https://launch.gig.game/api/1.0.1/img/demo1.jpg":`${y}/event/${r}/qr-code.jpg`}getServer(){return o}getCDN(){return y}getLanguage(){return e}initialize(){this.loadSignalR(()=>{this.postInitialize()})}postInitialize(){if(this.loadIdentifiers(),r!=null){const n=o+"/masterControlProgram";this.connection=(new signalR.HubConnectionBuilder).withUrl(n).configureLogging(signalR.LogLevel.Information).build();this.connection.on((n,...t)=>{this.handler(n,t)});this.connection.on("Event",this.eventHandler.bind(this));if(this.getMode()=="host")this.connection.on("GgHudMediaShare",this.hudMediaShareHandler.bind(this));this.connection.onclose(this.reconnect.bind(this));this.attachEvent("OnConnect",this.registerDevice.bind(this));this.attachEvent("RedirectToSignIn",this.redirectToSignIn.bind(this));this.startConnection()}}loadSignalR(n){const t=document.createElement("script");t.src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/3.1.9/signalr.min.js";t.onload=n;document.head.appendChild(t)}loadIdentifiers(){var h,t;const n=document.querySelector("body");let y=n.getAttribute("gg-hud");v=y!=null;let c=n.getAttribute("gg-token");if(c!=null){let t=n.getAttribute("gg-salt");h=JSON.parse(this.deob(c,t));r=h.gameKey;u=h.hostKey;s=h.gameCode;f=h.playerKey;o=h.apiRoot;e=h.languageCode;return}console.warn("$GG operating in Sandbox Mode. Debug turned on.");i=!0;a=!0;t="";r=n.getAttribute("gg-gamekey");r===null&&(t+=" 'gg-gamekey' attribute missing.");let l=n.getAttribute("gg-gamecode");if(l!==null&&(this.gameCode=l),u=n.getAttribute("gg-hostkey"),f=n.getAttribute("gg-playerkey"),u===null&&f===null&&(t+=" Either a 'gg-hostkey' (console mode) or a 'gg-playerkey' (controller mode) attribute must be set."),e=n.getAttribute("gg-language"),e===null&&(e="en"),t!==""){t="Sandbox parameter(s) missing from body tag: "+t+" Init aborted.";console.error(t);alert(t);r=null;return}o="https://sandbox.gig.game"}registerDevice(){if(this.loadingHide(),r==null||f==null&&u==null&&l==null){alert("Initialization failed.");return}u!=null&&(v?this.registerHudDevice():this.registerHostDevice());f!=null&&this.registerPlayerDevice();u!=null&&f!=null&&this.registerHudDevice();c||(c=!0,this.triggerLocal("OnReady"))}attachEvent(n,t,i=1){this.registeredEvents[n]||(this.registeredEvents[n]=[]);this.registeredEvents[n].push({fn:t,priority:i});this.registeredEvents[n].sort((n,t)=>n.priority-t.priority);n==="OnReady"&&t!==null&&c&&t();n==="OnConnect"&&t!==null&&this.isConnected&&t()}detachEvent(n,t){this.registeredEvents[n]&&(this.registeredEvents[n]=this.registeredEvents[n].filter(n=>n.fn!==t))}attachSystemEvent(n,t){this.connection.on(n,t)}detachSystemEvent(n,t){this.connection.off(n,t)}triggerLocal(n,t=null){this.triggerEvent(n,t,"Local",null)}triggerEvent(n,t=null,r=null,u=null){if(i&&console.info("triggeredEvent",n,t,r,u),this.registeredEvents[n]){const i=this.registeredEvents[n];for(const{fn:n}of i)setTimeout(()=>{n(t,r,u)},0)}}startConnection(){this.connection.start().then(()=>{this.isConnected=!0,this.hasConnected=!0,this.messageQueue.length>0&&setTimeout(()=>{this.checkQueue()},5e3),this.triggerEvent("OnConnect")}).catch(n=>{this.isConnected=!1,console.log("Connection error",n),setTimeout(this.startConnection.bind(this),5e3)})}closingConnection(){this.connection.stop().then(()=>{this.isConnected=!1,this.hasConnected=!1,this.triggerEvent("OnConnectClosed")}).catch(n=>{console.error("Error while closing connection:",n)})}reconnect(){this.hasConnected&&(this.isConnected=!1,this.triggerEvent("OnConnectLost"),setTimeout(this.startConnection.bind(this),5e3))}openServerHud(n=true){if(window.serverhud&&!window.serverhud.closed&&autoclose)window.serverhud.focus();else{if(this.getMode()!="host"){alert("Only hosts can open huds.");return}if(a){alert("In sandbox mode, directly open the html in the hud folder to test.");return}const t=`resizable=yes,width=600,height=400`,i=`https://hub.gig.game/${e}/event/${r}/hud`;n?window.serverhud=window.open(i,"hud",t):window.open(i,`hud_${Date.now()}`,t)}}redirectToSignIn(){var n=`https://hub.gig.game/${e}/play/${s}`;window.location.href=n}eventHandler(n){var t=n.eventName,i=n.eventOptions,r=n.sourceType,u=n.source;this.triggerEvent(t,i,r,u)}hudMediaShareHandler(n){var o=n.imageUrl,e=this,t=document.createElement("div"),i,f,r,u;t.style.position="fixed";t.style.top="0";t.style.left="0";t.style.width="100vw";t.style.height="100vh";t.style.backgroundColor="rgba(0, 0, 0, 0.7)";t.style.display="flex";t.style.justifyContent="center";t.style.alignItems="center";t.style.zIndex="1000";i=document.createElement("div");i.style.backgroundColor="#555";i.style.padding="20px";i.style.borderRadius="10px";i.style.boxShadow="0 4px 8px rgba(0, 0, 0, 0.2)";i.style.textAlign="center";i.style.maxWidth="90%";i.style.width="500px";f=document.createElement("img");f.src=o;f.style.maxWidth="100%";f.style.borderRadius="10px";f.style.marginBottom="20px";r=document.createElement("button");r.textContent="Approve";r.style.margin="0 10px";r.style.padding="10px 20px";r.style.backgroundColor="#4CAF50";r.style.color="#fff";r.style.border="none";r.style.borderRadius="5px";r.style.cursor="pointer";u=document.createElement("button");u.textContent="Decline";u.style.margin="0 10px";u.style.padding="10px 20px";u.style.backgroundColor="#f44336";u.style.color="#fff";u.style.border="none";u.style.borderRadius="5px";u.style.cursor="pointer";i.appendChild(f);i.appendChild(r);i.appendChild(u);t.appendChild(i);document.body.appendChild(t);r.onclick=function(){e.messageQueue.push({fn:"invokeAction",p:{id:"",actionName:"GgHudMediaShare",options:{imageUrl:n.imageUrl}}});e.checkQueue();document.body.removeChild(t)};u.onclick=function(){document.body.removeChild(t)}}registerHudDevice(){this.validateConnection();i&&console.info("registerHudDevice",r,l);this.connection.invoke("RegisterHudDevice",r,u).catch(n=>{console.error(n.toString())})}registerHostDevice(){this.validateConnection();i&&console.info("registerHostDevice",r,u);this.connection.invoke("RegisterHostDevice",r,u).catch(n=>{console.error(n.toString())})}registerPlayerDevice(){this.validateConnection();i&&console.info("registerPlayerDevice",r,f);this.connection.invoke("RegisterPlayerDevice",r,f).catch(n=>{console.error(n.toString())})}syncPlayersToHost(){i&&console.info("syncPlayersToHost");this.validateConnection();this.connection.invoke("SyncPlayersToHost").catch(n=>{console.error(n.toString())})}queueToEngine(n,t=null){i&&console.info("queueToEngine",n,t);this.messageQueue.push({fn:"broadcastToEngine",p:{eventName:n,options:t}});this.checkQueue()}queueToHud(n,t=null){i&&console.info("queueToHud",n,t);this.messageQueue.push({fn:"broadcastToHud",p:{eventName:n,options:t}});this.checkQueue()}queueToHost(n,t=null){i&&console.info("queueToHost",n,t);this.messageQueue.push({fn:"broadcastToHost",p:{eventName:n,options:t}});this.checkQueue()}queueToPlayers(n,t=null){i&&console.info("queueToPlayers",n,t);this.messageQueue.push({fn:"broadcastToPlayers",p:{eventName:n,options:t}});this.checkQueue()}queueToPlayer(n,t,r=null){i&&console.info("queueToPlayer",n,t,r);this.messageQueue.push({fn:"broadcastToPlayer",p:{playerId:n,eventName:t,options:r}});this.checkQueue()}checkQueue(){this.messageQueueProcessing||this.processQueue()}processQueue(){for(this.messageQueueProcessing=!0;this.messageQueue.length>0;){if(!this.isConnected){this.messageQueueProcessing=!1;return}var n=this.messageQueue.shift();switch(n.fn){case"invokeAction":this.invokeAction(n.p.id,n.p.actionName,n.p.options);break;case"broadcastToEngine":this.broadcastToEngine(n.p.eventName,n.p.options);break;case"broadcastToHost":this.broadcastToHost(n.p.eventName,n.p.options);break;case"broadcastToPlayer":this.broadcastToPlayer(n.p.playerId,n.p.eventName,n.p.options);break;case"broadcastToPlayers":this.broadcastToPlayers(n.p.eventName,n.p.options);break;default:console.error(`Unknown message type: ${n.fn}`)}}this.messageQueueProcessing=!1}broadcastToEngine(n,t=null){i&&console.info("broadcastToEngine",n,t);this.validateConnection();this.connection.invoke("BroadcastToEngine",n,t).catch(n=>{console.error(n.toString())})}broadcastToHud(n,t=null){i&&console.info("broadcastToHud",n,t);this.validateConnection();this.connection.invoke("BroadcastToHud",n,t).catch(n=>{console.error(n.toString())})}broadcastToHost(n,t=null){i&&console.info("broadcastToHost",n,t);this.validateConnection();this.connection.invoke("BroadcastToHost",n,t).catch(n=>{console.error(n.toString())})}broadcastToPlayers(n,t=null){i&&console.info("broadcastToPlayers",n,t);this.validateConnection();this.connection.invoke("BroadcastToPlayers",n,t).catch(n=>{console.error(n.toString())})}broadcastToPlayer(n,t,r=null){i&&console.info("broadcastToPlayer",n,t,r);this.validateConnection();this.connection.invoke("BroadcastToPlayer",n,t,r).catch(n=>{console.error(n.toString())})}invokeAction(n,t,r){i&&console.info("invokeAction",n,t,r);this.validateConnection();this.connection.invoke("InvokeAction",n,t,r).catch(n=>{console.error(n.toString())})}obKey(){const t=["ICBBbGwg","IENvcnAu","dmVkLg==","Z2h0IEdp","Q29weXJp","cmlnaHRz","IHJlc2Vy","ZyBHYW1l",],i=[4,3,7,1,0,5,6,2];let n="";for(let r of i)n+=t[r];return n}deob(n,t=null){t==null?t=this.obKey():(t=btoa(this.deob(t)),n=atob(n));let i=[];for(let r=0;r({Key:n,Value:i[n]}));let e={method:"POST",headers:this.getCommonHeaders(),body:JSON.stringify({EndPoint:n.url||"",Method:n.method||"GET",Headers:f,RequestBody:n.data||null,RequestContentType:n.contentType||"application/json"})};return this.fetchApi(u,e)}uploadImage(n){return new Promise((i,r)=>{try{let s=t.getServer(),e=t.getUserKey(),o=t.getMode();var u=o=="controller"?e:null,f=o=="host"?e:null;const h=`${s}/api/v1/event/imageupload`;let c={method:"POST",headers:this.getCommonHeaders(),body:JSON.stringify({fileData:n,playerKey:u,hostKey:f})};this.fetchApi(h,c).then(n=>{if(n.status===0){var t={event:"GgPlayerImageUpload",imageUrl:n.data.imagePath};window.postMessage(t,"*");i(n.data.imagePath)}else console.log("error",n),r(n.message)}).catch(n=>{console.error("Error uploading the image",n),r(n.message)})}catch(e){r(e.message)}})}}const t=new w,h=new b;t.initialize();n.$GG={server:{attachSystemEvent:t.attachSystemEvent.bind(t),detachSystemEvent:t.detachSystemEvent.bind(t),attachEvent:t.attachEvent.bind(t),detachEvent:t.detachEvent.bind(t),broadcastToEngine:t.broadcastToEngine.bind(t),broadcastToHud:t.broadcastToHud.bind(t),broadcastToHost:t.broadcastToHost.bind(t),broadcastToPlayer:t.broadcastToPlayer.bind(t),broadcastToPlayers:t.broadcastToPlayers.bind(t),queueToEngine:t.queueToEngine.bind(t),queueToHud:t.queueToHud.bind(t),queueToHost:t.queueToHost.bind(t),queueToPlayer:t.queueToPlayer.bind(t),queueToPlayers:t.queueToPlayers.bind(t),trigger:t.triggerLocal.bind(t),invokeAction:t.invokeAction.bind(t),syncPlayersToHost:t.syncPlayersToHost.bind(t),uploadImage:h.uploadImage.bind(h),ajax:h.ajax.bind(h),types:{service:p}},openServerHud:t.openServerHud.bind(t),getMode:t.getMode.bind(t),getSandbox:t.getSandbox.bind(t),getCDN:t.getCDN.bind(t),getServer:t.getServer.bind(t),getGameKey:t.getGameKey.bind(t),getGameCode:t.getGameCode.bind(t),getQrCode:t.getGameQrCode.bind(t),getUserKey:t.getUserKey.bind(t),getLanguage:t.getLanguage.bind(t)}})(typeof window!="undefined"?window:global);(n=>{const ft=()=>{let n="";for(let t=0;t<32;t++)n+=Math.floor(Math.random()*16).toString(16),(t===7||t===11||t===15||t===19)&&(n+="-");return n},et=n=>{if(typeof n!="number"||isNaN(n))throw new Error("Input must be a valid number");let t=n.toString(16);return t.length%2!=0&&(t="0"+t),t.toUpperCase()},ot=()=>{const n=navigator.userAgent||navigator.vendor||window.opera;return/iphone|ipad/i.test(n.toLowerCase())},b=()=>{const n=navigator.userAgent||navigator.vendor||window.opera;return/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(n.toLowerCase())},st=n=>{const t=document.createElement("script");t.src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js";t.onload=n;document.body.appendChild(t)},k=(n=null,t=false)=>new Promise((r,f)=>{try{t?st(()=>{i.initialize(n,!0),u.startClock(),r()}):(i.initialize(n,!1),u.startClock(),r())}catch(e){f(e)}}),a={byPriority:0,byZIndex:1},d={byPriority:{sortOnRegister:!0,sortOnRender:!1,compare:function(n,t){return n.Priority-t.Priority}},byZIndex:{sortOnRegister:!0,sortOnRender:!0,compare:function(n,t){return n.instance._zIndex-t.instance._zIndex}}},t={RESIZE:"resize",KEY_DOWN:"keydown",KEY_UP:"keyup",MOUSE_MOVE:"mousemove",MOUSE_UP:"mouseup",MOUSE_CLICK:"mouseclick",MOUSE_CLICK_OUT:"mouseclickout",MOUSE_DOUBLE_CLICK:"mousedoubleclick",RIGHT_MOUSE_CLICK:"rightmouseclick",CENTER_MOUSE_CLICK:"centermouseclick",RIGHT_MOUSE_UP:"rightmouseup",CENTER_MOUSE_UP:"centermouseup",MOUSE_SCROLL_UP:"mousescrollup",MOUSE_SCROLL_DOWN:"mousescrolldown",MOUSE_ENTER:"mouseenter",MOUSE_LEAVE:"mouseleave",MOUSE_CANVAS_ENTER:"mousecanvasenter",MOUSE_CANVAS_LEAVE:"mousecanvasleave",TOUCH_START:"touchstart",TOUCH_MOVE:"touchmove",TOUCH_END:"touchend",TOUCH_CANCEL:"touchcancel",SWIP_LEFT:"swipeleft",SWIPE_RIGHT:"swiperight",TAP:"tap",TAP_OUT:"tapout",DOUBLE_TAP:"tap",PINCH:"pinch",EXPAND:"expand",ROTATE:"rotate",SHAKE:"shake",DEVICE_ORIENTATION:"deviceorientation",DEVICE_MOTION:"devicemotion",VISIBILITY_CHANGE:"visibilitychange"},i=(()=>{let f=null,h=null,i=null,o=null,e=null,k=null,r=null,w=null,s=null,tt=null,a=null,d=null,g=null,lt=50,l=null,v=null,at=10,it=0,vt=15,yt=1e3,pt=null,b=null,wt=300,bt=200,n={};const kt=(n=null,u=false)=>{if(f=n==null?window:n,h=f.document.createElement("div"),h.id="htmlContainer",h.style.position="absolute",h.style.width="100%",h.style.height="100%",h.style.top="0",h.style.left="0",f.document.body.appendChild(h),u&&(r=f.document.createElement("canvas"),f.document.body.appendChild(r),r.id="1spark3D",r.style.position="fixed",r.style.top="0",r.style.left="0",r.style.margin="0",r.style.padding="0",r.style.display="block",r.style.visibility="hidden",r.width=f.innerWidth,r.height=f.innerHeight,w=r.getContext("webgl"),w?(w.viewportWidth=r.width,w.viewportHeight=r.height):console.log("Could not initialize WebGL"),s=document.createElement("canvas"),s.width=r.width,s.height=r.height,tt=s.getContext("2d")),i=document.createElement("canvas"),f.document.body.appendChild(i),i.id="1spark2D",i.style.position="fixed",i.style.top="0",i.style.left="0",i.style.margin="0",i.style.padding="0",i.style.display="block",i.width=f.innerWidth,i.height=f.innerHeight,o=i.getContext("2d"),!o){console.log("Could not initialize 2D");return}e=document.createElement("canvas");e.width=i.width;e.height=i.height;k=e.getContext("2d");i.addEventListener(t.MOUSE_MOVE,vi);i.addEventListener("mousedown",pi);i.addEventListener(t.MOUSE_UP,yi);i.addEventListener("wheel",ki);i.addEventListener("mouseenter",wi);i.addEventListener("mouseleave",bi);i.addEventListener(t.TOUCH_START,di);i.addEventListener(t.TOUCH_MOVE,gi);i.addEventListener(t.TOUCH_END,nr);i.addEventListener(t.TOUCH_CANCEL,tr);f.addEventListener("resize",()=>{rt(f.innerWidth,f.innerHeight)});window.addEventListener(t.KEY_DOWN,ai);window.addEventListener(t.KEY_UP,li);window.addEventListener(t.DEVICE_MOTION,ir);document.addEventListener(t.VISIBILITY_CHANGE,rr)},dt=()=>new Promise((n,i)=>{typeof DeviceMotionEvent.requestPermission=="function"?DeviceMotionEvent.requestPermission().then(r=>{r=="granted"?(window.addEventListener(t.DEVICE_ORIENTATION,ut),n("DeviceMotion permission granted.")):i("DeviceMotion permission not granted.")}).catch(n=>{i("DeviceMotion permission error: "+n)}):(window.addEventListener("deviceorientation",ut),n("DeviceMotion permission not required."))}),gt=()=>new Promise((n,t)=>{navigator.geolocation?navigator.geolocation.getCurrentPosition(t=>{n(t)},n=>{t(`Geolocation error: ${n.message}`)}):t("Geolocation not supported.")}),rt=(n,t)=>{r!=null&&(r.width=n,r.height=t,a&&a.setSize(n,t),s=f.document.createElement("canvas"),s.width=n,s.height=t,tt=s.getContext("2d")),i.width=n,i.height=t,o=i.getContext("2d"),o?(e=f.document.createElement("canvas"),e.width=i.width,e.height=i.height,k=e.getContext("2d")):console.log("Could not initialize 2D"),u.raiseResizeEvent(i.width,i.height)},ni=()=>f,ti=()=>{if(r!=null)return a||(a=new THREE.WebGLRenderer({context:w}),a.setSize(r.width,r.height)),a;throw new Error("Three support not initialized.");},ii=()=>i.style,ri=()=>({width:i.width,height:i.height}),ui=()=>h,fi=()=>k,ei=()=>s,oi=()=>{o.clearRect(0,0,i.width,i.height),s!=null&&tt.drawImage(r,0,0),r!=null&&o.drawImage(r,0,0),o.drawImage(e,0,0)},si=n=>{o.clearRect(0,0,i.width,i.height);const t=new Image;t.onload=function(){o.drawImage(t,0,0)};t.src=n},hi=()=>{const t=i,r=t.parentNode,n=document.createElement("canvas");n.id="1spark2D";n.width=t.width;n.height=t.height;n.style.cssText=t.style.cssText;r.replaceChild(n,t);i=n;o=i.getContext("2d");e=f.document.createElement("canvas");e.width=i.width;e.height=i.height;k=e.getContext("2d")},ci=()=>{try{return i.toDataURL()}catch(n){if(n instanceof DOMException&&n.name==="SecurityError")return console.warn("Canvas is tainted. Recreating canvas to reset the state."),hi(),i.toDataURL();throw n;}},y=n=>{const t=i.getBoundingClientRect();n.clientX&&(n.canvasX=n.clientX-t.left);n.clientY&&(n.canvasY=n.clientY-t.top)},li=i=>{if(n[t.KEY_UP]){n[t.KEY_UP].sort((n,t)=>n.source._globalZ-t.source._globalZ);for(let r=0;r{if(n[t.KEY_DOWN]){n[t.KEY_DOWN].sort((n,t)=>n.source._globalZ-t.source._globalZ);for(let r=0;r{y(n),c(n,t.MOUSE_MOVE)},yi=n=>{y(n);switch(n.button){case 0:c(n,t.MOUSE_UP);break;case 1:c(n,t.CENTER_MOUSE_UP);break;case 2:c(n,t.RIGHT_MOUSE_UP)}},pi=n=>{y(n);switch(n.button){case 0:c(n,t.MOUSE_CLICK);break;case 1:c(n,t.CENTER_MOUSE_CLICK);break;case 2:c(n,t.RIGHT_MOUSE_CLICK)}},wi=n=>{y(n),p(n,t.MOUSE_CANVAS_ENTER)},bi=n=>{y(n),p(n,t.MOUSE_CANVAS_LEAVE)},ki=n=>{y(n),n.deltaY>0?c(n,t.MOUSE_SCROLL_DOWN):c(n,t.MOUSE_SCROLL_UP)},di=n=>{n.touches.length===1?(d=n.touches[0].clientX,g=n.touches[0].clientY):n.touches.length===2&&(l=ht(n.touches[0],n.touches[1]),v=ct(n.touches[0],n.touches[1])),nt(n,t.TOUCH_START)},gi=n=>{if(n.touches.length===2){if(l!==null){const i=ht(n.touches[0],n.touches[1]);Math.abs(i-l)>at&&(i>l?ot(n,t.EXPAND):ot(n,t.PINCH),l=i)}if(v!==null){const i=ct(n.touches[0],n.touches[1]),r=i-v;ur(n,t.ROTATE,r);v=i}}nt(n,t.TOUCH_MOVE)},nr=n=>{if(n.touches.length===0&&l===null&&v===null&&(b!==null?(clearTimeout(b),b=null,ft(n,t.DOUBLE_TAP)):pt=setTimeout(()=>{ft(n,t.TAP),b=setTimeout(()=>{b=null},wt)},bt)),d!==null&&g!==null){const r=n.changedTouches[0],i=r.clientX-d,u=r.clientY-g;Math.abs(i)>Math.abs(u)&&Math.abs(i)>lt&&(i>0?et(n,t.SWIP_RIGHT):et(n,t.SWIP_LEFT))}d=null;g=null;l=null;v=null;nt(n,t.TOUCH_END)},tr=n=>{nt(n,t.TOUCH_CANCEL)},ut=n=>{st(n,t.DEVICE_ORIENTATION)},ir=n=>{if(st(n,t.DEVICE_MOTION),n.accelerationIncludingGravity){const{x:i,y:r,z:u}=n.accelerationIncludingGravity,f=Math.sqrt(i*i+r*r+u*u);f>vt&&Date.now()-it>yt&&(it=Date.now(),fr())}},rr=()=>{const n=document.hidden;er(n)},p=(t,i)=>{if(n[i]){n[i].sort((n,t)=>t.source._globalZ.localeCompare(n.source._globalZ));for(let r=0;r{if(n[r]){n[r].sort((n,t)=>t.source._globalZ.localeCompare(n.source._globalZ));for(let u=0;u=f.region.x2||i.canvasY<=f.region.y1||i.canvasY>=f.region.y2)){r==t.MOUSE_MOVE&&f.isOver&&(f.isOver=!1,p(i,t.MOUSE_LEAVE));r==t.MOUSE_CLICK&&(f.isOver=!1,p(i,t.MOUSE_CLICK_OUT));continue}r!=t.MOUSE_MOVE||f.isOver||(f.isOver=!0,p(i,t.MOUSE_ENTER));const e=f.eventHandler(i);if(e)break}}},nt=(t,i)=>{if(n[i]){n[i].sort((n,t)=>t.source._globalZ.localeCompare(n.source._globalZ));for(let r=0;r=u.region.x1&&i.clientX<=u.region.x2&&i.clientY>=u.region.y1&&i.clientY<=u.region.y2){f=!0;break}}if(f){const e=u.eventHandler(t);if(e)break}}}},ft=(i,r)=>{if(n[r]){n[r].sort((n,t)=>t.source._globalZ.localeCompare(n.source._globalZ));for(let u=0;u=f.region.x2||i.changedTouches[0].clientY<=f.region.y1||i.changedTouches[0].clientY>=f.region.y2)){r==t.TAP&&(f.isOver=!1,p(i,t.TAP_OUT));continue}const e=f.eventHandler(i);if(e)break}}},et=(t,i)=>{if(n[i]){n[i].sort((n,t)=>t.source._globalZ.localeCompare(n.source._globalZ));for(let r=0;r=u.region.x2)&&!(t.canvasY<=u.region.y1)&&!(t.canvasY>=u.region.y2)){const f=u.eventHandler(t);if(f)break}}}},ot=(t,i)=>{if(n[i]){n[i].sort((n,t)=>t.source._globalZ.localeCompare(n.source._globalZ));for(let r=0;r=u.region.x2)&&!(t.canvasY<=u.region.y1)&&!(t.canvasY>=u.region.y2)){const f=u.eventHandler(t);if(f)break}}}},ur=(t,i,r)=>{if(n[i]){n[i].sort((n,t)=>t.source._globalZ.localeCompare(n.source._globalZ));for(let u=0;u=f.region.x2)&&!(t.canvasY<=f.region.y1)&&!(t.canvasY>=f.region.y2)){const e=f.eventHandler(t,r);if(e)break}}}},st=(t,i)=>{if(n[i]){n[i].sort((n,t)=>t.source._globalZ.localeCompare(n.source._globalZ));for(let r=0;r{if(n[t.SHAKE]){n[t.SHAKE].sort((n,t)=>n.source._globalZ.localeCompare(t.source._globalZ));for(let i=0;i{if(n[t.VISIBILITY_CHANGE]){n[t.VISIBILITY_CHANGE].sort((n,t)=>n.source._globalZ.localeCompare(t.source._globalZ));for(let r=0;r{n[t]||(n[t]=[]);const u={source:i,eventHandler:r,isOver:!1};return n[t].push(u),u},sr=(t,i=null)=>{if(i==null)for(const i in n)n.hasOwnProperty(i)&&(n[i]=n[i].filter(n=>n.source.id!==t.id));else n.hasOwnProperty(i)&&(n[i]=n[i].filter(n=>n.source.id!==t.id))},hr=()=>{n={}},ht=(n,t)=>{const i=t.clientX-n.clientX,r=t.clientY-n.clientY;return Math.sqrt(i*i+r*r)},ct=(n,t)=>{const i=t.clientX-n.clientX,r=t.clientY-n.clientY;return Math.atan2(r,i)},cr=n=>{n?document.documentElement.requestFullscreen?document.documentElement.requestFullscreen():document.documentElement.mozRequestFullScreen?document.documentElement.mozRequestFullScreen():document.documentElement.webkitRequestFullscreen?document.documentElement.webkitRequestFullscreen():document.documentElement.msRequestFullscreen&&document.documentElement.msRequestFullscreen():document.exitFullscreen?document.exitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitExitFullscreen?document.webkitExitFullscreen():document.msExitFullscreen&&document.msExitFullscreen()};return{initialize:kt,resize:rt,setFullScreen:cr,getHtmlContainer:ui,getWorkWindow:ni,getContext:fi,getThreeRenderer:ti,getThreeBackgroundContext:ei,requestMotion:dt,requestGeoLocation:gt,publish:oi,getState:ci,setState:si,getStyle:ii,getSize:ri,attachEvent:or,releaseEvent:sr,clearEvents:hr}})();class nt{constructor(n=0,t=0){this.x=n;this.y=t}}class v extends nt{constructor(n=0,t=0,i=1,r=1,u=0){super(n,t);this.rotation=u;this.xScale=i;this.yScale=r}}class tt{constructor(n={}){if(this.id=ft(),this.isActive=!0,this.stageProps=[],this.eventListeners=[],this._zIndexTracker=10,this._zIndex=0,this._globalZ="0",this.onPreInit)this.onPreInit(n);this.isActive=n.isActive||!0;n.sortBy?this.setRenderSort(n.sortBy):this.setRenderSort(a.byZDepth)}setRenderSort=n=>{if(n==a.byPriority){this.sortBy=d.byPriority}else if(n==a.byZIndex){this.sortBy=d.byZIndex}else{this.sortBy=d.byZIndex}};registerProp(n,t={},i=1e5){if(!(n instanceof h))throw new Error("Not a StagePropType or TransformType component.");n._parent=this;n._zIndex=t.zIndex||0;n._zIndex==0&&(n._zIndex=this._zIndexTracker);n._zIndex>this._zIndexTracker&&(this._zIndexTracker=n._zIndex);this._zIndexTracker+=10;const r={instance:n,Properties:t,Priority:i};if(this.stageProps.push(r),this._globalZ=this.globalZIndex(),this.resetChildGZ(),this.sortBy.sortOnRegister&&this.stageProps.sort(this.sortBy.compare),n.onRegister)n.onRegister(t)}getProp=n=>{const t=this.stageProps.find(t=>t.instance.id===n);if(t){return t.instance}return null};destroyProp=n=>{const t=this.stageProps.findIndex(t=>t.instance.id===n);if(t!==-1){if(this.stageProps[t].onDestroy)this.stageProps[t].onDestroy();this.stageProps.splice(t,1);return true}return false};clearProps=()=>{for(var n=0;n0){this.sortBy.sortOnRender&&this.stageProps.sort(this.sortBy.compare);for(var t=0;t0)for(var n=0;n0)for(var n=0;n0)for(var n=0;n0)for(var n=0;n0)for(var n=0;n{this.eventListeners.push({inputEvent:n,fn:t})}):typeof n=="string"?this.eventListeners.push({inputEvent:n,fn:t}):console.error("Event must be a string or an array of strings")}off(n=null,t=null){if(n===null){this.eventListeners=[];return}typeof n=="string"&&(n=[n]);Array.isArray(n)?this.eventListeners=t===null?this.eventListeners.filter(t=>!n.includes(t.inputEvent)):this.eventListeners.filter(i=>!(n.includes(i.inputEvent)&&i.fn===t)):console.error("Event must be a string or an array of strings")}trigger(n,t={}){const i=this.eventListeners.filter(t=>t.inputEvent===n);i.forEach(n=>n.fn(t))}}class y extends tt{constructor(n,t={},i=false){super();const r=u.getStageSize();if(this.x=0,this.y=0,this.width=r.width,this.height=r.height,this.isVisible=!0,this.name=n,i||u.registerStage(n,this),this.onInit&&!i)this.onInit(t)}registerProp(n,t={},i=1e5){if(n._stage)throw new Error("Object is already a member of another stage.");n.isVisible=t.isVisible!==undefined?t.isVisible:!0;n.orientation=new v(t.x||0,t.y||0,t.xScale||1,t.yScale||1,t.rotation||0);n._stage=this;super.registerProp(n,t,i);n.raiseStageEvent();this.name==u.getStageName()&&n.raiseStageActiveEvent()}raiseRenderEvent(n){this.isActive&&this.isVisible&&super.raiseRenderEvent(n)}raiseStageActiveEvent(){super.raiseStageActiveEvent();const i=u.getStageSize(),n=i.width,t=i.height;(n!=this.width||t!=this.height)&&(this.width=n,this.height=t,this.raiseResizeEvent(n,t))}raiseResizeEvent(n,t){this.width=n;this.height=t;super.raiseResizeEvent(n,t)}}class h extends tt{constructor(n={},t=false){super(n);this.width=n.width||100;this.height=n.height||100;this.isVisible=!1;this.orientation=new v(0,0,1,1,0);const r=i.getSize();if(this.screenWidth=r.width,this.screenHeight=r.height,this.workCanvas=document.createElement("canvas"),this.workCanvas.width=this.width,this.workCanvas.height=this.height,this.workContext=this.workCanvas.getContext("2d"),this.onInit&&!t)this.onInit(n)}registerProp(n,t={},i=1e5){this._stage&&(n._stage=this._stage);n.isVisible=t.isVisible!==undefined?t.isVisible:!0;n.orientation=new v(t.x||0,t.y||0,t.xScale||1,t.yScale||1,t.rotation||0);super.registerProp(n,t,i);this._stage&&(n.raiseStageEvent(),n._stage.name==u.getStageName()&&n.raiseStageActiveEvent())}getScreenRegion(){var n=0,t=0,i;this._parent&&(this._parent instanceof h&&(i=this._parent.getScreenRegion(),n=i.x1,t=i.y1),this._parent instanceof y&&(n=this._parent.x,t=this._parent.y));const r=this.orientation.xScale,u=this.orientation.yScale;return{x1:this.orientation.x+n,y1:this.orientation.y+t,x2:this.orientation.x+n+this.width*r,y2:this.orientation.y+t+this.height*u}}getRegion(){const n=this.orientation.xScale,t=this.orientation.yScale;return{x1:this.orientation.x,y1:this.orientation.y,x2:this.orientation.x+this.width*n,y2:this.orientation.y+this.height*t}}setRegion(n){var t=Math.abs(n.x2-n.x1),i=Math.abs(n.y2-n.y1);this.orientation.xScale=t/this.width;this.orientation.yScale=i/this.height;this.orientation.x=n.x1;this.orientation.y=n.y1}show(){this.isVisible=!0;this.onShow&&this.onShow()}hide(){this.isVisible=!1;this.onHide&&this.onHide()}resize(n,t){this.width=n;this.height=t;this.workCanvas=document.createElement("canvas");this.workCanvas.width=this.width;this.workCanvas.height=this.height;this.workContext=this.workCanvas.getContext("2d");this.onResized&&this.onResized();for(var i=0;i1){const t=n-this.lastFrameUpdateTime;t>=this.frameDuration&&(this.lastFrameUpdateTime=n,this.frame++,this.frame>=this.activeLoop.clipPaths.length&&(this.frame=0))}}onDraw(n){if(this.activeLoop&&this.isVisible&&this.frame!=this.renderedFrame){const t=this.activeLoop.clipPaths[this.frame].ActiveStage,i=this.activeLoop.clipPaths[this.frame].CanvasContext;n.clearRect(0,0,n.canvas.width,n.canvas.height);n.drawImage(t,0,0);this.renderedFrame=this.frame}}loadGroup(n){if(!n)throw new Error("A sprite group is required.");const t=r.getSpriteLoop(n);if(!t)throw new Error(`Sprite group ${n} not found.`);this.adjustCanvas(t);this.spriteLoop[n]=t;this.activeLoop||(this.activeLoop=t)}loadImage(n,t){if(!n)throw new Error("An image is required.");const u=r.getImage(n);if(!u)throw new Error(`Sprite image ${n} not found.`);const i={group:n,clipPaths:[]};for(var f=0;f=1&&(this.opacity=1,this.transitionState=f.Idle)}if(this.transitionState==f.Active){let i=document.createElement("canvas");i.width=this.width;i.height=this.height;let r=i.getContext("2d");n.instance.raiseRenderEvent(r);t.globalAlpha=1-this.opacity;t.putImageData(this.fromImage,0,0);t.globalAlpha=this.opacity;t.drawImage(i,0,0);t.globalAlpha=1;return}n.instance.raiseRenderEvent(t)}}class lt extends c{constructor(n,t="left"){super();this.timeToSlide=n;this.direction=t;this.startTime=null;this.progress=0;this.isMobile=b()}setToStage(n){this.progress=0;this.startTime=new Date;super.setToStage(n)}onDraw(n,t){if(this.transitionState==f.Active){var i=new Date;let n=(i-this.startTime)/1e3;this.progress=n/this.timeToSlide;this.progress>=1&&(this.progress=1,this.transitionState=f.Idle)}if(this.transitionState==f.Active){let u=document.createElement("canvas");u.width=this.width;u.height=this.height;let f=u.getContext("2d");n.instance.raiseRenderEvent(f);let i=this.direction;this.isMobile&&(screen.orientation.type=="landscape-primary"||screen.orientation.type=="landscape-secondary")&&(this.direction=="left"?i="top":this.direction=="right"?i="bottom":this.direction=="top"?i="right":this.direction=="bottom"&&(i="left"));let r=this.progress;i==="left"||i==="right"?(r*=this.width,i==="left"?(t.putImageData(this.fromImage,-r,0),t.drawImage(u,this.width-r,0)):(t.putImageData(this.fromImage,r,0),t.drawImage(u,-this.width+r,0))):(i==="top"||i==="bottom")&&(r*=this.height,i==="bottom"?(t.putImageData(this.fromImage,0,-r),t.drawImage(u,0,this.height-r)):(t.putImageData(this.fromImage,0,r),t.drawImage(u,0,-this.height+r)));return}n.instance.raiseRenderEvent(t)}}class at extends c{constructor(n){super();this.timeToZoom=n;this.progress=0;this.startTime=null}setToStage(n){this.progress=0;this.startTime=new Date;super.setToStage(n)}onDraw(n,t){if(this.transitionState==f.Active){var i=new Date;let n=(i-this.startTime)/1e3;this.progress=n/this.timeToZoom;this.progress>=1&&(this.progress=1,this.transitionState=f.Idle)}if(this.transitionState==f.Active){let i=document.createElement("canvas");i.width=this.width;i.height=this.height;let r=i.getContext("2d");u.stages[this.stageName].instance.raiseRenderEvent(r);let n=2-this.progress;t.save();t.translate(this.width/2,this.height/2);t.scale(n,n);t.translate(-this.width/2,-this.height/2);t.putImageData(this.fromImage,0,0);t.restore();n=this.progress;t.save();t.translate(this.width/2,this.height/2);t.scale(n,n);t.translate(-this.width/2,-this.height/2);t.drawImage(i,0,0);t.restore();return}n.instance.raiseRenderEvent(t)}}class vt extends c{constructor(n,t="horizontal"){super();this.timeToFlip=n;this.direction=t;this.progress=0;this.startTime=null;this.isMobile=b()}setToStage(n){this.progress=0;this.startTime=new Date;super.setToStage(n)}onDraw(n,t){var i=new Date;if(this.transitionState==f.Active){let n=(i-this.startTime)/1e3;this.progress=n/this.timeToFlip;this.progress>=1&&(this.progress=1,this.transitionState=f.Idle)}if(this.transitionState==f.Active){let n=document.createElement("canvas");n.width=this.width;n.height=this.height;let f=n.getContext("2d");u.stages[this.stageName].instance.raiseRenderEvent(f);let r=this.progress<=.5?1-this.progress*2:(this.progress-.5)*2,e=this.progress<=.5;t.save();t.translate(this.width/2,this.height/2);let i=this.direction;this.isMobile&&(screen.orientation.type=="landscape-primary"||screen.orientation.type=="landscape-secondary")&&(i=i==="horizontal"?"vertical":"horizontal");i==="horizontal"?t.scale(r,1):t.scale(1,r);t.translate(-this.width/2,-this.height/2);e?t.putImageData(this.fromImage,0,0):t.drawImage(n,0,0);t.restore();return}n.instance.raiseRenderEvent(t)}}const o={Pending:0,Active:1,Complete:2};class w extends h{constructor(n={}){super(n);this.state=o.Pending}onResize(n,t){this.resize(n,t)}start(){this.resize(this._stage.width,this._stage.height);this.state=o.Active;this.isActive=!0;this.isVisible=!0;this.onStart&&this.onStart()}resize(n,t){this.width=n;this.height=t;this.workCanvas=document.createElement("canvas");this.workCanvas.width=this.width;this.workCanvas.height=this.height;this.workContext=this.workCanvas.getContext("2d")}raiseTickEvent(n,t){this.state!=o.Pending&&super.raiseTickEvent(n,t)}raiseRenderEvent(n){this.state!=o.Pending&&super.raiseRenderEvent(n)}}class g extends w{constructor(n,t=null,i=3e3,u={}){if(super(u),this.image=null,this.imageAngle=0,this.imageStartTime=0,this.imageElapsedTime=0,this.imageFadeInDuration=1e3,this.imageDisplayDuration=i,this.imageFadeOutDuration=1e3,this.imagePauseDuration=1e3,this.imageState="wait",n!=null)r.loadImage(n).then(n=>{this.image=n,this.imageState="ready"}).catch(n=>{console.error("Hud image load promises rejected:",n)});else{if(!t){console.error("No image data.");return}const n=new Image;n.src=t;n.onload=()=>{this.image={Image:n};var t=document.createElement("canvas"),i=t.getContext("2d");t.width=n.width;t.height=n.height;i.drawImage(n,0,0,n.width,n.height);this.image.ActiveStage=t;this.image.CanvasContext=i;this.imageState="ready"}}}onTick(n){if(this.state==o.Active)switch(this.imageState){case"ready":this.imageAngle=Math.random()*40-20;this.imageState="fadeIn";this.imageStartTime=n;this.imageElapsedTime=0;break;case"fadeIn":this.imageElapsedTime=n-this.imageStartTime;this.imageElapsedTime>=this.imageFadeInDuration&&(this.imageState="display",this.imageStartTime=n,this.imageElapsedTime=0);break;case"display":this.imageElapsedTime=n-this.imageStartTime;this.imageElapsedTime>=this.imageDisplayDuration&&(this.imageState="fadeOut",this.imageStartTime=n,this.imageElapsedTime=0);break;case"fadeOut":this.imageElapsedTime=n-this.imageStartTime;this.imageElapsedTime>=this.imageFadeOutDuration&&(this.imageState="done",this.state=o.Complete,this.imageStartTime=n,this.imageElapsedTime=0)}}onDraw(n){n.clearRect(0,0,n.canvas.width,n.canvas.height);let t=0;this.imageState!="wait"&&this.imageState!="ready"&&(this.imageState==="fadeIn"?t=this.imageElapsedTime/this.imageFadeInDuration:this.imageState==="display"?t=1:this.imageState==="fadeOut"&&(t=1-this.imageElapsedTime/this.imageFadeOutDuration),this.drawImage(n,t))}drawImage(n,t){const s=n.canvas,f=s.width,h=s.height,e=this.image.ActiveStage,c=e.width,l=e.height,o=c/l;let i,r;o>1?(i=f*.5,r=i/o):(r=h*.9,i=r*o);const a=f-(i/2+f*.1),v=h/2,u=5;n.save();n.translate(a,v);n.rotate(this.imageAngle*Math.PI/180);n.globalAlpha=t;n.shadowColor="rgba(0, 0, 0, 0.5)";n.shadowBlur=10;n.shadowOffsetX=5;n.shadowOffsetY=5;n.drawImage(e,-i/2,-r/2,i,r);n.shadowColor="transparent";n.shadowBlur=0;n.shadowOffsetX=0;n.shadowOffsetY=0;n.lineWidth=u;n.strokeStyle="white";n.strokeRect(-i/2-u/2,-r/2-u/2,i+u,r+u);n.restore()}}class l extends w{static FillType={Cover:0,Stretch:1};constructor(n,t={}){super(t);this.videoLoaded=!1;this.fill=t.fill||l.FillType.Cover;this.muted=t.muted==undefined?!0:t.muted;this.looped=t.looped==undefined?!1:t.looped;typeof n=="string"?r.preloadVideo(null,n).then(n=>{this.video=n.Video,this.video.loop=this.looped,this.video.muted=this.muted,this.video.play(),this.videoLoaded=!0,this.videoStarted=!1,this.video.addEventListener("ended",()=>{this.state=o.Complete,this.trigger("ended")})}).catch(n=>{console.error("Failed to load video: ",n)}):(this.video=n,this.video.loop=this.looped,this.video.muted=this.muted,this.video.play(),this.videoLoaded=!0,this.videoStarted=!1,this.video.addEventListener("ended",()=>{this.state=o.Complete,this.trigger("ended")}))}onTick(){this.state==o.Active&&this.videoLoaded&&!this.videoStarted&&(this.video.paused||!this.video.ended)&&(this.video.play(),this.video.currentTime=0,this.videoStarted=!0)}onDraw(n){n.clearRect(0,0,n.canvas.width,n.canvas.height);!this.videoLoaded||this.video.paused||this.video.ended||this.drawVideo(this.video,n)}stopVideo(){this.video&&(this.video.pause(),this.video.currentTime=0,this.state=o.Complete,this.videoStarted=!1)}drawVideo(n,t){if(n.videoWidth!==0&&n.videoHeight!==0){const s=n.videoWidth,h=n.videoHeight,i=t.canvas.width,r=t.canvas.height;let u,f,e=0,o=0;if(this.fill===l.FillType.Cover){const n=s/h,t=i/r;n>t?(f=r,u=r*n,e=(i-u)/2,o=0):(u=i,f=i/n,e=0,o=(r-f)/2)}else this.fill===l.FillType.Stretch&&(u=i,f=r,e=0,o=0);t.drawImage(n,0,0,n.videoWidth,n.videoHeight,e,o,u,f)}}}class rt extends w{constructor(n,t=3e3,i="fade",r={}){super(r);this.text=n;this.minDuration=t;this.transitionType=i;this.textState="ready";this.textStartTime=0;this.textElapsedTime=0;this.textLeadInDuration=1e3;this.textDisplayDuration=t;this.textLeadOutDuration=1e3;this.textPauseDuration=1e3;this.pixelsPerTime=0;this.verticalScroll=0;this.backgroundColor=r.backgroundColor||"rgba(0, 0, 0, 0.8)";this.borderColor=r.borderColor||"white";this.textColor=r.textColor||"white";this.textAlign=r.textAlign||"left";this.fontSize=r.fontSize==undefined?0:r.fontSize;this.font=null;this.lineSpacing=r.lineSpacing==undefined?2:r.lineSpacing;this.cached=!1;this.cachedValues={};this.preDisplayDuration=1e3;this.postDisplayDuration=1e3}onTick(n){this.state===o.Active&&this.updateTextState(n)}updateTextState(n){switch(this.textState){case"ready":this.startLeadIn(n);break;case"leadIn":this.handleLeadIn(n);break;case"pre-display":this.handlePreDisplay(n);break;case"display":this.handleDisplay(n);break;case"post-display":this.handlePostDisplay(n);break;case"leadOut":this.handleLeadOut(n)}}startLeadIn(n){this.textState="leadIn";this.textStartTime=n;this.textElapsedTime=0}handleLeadIn(n){this.textElapsedTime=n-this.textStartTime;this.textElapsedTime>=this.textLeadInDuration&&(this.textState=this.pixelsPerTime===0?"display":"pre-display",this.resetTime(n))}handlePreDisplay(n){this.textElapsedTime=n-this.textStartTime;this.textElapsedTime>=this.preDisplayDuration&&(this.textState="display",this.resetTime(n))}handleDisplay(n){this.textElapsedTime=n-this.textStartTime;this.verticalScroll=this.pixelsPerTime*this.textElapsedTime;this.textElapsedTime>=this.textDisplayDuration&&(this.textState=this.pixelsPerTime===0?"leadOut":"post-display",this.resetTime(n))}handlePostDisplay(n){this.textElapsedTime=n-this.textStartTime;this.textElapsedTime>=this.postDisplayDuration&&(this.textState="leadOut",this.resetTime(n))}handleLeadOut(n){this.textElapsedTime=n-this.textStartTime;this.textElapsedTime>=this.textLeadOutDuration&&(this.textState="done",this.state=o.Complete,this.resetTime(n))}resetTime(n){this.textStartTime=n;this.textElapsedTime=0}onDraw(n){if(n.clearRect(0,0,n.canvas.width,n.canvas.height),this.cached||(this.cacheValues(n),this.cached=!0),this.state==o.Active)switch(this.transitionType){case"fade":this.drawFade(n);break;case"slide-left":this.drawSlide(n,"left");break;case"slide-right":this.drawSlide(n,"right");break;case"slide-up":this.drawSlide(n,"up");break;case"slide-down":this.drawSlide(n,"down");break;case"slide-through-left":this.drawSlideThrough(n,"left");break;case"slide-through-right":this.drawSlideThrough(n,"right");break;case"expand":this.drawExpand(n);break;case"zoom":this.drawZoom(n)}}cacheValues(n){try{const v=n.canvas,{width:i,height:r}=v;let y=this.fontSize==0?r*.05:this.fontSize;this.font=`${y}px arial`;const u=5,t=20;n.font=this.font;const f=n.measureText(this.text),p=f.width+t*2,e=f.actualBoundingBoxAscent+f.actualBoundingBoxDescent+this.lineSpacing;let o=Math.min(i*.8,p);const s=this.wrapText(n,this.text,o-39);let h=Math.min(r*.8+t*2,e*s.length+t*2),c=e*s.length+40-h;c>0&&(this.pixelsPerTime=c/this.textDisplayDuration);const l=(i-o)/2,a=(r-h)/2,w=this.textAlign=="center"?i/2:l+u/2+t;this.cachedValues={x:l,y:a,textBoxWidth:o,textBoxHeight:h,lineHeight:e,lines:s,fontX:w,fontY:a+u/2+t,borderWidth:u}}catch(t){console.error("Error caching values: ",t)}}drawFade(n){const{x:t,y:i,textBoxWidth:r,textBoxHeight:u,lineHeight:f,lines:e,fontX:o,fontY:s,borderWidth:h}=this.cachedValues;n.save();n.globalAlpha=this.getFadeAlpha();n.fillStyle=this.backgroundColor;n.fillRect(t,i,r,u);n.beginPath();n.rect(t,i,r,u);n.clip();n.lineWidth=h;n.strokeStyle=this.borderColor;n.strokeRect(t,i,r,u);n.fillStyle=this.textColor;n.font=this.font;n.textAlign=this.textAlign;n.textBaseline="top";const c=s-this.verticalScroll;e.forEach((t,i)=>{n.fillText(t,o,c+i*f)});n.restore()}getFadeAlpha(){switch(this.textState){case"leadIn":return this.textElapsedTime/this.textLeadInDuration;case"pre-display":case"display":case"post-display":return 1;case"fadeOut":return 1-this.textElapsedTime/this.textLeadOutDuration;default:return 0}}drawSlide(n,t){const{x:r,y:u,textBoxWidth:f,textBoxHeight:e,lineHeight:h,lines:c,fontX:l,fontY:a,borderWidth:v}=this.cachedValues;n.save();let o=0,s=0;const i=this.getSlideProgress();switch(t){case"left":o=n.canvas.width*(1-i);break;case"right":o=n.canvas.width*(i-1);break;case"up":s=n.canvas.height*(1-i);break;case"down":s=n.canvas.height*(i-1)}n.translate(o,s);n.fillStyle=this.backgroundColor;n.fillRect(r,u,f,e);n.beginPath();n.rect(r,u,f,e);n.clip();n.lineWidth=v;n.strokeStyle=this.borderColor;n.strokeRect(r,u,f,e);n.fillStyle=this.textColor;n.font=this.font;n.textAlign="left";n.textBaseline="top";const y=a-this.verticalScroll;c.forEach((t,i)=>{n.fillText(t,l,y+i*h)});n.restore()}getSlideProgress(){switch(this.textState){case"leadIn":return this.textElapsedTime/this.textLeadInDuration;case"pre-display":case"display":case"post-display":return 1;case"leadOut":return 1-this.textElapsedTime/this.textLeadOutDuration;default:return 0}}drawExpand(n){const{x:c,y:l,textBoxWidth:f,textBoxHeight:e,lineHeight:a,lines:v,fontX:y,fontY:p,borderWidth:w}=this.cachedValues;n.save();const o=this.getExpandProgress(),t=f*o,i=e*o,s=(f-t)/2,h=(e-i)/2,r=c+s,u=l+h;n.fillStyle=this.backgroundColor;n.fillRect(r,u,t,i);n.beginPath();n.rect(r,u,t,i);n.clip();n.lineWidth=w;n.strokeStyle=this.borderColor;n.strokeRect(r,u,t,i);n.fillStyle=this.textColor;n.font=this.font;n.textAlign="left";n.textBaseline="top";const b=p-this.verticalScroll+h;v.forEach((t,i)=>{n.fillText(t,y+s,b+i*a)});n.restore()}getExpandProgress(){switch(this.textState){case"leadIn":return this.textElapsedTime/this.textLeadInDuration;case"pre-display":case"display":case"post-display":return 1;case"leadOut":return 1-this.textElapsedTime/this.textLeadOutDuration;default:return 0}}drawZoom(n){const{x:s,y:h,textBoxWidth:e,textBoxHeight:o,lineHeight:c,lines:l,fontX:a,fontY:v,borderWidth:y}=this.cachedValues;n.save();const p=this.getZoomProgress(),t=p,i=e*t,r=o*t,w=(e-i)/2,b=(o-r)/2,u=s+w,f=h+b;n.translate(u+i/2,f+r/2);n.scale(t,t);n.translate(-(u+i/2),-(f+r/2));n.fillStyle=this.backgroundColor;n.fillRect(u,f,i,r);n.beginPath();n.rect(u,f,i,r);n.clip();n.lineWidth=y;n.strokeStyle=this.borderColor;n.strokeRect(u,f,i,r);n.fillStyle=this.textColor;n.font=this.font;n.textAlign="left";n.textBaseline="top";const k=v-this.verticalScroll/t;l.forEach((i,r)=>{n.fillText(i,a/t,k+r*c/t)});n.restore()}getZoomProgress(){switch(this.textState){case"leadIn":return this.textElapsedTime/this.textLeadInDuration;case"pre-display":case"display":case"post-display":return 1;case"leadOut":return 1-this.textElapsedTime/this.textLeadOutDuration;default:return 0}}drawSlideThrough(n,t){const{x:i,y:r,textBoxWidth:u,textBoxHeight:f,lineHeight:o,lines:s,fontX:h,fontY:c,borderWidth:l}=this.cachedValues;n.save();let e=this.getSlideThroughProgress();t=="right"&&(e=e*-1);const a=n.canvas.width,v=a/2*e;n.translate(v,0);n.fillStyle=this.backgroundColor;n.fillRect(i,r,u,f);n.beginPath();n.rect(i,r,u,f);n.clip();n.lineWidth=l;n.strokeStyle=this.borderColor;n.strokeRect(i,r,u,f);n.fillStyle=this.textColor;n.font=this.font;n.textAlign="left";n.textBaseline="top";const y=c-this.verticalScroll;s.forEach((t,i)=>{n.fillText(t,h,y+i*o)});n.restore()}getSlideThroughProgress(){let n=0;switch(this.textState){case"leadIn":n=(1-this.textElapsedTime/this.textLeadInDuration)*-1.5;break;case"pre-display":n=0;break;case"display":n=0;break;case"post-display":n=0;break;case"leadOut":n=this.textElapsedTime/this.textLeadInDuration*1.5;break;default:n=this.textElapsedTime/this.textLeadInDuration*1.5}return n}wrapText(n,t,i){const u=t.split(" ");let f=[],r=u[0];for(let t=1;t{this._qrImageLoaded=!0})}if(t.backgroundVideo&&(this._videoLoaded=!1,r.loadVideo(t.backgroundVideo).then(n=>{this._video=n.Video,this._video.loop=!0,this._video.muted=!0,this._video.play(),this._video.currentTime=0,this._videoLoaded=!0})),this.onInit&&!i)this.onInit(t)}raiseTickEvent(n,t){if(this.isActive){switch(this._actionState){case 0:this._actionQueue.length>0&&(this._action=this._actionQueue.shift(),this._action.start(),this._action.trigger("started"),this._actionState=1);break;case 1:this._action.state==o.Complete&&(this._action.trigger("completed"),this.destroyProp(this._action.id),this._action=null,this._actionState=2,this._actionStartTime=n,this._actionElapsedTime=0);break;case 2:this._actionElapsedTime=n-this._actionStartTime;this._actionElapsedTime>=this._actionQueueDelay&&(this._actionState=0)}super.raiseTickEvent(n,t)}}raiseRenderEvent(n){if(this.isActive){if(n.clearRect(0,0,n.canvas.width,n.canvas.height),this._videoLoaded&&this._drawVideo(this._video,n),super.raiseRenderEvent(n),this._action!=null&&this._action.raiseRenderEvent(n),this.onPostActionDraw!=null)this.onPostActionDraw(n);this._showQrCode&&this._drawQrCode(n)}}raiseStageActiveEvent(){$GG.server.attachSystemEvent("GgHudMediaShare",this._handleBroadcastImages.bind(this));this._videoLoaded&&(this._video.paused||this._video.ended)&&(this._video.play(),this._video.currentTime=0);super.raiseStageActiveEvent()}raiseStageInactiveEvent(){$GG.server.detachSystemEvent("GgHudMediaShare",this._handleBroadcastImages.bind(this));this._videoLoaded&&(this._video.paused||this._video.ended||(this._video.pause(),this._video.currentTime=0));super.raiseStageInactiveEvent()}queue(n){return n.isActive=!1,this._actionQueue.push(n),this.registerProp(n),n}queueImage(n,t,i={}){const r=new g(n,null,t,i);return r.isActive=!1,this.registerProp(r),this._actionQueue.push(r),r}queueImageData(n,t,i={}){const r=new g(null,n,t,i);return r.isActive=!1,this.registerProp(r),this._actionQueue.push(r),r}queueVideo(n,t={}){const i=new l(n,t);return i.isActive=!1,this.registerProp(i),this._actionQueue.push(i),i}queueText(n,t=3e3,i="fade",r={}){const u=new rt(n,t,i,r);return u.isActive=!1,this.registerProp(u),this._actionQueue.push(u),u}_handleBroadcastImages(n){this.queueImage(n.imageUrl,5e3)}_drawQrCode(n){const e=this._qrCode,o=r.getImage("qrcode"),i=this.height*.01,t=this.height*.2,u=i,f=this.height-(t+i);this._qrImageLoaded&&n.drawImage(o.ActiveStage,u,f,t,t);n.font=`${t*.2}px Arial`;n.textAlign="center";n.textBaseline="bottom";n.shadowColor="rgba(0, 0, 0, 0.5)";n.shadowBlur=4;n.shadowOffsetX=2;n.shadowOffsetY=2;n.fillStyle="white";const s=u+t/2,h=f-i;n.fillText(e,s,h);n.shadowColor="transparent";n.shadowBlur=0;n.shadowOffsetX=0;n.shadowOffsetY=0}_drawVideo(n,t){if(!n.paused&&!n.ended){const h=n.videoWidth,c=n.videoHeight,i=this.width,r=this.height,e=h/c;let u,f,o,s;const l=i/r;e{window.hud&&!window.hud.closed&&(this.hudStageName=null,u.reset(),e.stopAll(),window.hud.close())});window.addEventListener("message",n=>{n.data&&n.data.event==="GgHudClose"&&(this.hudStageName=null,u.reset(),e.stopAll())});const n=document.querySelector("base"),t=n?n.getAttribute("href"):null;this.html=`Gig Games HUD`}isOpen(){return!window.hud||window.hud.closed?!1:!0}getStage(){return this.hudStageName==null?null:u.getStage(this.hudStageName)}init(n=null){return new Promise(t=>{k(null,!0).then(()=>{u.setTransition(new p);var i=this.setStage(n),r=i.queueVideo("https://launch.gig.game/api/1.0.1/mp4/hudintro.mp4",{muted:!1});r.on("completed",()=>{t(i)})})})}open(n=null,t={}){return new Promise(i=>{if(!window.hud||window.hud.closed){const r=`resizable=yes,width=600,height=400`;window.hud=window.open("","hud",r);window.hud.document.write(this.html);window.hud.document.close();window.hud.onload=()=>{setTimeout(()=>{k(window.hud,!0).then(()=>{if(u.setTransition(new p),t.skipIntro!=!0){var r=this.setStage(n),f=r.queueVideo("https://launch.gig.game/api/1.0.1/mp4/hudintro.mp4",{muted:!1});f.on("completed",()=>{i(r)})}else i(r)})},500)}}else{window.hud.focus();var r=this.setStage(n);i(r)}})}setStage(n){n==null&&(n="_default-hud");this.hudStageName=n;var t=u.stages[n];if(t!=null&&(t=t.instance),t==null&&n=="_default-hud")t=new ut("_default-hud",{backgroundVideo:"https://launch.gig.game/api/1.0.1/mp4/hud.mp4"});else if(t==null)return null;return u.setToStage(this.hudStageName),t}close(){window.hud&&!window.hud.closed&&(this.hudStageName=null,u.reset(),window.hud.close())}}class pt{assetSheet={audio:[],images:[],videos:[],loops:[],layouts:[],data:[]};constructor(){}load=n=>{return new Promise((t,i)=>{try{var r=new XMLHttpRequest;r.open("GET",n,true);r.onload=()=>{let n=[];if(r.status===200){const t=JSON.parse(r.responseText);if(Array.isArray(t.audio)){const i=t.audio;i.forEach(t=>{n.push(this.preloadAudioNode(t))})}if(Array.isArray(t.images)){const i=t.images;i.forEach(t=>{n.push(this.preloadImageNode(t))})}if(Array.isArray(t.videos)){const i=t.videos;i.forEach(t=>{n.push(this.preloadVideoNode(t))})}if(Array.isArray(t.layouts)){this.assetSheet.layouts=t.layouts}if(Array.isArray(t.data)){this.assetSheet.data=t.data}}Promise.all(n).then(()=>{t()}).catch(n=>{console.error("One of the promises rejected:",n);i(n)})};r.onerror=()=>{console.error(`Error loading asset sheet`,r.statusText);i(r.statusText)};r.send()}catch(u){console.log("Error loading asset sheet",u);i(u.message)}})};getAudio(n){return this.assetSheet.audio.find(t=>t.name===n)||null}getImage(n){return this.assetSheet.images.find(t=>t.name===n)||null}getVideo(n){return this.assetSheet.videos.find(t=>t.name===n)||null}getSpriteLoop(n){return this.assetSheet.loops.find(t=>t.group===n)||null}getTileset(n){return this.assetSheet.layouts.find(t=>t.name===n)||null}getData(n){return this.assetSheet.data.find(t=>t.name===n)||null}loadImage=n=>{return new Promise((t,i)=>{if(!n)i();var r=new Image;r.src=n;r.onload=()=>{var i=document.createElement("canvas");var f=i.getContext("2d");i.width=r.width;i.height=r.height;f.drawImage(r,0,0,r.width,r.height);let u={path:n};u.Image=r;u.ActiveStage=i;u.CanvasContext=f;t(u)}})};loadVideo=n=>{return new Promise((t,i)=>{if(!n)i();let u={path:n};var r=document.createElement("video");r.src=u.path;r.preload="auto";r.crossOrigin="anonymous";r.onloadeddata=()=>{u.Video=r;t(u)};r.onerror=()=>{i(new Error("Error loading video: "+u.path))}})};loadAudio(n){return new Promise((t,i)=>{if(!n)return i(new Error("Audio path is missing"));const r=new Audio;r.src=n;r.preload="auto";r.crossOrigin="anonymous";const u={path:n,Audio:r};t(u)})}preloadImage=(n,t)=>{return this.preloadImageNode({name:n,path:t})};preloadVideo=(n,t)=>{return this.preloadVideoNode({name:n,path:t})};preloadAudio=(n,t)=>{return this.preloadAudioNode({name:n,path:t})};preloadImageNode=n=>{return new Promise((t,i)=>{if(!n.path){i("Image path is missing");return}var r=new Image;r.src=n.path;r.onload=()=>{var u=document.createElement("canvas");var i=u.getContext("2d");u.width=r.width;u.height=r.height;i.drawImage(r,0,0,r.width,r.height);if(n.clipPaths&&n.clipPaths.length>0){n.clipPaths.forEach(n=>{var f=Infinity,s=-Infinity,e=Infinity,h=-Infinity;for(var t=0;t{return new Promise((t,i)=>{if(!n.path){i("Video path is missing");return}console.log("video load started",n);const r=document.createElement("video");r.src=n.path;r.crossOrigin="anonymous";r.preload="auto";r.oncanplaythrough=()=>{console.log("video loaded",n);n.Video=r;if(n.name){this.assetSheet.videos.push(n)}t(n)};r.onerror=()=>{i(`Error loading video: ${n.path}`)}})};preloadAudioNode(n){return new Promise((t,i)=>{if(!n.path)return i("Audio path is missing");if(ot())n.Audio=new Audio(n.path),n.isLoaded=!1,n.name&&this.assetSheet.audio.push(n),t(n);else{var r=setTimeout(()=>{n.isLoaded=!1,console.warn("Timed out:",n.path),n.name&&this.assetSheet.audio.push(n),t(n)},5e3);const u=new Audio;u.src=n.path;u.crossOrigin="anonymous";u.preload="auto";n.isLoaded=!1;u.oncanplaythrough=()=>{clearTimeout(r),n.Audio=u,n.isLoaded=!0,n.name&&this.assetSheet.audio.push(n),t(n)};u.onerror=t=>{console.error("Error loading audio:",n.path,t),i(new Error(`Error loading audio: ${n.path}`))}}})}releaseImage(n){const t=this.assetSheet.images.findIndex(t=>t.name===n);if(t!==-1){const i=this.assetSheet.images[t];i.Image=null;i.ActiveStage=null;i.CanvasContext=null;this.assetSheet.images.splice(t,1);console.log(`Image '${n}' released from memory.`)}}releaseVideo(n){const t=this.assetSheet.videos.findIndex(t=>t.name===n);if(t!==-1){const i=this.assetSheet.videos[t];i.Video&&(i.Video.pause(),i.Video.src="",i.Video.load(),i.Video=null);this.assetSheet.videos.splice(t,1);console.log(`Video '${n}' released from memory.`)}}releaseAudio(n){const t=this.assetSheet.audio.findIndex(t=>t.name===n);if(t!==-1){const i=this.assetSheet.audio[t];i.Audio&&(i.Audio.pause(),i.Audio.src="",i.Audio.load(),i.Audio=null);this.assetSheet.audio.splice(t,1);console.log(`Audio '${n}' released from memory.`)}}}class wt{audioCache=new Map;activeAudios=new Set;constructor(){}play=(n,t=false,i=1,u=false)=>{const e=r.getAudio(n);if(e==null)return;let f=e.Audio;if(u){f=this.clone(e)}const o=()=>{this.activeAudios.delete(f);f.removeEventListener("ended",o)};f.addEventListener("ended",o);if(!e.isLoaded){f.loop=t;f.volume=i;f.currentTime=0;f.play();this.activeAudios.add(f);return f}if(this.activeAudios.has(f)){f.currentTime=0}else{this.activeAudios.add(f)}if(t){f.loop=true}if(i!==1){f.volume=i}f.play();return f};playTrack=(n,t=1)=>{const u=r.getAudio(n);if(u==null)return Promise.reject(new Error("Audio not found"));let i=u.Audio;i=this.clone(u);return new Promise((n,r)=>{const f=()=>{this.activeAudios.delete(i);i.removeEventListener("ended",f);n()};i.addEventListener("ended",f);if(!u.isLoaded){i.loop=false;i.volume=t;i.currentTime=0;i.play().then(()=>this.activeAudios.add(i)).catch(r);return}if(this.activeAudios.has(i)){i.currentTime=0}else{this.activeAudios.add(i)}i.loop=false;if(t!==1){i.volume=t}i.play().then(()=>{}).catch(r)})};playTrackNode=(n,t=1,i=false)=>{if(n==null)return;let r=n.Audio;if(i){r=this.clone(n)}return new Promise((n,i)=>{const u=()=>{this.activeAudios.delete(r);r.removeEventListener("ended",u);n()};r.addEventListener("ended",u);if(this.activeAudios.has(r)){r.currentTime=0}else{this.activeAudios.add(r)}r.loop=false;if(t!==1){r.volume=t}r.play().then(()=>{}).catch(i)})};stop=n=>{if(typeof n==="string"){const i=r.getAudio(n);if(i==null)return;const t=i.Audio;if(t&&this.activeAudios.has(t)){t.pause();t.currentTime=0;this.activeAudios.delete(t)}}else if(n instanceof Audio){if(this.activeAudios.has(n)){n.pause();n.currentTime=0;this.activeAudios.delete(n)}}};stopAll=()=>{this.activeAudios.forEach(n=>{n.pause();n.currentTime=0;this.activeAudios.delete(n)})};fadeOut=(n,t=1e3)=>{const u=r.getAudio(n);if(u==null)return;const i=u.Audio;if(i&&this.activeAudios.has(i)){const r=i.volume;const n=r/(t/100);const u=setInterval(()=>{if(i.volume>n){i.volume-=n}else{i.volume=0;i.pause();i.currentTime=0;this.activeAudios.delete(i);clearInterval(u)}},100)}};fadeIn=(n,t=1e3,i=1,u=0)=>{const e=r.getAudio(n);if(e==null)return;const f=e.Audio;if(!this.activeAudios.has(f)){this.activeAudios.add(f)}f.currentTime=u;f.volume=0;f.play();const o=i/(t/100);const s=setInterval(()=>{if(f.volume{let t=new Audio;t.src=n.path;return t};}class bt{stages={};activeStageName=null;clockRunning=false;lastTime=0;transition=null;frameDuration=1e3/60;lastTimeFrameUpdate=0;aspectRatio="unset";aspectRatios={"4:3":[4,3],"16:9":[16,9],"21:9":[21,9],"1:1":[1,1],"9:16":[9,16]};constructor(){this.transition=new p}setTransition=n=>{if(n==null)this.transition=null;if(!(n instanceof c))throw new Error("Not a StageTransition.");this.transition=n};raiseResizeEvent=(n,t)=>{if(this.activeStageName==null)return;const i=this.stages[this.activeStageName];if(!i)return;const r=this.getStageSize();i.instance.raiseResizeEvent(r.width,r.height)};raiseRenderEvent=()=>{const r=i.getContext();const f=r.canvas;const u=f.width;const t=f.height;let n=r;if(this.aspectRatio!=="unset"){let r=u;let i=t;const e=this.aspectRatios[this.aspectRatio];if(!e)return;const[o,s]=e;r=u;i=(u/o)*s;if(i>t){i=t;r=(t/s)*o}const f=document.createElement("canvas");f.width=r;f.height=i;n=f.getContext("2d")}if(this.transition!=null)this.transition.raiseRenderEvent(n);else{if(this.activeStageName==null)return;const t=this.stages[this.activeStageName];if(!t)return;t.instance.raiseRenderEvent(n)}if(n!==r){const i=(u-n.canvas.width)/2;const f=(t-n.canvas.height)/2;r.clearRect(0,0,u,t);r.drawImage(n.canvas,i,f,n.canvas.width,n.canvas.height)}i.publish()};registerStage=(n,t=null)=>{if(!n)throw new Error("Invalid stage name.");if(this.stages[n])throw new Error("Stage already defined.");if(t==null||!(t instanceof y))throw new Error("Not a StageType.");this.stages[n]={Name:n,instance:t,SavedState:null}};destroyStage=(n=null)=>{n=n||this.activeStageName;if(this.activeStageName===n){this.activeStageName=null}const t=this.stages[n];if(!t){throw new Error("Stage not found.");}t.instance.clearProps();delete this.stages[n]};setToStage=n=>{if(this.activeStageName==n)return;if(this.activeStageName!=null){this.stages[this.activeStageName].instance.raiseStageInactiveEvent();i.clearEvents();this.stages[this.activeStageName].SavedState=i.getState()}if(n==null){this.activeStageName=null;return}if(!this.stages[n]){throw new Error(`Stage not found: ${n}`);}if(this.transition!=null)this.transition.setToStage(n);else{this.activeStageName=n;this.stages[this.activeStageName].instance.raiseStageActiveEvent()}};getStage=(n=null)=>{var t=null;if(n!=null){return this.stages[n]}if(this.activeStageName!=null){t=this.stages[this.activeStageName]}return t};setFPS=n=>{this.frameDuration=1e3/n};setAspectRatio=n=>{switch(n){case"unset":this.aspectRatio="unset";break;case"4:3":this.aspectRatio="4:3";break;case"16:9":this.aspectRatio="16:9";break;case"21:9":this.aspectRatio="21:9";break;case"1:1":this.aspectRatio="1:1";break;case"9:16":this.aspectRatio="9:16";break;default:this.aspectRatio="unset"}};getStageName=()=>{return this.activeStageName};getStageSize=()=>{const s=i.getContext();const{width:t,height:n}=s.canvas;if(this.aspectRatio==="unset"){return{width:t,height:n}}const u=this.aspectRatios[this.aspectRatio];if(!u)return{width:t,height:n};const[f,e]=u;let o=t;let r=(t/f)*e;if(r>n){r=n;o=(n/e)*f}return{width:o,height:r}};startClock=()=>{this.lastTime=0;this.clockRunning=true;window.requestAnimationFrame(this.tick)};stopClock=()=>{this.clockRunning=false};tick=n=>{let t=n-this.lastTime;if(this.activeStageName){if((this.transition!=null)&(this.transition.raiseTickEvent!=null))this.transition.raiseTickEvent(n,t);const i=this.stages[this.activeStageName];i.instance.raiseTickEvent(n,t)}this.lastTimeFrameUpdate+=t;if(this.lastTimeFrameUpdate>this.frameDuration){this.lastTimeFrameUpdate=0;this.raiseRenderEvent()}this.lastTime=n;if(this.clockRunning){window.requestAnimationFrame(this.tick)}};reset=()=>{const t=Object.keys(this.stages);for(var n=0;n