Файловый менеджер - Редактировать - /home/jogoso94/public_html/jogos/dark_quest/scripts/main.js
�азад
// Generated by Construct, the game and animation creation tool // Visit: https://www.construct.net "use strict";window.DOMHandler=class{constructor(e,t){this._iRuntime=e,this._componentId=t,this._hasTickCallback=!1,this._tickCallback=()=>this.Tick()}Attach(){}PostToRuntime(e,t,i,s){this._iRuntime.PostToRuntimeComponent(this._componentId,e,t,i,s)}PostToRuntimeAsync(e,t,i,s){return this._iRuntime.PostToRuntimeComponentAsync(this._componentId,e,t,i,s)}_PostToRuntimeMaybeSync(e,t,i){this._iRuntime.UsesWorker()?this.PostToRuntime(e,t,i):this._iRuntime._GetLocalRuntime()._OnMessageFromDOM({type:"event",component:this._componentId,handler:e,dispatchOpts:i||null,data:t,responseId:null})}AddRuntimeMessageHandler(e,t){this._iRuntime.AddRuntimeComponentMessageHandler(this._componentId,e,t)}AddRuntimeMessageHandlers(e){for(const[t,i]of e)this.AddRuntimeMessageHandler(t,i)}GetRuntimeInterface(){return this._iRuntime}GetComponentID(){return this._componentId}_StartTicking(){this._hasTickCallback||(this._iRuntime._AddRAFCallback(this._tickCallback),this._hasTickCallback=!0)}_StopTicking(){this._hasTickCallback&&(this._iRuntime._RemoveRAFCallback(this._tickCallback),this._hasTickCallback=!1)}Tick(){}},window.RateLimiter=class{constructor(e,t){this._callback=e,this._interval=t,this._timerId=-1,this._lastCallTime=-1/0,this._timerCallFunc=()=>this._OnTimer(),this._ignoreReset=!1,this._canRunImmediate=!1}SetCanRunImmediate(e){this._canRunImmediate=!!e}Call(){if(-1===this._timerId){const e=Date.now(),t=e-this._lastCallTime,i=this._interval;i<=t&&this._canRunImmediate?(this._lastCallTime=e,this._RunCallback()):this._timerId=self.setTimeout(this._timerCallFunc,Math.max(i-t,4))}}_RunCallback(){this._ignoreReset=!0,this._callback(),this._ignoreReset=!1}Reset(){this._ignoreReset||(this._CancelTimer(),this._lastCallTime=Date.now())}_OnTimer(){this._timerId=-1,this._lastCallTime=Date.now(),this._RunCallback()}_CancelTimer(){-1!==this._timerId&&(self.clearTimeout(this._timerId),this._timerId=-1)}Release(){this._CancelTimer(),this._callback=null,this._timerCallFunc=null}};{class y{constructor(e){this._elem=e,this._hadFirstUpdate=!1,this._isVisibleFlag=!0,this._wantHtmlIndex=-1,this._actualHtmlIndex=-1,this._htmlZIndex=-1}SetVisibleFlag(e){this._isVisibleFlag=!!e}GetVisibleFlag(){return this._isVisibleFlag}HadFirstUpdate(){return this._hadFirstUpdate}SetHadFirstUpdate(){this._hadFirstUpdate=!0}GetWantHTMLIndex(){return this._wantHtmlIndex}SetWantHTMLIndex(e){this._wantHtmlIndex=e}GetActualHTMLIndex(){return this._actualHtmlIndex}SetActualHTMLIndex(e){this._actualHtmlIndex=e}SetHTMLZIndex(e){this._htmlZIndex=e}GetHTMLZIndex(){return this._htmlZIndex}GetElement(){return this._elem}}window.DOMElementHandler=class extends self.DOMHandler{constructor(e,t){super(e,t),this._elementMap=new Map,this._autoAttach=!0,this.AddRuntimeMessageHandlers([["create",e=>this._OnCreate(e)],["destroy",e=>this._OnDestroy(e)],["set-visible",e=>this._OnSetVisible(e)],["update-position",e=>this._OnUpdatePosition(e)],["update-state",e=>this._OnUpdateState(e)],["focus",e=>this._OnSetFocus(e)],["set-css-style",e=>this._OnSetCssStyle(e)],["set-attribute",e=>this._OnSetAttribute(e)],["remove-attribute",e=>this._OnRemoveAttribute(e)]]),this.AddDOMElementMessageHandler("get-element",e=>e)}SetAutoAttach(e){this._autoAttach=!!e}AddDOMElementMessageHandler(e,s){this.AddRuntimeMessageHandler(e,e=>{const t=e.elementId,i=this.GetElementById(t);return s(i,e)})}AddDOMElementMessageHandlers(e){for(const[t,i]of e)this.AddDOMElementMessageHandler(t,i)}_OnCreate(e){const t=e.elementId,i=this.CreateElement(t,e),s=new y(i),n=(this._elementMap.set(t,s),i.style.boxSizing="border-box",i.style.display="none",s.SetVisibleFlag(e.isVisible),this._GetFocusElement(i)),o=(n.addEventListener("focus",e=>this._OnFocus(t)),n.addEventListener("blur",e=>this._OnBlur(t)),e.htmlIndex);if(s.SetWantHTMLIndex(o),s.SetHTMLZIndex(e.htmlZIndex),this._autoAttach){const a=this.GetRuntimeInterface().GetAvailableHTMLIndex(o),r=(s.SetActualHTMLIndex(a),this.GetRuntimeInterface().GetHTMLWrapElement(a));r.appendChild(i)}}CreateElement(e,t){throw new Error("required override")}DestroyElement(e){}_OnDestroy(e){const t=e.elementId,i=this.GetElementById(t);this.DestroyElement(i),this._autoAttach&&i.parentElement.removeChild(i),this._elementMap.delete(t)}PostToRuntimeElement(e,t,i){(i=i||{}).elementId=t,this.PostToRuntime(e,i)}_PostToRuntimeElementMaybeSync(e,t,i){(i=i||{}).elementId=t,this._PostToRuntimeMaybeSync(e,i)}_OnSetVisible(e){if(this._autoAttach){const t=this._elementMap.get(e.elementId),i=t.GetElement();t.HadFirstUpdate()?i.style.display=e.isVisible?"":"none":t.SetVisibleFlag(e.isVisible)}}_OnUpdatePosition(e){if(this._autoAttach){const t=this._elementMap.get(e.elementId),i=t.GetElement(),s=this.GetRuntimeInterface(),n=(i.style.left=e.left+"px",i.style.top=e.top+"px",i.style.width=e.width+"px",i.style.height=e.height+"px",e.fontSize),o=(null!==n&&(i.style.fontSize=n+"em"),e.htmlIndex),a=(t.SetWantHTMLIndex(o),s.GetAvailableHTMLIndex(o));if(a!==t.GetActualHTMLIndex()){i.remove();const d=s.GetHTMLWrapElement(a);d.appendChild(i),t.SetActualHTMLIndex(a),s._UpdateHTMLElementsZOrder()}const r=e.htmlZIndex;r!==t.GetHTMLZIndex()&&(t.SetHTMLZIndex(r),s._UpdateHTMLElementsZOrder()),t.HadFirstUpdate()||(t.SetHadFirstUpdate(),t.GetVisibleFlag()&&(i.style.display=""))}}_OnHTMLLayersChanged(){if(this._autoAttach)for(const e of this._elementMap.values()){const t=this.GetRuntimeInterface().GetAvailableHTMLIndex(e.GetWantHTMLIndex()),i=e.GetActualHTMLIndex();if(-1!==t&&-1!==i&&t!==i){const s=e.GetElement(),n=(s.remove(),this.GetRuntimeInterface().GetHTMLWrapElement(t));n.appendChild(s),e.SetActualHTMLIndex(t)}}}_GetAllElementStatesForZOrderUpdate(){return this._autoAttach?[...this._elementMap.values()]:null}_OnUpdateState(e){const t=this.GetElementById(e.elementId);this.UpdateState(t,e)}UpdateState(e,t){throw new Error("required override")}_GetFocusElement(e){return e}_OnFocus(e){this.PostToRuntimeElement("elem-focused",e)}_OnBlur(e){this.PostToRuntimeElement("elem-blurred",e)}_OnSetFocus(e){const t=this._GetFocusElement(this.GetElementById(e.elementId));e.focus?t.focus():t.blur()}_OnSetCssStyle(e){const t=this.GetElementById(e.elementId),i=e.prop,s=e.val;i.startsWith("--")?t.style.setProperty(i,s):t.style[i]=s}_OnSetAttribute(e){const t=this.GetElementById(e.elementId);t.setAttribute(e.name,e.val)}_OnRemoveAttribute(e){const t=this.GetElementById(e.elementId);t.removeAttribute(e.name)}GetElementById(e){const t=this._elementMap.get(e);if(t)return t.GetElement();throw new Error("no element with id "+e)}}}{const b0=/(iphone|ipod|ipad|macos|macintosh|mac os x)/i.test(navigator.userAgent),c0=/android/i.test(navigator.userAgent),d0=/safari/i.test(navigator.userAgent)&&!/(chrome|chromium|edg\/|OPR\/|nwjs)/i.test(navigator.userAgent);let n=0;function AddScript(i){const s=document.createElement("script");return s.async=!1,s.type="module",i.isStringSrc?new Promise(e=>{const t="c3_resolve_"+n;++n,self[t]=e,s.textContent=i.str+` self["${t}"]();`,document.head.appendChild(s)}):new Promise((e,t)=>{s.onload=e,s.onerror=t,s.src=i,document.head.appendChild(s)})}async function CheckSupportsWorkerMode(){if(!navigator.userActivation||"undefined"==typeof OffscreenCanvas)return!1;try{let e=!1;const t=new Blob([` self.addEventListener("message", () => { try { const offscreenCanvas = new OffscreenCanvas(32, 32); const gl = offscreenCanvas.getContext("webgl"); self.postMessage(!!gl); } catch (err) { console.warn("Feature detection worker error:", err); self.postMessage(false); } });`],{type:"text/javascript"}),i=new Worker(URL.createObjectURL(t),{get type(){e=!0}}),s=await new Promise(t=>{i.addEventListener("message",e=>{i.terminate(),t(e.data)}),i.postMessage("")});return e&&s}catch(e){return console.warn("Error feature detecting worker mode: ",e),!1}}let e=new Audio;const g0={"audio/webm; codecs=opus":!!e.canPlayType("audio/webm; codecs=opus"),"audio/ogg; codecs=opus":!!e.canPlayType("audio/ogg; codecs=opus"),"audio/webm; codecs=vorbis":!!e.canPlayType("audio/webm; codecs=vorbis"),"audio/ogg; codecs=vorbis":!!e.canPlayType("audio/ogg; codecs=vorbis"),"audio/mp4":!!e.canPlayType("audio/mp4"),"audio/mpeg":!!e.canPlayType("audio/mpeg")};async function BlobToString(e){const t=await BlobToArrayBuffer(e),i=new TextDecoder("utf-8");return i.decode(t)}function BlobToArrayBuffer(s){return new Promise((t,i)=>{const e=new FileReader;e.onload=e=>t(e.target.result),e.onerror=e=>i(e),e.readAsArrayBuffer(s)})}e=null;const h0=[];let s=0;const j0=8,k0=(window.RealFile=window.File,[]),l0=new Map,m0=new Map;let r=0;const o0=[],p0=(self.runOnStartup=function(e){if("function"!=typeof e)throw new Error("runOnStartup called without a function");o0.push(e)},new Set(["cordova","playable-ad-single-file","playable-ad-zip","instant-games"]));function IsWebViewExportType(e){return p0.has(e)}let t=!1;window.RuntimeInterface=class P0{constructor(e){if(this._useWorker=e.useWorker,this._messageChannelPort=null,this._runtimeBaseUrl="",this._scriptFolder=e.scriptFolder,this._worker=null,this._localRuntime=null,this._domHandlers=[],this._runtimeDomHandler=null,this._isFirstSizeUpdate=!0,this._canvasLayers=[],this._pendingRemoveElements=[],this._pendingUpdateHTMLZOrder=!1,this._updateHTMLZOrderRAFCallback=()=>this._DoUpdateHTMLElementsZOrder(),this._isExportingToVideo=!1,this._exportToVideoDuration=0,this._jobScheduler=null,this._rafId=-1,this._rafFunc=()=>this._OnRAFCallback(),this._rafCallbacks=new Set,this._wrapperInitResolve=null,this._wrapperComponentIds=[],this._exportType=e.exportType,this._isFileProtocol="file"===location.protocol.substr(0,4),this._directoryHandles=[],"playable-ad-single-file"!==this._exportType&&"playable-ad-zip"!==this._exportType&&"instant-games"!==this._exportType||(this._useWorker=!1),d0&&(this._useWorker=!1),"cordova"===this._exportType&&this._useWorker&&c0){const t=/Chrome\/(\d+)/i.exec(navigator.userAgent);t&&90<=parseInt(t[1],10)||(this._useWorker=!1)}this.IsAnyWebView2Wrapper()?self.chrome.webview.addEventListener("message",e=>this._OnWrapperMessage(e.data,e.additionalObjects)):"macos-wkwebview"===this._exportType?self.C3WrapperOnMessage=e=>this._OnWrapperMessage(JSON.parse(e)):"linux-cef"===this._exportType&&self.c3_linux_cef_set_message_callback(e=>this._OnWrapperMessage(JSON.parse(e))),this._localFileBlobs=null,this._localFileStrings=null,"html5"!==this._exportType||window.isSecureContext||console.warn("[Construct] Warning: the browser indicates this is not a secure context. Some features may be unavailable. Use secure (HTTPS) hosting to ensure all features are available."),this.AddRuntimeComponentMessageHandler("canvas","update-size",e=>this._OnUpdateCanvasSize(e)),this.AddRuntimeComponentMessageHandler("canvas","set-html-layer-count",e=>this._OnSetHTMLLayerCount(e)),this.AddRuntimeComponentMessageHandler("canvas","cleanup-html-layers",()=>this._OnCleanUpHTMLLayers()),this.AddRuntimeComponentMessageHandler("canvas","update-html-layer-dom-state",e=>this._UpdateHTMLLayerDOMProperties(e.layersDomState)),this.AddRuntimeComponentMessageHandler("runtime","cordova-fetch-local-file",e=>this._OnCordovaFetchLocalFile(e)),this.AddRuntimeComponentMessageHandler("runtime","create-job-worker",e=>this._OnCreateJobWorker(e)),this.AddRuntimeComponentMessageHandler("runtime","send-wrapper-extension-message",e=>this._OnSendWrapperExtensionMessage(e)),"cordova"===this._exportType?document.addEventListener("deviceready",()=>this._Init(e)):this._Init(e),this._skipAndroidVirtualKeyboardDetection=0}Release(){this._CancelAnimationFrame(),this._messageChannelPort&&(this._messageChannelPort.onmessage=null,this._messageChannelPort=null),this._worker&&(this._worker.terminate(),this._worker=null),this._localRuntime&&(this._localRuntime.Release(),this._localRuntime=null);for(const{canvas:e,htmlWrap:t}of this._canvasLayers)e.remove(),t.remove();this._canvasLayers.length=0}GetMainCanvas(){return this._canvasLayers[0].canvas}GetAvailableHTMLIndex(e){return Math.min(e,this._canvasLayers.length-1)}GetHTMLWrapElement(e){if(e<0||e>=this._canvasLayers.length)throw new RangeError("invalid canvas layer");return this._canvasLayers[e].htmlWrap}["_GetHTMLWrapElement"](e){return this.GetHTMLWrapElement(e)}GetRuntimeBaseURL(){return this._runtimeBaseUrl}UsesWorker(){return this._useWorker}GetExportType(){return this._exportType}IsFileProtocol(){return this._isFileProtocol}GetScriptFolder(){return this._scriptFolder}IsiOSCordova(){return b0&&"cordova"===this._exportType}IsiOSWebView(){const e=navigator.userAgent;return b0&&IsWebViewExportType(this._exportType)||navigator.standalone||/crios\/|fxios\/|edgios\//i.test(e)}IsAndroid(){return c0}IsAndroidWebView(){return c0&&IsWebViewExportType(this._exportType)}IsWindowsWebView2(){return"windows-webview2"===this._exportType||!!("preview"===this._exportType&&window.chrome&&window.chrome.webview&&window.chrome.webview.postMessage)}IsAnyWebView2Wrapper(){return this.IsWindowsWebView2()||"xbox-uwp-webview2"===this._exportType}SkipNextAndroidVirtualKeyboardDetection(){this.IsAndroidWebView()&&this._skipAndroidVirtualKeyboardDetection++}CanDoAndroidVirtualKeyboardDetection(){return this._CanDoAndroidVirtualKeyboardDetection().next().value}*_CanDoAndroidVirtualKeyboardDetection(){if(!this.IsAndroidWebView())return!0;yield 0===this._skipAndroidVirtualKeyboardDetection,0<this._skipAndroidVirtualKeyboardDetection&&this._skipAndroidVirtualKeyboardDetection--}async _Init(e){if(this._useWorker){const i=await CheckSupportsWorkerMode();i||(this._useWorker=!1)}if("macos-wkwebview"===this._exportType&&this._SendWrapperMessage({type:"ready"}),this.IsAnyWebView2Wrapper()||"macos-wkwebview"===this._exportType||"linux-cef"===this._exportType){this._SetupDesktopWrapperPolyfills();const s=await this._InitWrapper();this._wrapperComponentIds=s.registeredComponentIds}if("playable-ad-single-file"===this._exportType&&(this._localFileBlobs=self.c3_base64files,this._localFileStrings={},await this._ConvertDataUrisToBlobs()),"nwjs"===this._exportType&&self.nw){const n=self.nw.Window.get();if(n.on("close",()=>self.nw.App.quit()),self.nw.App.manifest["c3-steam-mode"]){let e=0;this._AddRAFCallback(()=>{e++,document.documentElement.style.opacity=e%2==0?"1":"0.999"})}}if(e.runtimeBaseUrl)this._runtimeBaseUrl=e.runtimeBaseUrl;else{const o=location.origin,a=(this._runtimeBaseUrl=("null"===o?"file:///":o)+location.pathname,this._runtimeBaseUrl.lastIndexOf("/"));-1!==a&&(this._runtimeBaseUrl=this._runtimeBaseUrl.substr(0,a+1))}const t=new MessageChannel;if(this._messageChannelPort=t.port1,this._messageChannelPort.onmessage=e=>this._OnMessageFromRuntime(e.data),window.c3_addPortMessageHandler&&window.c3_addPortMessageHandler(e=>this._OnMessageFromDebugger(e)),this._jobScheduler=new self.JobSchedulerDOM(this),await this._jobScheduler.Init(),"object"==typeof window.StatusBar&&window.StatusBar.hide(),"object"==typeof window.AndroidFullScreen)try{await new Promise((e,t)=>{window.AndroidFullScreen.immersiveMode(e,t)})}catch(e){console.error("Failed to enter Android immersive mode: ",e)}this._useWorker?await this._InitWorker(e,t.port2):await this._InitDOM(e,t.port2)}_GetCommonRuntimeOptions(e){return{runtimeBaseUrl:this._runtimeBaseUrl,previewUrl:location.href,windowInnerWidth:this._GetWindowInnerWidth(),windowInnerHeight:this._GetWindowInnerHeight(),cssDisplayMode:this.GetCssDisplayMode(),devicePixelRatio:window.devicePixelRatio,isFullscreen:P0.IsDocumentFullscreen(),swClientId:window.cr_swClientId||"",exportType:e.exportType,isNWjs:"undefined"!=typeof nw,fileMap:globalThis.c3_swFileMap??new Map(Object.entries(this._localFileBlobs??{})),scriptFolder:this._scriptFolder,isDebug:new URLSearchParams(self.location.search).has("debug"),ife:!!self.ife,jobScheduler:this._jobScheduler.GetPortData(),supportedAudioFormats:g0,isFileProtocol:this._isFileProtocol,isiOSCordova:this.IsiOSCordova(),isiOSWebView:this.IsiOSWebView(),isWindowsWebView2:this.IsWindowsWebView2(),isAnyWebView2Wrapper:this.IsAnyWebView2Wrapper(),wrapperComponentIds:this._wrapperComponentIds,isFBInstantAvailable:void 0!==self.FBInstant}}async _InitWorker(e,t){const n=e.workerMainUrl,i=("preview"===this._exportType?(this._worker=new Worker("previewworker.js",{type:"module",name:"Runtime"}),await new Promise((t,i)=>{const s=e=>{this._worker.removeEventListener("message",s),(e.data&&"ok"===e.data.type?t:i)()};this._worker.addEventListener("message",s),this._worker.postMessage({type:"construct-worker-init",import:new URL(n,this._runtimeBaseUrl).toString()})})):this._worker=await this.CreateWorker(n,{type:"module",name:"Runtime"}),document.createElement("canvas")),s=(i.style.display="none",i.transferControlToOffscreen()),o=(document.body.appendChild(i),document.createElement("div"));o.className="c3htmlwrap",o.setAttribute("interactive",""),document.body.appendChild(o),this._canvasLayers.push({canvas:i,htmlWrap:o,lastHtmlLayerDomState:{isVisible:!0,opacity:1,isInteractive:!0}}),window.c3canvas=i,self.C3_InsertHTMLPlaceholders&&self.C3_InsertHTMLPlaceholders(),this._worker.postMessage(Object.assign(this._GetCommonRuntimeOptions(e),{type:"init-runtime",isInWorker:!0,messagePort:t,canvas:s,runtimeScriptList:e.runtimeScriptList,projectMainScriptPath:e.projectMainScriptPath,scriptsInEventsPath:e.scriptsInEventsPath}),[t,s,...this._jobScheduler.GetPortTransferables()]),this._domHandlers=k0.map(e=>new e(this)),this._FindRuntimeDOMHandler(),this._runtimeDomHandler._AddDefaultCanvasEventHandlers(i),this._runtimeDomHandler._AddDefaultHTMLWrapEventHandlers(o),this._runtimeDomHandler._EnableWindowResizeEvent(),self.c3_callFunction=(e,t)=>this._runtimeDomHandler._InvokeFunctionFromJS(e,t),"preview"===this._exportType&&(self.goToLastErrorScript=()=>this.PostToRuntimeComponent("runtime","go-to-last-error-script"))}async _InitDOM(e,t){const i=document.createElement("canvas"),s=(i.style.display="none",document.body.appendChild(i),document.createElement("div")),n=(s.className="c3htmlwrap",s.setAttribute("interactive",""),document.body.appendChild(s),this._canvasLayers.push({canvas:i,htmlWrap:s,lastHtmlLayerDomState:{isVisible:!0,opacity:1,isInteractive:!0}}),window.c3canvas=i,self.C3_InsertHTMLPlaceholders&&self.C3_InsertHTMLPlaceholders(),this._domHandlers=k0.map(e=>new e(this)),this._FindRuntimeDOMHandler(),this._runtimeDomHandler._AddDefaultCanvasEventHandlers(i),this._runtimeDomHandler._AddDefaultHTMLWrapEventHandlers(s),await Promise.all(e.runtimeScriptList.map(e=>this._MaybeGetPlatformSpecificScriptURL(e)))),o=(await Promise.all(n.map(e=>AddScript(e))),e.projectMainScriptPath),a=e.scriptsInEventsPath;if(o)try{if(await AddScript(o),"preview"===this._exportType&&!globalThis.C3_ProjectMainScriptOK)throw new Error("main script did not run to completion")}catch(e){this._RemoveLoadingMessage(),console.error("Error loading project main script: ",e),alert(`Failed to load the project main script (${o}). Check all your JavaScript code has valid syntax, all imports are written correctly, and that an exception was not thrown running the script. Press F12 and check the console for error details.`)}if(a)try{if(await AddScript(a),"preview"===this._exportType&&!globalThis.C3.ScriptsInEvents)throw new Error("scripts in events did not run to completion")}catch(e){this._RemoveLoadingMessage(),console.error("Error loading scripts in events: ",e),alert("Failed to load scripts in events. Check all your JavaScript code has valid syntax, all imports are written correctly, and that an exception was not thrown running the 'Imports for events' script. Press F12 and check the console for error details.")}const r=Object.assign(this._GetCommonRuntimeOptions(e),{isInWorker:!1,messagePort:t,canvas:i,runOnStartupFunctions:o0});this._runtimeDomHandler._EnableWindowResizeEvent(),this._OnBeforeCreateRuntime(),this._localRuntime=self.C3_CreateRuntime(r),await self.C3_InitRuntime(this._localRuntime,r)}async CreateWorker(e,t){if(e.startsWith("blob:"))return new Worker(e,t);if("cordova"===this._exportType&&this._isFileProtocol){const n=await this.CordovaFetchLocalFileAsArrayBuffer(e),o=new Blob([n],{type:"application/javascript"});return new Worker(URL.createObjectURL(o),t)}if("playable-ad-single-file"===this._exportType){const a=this._localFileBlobs[e];if(a)return new Worker(URL.createObjectURL(a),t);throw new Error("missing script: "+e)}const i=new URL(e,location.href),s=location.origin!==i.origin;if(s){const r=await fetch(i);if(!r.ok)throw new Error("failed to fetch worker script");const d=await r.blob();return new Worker(URL.createObjectURL(d),t)}return new Worker(i,t)}_GetWindowInnerWidth(){return Math.max(window.innerWidth,1)}_GetWindowInnerHeight(){return Math.max(window.innerHeight,1)}GetCssDisplayMode(){if(this.IsAnyWebView2Wrapper())return"standalone";const e=this.GetExportType(),t=new Set(["cordova","nwjs","macos-wkwebview","linux-cef"]);return t.has(e)?"standalone":window.matchMedia("(display-mode: fullscreen)").matches?"fullscreen":window.matchMedia("(display-mode: standalone)").matches?"standalone":window.matchMedia("(display-mode: minimal-ui)").matches?"minimal-ui":navigator.standalone?"standalone":"browser"}_OnBeforeCreateRuntime(){this._RemoveLoadingMessage()}_RemoveLoadingMessage(){const e=window.cr_previewLoadingElem;e&&(e.parentElement.removeChild(e),window.cr_previewLoadingElem=null)}async _OnCreateJobWorker(e){const t=await this._jobScheduler._CreateJobWorker();return{outputPort:t,transferables:[t]}}_OnUpdateCanvasSize(e){if(!this.IsExportingToVideo()){const t=e.styleWidth+"px",i=e.styleHeight+"px",s=e.marginLeft+"px",n=e.marginTop+"px";for(const{canvas:o,htmlWrap:a}of this._canvasLayers)o.style.width=t,o.style.height=i,o.style.marginLeft=s,o.style.marginTop=n,a.style.width=t,a.style.height=i,a.style.marginLeft=s,a.style.marginTop=n,this._isFirstSizeUpdate&&(o.style.display="",a.style.display="");document.documentElement.style.setProperty("--construct-scale",e.displayScale),this._isFirstSizeUpdate=!1}}["_OnSetHTMLLayerCount"](e){const i=e.count,t=e.layersDomState,s=e.immediate,n=e.styleWidth+"px",o=e.styleHeight+"px",a=e.marginLeft+"px",r=e.marginTop+"px",d=[],l=[];if(i<this._canvasLayers.length)for(;this._canvasLayers.length>i;){const{canvas:h,htmlWrap:c}=this._canvasLayers.pop();c.remove(),this._useWorker&&!s?this._pendingRemoveElements.push(h):h.remove()}else if(i>this._canvasLayers.length)for(let e=0,t=i-this._canvasLayers.length;e<t;++e){const u=document.createElement("canvas");if(u.classList.add("c3overlay"),this._useWorker){const m=u.transferControlToOffscreen();d.push(m),l.push(m)}else d.push(u);document.body.appendChild(u);const _=document.createElement("div");_.classList.add("c3htmlwrap","c3overlay"),_.setAttribute("interactive",""),document.body.appendChild(_),u.style.width=n,u.style.height=o,u.style.marginLeft=a,u.style.marginTop=r,_.style.width=n,_.style.height=o,_.style.marginLeft=a,_.style.marginTop=r,this._runtimeDomHandler._AddDefaultCanvasEventHandlers(u),this._runtimeDomHandler._AddDefaultHTMLWrapEventHandlers(_),this._canvasLayers.push({canvas:u,htmlWrap:_,lastHtmlLayerDomState:{isVisible:!0,opacity:1,isInteractive:!0}})}this._UpdateHTMLLayerDOMProperties(t);for(const p of this._domHandlers)p instanceof window.DOMElementHandler&&p._OnHTMLLayersChanged();return this._UpdateHTMLElementsZOrder(),{addedCanvases:d,transferables:l}}_UpdateHTMLLayerDOMProperties(i){for(let e=0,t=Math.min(this._canvasLayers.length,i.length);e<t;++e){const{htmlWrap:s,lastHtmlLayerDomState:n}=this._canvasLayers[e],o=i[e],a=o.isVisible,r=o.opacity,d=o.isInteractive;a!==n.isVisible&&(s.style.display=a?"":"none",n.isVisible=a),r!==n.opacity&&(s.style.opacity=1===r?"":String(r),n.opacity=r),d!==n.isInteractive&&(s.style.pointerEvents=d?"":"none",d?s.setAttribute("interactive",""):s.removeAttribute("interactive"),n.isInteractive=d)}}_OnCleanUpHTMLLayers(){for(const e of this._pendingRemoveElements)e.remove();this._pendingRemoveElements.length=0}_UpdateHTMLElementsZOrder(){this._pendingUpdateHTMLZOrder||(this._pendingUpdateHTMLZOrder=!0,this._AddRAFCallback(this._updateHTMLZOrderRAFCallback))}_DoUpdateHTMLElementsZOrder(){this._RemoveRAFCallback(this._updateHTMLZOrderRAFCallback),this._pendingUpdateHTMLZOrder=!1;let e=[];for(const o of this._domHandlers)if(o instanceof window.DOMElementHandler){const a=o._GetAllElementStatesForZOrderUpdate();a&&e.push(...a)}e.sort((e,t)=>{const i=e.GetActualHTMLIndex(),s=t.GetActualHTMLIndex();if(i!==s)return i-s;const n=e.GetHTMLZIndex(),o=t.GetHTMLZIndex();return n-o});let t=0,i=0,s=0,n=e.length;for(;s<n;++s){const r=e[s];r.GetActualHTMLIndex()!==t&&(this._DoUpdateHTMLElementsZOrderOnHTMLLayer(t,e.slice(i,s)),t=r.GetActualHTMLIndex(),i=s)}i<s&&this._DoUpdateHTMLElementsZOrderOnHTMLLayer(t,e.slice(i,s))}_DoUpdateHTMLElementsZOrderOnHTMLLayer(e,t){if(!(t.length<=1||e>=this._canvasLayers.length)){const s=t.map(e=>e.GetElement()),i=new Set(s),n=this.GetHTMLWrapElement(e),o=Array.from(n.children).filter(e=>i.has(e));for(let e=0,t=0,i=s.length;e<i;++e){const a=s[e],r=o[t];a===r?++t:n.insertBefore(a,r)}}}_GetLocalRuntime(){if(this._useWorker)throw new Error("not available in worker mode");return this._localRuntime}PostToRuntimeComponent(e,t,i,s,n){this._messageChannelPort.postMessage({type:"event",component:e,handler:t,dispatchOpts:s||null,data:i,responseId:null},n)}PostToRuntimeComponentAsync(e,t,i,s,n){const o=r++,a=new Promise((e,t)=>{m0.set(o,{resolve:e,reject:t})});return this._messageChannelPort.postMessage({type:"event",component:e,handler:t,dispatchOpts:s||null,data:i,responseId:o},n),a}["_OnMessageFromRuntime"](e){const t=e.type;if("event"===t)return this._OnEventFromRuntime(e);if("result"===t)this._OnResultFromRuntime(e);else if("runtime-ready"===t)this._OnRuntimeReady();else if("alert-error"===t)this._RemoveLoadingMessage(),alert(e.message);else{if("creating-runtime"!==t)throw new Error(`unknown message '${t}'`);this._OnBeforeCreateRuntime()}}_OnEventFromRuntime(t){const i=t.component,s=t.handler,n=t.data,o=t.responseId,e=l0.get(i);if(e){const a=e.get(s);if(a){let e=null;try{e=a(n)}catch(t){return console.error(`Exception in '${i}' handler '${s}':`,t),void(null!==o&&this._PostResultToRuntime(o,!1,""+t))}if(null===o)return e;e&&e.then?e.then(e=>this._PostResultToRuntime(o,!0,e)).catch(e=>{console.error(`Rejection from '${i}' handler '${s}':`,e),this._PostResultToRuntime(o,!1,""+e)}):this._PostResultToRuntime(o,!0,e)}else console.warn(`[DOM] No handler '${s}' for component '${i}'`)}else console.warn(`[DOM] No event handlers for component '${i}'`)}_PostResultToRuntime(e,t,i){let s;i&&i.transferables&&(s=i.transferables),this._messageChannelPort.postMessage({type:"result",responseId:e,isOk:t,result:i},s)}_OnResultFromRuntime(e){const t=e.responseId,i=e.isOk,s=e.result,n=m0.get(t);i?n.resolve(s):n.reject(s),m0.delete(t)}AddRuntimeComponentMessageHandler(e,t,i){let s=l0.get(e);if(s||(s=new Map,l0.set(e,s)),s.has(t))throw new Error(`[DOM] Component '${e}' already has handler '${t}'`);s.set(t,i)}static AddDOMHandlerClass(e){if(k0.includes(e))throw new Error("DOM handler already added");k0.push(e)}_FindRuntimeDOMHandler(){for(const e of this._domHandlers)if("runtime"===e.GetComponentID())return void(this._runtimeDomHandler=e);throw new Error("cannot find runtime DOM handler")}_OnMessageFromDebugger(e){this.PostToRuntimeComponent("debugger","message",e)}_OnRuntimeReady(){for(const e of this._domHandlers)e.Attach()}static IsDocumentFullscreen(){return!!(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||t)}static _SetWrapperIsFullscreenFlag(e){t=!!e}async GetRemotePreviewStatusInfo(){return this.PostToRuntimeComponentAsync("runtime","get-remote-preview-status-info")}_AddRAFCallback(e){this._rafCallbacks.add(e),this._RequestAnimationFrame()}_RemoveRAFCallback(e){this._rafCallbacks.delete(e),0===this._rafCallbacks.size&&this._CancelAnimationFrame()}_RequestAnimationFrame(){-1===this._rafId&&0<this._rafCallbacks.size&&(this._rafId=requestAnimationFrame(this._rafFunc))}_CancelAnimationFrame(){-1!==this._rafId&&(cancelAnimationFrame(this._rafId),this._rafId=-1)}_OnRAFCallback(){this._rafId=-1;for(const e of this._rafCallbacks)e();this._RequestAnimationFrame()}TryPlayMedia(e){this._runtimeDomHandler.TryPlayMedia(e)}RemovePendingPlay(e){this._runtimeDomHandler.RemovePendingPlay(e)}_PlayPendingMedia(){this._runtimeDomHandler._PlayPendingMedia()}SetSilent(e){this._runtimeDomHandler.SetSilent(e)}IsAudioFormatSupported(e){return!!g0[e]}SetIsExportingToVideo(e){this._isExportingToVideo=!0,this._exportToVideoDuration=e}IsExportingToVideo(){return this._isExportingToVideo}GetExportToVideoDuration(){return this._exportToVideoDuration}IsAbsoluteURL(e){return/^(?:[a-z\-]+:)?\/\//.test(e)||"data:"===e.substr(0,5)||"blob:"===e.substr(0,5)}IsRelativeURL(e){return!this.IsAbsoluteURL(e)}async _MaybeGetPlatformSpecificScriptURL(t){if("cordova"===this._exportType&&(t.startsWith("file:")||this._isFileProtocol&&this.IsRelativeURL(t))){let e=t;e.startsWith(this._runtimeBaseUrl)&&(e=e.substr(this._runtimeBaseUrl.length));const i=await this.CordovaFetchLocalFileAsArrayBuffer(e),s=new Blob([i],{type:"application/javascript"});return URL.createObjectURL(s)}if("playable-ad-single-file"!==this._exportType)return t;if(this._localFileStrings.hasOwnProperty(t))return{isStringSrc:!0,str:this._localFileStrings[t]};if(this._localFileBlobs.hasOwnProperty(t))return URL.createObjectURL(this._localFileBlobs[t]);throw new Error("missing script: "+t)}async _OnCordovaFetchLocalFile(e){const t=e.filename;switch(e.as){case"text":return this.CordovaFetchLocalFileAsText(t);case"buffer":return this.CordovaFetchLocalFileAsArrayBuffer(t);default:throw new Error("unsupported type")}}CordovaFetchLocalFile(e){const s=window.cordova.file.applicationDirectory+"www/"+e;return new Promise((t,i)=>{window.resolveLocalFileSystemURL(s,e=>{e.file(t,i)},i)})}async CordovaFetchLocalFileAsText(e){const t=await this.CordovaFetchLocalFile(e);return BlobToString(t)}_CordovaMaybeStartNextArrayBufferRead(){if(h0.length&&!(s>=j0)){s++;const e=h0.shift();this._CordovaDoFetchLocalFileAsAsArrayBuffer(e.filename,e.successCallback,e.errorCallback)}}CordovaFetchLocalFileAsArrayBuffer(e){return new Promise((t,i)=>{h0.push({filename:e,successCallback:e=>{s--,this._CordovaMaybeStartNextArrayBufferRead(),t(e)},errorCallback:e=>{s--,this._CordovaMaybeStartNextArrayBufferRead(),i(e)}}),this._CordovaMaybeStartNextArrayBufferRead()})}async _CordovaDoFetchLocalFileAsAsArrayBuffer(e,t,i){try{const s=await this.CordovaFetchLocalFile(e),n=await BlobToArrayBuffer(s);t(n)}catch(e){i(e)}}["_PlayableAdFetchBlob"](e){if(this._localFileBlobs.hasOwnProperty(e))return this._localFileBlobs[e];throw new Error("missing file: "+e)}_GetPermissionAPI(){const e=window.cordova&&window.cordova.plugins&&window.cordova.plugins.permissions;if("object"!=typeof e)throw new Error("Permission API is not loaded");return e}_MapPermissionID(e,t){const i=e[t];if("string"!=typeof i)throw new Error("Invalid permission name");return i}_HasPermission(i){const s=this._GetPermissionAPI();return new Promise((t,e)=>s.checkPermission(this._MapPermissionID(s,i),e=>t(!!e.hasPermission),e))}_RequestPermission(i){const s=this._GetPermissionAPI();return new Promise((t,e)=>s.requestPermission(this._MapPermissionID(s,i),e=>t(!!e.hasPermission),e))}async RequestPermissions(e){if("cordova"===this.GetExportType()&&!this.IsiOSCordova())for(const t of e){const i=await this._HasPermission(t);if(!i){const s=await this._RequestPermission(t);if(!1===s)return!1}}return!0}async RequirePermissions(...e){if(!1===await this.RequestPermissions(e))throw new Error("Permission not granted")}_OnWrapperMessage(e,t){if("object"==typeof e&&e){const i=e.type;if("directory-handles"===i)this._directoryHandles=t;else if("wrapper-init-response"===i)this._wrapperInitResolve(e),this._wrapperInitResolve=null;else if("fullscreen-change"===i)P0._SetWrapperIsFullscreenFlag(e.isFullscreen),this._runtimeDomHandler._OnFullscreenChange();else if("log-to-console"===i)switch(e.logType){case"error":console.error(e.message);break;case"warning":console.warn(e.message);break;default:console.log(e.message)}else"extension-message"===i?this.PostToRuntimeComponent("runtime","wrapper-extension-message",e):console.warn("Unknown wrapper message: ",e)}else console.warn("Unknown wrapper message: ",e)}_OnSendWrapperExtensionMessage(e){this._SendWrapperMessage({type:"extension-message",componentId:e.componentId,messageId:e.messageId,params:e.params||[],asyncId:e.asyncId})}_SendWrapperMessage(e){this.IsAnyWebView2Wrapper()?window.chrome.webview.postMessage(JSON.stringify(e)):"macos-wkwebview"===this._exportType?window.webkit.messageHandlers.C3Wrapper.postMessage(JSON.stringify(e)):"linux-cef"===this._exportType&&window.c3_linux_cef_sendmessage(JSON.stringify(e))}_SetupDesktopWrapperPolyfills(){window.moveTo=(e,t)=>{this._SendWrapperMessage({type:"set-window-position",windowX:Math.ceil(e),windowY:Math.ceil(t)})},window.resizeTo=(e,t)=>{this._SendWrapperMessage({type:"set-window-size",windowWidth:Math.ceil(e),windowHeight:Math.ceil(t)})}}_InitWrapper(){return new Promise(e=>{this._wrapperInitResolve=e,this._SendWrapperMessage({type:"wrapper-init"})})}_GetDirectoryHandles(){return this._directoryHandles}async _ConvertDataUrisToBlobs(){const e=[];for(const[t,i]of Object.entries(this._localFileBlobs))e.push(this._ConvertDataUriToBlobs(t,i));await Promise.all(e)}async _ConvertDataUriToBlobs(t,i){if("object"==typeof i)this._localFileBlobs[t]=new Blob([i.str],{type:i.type}),this._localFileStrings[t]=i.str;else{let e=await this._FetchDataUri(i);e=e||this._DataURIToBinaryBlobSync(i),this._localFileBlobs[t]=e}}async _FetchDataUri(e){try{const t=await fetch(e);return await t.blob()}catch(e){return console.warn("Failed to fetch a data: URI. Falling back to a slower workaround. This is probably because the Content Security Policy unnecessarily blocked it. Allow data: URIs in your CSP to avoid this.",e),null}}_DataURIToBinaryBlobSync(e){const t=this._ParseDataURI(e);return this._BinaryStringToBlob(t.data,t.mime_type)}_ParseDataURI(e){const t=e.indexOf(",");if(t<0)throw new URIError("expected comma in data: uri");const i=e.substring(5,t),s=e.substring(t+1),n=i.split(";"),o=n[0]||"",a=n[1],r=n[2];return{mime_type:o,data:("base64"===a||"base64"===r?atob:decodeURIComponent)(s)}}_BinaryStringToBlob(e,t){let i=e.length,s=i>>2,n=new Uint8Array(i),o=new Uint32Array(n.buffer,0,s),a,r;for(a=0,r=0;a<s;++a)o[a]=e.charCodeAt(r++)|e.charCodeAt(r++)<<8|e.charCodeAt(r++)<<16|e.charCodeAt(r++)<<24;let d=3&i;for(;d--;)n[r]=e.charCodeAt(r),++r;return new Blob([n],{type:t})}}}{const Md=self.RuntimeInterface;function IsCompatibilityMouseEvent(e){return e.sourceCapabilities&&e.sourceCapabilities.firesTouchEvents||e.originalEvent&&e.originalEvent.sourceCapabilities&&e.originalEvent.sourceCapabilities.firesTouchEvents}const Nd=new Map([["OSLeft","MetaLeft"],["OSRight","MetaRight"]]),Od={dispatchRuntimeEvent:!0,dispatchUserScriptEvent:!0},Pd={dispatchUserScriptEvent:!0},Qd={dispatchRuntimeEvent:!0};function AddStyleSheet(s){return new Promise((e,t)=>{const i=document.createElement("link");i.onload=()=>e(i),i.onerror=e=>t(e),i.rel="stylesheet",i.href=s,document.head.appendChild(i)})}function FetchImage(s){return new Promise((e,t)=>{const i=new Image;i.onload=()=>e(i),i.onerror=e=>t(e),i.src=s})}async function BlobToImage(e){const t=URL.createObjectURL(e);try{return await FetchImage(t)}finally{URL.revokeObjectURL(t)}}function BlobToString(s){return new Promise((t,i)=>{let e=new FileReader;e.onload=e=>t(e.target.result),e.onerror=e=>i(e),e.readAsText(s)})}function IsInContentEditable(e){do{if(e.parentNode&&e.hasAttribute("contenteditable"))return!0}while(e=e.parentNode);return!1}const Rd=new Set(["input","textarea","datalist","select"]);function IsKeyboardInputElement(e){return Rd.has(e.tagName.toLowerCase())||IsInContentEditable(e)}const Sd=new Set(["canvas","body","html"]);function PreventDefaultOnCanvasOrDoc(e){if(e.target.tagName){const t=e.target.tagName.toLowerCase();Sd.has(t)&&e.preventDefault()}}function PreventDefaultOnHTMLWrap(e){e.target.tagName&&e.target.classList.contains("c3htmlwrap")&&e.preventDefault()}function BlockWheelZoom(e){(e.metaKey||e.ctrlKey)&&e.preventDefault()}self.C3_GetSvgImageSize=async function(e){const t=await BlobToImage(e);if(0<t.width&&0<t.height)return[t.width,t.height];{t.style.position="absolute",t.style.left="0px",t.style.top="0px",t.style.visibility="hidden",document.body.appendChild(t);const i=t.getBoundingClientRect();return document.body.removeChild(t),[i.width,i.height]}};let e=!(self.C3_RasterSvgImageBlob=async function(e,t,i,s,n){const o=await BlobToImage(e),a=document.createElement("canvas"),r=(a.width=s,a.height=n,a.getContext("2d"));return r.drawImage(o,0,0,t,i),a});function ParentHasFocus(){try{return window.parent&&window.parent.document.hasFocus()}catch(e){return!1}}document.addEventListener("pause",()=>e=!0),document.addEventListener("resume",()=>e=!1);const Ud="runtime",Vd=class extends self.DOMHandler{constructor(e){super(e,Ud),this._enableWindowResizeEvent=!1,this._simulatedResizeTimerId=-1,this._targetOrientation="any",this._attachedDeviceOrientationEvent=!1,this._attachedDeviceMotionEvent=!1,this._pageVisibilityIsHidden=!1,this._screenReaderTextWrap=document.createElement("div"),this._screenReaderTextWrap.className="c3-screen-reader-text",this._screenReaderTextWrap.setAttribute("aria-live","polite"),document.body.appendChild(this._screenReaderTextWrap),this._debugHighlightElem=null,this._isExportToVideo=!1,this._exportVideoProgressMessage="",this._exportVideoUpdateTimerId=-1,this._enableAndroidVKDetection=!1,this._lastWindowWidth=e._GetWindowInnerWidth(),this._lastWindowHeight=e._GetWindowInnerHeight(),this._virtualKeyboardHeight=0,this._vkTranslateYOffset=0,e.AddRuntimeComponentMessageHandler("runtime","invoke-download",e=>this._OnInvokeDownload(e)),e.AddRuntimeComponentMessageHandler("runtime","load-webfonts",e=>this._OnLoadWebFonts(e)),e.AddRuntimeComponentMessageHandler("runtime","raster-svg-image",e=>this._OnRasterSvgImage(e)),e.AddRuntimeComponentMessageHandler("runtime","get-svg-image-size",e=>this._OnGetSvgImageSize(e)),e.AddRuntimeComponentMessageHandler("runtime","set-target-orientation",e=>this._OnSetTargetOrientation(e)),e.AddRuntimeComponentMessageHandler("runtime","register-sw",()=>this._OnRegisterSW()),e.AddRuntimeComponentMessageHandler("runtime","post-to-debugger",e=>this._OnPostToDebugger(e)),e.AddRuntimeComponentMessageHandler("runtime","go-to-script",e=>this._OnPostToDebugger(e)),e.AddRuntimeComponentMessageHandler("runtime","before-start-ticking",()=>this._OnBeforeStartTicking()),e.AddRuntimeComponentMessageHandler("runtime","debug-highlight",e=>this._OnDebugHighlight(e)),e.AddRuntimeComponentMessageHandler("runtime","enable-device-orientation",()=>this._AttachDeviceOrientationEvent()),e.AddRuntimeComponentMessageHandler("runtime","enable-device-motion",()=>this._AttachDeviceMotionEvent()),e.AddRuntimeComponentMessageHandler("runtime","add-stylesheet",e=>this._OnAddStylesheet(e)),e.AddRuntimeComponentMessageHandler("runtime","script-create-worker",e=>this._OnScriptCreateWorker(e)),e.AddRuntimeComponentMessageHandler("runtime","alert",e=>this._OnAlert(e)),e.AddRuntimeComponentMessageHandler("runtime","screen-reader-text",e=>this._OnScreenReaderTextEvent(e)),e.AddRuntimeComponentMessageHandler("runtime","hide-cordova-splash",()=>this._OnHideCordovaSplash()),e.AddRuntimeComponentMessageHandler("runtime","set-exporting-to-video",e=>this._SetExportingToVideo(e)),e.AddRuntimeComponentMessageHandler("runtime","export-to-video-progress",e=>this._OnExportVideoProgress(e)),e.AddRuntimeComponentMessageHandler("runtime","exported-to-video",e=>this._OnExportedToVideo(e)),e.AddRuntimeComponentMessageHandler("runtime","exported-to-image-sequence",e=>this._OnExportedToImageSequence(e));const s=new Set(["input","textarea","datalist"]);if(window.addEventListener("contextmenu",e=>{const t=e.target,i=t.tagName.toLowerCase();s.has(i)||IsInContentEditable(t)||e.preventDefault()}),window.addEventListener("selectstart",PreventDefaultOnCanvasOrDoc),window.addEventListener("gesturehold",PreventDefaultOnCanvasOrDoc),window.addEventListener("touchstart",PreventDefaultOnCanvasOrDoc,{passive:!1}),window.addEventListener("pointerdown",PreventDefaultOnCanvasOrDoc,{passive:!1}),this._mousePointerLastButtons=0,window.addEventListener("mousedown",e=>{1===e.button&&e.preventDefault()}),window.addEventListener("mousewheel",BlockWheelZoom,{passive:!1}),window.addEventListener("wheel",BlockWheelZoom,{passive:!1}),window.addEventListener("resize",()=>this._OnWindowResize()),window.addEventListener("fullscreenchange",()=>this._OnFullscreenChange()),window.addEventListener("webkitfullscreenchange",()=>this._OnFullscreenChange()),window.addEventListener("mozfullscreenchange",()=>this._OnFullscreenChange()),window.addEventListener("fullscreenerror",e=>this._OnFullscreenError(e)),window.addEventListener("webkitfullscreenerror",e=>this._OnFullscreenError(e)),window.addEventListener("mozfullscreenerror",e=>this._OnFullscreenError(e)),e.IsiOSWebView()){let t=1/0;window.visualViewport.addEventListener("resize",()=>{const e=window.visualViewport.height;e>t&&(document.scrollingElement.scrollTop=0,document.scrollingElement.scrollLeft=0),t=e}),document.documentElement.setAttribute("ioswebview","")}this._mediaPendingPlay=new Set,this._mediaRemovedPendingPlay=new WeakSet,this._isSilent=!1}_AddDefaultCanvasEventHandlers(e){e.addEventListener("selectstart",PreventDefaultOnCanvasOrDoc),e.addEventListener("gesturehold",PreventDefaultOnCanvasOrDoc),e.addEventListener("pointerdown",PreventDefaultOnCanvasOrDoc)}_AddDefaultHTMLWrapEventHandlers(e){e.addEventListener("selectstart",PreventDefaultOnHTMLWrap),e.addEventListener("gesturehold",PreventDefaultOnHTMLWrap),e.addEventListener("touchstart",PreventDefaultOnHTMLWrap)}_OnBeforeStartTicking(){return self.setTimeout(()=>{this._enableAndroidVKDetection=!0},1e3),"cordova"===this._iRuntime.GetExportType()?(document.addEventListener("pause",()=>this._OnVisibilityChange(!0)),document.addEventListener("resume",()=>this._OnVisibilityChange(!1))):document.addEventListener("visibilitychange",()=>this._OnVisibilityChange("hidden"===document.visibilityState)),this._pageVisibilityIsHidden=!("hidden"!==document.visibilityState&&!e),{isSuspended:this._pageVisibilityIsHidden}}Attach(){window.addEventListener("focus",()=>this._PostRuntimeEvent("window-focus")),window.addEventListener("blur",()=>{this._PostRuntimeEvent("window-blur",{parentHasFocus:ParentHasFocus()}),this._mousePointerLastButtons=0}),window.addEventListener("focusin",e=>{IsKeyboardInputElement(e.target)&&this._PostRuntimeEvent("keyboard-blur")}),window.addEventListener("keydown",e=>this._OnKeyEvent("keydown",e)),window.addEventListener("keyup",e=>this._OnKeyEvent("keyup",e)),window.addEventListener("mousedown",e=>this._OnMouseEvent("mousedown",e,Pd)),window.addEventListener("mousemove",e=>this._OnMouseEvent("mousemove",e,Pd)),window.addEventListener("mouseup",e=>this._OnMouseEvent("mouseup",e,Pd)),window.addEventListener("dblclick",e=>this._OnMouseEvent("dblclick",e,Od)),window.addEventListener("wheel",e=>this._OnMouseWheelEvent("wheel",e,Od)),window.addEventListener("pointerdown",e=>{this._HandlePointerDownFocus(e),this._OnPointerEvent("pointerdown",e)}),this._iRuntime.UsesWorker()&&void 0!==window.onpointerrawupdate&&self===self.top?window.addEventListener("pointerrawupdate",e=>this._OnPointerRawUpdate(e)):window.addEventListener("pointermove",e=>this._OnPointerEvent("pointermove",e)),window.addEventListener("pointerup",e=>this._OnPointerEvent("pointerup",e)),window.addEventListener("pointercancel",e=>this._OnPointerEvent("pointercancel",e));const e=()=>this._PlayPendingMedia();window.addEventListener("pointerup",e,!0),window.addEventListener("touchend",e,!0),window.addEventListener("click",e,!0),window.addEventListener("keydown",e,!0),window.addEventListener("gamepadconnected",e,!0),this._iRuntime.IsAndroid()&&!this._iRuntime.IsAndroidWebView()&&navigator.virtualKeyboard&&(navigator.virtualKeyboard.overlaysContent=!0,navigator.virtualKeyboard.addEventListener("geometrychange",()=>{this._OnAndroidVirtualKeyboardChange(this._GetWindowInnerHeight(),navigator.virtualKeyboard.boundingRect.height)})),this._iRuntime.IsiOSWebView()&&(document.scrollingElement.scrollTop=0,document.scrollingElement.scrollLeft=0)}_OnAndroidVirtualKeyboardChange(t,i){if(document.body.style.position="",document.body.style.overflow="",document.body.style.transform="",(this._vkTranslateYOffset=0)<i){const s=document.activeElement;if(s){const n=s.getBoundingClientRect(),o=(n.top+n.bottom)/2,a=(t-i)/2;let e=o-a;0<(e=(e=i<e?i:e)<0?0:e)&&(document.body.style.position="absolute",document.body.style.overflow="visible",document.body.style.transform=`translateY(${-e}px)`,this._vkTranslateYOffset=e)}}}_PostRuntimeEvent(e,t){this.PostToRuntime(e,t||null,Qd)}_GetWindowInnerWidth(){return this._iRuntime._GetWindowInnerWidth()}_GetWindowInnerHeight(){return this._iRuntime._GetWindowInnerHeight()}_EnableWindowResizeEvent(){this._enableWindowResizeEvent=!0,this._lastWindowWidth=this._iRuntime._GetWindowInnerWidth(),this._lastWindowHeight=this._iRuntime._GetWindowInnerHeight()}_OnWindowResize(){if(!this._isExportToVideo&&this._enableWindowResizeEvent){const e=this._GetWindowInnerWidth(),t=this._GetWindowInnerHeight();if(this._iRuntime.IsAndroidWebView()){if(this._enableAndroidVKDetection){const i=this._iRuntime.CanDoAndroidVirtualKeyboardDetection();if(i&&this._lastWindowWidth===e&&t<this._lastWindowHeight)return this._virtualKeyboardHeight=this._lastWindowHeight-t,void this._OnAndroidVirtualKeyboardChange(this._lastWindowHeight,this._virtualKeyboardHeight);0<this._virtualKeyboardHeight&&(this._virtualKeyboardHeight=0,this._OnAndroidVirtualKeyboardChange(t,this._virtualKeyboardHeight))}this._lastWindowWidth=e,this._lastWindowHeight=t}this.PostToRuntime("window-resize",{innerWidth:e,innerHeight:t,devicePixelRatio:window.devicePixelRatio,isFullscreen:Md.IsDocumentFullscreen(),cssDisplayMode:this._iRuntime.GetCssDisplayMode()}),this._iRuntime.IsiOSWebView()&&(-1!==this._simulatedResizeTimerId&&clearTimeout(this._simulatedResizeTimerId),this._OnSimulatedResize(e,t,0))}}_ScheduleSimulatedResize(e,t,i){-1!==this._simulatedResizeTimerId&&clearTimeout(this._simulatedResizeTimerId),this._simulatedResizeTimerId=setTimeout(()=>this._OnSimulatedResize(e,t,i),48)}_OnSimulatedResize(e,t,i){const s=this._GetWindowInnerWidth(),n=this._GetWindowInnerHeight();this._simulatedResizeTimerId=-1,s!=e||n!=t?this.PostToRuntime("window-resize",{innerWidth:s,innerHeight:n,devicePixelRatio:window.devicePixelRatio,isFullscreen:Md.IsDocumentFullscreen(),cssDisplayMode:this._iRuntime.GetCssDisplayMode()}):i<10&&this._ScheduleSimulatedResize(s,n,i+1)}_OnSetTargetOrientation(e){this._targetOrientation=e.targetOrientation}_TrySetTargetOrientation(){const t=this._targetOrientation;if(screen.orientation&&screen.orientation.lock)screen.orientation.lock(t).catch(e=>console.warn("[Construct] Failed to lock orientation: ",e));else try{let e=!1;screen.lockOrientation?e=screen.lockOrientation(t):screen.webkitLockOrientation?e=screen.webkitLockOrientation(t):screen.mozLockOrientation?e=screen.mozLockOrientation(t):screen.msLockOrientation&&(e=screen.msLockOrientation(t)),e||console.warn("[Construct] Failed to lock orientation")}catch(e){console.warn("[Construct] Failed to lock orientation: ",e)}}_OnFullscreenChange(){if(!this._isExportToVideo){const e=Md.IsDocumentFullscreen();e&&"any"!==this._targetOrientation&&this._TrySetTargetOrientation(),this.PostToRuntime("fullscreenchange",{isFullscreen:e,innerWidth:this._GetWindowInnerWidth(),innerHeight:this._GetWindowInnerHeight()})}}_OnFullscreenError(e){console.warn("[Construct] Fullscreen request failed: ",e),this.PostToRuntime("fullscreenerror",{isFullscreen:Md.IsDocumentFullscreen(),innerWidth:this._GetWindowInnerWidth(),innerHeight:this._GetWindowInnerHeight()})}_OnVisibilityChange(e){if(this._pageVisibilityIsHidden!==e&&((this._pageVisibilityIsHidden=e)?this._iRuntime._CancelAnimationFrame():this._iRuntime._RequestAnimationFrame(),this.PostToRuntime("visibilitychange",{hidden:e}),!e)&&this._iRuntime.IsiOSWebView()){const t=()=>{document.scrollingElement.scrollTop=0,document.scrollingElement.scrollLeft=0};setTimeout(t,50),setTimeout(t,100),setTimeout(t,250),setTimeout(t,500)}}_OnKeyEvent(e,t){if(void 0!==t.key&&("Backspace"===t.key&&PreventDefaultOnCanvasOrDoc(t),"nwjs"===this._iRuntime.GetExportType()&&"u"===t.key&&(t.ctrlKey||t.metaKey)&&t.preventDefault(),!this._isExportToVideo)){const i=Nd.get(t.code)||t.code;this._PostToRuntimeMaybeSync(e,{code:i,key:t.key,which:t.which,repeat:t.repeat,altKey:t.altKey,ctrlKey:t.ctrlKey,metaKey:t.metaKey,shiftKey:t.shiftKey,timeStamp:t.timeStamp},Od)}}_OnMouseWheelEvent(e,t,i){this._isExportToVideo||this.PostToRuntime(e,{clientX:t.clientX,clientY:t.clientY+this._vkTranslateYOffset,pageX:t.pageX,pageY:t.pageY+this._vkTranslateYOffset,deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode,timeStamp:t.timeStamp},i)}_OnMouseEvent(e,t,i){this._isExportToVideo||IsCompatibilityMouseEvent(t)||this._PostToRuntimeMaybeSync(e,{button:t.button,buttons:t.buttons,clientX:t.clientX,clientY:t.clientY+this._vkTranslateYOffset,pageX:t.pageX,pageY:t.pageY+this._vkTranslateYOffset,movementX:t.movementX||0,movementY:t.movementY||0,timeStamp:t.timeStamp},i)}_OnPointerEvent(t,i){if(!this._isExportToVideo){let e=0;"mouse"===i.pointerType&&(e=this._mousePointerLastButtons),this._PostToRuntimeMaybeSync(t,{pointerId:i.pointerId,pointerType:i.pointerType,button:i.button,buttons:i.buttons,lastButtons:e,clientX:i.clientX,clientY:i.clientY+this._vkTranslateYOffset,pageX:i.pageX,pageY:i.pageY+this._vkTranslateYOffset,movementX:i.movementX||0,movementY:i.movementY||0,width:i.width||0,height:i.height||0,pressure:i.pressure||0,tangentialPressure:i.tangentialPressure||0,tiltX:i.tiltX||0,tiltY:i.tiltY||0,twist:i.twist||0,timeStamp:i.timeStamp},Od),"mouse"===i.pointerType&&(this._mousePointerLastButtons=i.buttons)}}_OnPointerRawUpdate(e){this._OnPointerEvent("pointermove",e)}_OnTouchEvent(i,s){if(!this._isExportToVideo)for(let e=0,t=s.changedTouches.length;e<t;++e){const n=s.changedTouches[e];this._PostToRuntimeMaybeSync(i,{pointerId:n.identifier,pointerType:"touch",button:0,buttons:0,lastButtons:0,clientX:n.clientX,clientY:n.clientY+this._vkTranslateYOffset,pageX:n.pageX,pageY:n.pageY+this._vkTranslateYOffset,movementX:s.movementX||0,movementY:s.movementY||0,width:2*(n.radiusX||n.webkitRadiusX||0),height:2*(n.radiusY||n.webkitRadiusY||0),pressure:n.force||n.webkitForce||0,tangentialPressure:0,tiltX:0,tiltY:0,twist:n.rotationAngle||0,timeStamp:s.timeStamp},Od)}}_HandlePointerDownFocus(e){window!==window.top&&window.focus(),this._IsElementCanvasOrDocument(e.target)&&document.activeElement&&!this._IsElementCanvasOrDocument(document.activeElement)&&document.activeElement.blur()}_IsElementCanvasOrDocument(e){return!e||e===document||e===window||e===document.body||"canvas"===e.tagName.toLowerCase()}_AttachDeviceOrientationEvent(){this._attachedDeviceOrientationEvent||(this._attachedDeviceOrientationEvent=!0,window.addEventListener("deviceorientation",e=>this._OnDeviceOrientation(e)),window.addEventListener("deviceorientationabsolute",e=>this._OnDeviceOrientationAbsolute(e)))}_AttachDeviceMotionEvent(){this._attachedDeviceMotionEvent||(this._attachedDeviceMotionEvent=!0,window.addEventListener("devicemotion",e=>this._OnDeviceMotion(e)))}_OnDeviceOrientation(e){this._isExportToVideo||this.PostToRuntime("deviceorientation",{absolute:!!e.absolute,alpha:e.alpha||0,beta:e.beta||0,gamma:e.gamma||0,timeStamp:e.timeStamp,webkitCompassHeading:e.webkitCompassHeading,webkitCompassAccuracy:e.webkitCompassAccuracy},Od)}_OnDeviceOrientationAbsolute(e){this._isExportToVideo||this.PostToRuntime("deviceorientationabsolute",{absolute:!!e.absolute,alpha:e.alpha||0,beta:e.beta||0,gamma:e.gamma||0,timeStamp:e.timeStamp},Od)}_OnDeviceMotion(s){if(!this._isExportToVideo){let e=null;const n=s.acceleration;n&&(e={x:n.x||0,y:n.y||0,z:n.z||0});let t=null;const o=s.accelerationIncludingGravity;o&&(t={x:o.x||0,y:o.y||0,z:o.z||0});let i=null;const a=s.rotationRate;a&&(i={alpha:a.alpha||0,beta:a.beta||0,gamma:a.gamma||0}),this.PostToRuntime("devicemotion",{acceleration:e,accelerationIncludingGravity:t,rotationRate:i,interval:s.interval,timeStamp:s.timeStamp},Od)}}_OnInvokeDownload(e){const t=e.url,i=e.filename,s=document.createElement("a"),n=document.body;s.textContent=i,s.href=t,s.download=i,n.appendChild(s),s.click(),n.removeChild(s)}async _OnLoadWebFonts(e){const t=e.webfonts;await Promise.all(t.map(async e=>{const t=new FontFace(e.name,`url('${e.url}')`);document.fonts.add(t),await t.load()}))}async _OnRasterSvgImage(e){const t=e.blob,i=e.imageWidth,s=e.imageHeight,n=e.surfaceWidth,o=e.surfaceHeight,a=e.imageBitmapOpts,r=await self.C3_RasterSvgImageBlob(t,i,s,n,o);let d;return{imageBitmap:d=a?await createImageBitmap(r,a):await createImageBitmap(r),transferables:[d]}}async _OnGetSvgImageSize(e){return self.C3_GetSvgImageSize(e.blob)}async _OnAddStylesheet(e){await AddStyleSheet(e.url)}_PlayPendingMedia(){const e=[...this._mediaPendingPlay];if(this._mediaPendingPlay.clear(),!this._isSilent)for(const t of e){const i=t.play();i&&i.catch(e=>{this._mediaRemovedPendingPlay.has(t)||this._mediaPendingPlay.add(t)})}}TryPlayMedia(t){if("function"!=typeof t.play)throw new Error("missing play function");this._mediaRemovedPendingPlay.delete(t);let e;try{e=t.play()}catch(e){return void this._mediaPendingPlay.add(t)}e&&e.catch(e=>{this._mediaRemovedPendingPlay.has(t)||this._mediaPendingPlay.add(t)})}RemovePendingPlay(e){this._mediaPendingPlay.delete(e),this._mediaRemovedPendingPlay.add(e)}SetSilent(e){this._isSilent=!!e}_OnHideCordovaSplash(){navigator.splashscreen&&navigator.splashscreen.hide&&navigator.splashscreen.hide()}_OnDebugHighlight(e){const t=e.show;if(t){this._debugHighlightElem||(this._debugHighlightElem=document.createElement("div"),this._debugHighlightElem.id="inspectOutline",document.body.appendChild(this._debugHighlightElem));const i=this._debugHighlightElem;i.style.display="",i.style.left=e.left-1+"px",i.style.top=e.top-1+"px",i.style.width=e.width+2+"px",i.style.height=e.height+2+"px",i.textContent=e.name}else this._debugHighlightElem&&(this._debugHighlightElem.style.display="none")}_OnRegisterSW(){window.C3_RegisterSW&&window.C3_RegisterSW()}_OnPostToDebugger(e){window.c3_postToMessagePort&&(e.from="runtime",window.c3_postToMessagePort(e))}_InvokeFunctionFromJS(e,t){return this.PostToRuntimeAsync("js-invoke-function",{name:e,params:t})}_OnScriptCreateWorker(e){const t=e.url,i=e.opts,s=e.port2,n=new Worker(t,i);n.postMessage({type:"construct-worker-init",port2:s},[s])}_OnAlert(e){alert(e.message)}_OnScreenReaderTextEvent(e){const t=e.type;if("create"===t){const i=document.createElement("p");i.id="c3-sr-"+e.id,i.textContent=e.text,this._screenReaderTextWrap.appendChild(i)}else if("update"===t){const s=document.getElementById("c3-sr-"+e.id);s?s.textContent=e.text:console.warn("[Construct] Missing screen reader text with id "+e.id)}else if("release"===t){const n=document.getElementById("c3-sr-"+e.id);n?n.remove():console.warn("[Construct] Missing screen reader text with id "+e.id)}else console.warn(`[Construct] Unknown screen reader text update '${t}'`)}_SetExportingToVideo(e){this._isExportToVideo=!0;const t=document.createElement("h1");t.id="exportToVideoMessage",t.textContent=e.message,document.body.prepend(t),document.body.classList.add("exportingToVideo"),this.GetRuntimeInterface().GetMainCanvas().style.display="",this._iRuntime.SetIsExportingToVideo(e.duration)}_OnExportVideoProgress(e){this._exportVideoProgressMessage=e.message,-1===this._exportVideoUpdateTimerId&&(this._exportVideoUpdateTimerId=setTimeout(()=>this._DoUpdateExportVideoProgressMessage(),250))}_DoUpdateExportVideoProgressMessage(){this._exportVideoUpdateTimerId=-1;const e=document.getElementById("exportToVideoMessage");e&&(e.textContent=this._exportVideoProgressMessage)}_OnExportedToVideo(e){window.c3_postToMessagePort({type:"exported-video",arrayBuffer:e.arrayBuffer,contentType:e.contentType,time:e.time})}_OnExportedToImageSequence(e){window.c3_postToMessagePort({type:"exported-image-sequence",blobArr:e.blobArr,time:e.time,gif:e.gif})}};Md.AddDOMHandlerClass(Vd)}{const Af="dispatchworker.js",Bf="jobworker.js";self.JobSchedulerDOM=class{constructor(e){this._runtimeInterface=e,this._maxNumWorkers=Math.min(navigator.hardwareConcurrency||2,16),this._dispatchWorker=null,this._jobWorkers=[],this._inputPort=null,this._outputPort=null}async Init(){if(this._hasInitialised)throw new Error("already initialised");this._hasInitialised=!0;const e=this._runtimeInterface.GetScriptFolder()+Af,t=(this._dispatchWorker=await this._runtimeInterface.CreateWorker(e,{name:"DispatchWorker"}),new MessageChannel);this._inputPort=t.port1,this._dispatchWorker.postMessage({type:"_init","in-port":t.port2},[t.port2]),this._outputPort=await this._CreateJobWorker()}async _CreateJobWorker(){const e=this._jobWorkers.length,t=this._runtimeInterface.GetScriptFolder()+Bf,i=await this._runtimeInterface.CreateWorker(t,{name:"JobWorker"+e}),s=new MessageChannel,n=new MessageChannel;return this._dispatchWorker.postMessage({type:"_addJobWorker",port:s.port1},[s.port1]),i.postMessage({type:"init",number:e,"dispatch-port":s.port2,"output-port":n.port2},[s.port2,n.port2]),this._jobWorkers.push(i),n.port1}GetPortData(){return{inputPort:this._inputPort,outputPort:this._outputPort,maxNumWorkers:this._maxNumWorkers}}GetPortTransferables(){return[this._inputPort,this._outputPort]}}}{const Kf="localstorage",Lf=class extends self.DOMHandler{constructor(e){super(e,Kf),this.AddRuntimeMessageHandlers([["init",()=>this._Init()],["request-persistent",()=>this._OnRequestPersistent()]])}async _Init(){let t=!1;try{t=await navigator.storage.persisted()}catch(e){t=!1,console.warn("[Construct] Error checking storage persisted state: ",e)}return{isPersistent:t}}async _OnRequestPersistent(){try{const e=await navigator.storage.persist();return{isOk:!0,isPersistent:e}}catch(e){return console.error("[Construct] Error requesting persistent storage: ",e),{isOk:!1}}}};self.RuntimeInterface.AddDOMHandlerClass(Lf)}{let t=null,i=null;function elemsForSelector(e,t){if(e){if(t)return Array.from(document.querySelectorAll(e));{const i=document.querySelector(e);return i?[i]:[]}}return[document.documentElement]}function noop(){}window.addEventListener("beforeinstallprompt",e=>(e.preventDefault(),t=e,i&&i._OnBeforeInstallPrompt(),!1));const Tf="browser",Uf=class extends self.DOMHandler{constructor(e){super(e,Tf),this._exportType="",this.AddRuntimeMessageHandlers([["get-initial-state",e=>this._OnGetInitialState(e)],["ready-for-sw-messages",()=>this._OnReadyForSWMessages()],["alert",e=>this._OnAlert(e)],["close",()=>this._OnClose()],["set-focus",e=>this._OnSetFocus(e)],["vibrate",e=>this._OnVibrate(e)],["lock-orientation",e=>this._OnLockOrientation(e)],["unlock-orientation",()=>this._OnUnlockOrientation()],["navigate",e=>this._OnNavigate(e)],["request-fullscreen",e=>this._OnRequestFullscreen(e)],["exit-fullscreen",()=>this._OnExitFullscreen()],["set-hash",e=>this._OnSetHash(e)],["set-document-css-style",e=>this._OnSetDocumentCSSStyle(e)],["get-document-css-style",e=>this._OnGetDocumentCSSStyle(e)],["set-window-size",e=>this._OnSetWindowSize(e)],["set-window-position",e=>this._OnSetWindowPosition(e)],["request-install",()=>this._OnRequestInstall()],["set-warn-on-close",e=>this._OnSetWarnOnClose(e)]]),window.addEventListener("online",()=>this._OnOnlineStateChanged(!0)),window.addEventListener("offline",()=>this._OnOnlineStateChanged(!1)),window.addEventListener("hashchange",()=>this._OnHashChange()),this._beforeunload_handler=e=>e.preventDefault(),document.addEventListener("backbutton",()=>this._OnCordovaBackButton())}Attach(){t?this._OnBeforeInstallPrompt():i=this,window.addEventListener("appinstalled",()=>this._OnAppInstalled())}_OnGetInitialState(e){return this._exportType=e.exportType,{location:location.toString(),isOnline:!!navigator.onLine,referrer:document.referrer,title:document.title,isCookieEnabled:!!navigator.cookieEnabled,screenWidth:screen.width,screenHeight:screen.height,windowOuterWidth:window.outerWidth,windowOuterHeight:window.outerHeight,isConstructArcade:void 0!==window.is_scirra_arcade,windowHasFocus:document.hasFocus()}}_OnReadyForSWMessages(){window.C3_RegisterSW&&window.OfflineClientInfo&&window.OfflineClientInfo.SetMessageCallback(e=>this.PostToRuntime("sw-message",e.data))}_OnBeforeInstallPrompt(){this.PostToRuntime("install-available")}async _OnRequestInstall(){if(!t)return{result:"unavailable"};try{t.prompt();const e=await t.userChoice;return{result:e.outcome}}catch(e){return console.error("[Construct] Requesting install failed: ",e),{result:"failed"}}}_OnAppInstalled(){this.PostToRuntime("app-installed")}_OnOnlineStateChanged(e){this.PostToRuntime("online-state",{isOnline:e})}_OnCordovaBackButton(){this.PostToRuntime("backbutton")}GetNWjsWindow(){return"nwjs"===this._exportType?nw.Window.get():null}_OnAlert(e){alert(e.message)}_OnClose(){navigator.app&&navigator.app.exitApp?navigator.app.exitApp():navigator.device&&navigator.device.exitApp?navigator.device.exitApp():self.nw?self.nw.App.quit():window.close()}_OnSetFocus(e){const t=e.isFocus;if("nwjs"===this._exportType){const i=this.GetNWjsWindow();t?i.focus():i.blur()}else t?window.focus():window.blur()}_OnVibrate(e){navigator.vibrate&&navigator.vibrate(e.pattern)}_OnLockOrientation(e){const t=e.orientation;if(screen.orientation&&screen.orientation.lock)screen.orientation.lock(t).catch(e=>console.warn("[Construct] Failed to lock orientation: ",e));else try{let e=!1;screen.lockOrientation?e=screen.lockOrientation(t):screen.webkitLockOrientation?e=screen.webkitLockOrientation(t):screen.mozLockOrientation?e=screen.mozLockOrientation(t):screen.msLockOrientation&&(e=screen.msLockOrientation(t)),e||console.warn("[Construct] Failed to lock orientation")}catch(e){console.warn("[Construct] Failed to lock orientation: ",e)}}_OnUnlockOrientation(){try{screen.orientation&&screen.orientation.unlock?screen.orientation.unlock():screen.unlockOrientation?screen.unlockOrientation():screen.webkitUnlockOrientation?screen.webkitUnlockOrientation():screen.mozUnlockOrientation?screen.mozUnlockOrientation():screen.msUnlockOrientation&&screen.msUnlockOrientation()}catch(e){}}_OnNavigate(e){const t=e.type;if("back"===t)navigator.app&&navigator.app.backHistory?navigator.app.backHistory():window.history.back();else if("forward"===t)window.history.forward();else if("reload"===t)location.reload();else if("url"===t){const i=e.url,s=e.target,n=e.exportType;self.cordova&&self.cordova.InAppBrowser?self.cordova.InAppBrowser.open(i,"_system"):"preview"===n||"macos-wkwebiew"===n||"linux-cef"===n||this._iRuntime.IsAnyWebView2Wrapper()?window.open(i,"_blank"):this._isConstructArcade||(2===s?window.top.location=i:1===s?window.parent.location=i:window.location=i)}else if("new-window"===t){const o=e.url,a=e.tag;self.cordova&&self.cordova.InAppBrowser?self.cordova.InAppBrowser.open(o,"_system"):window.open(o,a)}}_OnRequestFullscreen(t){if(this._iRuntime.IsAnyWebView2Wrapper()||"macos-wkwebview"===this._exportType||"linux-cef"===this._exportType)self.RuntimeInterface._SetWrapperIsFullscreenFlag(!0),this._iRuntime._SendWrapperMessage({type:"set-fullscreen",fullscreen:!0});else{const i={navigationUI:"auto"},s=t.navUI,n=(1===s?i.navigationUI="hide":2===s&&(i.navigationUI="show"),document.documentElement);let e;n.requestFullscreen?e=n.requestFullscreen(i):n.mozRequestFullScreen?e=n.mozRequestFullScreen(i):n.msRequestFullscreen?e=n.msRequestFullscreen(i):n.webkitRequestFullScreen&&(e=void 0!==Element.ALLOW_KEYBOARD_INPUT?n.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT):n.webkitRequestFullScreen()),e instanceof Promise&&e.catch(noop)}}_OnExitFullscreen(){if(this._iRuntime.IsAnyWebView2Wrapper()||"macos-wkwebview"===this._exportType||"linux-cef"===this._exportType)self.RuntimeInterface._SetWrapperIsFullscreenFlag(!1),this._iRuntime._SendWrapperMessage({type:"set-fullscreen",fullscreen:!1});else{let e;document.exitFullscreen?e=document.exitFullscreen():document.mozCancelFullScreen?e=document.mozCancelFullScreen():document.msExitFullscreen?e=document.msExitFullscreen():document.webkitCancelFullScreen&&(e=document.webkitCancelFullScreen()),e instanceof Promise&&e.catch(noop)}}_OnSetHash(e){location.hash=e.hash}_OnHashChange(){this.PostToRuntime("hashchange",{location:location.toString()})}_OnSetDocumentCSSStyle(e){const t=e.prop,i=e.value,s=e.selector,n=e["is-all"];try{const o=elemsForSelector(s,n);for(const e of o)t.startsWith("--")?e.style.setProperty(t,i):e.style[t]=i}catch(e){console.warn("[Browser] Failed to set style: ",e)}}_OnGetDocumentCSSStyle(e){const t=e.prop,i=e.selector;try{const s=document.querySelector(i);if(s){const n=window.getComputedStyle(s);return{isOk:!0,result:n.getPropertyValue(t)}}return{isOk:!1}}catch(e){return console.warn("[Browser] Failed to get style: ",e),{isOk:!1}}}_OnSetWindowSize(e){window.resizeTo(e.windowWidth,e.windowHeight)}_OnSetWindowPosition(e){window.moveTo(e.windowX,e.windowY)}_OnSetWarnOnClose(e){const t=e.enabled;t?window.addEventListener("beforeunload",this._beforeunload_handler):window.removeEventListener("beforeunload",this._beforeunload_handler)}};self.RuntimeInterface.AddDOMHandlerClass(Uf)}{const cg="platform-info";function GetAndroidInsetTop(i){return new Promise((e,t)=>{i.getInsetTop(e,t)})}function GetAndroidInsetRight(i){return new Promise((e,t)=>{i.getInsetRight(e,t)})}function GetAndroidInsetBottom(i){return new Promise((e,t)=>{i.getInsetBottom(e,t)})}function GetAndroidInsetLeft(i){return new Promise((e,t)=>{i.getInsetLeft(e,t)})}const dg=class extends self.DOMHandler{constructor(e){super(e,cg),this.AddRuntimeMessageHandlers([["get-initial-state",()=>this._OnGetInitialState()],["request-wake-lock",()=>this._OnRequestWakeLock()],["release-wake-lock",()=>this._OnReleaseWakeLock()]]),window.addEventListener("resize",()=>this._OnResize()),this._screenWakeLock=null}async _OnGetInitialState(){const e=await this._GetSafeAreaInset();return{screenWidth:screen.width,screenHeight:screen.height,windowOuterWidth:window.outerWidth,windowOuterHeight:window.outerHeight,safeAreaInset:e,supportsWakeLock:!!navigator.wakeLock}}async _GetSafeAreaInset(){const e=self.AndroidNotch;if(!e){const t=document.body,i=t.style,s=(i.setProperty("--temp-sai-top","env(safe-area-inset-top)"),i.setProperty("--temp-sai-right","env(safe-area-inset-right)"),i.setProperty("--temp-sai-bottom","env(safe-area-inset-bottom)"),i.setProperty("--temp-sai-left","env(safe-area-inset-left)"),getComputedStyle(t)),n=[s.getPropertyValue("--temp-sai-top"),s.getPropertyValue("--temp-sai-right"),s.getPropertyValue("--temp-sai-bottom"),s.getPropertyValue("--temp-sai-left")].map(e=>{const t=parseInt(e,10);return isFinite(t)?t:0});return i.removeProperty("--temp-sai-top"),i.removeProperty("--temp-sai-right"),i.removeProperty("--temp-sai-bottom"),i.removeProperty("--temp-sai-left"),n}try{return await Promise.all([GetAndroidInsetTop(e),GetAndroidInsetRight(e),GetAndroidInsetBottom(e),GetAndroidInsetLeft(e)])}catch(e){return console.error("[Construct] Failed to get Android safe area inset: ",e),[0,0,0,0]}}async _OnResize(){const e=await this._GetSafeAreaInset();this.PostToRuntime("window-resize",{windowOuterWidth:window.outerWidth,windowOuterHeight:window.outerHeight,safeAreaInset:e})}async _OnRequestWakeLock(){if(!this._screenWakeLock)try{this._screenWakeLock=await navigator.wakeLock.request("screen"),this._screenWakeLock.addEventListener("release",()=>this._OnWakeLockReleased()),console.log("[Construct] Screen wake lock acquired"),this.PostToRuntime("wake-lock-acquired")}catch(e){console.warn("[Construct] Failed to acquire screen wake lock: ",e),this.PostToRuntime("wake-lock-error")}}_OnReleaseWakeLock(){this._screenWakeLock&&(this._screenWakeLock.release(),this._screenWakeLock=null)}_OnWakeLockReleased(){console.log("[Construct] Screen wake lock released"),this._screenWakeLock=null,this.PostToRuntime("wake-lock-released")}};self.RuntimeInterface.AddDOMHandlerClass(dg)}{const Bg="mouse",Cg=class extends self.DOMHandler{constructor(e){super(e,Bg),this.AddRuntimeMessageHandlers([["cursor",e=>this._OnChangeCursorStyle(e)],["request-pointer-lock",e=>this._OnRequestPointerLock(e)],["release-pointer-lock",()=>this._OnReleasePointerLock()]]),document.addEventListener("pointerlockchange",e=>this._OnPointerLockChange()),document.addEventListener("pointerlockerror",e=>this._OnPointerLockError())}_OnChangeCursorStyle(e){document.documentElement.style.cursor=e}_OnRequestPointerLock(e){this._iRuntime.GetMainCanvas().requestPointerLock(e)}_OnReleasePointerLock(){document.exitPointerLock()}_OnPointerLockChange(){this.PostToRuntime("pointer-lock-change",{"has-pointer-lock":!!document.pointerLockElement})}_OnPointerLockError(){this.PostToRuntime("pointer-lock-error",{"has-pointer-lock":!!document.pointerLockElement})}};self.RuntimeInterface.AddDOMHandlerClass(Cg)}{const Kg="keyboard",Lg=class extends self.DOMHandler{constructor(e){super(e,Kg),this._isKeyboardLockSupported=!(!navigator.keyboard||!navigator.keyboard.lock),this.AddRuntimeMessageHandlers([["init",()=>this._OnInit()],["lock-keyboard",e=>this._OnLockKeyboard(e)],["unlock-keyboard",()=>this._OnUnlockKeyboard()]])}_OnInit(){return{isKeyboardLockSupported:this._isKeyboardLockSupported}}async _OnLockKeyboard(e){const t=e.keysArr;try{return 0===t.length?await navigator.keyboard.lock():await navigator.keyboard.lock(t),{isOk:!0}}catch(e){return console.error("Error locking keyboard:",e),{isOk:!1}}}_OnUnlockKeyboard(){try{navigator.keyboard.unlock()}catch(e){console.error("Error unlocking keyboard:",e)}}};self.RuntimeInterface.AddDOMHandlerClass(Lg)}{const Rg="touch",Sg=class extends self.DOMHandler{constructor(e){super(e,Rg),this.AddRuntimeMessageHandler("request-permission",e=>this._OnRequestPermission(e))}async _OnRequestPermission(e){const t=e.type;let i=!0;0===t?i=await this._RequestOrientationPermission():1===t&&(i=await this._RequestMotionPermission()),this.PostToRuntime("permission-result",{type:t,result:i})}async _RequestOrientationPermission(){if(!self.DeviceOrientationEvent||!self.DeviceOrientationEvent.requestPermission)return!0;try{const e=await self.DeviceOrientationEvent.requestPermission();return"granted"===e}catch(e){return console.warn("[Touch] Failed to request orientation permission: ",e),!1}}async _RequestMotionPermission(){if(!self.DeviceMotionEvent||!self.DeviceMotionEvent.requestPermission)return!0;try{const e=await self.DeviceMotionEvent.requestPermission();return"granted"===e}catch(e){return console.warn("[Touch] Failed to request motion permission: ",e),!1}}};self.RuntimeInterface.AddDOMHandlerClass(Sg)}{function IsVideoPlaying(e){return e&&!e.paused&&!e.ended&&0<e.currentTime}const a6="video",b6=class extends self.DOMElementHandler{constructor(e){super(e,a6),this.SetAutoAttach(!1),this._isRuntimeInWorker=!1,this._supportsRvfc=!1,this._postImageBitmaps=!1,this._sequenceNumber=0,this._numVideos=0,this._destroyedVideos=new WeakSet,this.AddRuntimeMessageHandler("init",e=>this._OnInit(e)),this.AddDOMElementMessageHandlers([["play",e=>this._OnPlay(e)],["pause",e=>this._OnPause(e)],["set-source",(e,t)=>this._OnSetSource(e,t)],["set-playback-time",(e,t)=>this._OnSetPlaybackTime(e,t)],["set-playback-rate",(e,t)=>this._OnSetPlaybackRate(e,t)],["set-looping",(e,t)=>this._OnSetLooping(e,t)],["set-muted",(e,t)=>this._OnSetMuted(e,t)],["set-volume",(e,t)=>this._OnSetVolume(e,t)]]),self.C3Video_GetElement=e=>this.GetElementById(e)}async _OnInit(e){this._isRuntimeInWorker=e.isInWorker;const t=document.createElement("video"),i=(this._supportsRvfc=!!t.requestVideoFrameCallback&&!this._iRuntime.IsAndroidWebView(),!!self.createImageBitmap);return this._postImageBitmaps=this._isRuntimeInWorker||i,{postImageBitmaps:this._postImageBitmaps,supportedFormats:{"webm-vp8":!!t.canPlayType("video/webm;codecs=vp8"),"webm-vp9":!!t.canPlayType("video/webm;codecs=vp9"),"webm-av1":!!t.canPlayType("video/webm;codecs=av01.0.00M.08"),"mp4-h264":!!t.canPlayType("video/mp4;codecs=avc1.420034"),"mp4-h265":!!t.canPlayType("video/mp4;codecs=hev1.1.2.L93.B0"),"mp4-av1":!!t.canPlayType("video/mp4;codecs=av01.0.00M.08")}}}TryPlayMedia(e){this._iRuntime.TryPlayMedia(e),this._postImageBitmaps&&this._supportsRvfc&&-1===e.c3_rvfcId&&(e.c3_rvfcId=e.requestVideoFrameCallback(()=>this._OnVideoFrameCallback(e)))}RemovePendingPlay(e){this._iRuntime.RemovePendingPlay(e),this._postImageBitmaps&&this._supportsRvfc&&-1!==e.c3_rvfcId&&(e.cancelVideoFrameCallback(e.c3_rvfcId),e.c3_rvfcId=-1)}async _OnVideoFrameCallback(e){if(!this._destroyedVideos.has(e)){e.c3_rvfcId=e.requestVideoFrameCallback(()=>this._OnVideoFrameCallback(e));try{const t=e.c3_sequenceNumber++,i=await createImageBitmap(e);t>e.c3_lastFrameSequence&&(e.c3_imageBitmap=i,e.c3_lastFrameSequence=t)}catch(e){}}}CreateElement(e,t){const i=document.createElement("video"),s=(i.crossOrigin="anonymous",i.playsInline=!0,i.c3_imageBitmap=null,i.c3_rvfcId=-1,i.c3_sequenceNumber=0,i.c3_lastFrameSequence=-1,i.addEventListener("canplay",()=>this._SendPlaybackEvent(i,e,0)),i.addEventListener("canplaythrough",()=>this._SendPlaybackEvent(i,e,1)),i.addEventListener("ended",()=>this._SendPlaybackEvent(i,e,2)),i.addEventListener("error",()=>this._SendPlaybackEvent(i,e,3)),i.addEventListener("loadstart",()=>this._SendPlaybackEvent(i,e,4)),i.addEventListener("playing",()=>this._SendPlaybackEvent(i,e,5)),i.addEventListener("pause",()=>this._SendPlaybackEvent(i,e,6)),i.addEventListener("stalled",()=>this._SendPlaybackEvent(i,e,7)),t.autoplay);return 0===s?(i.autoplay=!1,i.preload="none"):1===s?(i.autoplay=!1,i.preload="auto"):i.autoplay=!0,t.src&&(i.src=t.src),2===s&&this.TryPlayMedia(i),this._numVideos++,this._StartTicking(),i}_SendPlaybackEvent(e,t,i){this._destroyedVideos.has(e)||this.PostToRuntimeElement("playback-event",t,{type:i})}UpdateState(e,t){}DestroyElement(e){this.RemovePendingPlay(e),IsVideoPlaying(e)&&e.pause(),e.src="",this._numVideos=Math.max(this._numVideos-1,0),0===this._numVideos&&this._StopTicking(),this._destroyedVideos.add(e)}_OnPlay(e){this.TryPlayMedia(e)}_OnPause(e){this.RemovePendingPlay(e),e.pause()}_OnSetSource(e,t){e.src=t.src,e.load()}_OnSetPlaybackTime(e,t){try{e.currentTime=t.time}catch(e){console.error("[Video] Exception setting playback time: ",e)}}_OnSetPlaybackRate(e,t){try{e.playbackRate=t.rate}catch(e){console.error("[Video] Exception setting playback rate: ",e)}}_OnSetLooping(e,t){e.loop=t.isLooping}_OnSetMuted(e,t){e.muted=t.isMuted}_OnSetVolume(e,t){e.volume=t.volume}Tick(){const e={},t={sequenceNumber:this._sequenceNumber++,videoData:e},i=[],s=[];for(const[n,o]of this._elementMap.entries()){const a=o.GetElement(),r={currentTime:a.currentTime,playbackRate:a.playbackRate,duration:a.duration,videoWidth:a.videoWidth,videoHeight:a.videoHeight};if(this._postImageBitmaps)if(this._supportsRvfc){const d=a.c3_imageBitmap;a.c3_imageBitmap=null,(r.imageBitmap=d)&&i.push(d)}else s.push(createImageBitmap(a).then(e=>{r.imageBitmap=e,i.push(e)}).catch(e=>{r.imageBitmap=null}));e[n.toString()]=r}Promise.all(s).then(()=>{this._isRuntimeInWorker?this.PostToRuntime("state",t,!1,i):this._PostToRuntimeMaybeSync("state",t)})}};self.RuntimeInterface.AddDOMHandlerClass(b6)}{const jh=180/Math.PI,kh="audio";self.AudioDOMHandler=class extends self.DOMHandler{constructor(e){super(e,kh),this._audioContext=null,this._destinationNode=null,this._hasUnblocked=!1,this._hasAttachedUnblockEvents=!1,this._unblockFunc=()=>this._UnblockAudioContext(),this._audioBuffers=[],this._audioInstances=[],this._lastAudioInstance=null,this._lastPlayedTags=[],this._loadedAudioUrls=new Set,this._lastTickCount=-1,this._pendingTags=new Map,this._masterVolume=1,this._isSilent=!1,this._timeScaleMode=0,this._timeScale=1,this._gameTime=0,this._panningModel="HRTF",this._distanceModel="inverse",this._refDistance=600,this._maxDistance=1e4,this._rolloffFactor=1,this._lastListenerPos=[0,0,0],this._lastListenerOrientation=[0,0,-1,0,1,0],this._playMusicAsSound=!1,this._lastMusicBuffer=null,this._effects=new Map,this._analysers=new Set,this._isPendingPostFxState=!1,this._hasStartedOfflineRender=!1,this._microphoneTag="",this._microphoneSource=null,self.C3Audio_OnMicrophoneStream=(e,t)=>this._OnMicrophoneStream(e,t),this._destMediaStreamNode=null,self.C3Audio_GetOutputStream=()=>this._OnGetOutputStream(),(self.C3Audio_DOMInterface=this).AddRuntimeMessageHandlers([["create-audio-context",e=>this._CreateAudioContext(e)],["play",e=>this._Play(e)],["stop",e=>this._Stop(e)],["stop-all",()=>this._StopAll()],["set-paused",e=>this._SetPaused(e)],["set-volume",e=>this._SetVolume(e)],["fade-volume",e=>this._FadeVolume(e)],["set-master-volume",e=>this._SetMasterVolume(e)],["set-muted",e=>this._SetMuted(e)],["set-silent",e=>this._SetSilent(e)],["set-looping",e=>this._SetLooping(e)],["set-playback-rate",e=>this._SetPlaybackRate(e)],["set-stereo-pan",e=>this._SetStereoPan(e)],["seek",e=>this._Seek(e)],["preload",e=>this._Preload(e)],["unload",e=>this._Unload(e)],["unload-all",()=>this._UnloadAll()],["set-suspended",e=>this._SetSuspended(e)],["add-effect",e=>this._AddEffect(e)],["set-effect-param",e=>this._SetEffectParam(e)],["remove-effects",e=>this._RemoveEffects(e)],["tick",e=>this._OnTick(e)],["load-state",e=>this._OnLoadState(e)],["offline-render-audio",e=>this._OnOfflineRenderAudio(e)],["offline-render-finish",()=>this._OnOfflineRenderFinish()]])}async _CreateAudioContext(e){e.usePlayMusicAsSoundWorkaround&&(this._playMusicAsSound=!0),this._timeScaleMode=e.timeScaleMode,this._panningModel=["equalpower","HRTF","soundfield"][e.panningModel],this._distanceModel=["linear","inverse","exponential"][e.distanceModel],this._refDistance=e.refDistance,this._maxDistance=e.maxDistance,this._rolloffFactor=e.rolloffFactor,this._iRuntime.IsExportingToVideo()?(this._playMusicAsSound=!0,this._audioContext=new OfflineAudioContext({numberOfChannels:2,sampleRate:48e3,length:Math.ceil(48e3*this._iRuntime.GetExportToVideoDuration())})):(this._audioContext=new AudioContext({latencyHint:e.latencyHint}),this._AttachUnblockEvents(),this._audioContext.onstatechange=()=>{"running"!==this._audioContext.state&&this._AttachUnblockEvents(),this.PostToRuntime("audiocontext-state",{audioContextState:this._audioContext.state})}),this._destinationNode=this._audioContext.createGain(),this._destinationNode.connect(this._audioContext.destination);const t=e.listenerPos;this._lastListenerPos[0]=t[0],this._lastListenerPos[1]=t[1],this._lastListenerPos[2]=t[2],this._audioContext.listener.setPosition(t[0],t[1],t[2]),this._audioContext.listener.setOrientation(...this._lastListenerOrientation),self.C3_GetAudioContextCurrentTime=()=>this.GetAudioCurrentTime();try{await Promise.all(e.preloadList.map(e=>this._GetAudioBuffer(e.originalUrl,e.url,e.type,!1)))}catch(e){console.error("[Construct] Preloading sounds failed: ",e)}return{sampleRate:this._audioContext.sampleRate,audioContextState:this._audioContext.state,outputLatency:this._audioContext.outputLatency||0}}_AttachUnblockEvents(){this._hasAttachedUnblockEvents||(this._hasUnblocked=!1,window.addEventListener("pointerup",this._unblockFunc,!0),window.addEventListener("touchend",this._unblockFunc,!0),window.addEventListener("click",this._unblockFunc,!0),window.addEventListener("keydown",this._unblockFunc,!0),this._hasAttachedUnblockEvents=!0)}_DetachUnblockEvents(){this._hasAttachedUnblockEvents&&(this._hasUnblocked=!0,window.removeEventListener("pointerup",this._unblockFunc,!0),window.removeEventListener("touchend",this._unblockFunc,!0),window.removeEventListener("click",this._unblockFunc,!0),window.removeEventListener("keydown",this._unblockFunc,!0),this._hasAttachedUnblockEvents=!1)}_UnblockAudioContext(){if(!this._hasUnblocked){const e=this._audioContext,t=("suspended"===e.state&&e.resume&&e.resume(),e.createBuffer(1,220,22050)),i=e.createBufferSource();i.buffer=t,i.connect(e.destination),i.start(0),"running"===e.state&&this._DetachUnblockEvents()}}_MatchTagLists(t,e){for(const i of e){let e=!1;for(const s of t)if(self.AudioDOMHandler.EqualsNoCase(s,i)){e=!0;break}if(!e)return!1}return!0}GetAudioContext(){return this._audioContext}GetAudioCurrentTime(){return this._audioContext.currentTime}GetDestinationNode(){return this._destinationNode}["GetAudioContextExtern"](){return this.GetAudioContext()}["GetDestinationNodeExtern"](){return this.GetDestinationNode()}GetDestinationForTag(e){const t=this._effects.get(e.toLowerCase());return t?t[0].GetInputNode():this.GetDestinationNode()}AddEffectForTag(e,t){e=e.toLowerCase();let i=this._effects.get(e);i||(i=[],this._effects.set(e,i)),t._SetIndex(i.length),t._SetTag(e),i.push(t),this._ReconnectEffects(e)}_ReconnectEffects(e){e=e.toLowerCase();let t=this.GetDestinationNode();const i=this._effects.get(e);if(i&&i.length){t=i[0].GetInputNode();for(let e=0,t=i.length;e<t;++e){const s=i[e];e+1===t?s.ConnectTo(this.GetDestinationNode()):s.ConnectTo(i[e+1].GetInputNode())}}for(const n of this.audioInstancesByEffectTag(e))n.Reconnect(t);this._microphoneSource&&this._microphoneTag===e&&(this._microphoneSource.disconnect(),this._microphoneSource.connect(t))}GetMasterVolume(){return this._masterVolume}IsSilent(){return this._isSilent}GetTimeScaleMode(){return this._timeScaleMode}GetTimeScale(){return this._timeScale}GetGameTime(){return this._gameTime}IsPlayMusicAsSound(){return this._playMusicAsSound}GetPanningModel(){return this._panningModel}GetDistanceModel(){return this._distanceModel}GetReferenceDistance(){return this._refDistance}GetMaxDistance(){return this._maxDistance}GetRolloffFactor(){return this._rolloffFactor}TryPlayMedia(e){this._iRuntime.TryPlayMedia(e)}RemovePendingPlay(e){this._iRuntime.RemovePendingPlay(e)}ReleaseInstancesForBuffer(i){let s=0;for(let e=0,t=this._audioInstances.length;e<t;++e){const n=this._audioInstances[e];(this._audioInstances[s]=n).GetBuffer()===i?n.Release():++s}this._audioInstances.length=s}ReleaseAllMusicBuffersExceptLast(){let i=0;for(let e=0,t=this._audioBuffers.length;e<t;++e){const s=this._audioBuffers[e];(this._audioBuffers[i]=s).IsMusic()&&s!==this._lastMusicBuffer?s.Release():++i}this._audioBuffers.length=i}*audioInstancesMatchingTags(e){if(0<e.length)for(const t of this._audioInstances)this._MatchTagLists(t.GetTags(),e)&&(yield t);else this._lastAudioInstance&&!this._lastAudioInstance.HasEnded()&&(yield this._lastAudioInstance)}*audioInstancesByEffectTag(e){if(e)for(const t of this._audioInstances)self.AudioDOMHandler.EqualsNoCase(t.GetEffectTag(),e)&&(yield t);else this._lastAudioInstance&&!this._lastAudioInstance.HasEnded()&&(yield this._lastAudioInstance)}async _GetAudioBuffer(e,t,i,s,n){for(const a of this._audioBuffers)if(a.GetUrl()===t)return s&&this._playMusicAsSound&&(this._lastMusicBuffer=a),await a.Load(),a;if(n)return null;s&&this._playMusicAsSound&&this.ReleaseAllMusicBuffersExceptLast();const o=self.C3AudioBuffer.Create(this,e,t,i,s);return this._audioBuffers.push(o),s&&this._playMusicAsSound&&(this._lastMusicBuffer=o),await o.Load(),this._loadedAudioUrls.has(e)||(this.PostToRuntime("buffer-metadata",{originalUrl:e,duration:o.GetDuration()}),this._loadedAudioUrls.add(e)),o}async _GetAudioInstance(e,t,i,s,n){for(const r of this._audioInstances)if(r.GetUrl()===t&&(r.CanBeRecycled()||n))return n&&this._playMusicAsSound&&(this._lastMusicBuffer=r.GetBuffer()),r.SetTags(s),r;const o=await this._GetAudioBuffer(e,t,i,n);if(o.WasReleased())throw new Error(`buffer '${e}' unloaded while loading`);const a=o.CreateInstance(s);return this._audioInstances.push(a),a}_AddPendingTags(e){const i=e.join(" ");let s=this._pendingTags.get(i);if(!s){let t=null;const n=new Promise(e=>t=e);s={pendingCount:0,promise:n,resolve:t},this._pendingTags.set(i,s)}s.pendingCount++}_RemovePendingTags(e){const t=e.join(" "),i=this._pendingTags.get(t);if(!i)throw new Error("expected pending tag");i.pendingCount--,0===i.pendingCount&&(i.resolve(),this._pendingTags.delete(t))}TagsReady(e){const t=(0===e.length?this._lastPlayedTags:e).join(" "),i=this._pendingTags.get(t);return i?i.promise:Promise.resolve()}_MaybeStartTicking(){if(0<this._analysers.size)this._StartTicking();else for(const e of this._audioInstances)if(e.IsActive())return void this._StartTicking()}Tick(){for(const i of this._analysers)i.Tick();const e=this.GetAudioCurrentTime();for(const s of this._audioInstances)s.Tick(e);const t=this._audioInstances.filter(e=>e.IsActive()).map(e=>e.GetState());this.PostToRuntime("state",{tickCount:this._lastTickCount,outputLatency:this._audioContext.outputLatency||0,audioInstances:t,analysers:[...this._analysers].map(e=>e.GetData())}),0===t.length&&0===this._analysers.size&&this._StopTicking()}PostTrigger(e,t,i){this.PostToRuntime("trigger",{type:e,tags:t,aiid:i})}async _Play(e){const t=e.originalUrl,i=e.url,s=e.type,n=e.isMusic,o=e.tags,a=e.isLooping,r=e.vol,d=e.pos,l=e.panning,h=e.stereoPan;let c=e.off;if(0<c&&!e.trueClock)if(this._audioContext.getOutputTimestamp){const u=this._audioContext.getOutputTimestamp();c=c-u.performanceTime/1e3+u.contextTime}else c=c-performance.now()/1e3+this._audioContext.currentTime;this._lastPlayedTags=o.slice(0),this._AddPendingTags(o);try{this._lastAudioInstance=await this._GetAudioInstance(t,i,s,o,n),l?(this._lastAudioInstance.SetPannerEnabled(!0),this._lastAudioInstance.SetPan(l.x,l.y,l.z,l.angle,l.innerAngle,l.outerAngle,l.outerGain),l.hasOwnProperty("uid")&&this._lastAudioInstance.SetUID(l.uid)):"number"==typeof h&&0!==h?(this._lastAudioInstance.SetStereoPannerEnabled(!0),this._lastAudioInstance.SetStereoPan(h)):(this._lastAudioInstance.SetPannerEnabled(!1),this._lastAudioInstance.SetStereoPannerEnabled(!1)),this._lastAudioInstance.Play(a,r,d,c)}catch(e){return void console.error("[Construct] Audio: error starting playback: ",e)}finally{this._RemovePendingTags(o)}this._StartTicking()}_Stop(e){const t=e.tags;for(const i of this.audioInstancesMatchingTags(t))i.Stop()}_StopAll(){for(const e of this._audioInstances)e.Stop()}_SetPaused(e){const t=e.tags,i=e.paused;for(const s of this.audioInstancesMatchingTags(t))i?s.Pause():s.Resume();this._MaybeStartTicking()}_SetVolume(e){const t=e.tags,i=e.vol;for(const s of this.audioInstancesMatchingTags(t))s.SetVolume(i)}_SetStereoPan(e){const t=e.tags,i=e.p;for(const s of this.audioInstancesMatchingTags(t))s.SetStereoPannerEnabled(!0),s.SetStereoPan(i)}async _FadeVolume(e){const t=e.tags,i=e.vol,s=e.duration,n=e.stopOnEnd;await this.TagsReady(t);for(const o of this.audioInstancesMatchingTags(t))o.FadeVolume(i,s,n);this._MaybeStartTicking()}_SetMasterVolume(e){this._masterVolume=e.vol,this._destinationNode.gain.value=this._masterVolume}_SetMuted(e){const t=e.tags,i=e.isMuted;for(const s of this.audioInstancesMatchingTags(t))s.SetMuted(i)}_SetSilent(e){this._isSilent=e.isSilent,this._iRuntime.SetSilent(this._isSilent);for(const t of this._audioInstances)t._UpdateMuted()}_SetLooping(e){const t=e.tags,i=e.isLooping;for(const s of this.audioInstancesMatchingTags(t))s.SetLooping(i)}async _SetPlaybackRate(e){const t=e.tags,i=e.rate;await this.TagsReady(t);for(const s of this.audioInstancesMatchingTags(t))s.SetPlaybackRate(i)}async _Seek(e){const t=e.tags,i=e.pos;await this.TagsReady(t);for(const s of this.audioInstancesMatchingTags(t))s.Seek(i)}async _Preload(e){const t=e.originalUrl,i=e.url,s=e.type,n=e.isMusic;try{await this._GetAudioInstance(t,i,s,"",n)}catch(e){console.error("[Construct] Audio: error preloading: ",e)}}async _Unload(e){const t=e.url,i=e.type,s=e.isMusic,n=await this._GetAudioBuffer("",t,i,s,!0);if(n){n.Release(),this._lastMusicBuffer===n&&(this._lastMusicBuffer=null);const o=this._audioBuffers.indexOf(n);-1!==o&&this._audioBuffers.splice(o,1)}}_UnloadAll(){for(const e of this._audioBuffers)e.Release(),this._lastMusicBuffer===e&&(this._lastMusicBuffer=null);this._audioBuffers.length=0}_SetSuspended(e){const t=e.isSuspended;!t&&this._audioContext.resume&&this._audioContext.resume();for(const i of this._audioInstances)i.SetSuspended(t);t&&this._audioContext.suspend&&this._audioContext.suspend()}_OnTick(e){if(this._timeScale=e.timeScale,this._gameTime=e.gameTime,this._lastTickCount=e.tickCount,0!==this._timeScaleMode)for(const s of this._audioInstances)s._UpdatePlaybackRate();const t=e.listenerPos,i=(!t||this._lastListenerPos[0]===t[0]&&this._lastListenerPos[1]===t[1]&&this._lastListenerPos[2]===t[2]||(this._lastListenerPos[0]=t[0],this._lastListenerPos[1]=t[1],this._lastListenerPos[2]=t[2],this._audioContext.listener.setPosition(t[0],t[1],t[2])),e.listenerOrientation);if(i&&(this._lastListenerOrientation[0]!==i[0]||this._lastListenerOrientation[1]!==i[1]||this._lastListenerOrientation[2]!==i[2]||this._lastListenerOrientation[3]!==i[3]||this._lastListenerOrientation[4]!==i[4]||this._lastListenerOrientation[5]!==i[5])){for(let e=0;e<6;++e)this._lastListenerOrientation[e]=i[e];this._audioContext.listener.setOrientation(...this._lastListenerOrientation)}for(const n of e.instPans){const o=n.uid;for(const a of this._audioInstances)a.GetUID()===o&&a.SetPanXYZA(n.x,n.y,n.z,n.angle)}}async _AddEffect(e){const t=e.type,i=e.hasOwnProperty("tags")?e.tags:[e.tag],s=e.params;let n,o;if("convolution"===t)try{o=await this._GetAudioBuffer(e.bufferOriginalUrl,e.bufferUrl,e.bufferType,!1)}catch(e){return void console.log("[Construct] Audio: error loading convolution: ",e)}for(const a of i){if("filter"===t)n=new self.C3AudioFilterFX(this,...s);else if("delay"===t)n=new self.C3AudioDelayFX(this,...s);else if("convolution"===t)(n=new self.C3AudioConvolveFX(this,o.GetAudioBuffer(),...s))._SetBufferInfo(e.bufferOriginalUrl,e.bufferUrl,e.bufferType);else if("flanger"===t)n=new self.C3AudioFlangerFX(this,...s);else if("phaser"===t)n=new self.C3AudioPhaserFX(this,...s);else if("gain"===t)n=new self.C3AudioGainFX(this,...s);else if("stereopan"===t)n=new self.C3AudioStereoPanFX(this,...s);else if("tremolo"===t)n=new self.C3AudioTremoloFX(this,...s);else if("ringmod"===t)n=new self.C3AudioRingModFX(this,...s);else if("distortion"===t)n=new self.C3AudioDistortionFX(this,...s);else if("compressor"===t)n=new self.C3AudioCompressorFX(this,...s);else{if("analyser"!==t)throw new Error("invalid effect type");n=new self.C3AudioAnalyserFX(this,...s)}this.AddEffectForTag(a,n)}this._PostUpdatedFxState()}_SetEffectParam(e){const t=e.tags,i=e.index,s=e.param,n=e.value,o=e.ramp,a=e.time;for(const r of t){const d=this._effects.get(r.toLowerCase());!d||i<0||i>=d.length||d[i].SetParam(s,n,o,a)}this._PostUpdatedFxState()}_RemoveEffects(e){const t=e.tags;for(const i of t){const s=i.toLowerCase(),n=this._effects.get(s);if(!n||!n.length)return;for(const o of n)o.Release();this._effects.delete(s),this._ReconnectEffects(s)}}_AddAnalyser(e){this._analysers.add(e),this._MaybeStartTicking()}_RemoveAnalyser(e){this._analysers.delete(e)}_PostUpdatedFxState(){this._isPendingPostFxState||(this._isPendingPostFxState=!0,Promise.resolve().then(()=>this._DoPostUpdatedFxState()))}_DoPostUpdatedFxState(){const e={};for(const[t,i]of this._effects)e[t]=i.map(e=>e.GetState());this.PostToRuntime("fxstate",{fxstate:e}),this._isPendingPostFxState=!1}async _OnLoadState(e){const t=e.saveLoadMode;if(3!==t){const o=[];for(const a of this._audioInstances)a.IsMusic()&&1===t||!a.IsMusic()&&2===t?o.push(a):a.Release();this._audioInstances=o}for(const r of this._effects.values())for(const d of r)d.Release();this._effects.clear(),this._timeScale=e.timeScale,this._gameTime=e.gameTime;const i=e.listenerPos,s=(this._lastListenerPos[0]=i[0],this._lastListenerPos[1]=i[1],this._lastListenerPos[2]=i[2],this._audioContext.listener.setPosition(i[0],i[1],i[2]),e.listenerOrientation);if(Array.isArray(s)){for(let e=0;e<6;++e)this._lastListenerOrientation[e]=s[e];this._audioContext.listener.setOrientation(...this._lastListenerOrientation)}this._isSilent=e.isSilent,this._iRuntime.SetSilent(this._isSilent),this._masterVolume=e.masterVolume,this._destinationNode.gain.value=this._masterVolume;const n=[];for(const l of Object.values(e.effects))n.push(Promise.all(l.map(e=>this._AddEffect(e))));await Promise.all(n),await Promise.all(e.playing.map(e=>this._LoadAudioInstance(e,t))),this._MaybeStartTicking()}async _LoadAudioInstance(t,i){if(3!==i){const s=t.bufferOriginalUrl,n=t.bufferUrl,o=t.bufferType,a=t.isMusic,r=t.tags,d=t.isLooping,l=t.volume,h=t.playbackTime;if((!a||1!==i)&&(a||2!==i)){let e=null;try{e=await this._GetAudioInstance(s,n,o,r,a)}catch(i){return void console.error("[Construct] Audio: error loading audio state: ",i)}e.LoadPanState(t.pan),e.LoadStereoPanState(t.stereoPan),e.Play(d,l,h,0),t.isPlaying||e.Pause(),e._LoadAdditionalState(t)}}}_OnMicrophoneStream(e,t){this._microphoneSource&&this._microphoneSource.disconnect(),this._microphoneTag=t.toLowerCase(),this._microphoneSource=this._audioContext.createMediaStreamSource(e),this._microphoneSource.connect(this.GetDestinationForTag(this._microphoneTag))}_OnGetOutputStream(){return this._destMediaStreamNode||(this._destMediaStreamNode=this._audioContext.createMediaStreamDestination(),this._destinationNode.connect(this._destMediaStreamNode)),this._destMediaStreamNode.stream}async _OnOfflineRenderAudio(e){try{const t=e.time,i=this._audioContext.suspend(t);this._hasStartedOfflineRender?this._audioContext.resume():(this._audioContext.startRendering().then(e=>this._OnOfflineRenderCompleted(e)).catch(e=>this._OnOfflineRenderError(e)),this._hasStartedOfflineRender=!0),await i}catch(e){this._OnOfflineRenderError(e)}}_OnOfflineRenderFinish(){this._audioContext.resume()}_OnOfflineRenderCompleted(i){const s=[];for(let e=0,t=i.numberOfChannels;e<t;++e){const n=i.getChannelData(e);s.push(n.buffer)}this._iRuntime.PostToRuntimeComponent("runtime","offline-audio-render-completed",{duration:i.duration,length:i.length,numberOfChannels:i.numberOfChannels,sampleRate:i.sampleRate,channelData:s},null,s)}_OnOfflineRenderError(e){console.error("[Audio] Offline rendering error: ",e)}static EqualsNoCase(e,t){return e===t||e.normalize().toLowerCase()===t.normalize().toLowerCase()}static ToDegrees(e){return e*jh}static DbToLinearNoCap(e){return Math.pow(10,e/20)}static DbToLinear(e){return Math.max(Math.min(self.AudioDOMHandler.DbToLinearNoCap(e),1),0)}static LinearToDbNoCap(e){return Math.log(e)/Math.log(10)*20}static LinearToDb(e){return self.AudioDOMHandler.LinearToDbNoCap(Math.max(Math.min(e,1),0))}static e4(e,t){return 1-Math.exp(-t*e)}},self.RuntimeInterface.AddDOMHandlerClass(self.AudioDOMHandler)}self.C3AudioBuffer=class{constructor(e,t,i,s,n){this._audioDomHandler=e,this._originalUrl=t,this._url=i,this._type=s,this._isMusic=n,this._api="",this._loadState="not-loaded",this._loadPromise=null}Release(){this._loadState="not-loaded",this._audioDomHandler=null,this._loadPromise=null}WasReleased(){return!this._audioDomHandler}static Create(e,t,i,s,n){return new(!n||e.IsPlayMusicAsSound()?self.C3WebAudioBuffer:self.C3Html5AudioBuffer)(e,t,i,s,n)}CreateInstance(e){return new("html5"===this._api?self.C3Html5AudioInstance:self.C3WebAudioInstance)(this._audioDomHandler,this,e)}_Load(){}Load(){return this._loadPromise||(this._loadPromise=this._Load()),this._loadPromise}IsLoaded(){}IsLoadedAndDecoded(){}HasFailedToLoad(){return"failed"===this._loadState}GetAudioContext(){return this._audioDomHandler.GetAudioContext()}GetApi(){return this._api}GetOriginalUrl(){return this._originalUrl}GetUrl(){return this._url}GetContentType(){return this._type}IsMusic(){return this._isMusic}GetDuration(){}},self.C3Html5AudioBuffer=class extends self.C3AudioBuffer{constructor(e,t,i,s,n){super(e,t,i,s,n),this._api="html5",this._audioElem=new Audio,this._audioElem.crossOrigin="anonymous",this._audioElem.autoplay=!1,this._audioElem.preload="auto",this._loadResolve=null,this._loadReject=null,this._reachedCanPlayThrough=!1,this._audioElem.addEventListener("canplaythrough",()=>this._reachedCanPlayThrough=!0),this._outNode=this.GetAudioContext().createGain(),this._mediaSourceNode=null,this._audioElem.addEventListener("canplay",()=>{this._loadResolve&&(this._loadState="loaded",this._loadResolve(),this._loadResolve=null,this._loadReject=null),!this._mediaSourceNode&&this._audioElem&&(this._mediaSourceNode=this.GetAudioContext().createMediaElementSource(this._audioElem),this._mediaSourceNode.connect(this._outNode))}),this.onended=null,this._audioElem.addEventListener("ended",()=>{this.onended&&this.onended()}),this._audioElem.addEventListener("error",e=>this._OnError(e))}Release(){this._audioDomHandler.ReleaseInstancesForBuffer(this),this._outNode.disconnect(),this._outNode=null,this._mediaSourceNode.disconnect(),this._mediaSourceNode=null,this._audioElem&&!this._audioElem.paused&&this._audioElem.pause(),this.onended=null,this._audioElem=null,super.Release()}_Load(){return this._loadState="loading",new Promise((e,t)=>{this._loadResolve=e,this._loadReject=t,this._audioElem.src=this._url})}_OnError(e){console.error(`[Construct] Audio '${this._url}' error: `,e),this._loadReject&&(this._loadState="failed",this._loadReject(e),this._loadResolve=null,this._loadReject=null)}IsLoaded(){const e=4<=this._audioElem.readyState;return e&&(this._reachedCanPlayThrough=!0),e||this._reachedCanPlayThrough}IsLoadedAndDecoded(){return this.IsLoaded()}GetAudioElement(){return this._audioElem}GetOutputNode(){return this._outNode}GetDuration(){return this._audioElem.duration}},self.C3WebAudioBuffer=class extends self.C3AudioBuffer{constructor(e,t,i,s,n){super(e,t,i,s,n),this._api="webaudio",this._audioData=null,this._audioBuffer=null}Release(){this._audioDomHandler.ReleaseInstancesForBuffer(this),this._audioData=null,this._audioBuffer=null,super.Release()}async _Fetch(){if(this._audioData)return this._audioData;const e=this._audioDomHandler.GetRuntimeInterface();if("cordova"===e.GetExportType()&&e.IsRelativeURL(this._url)&&e.IsFileProtocol())this._audioData=await e.CordovaFetchLocalFileAsArrayBuffer(this._url);else if("playable-ad-single-file"===e.GetExportType()&&e.IsRelativeURL(this._url)){const t=e._PlayableAdFetchBlob(this._url);this._audioData=await t.arrayBuffer()}else{const i=await fetch(this._url);if(!i.ok)throw new Error(`error fetching audio data: ${i.status} `+i.statusText);this._audioData=await i.arrayBuffer()}}async _Decode(){if(this._audioBuffer)return this._audioBuffer;const e=this._audioDomHandler.GetAudioContext();this._audioBuffer=await e.decodeAudioData(this._audioData),this._audioData=null}async _Load(){try{this._loadState="loading",await this._Fetch(),this.WasReleased()||(await this._Decode(),this._loadState="loaded")}catch(e){this._loadState="failed",console.error(`[Construct] Failed to load audio '${this._url}': `,e)}}IsLoaded(){return!(!this._audioData&&!this._audioBuffer)}IsLoadedAndDecoded(){return!!this._audioBuffer}GetAudioBuffer(){return this._audioBuffer}GetDuration(){return this._audioBuffer?this._audioBuffer.duration:0}};{let n=0;self.C3AudioInstance=class{constructor(e,t,i){this._audioDomHandler=e,this._buffer=t,this._tags=i,this._aiId=n++,this._gainNode=this.GetAudioContext().createGain(),this._gainNode.connect(this.GetDestinationNode()),this._pannerNode=null,this._isPannerEnabled=!1,this._pannerPosition=[0,0,0],this._pannerOrientation=[0,0,0],this._pannerConeParams=[0,0,0],this._stereoPannerNode=null,this._isStereoPannerEnabled=!1,this._stereoPan=0,this._isStopped=!0,this._isPaused=!1,this._resumeMe=!1,this._isLooping=!1,this._volume=1,this._isMuted=!1,this._playbackRate=1;const s=this._audioDomHandler.GetTimeScaleMode();this._isTimescaled=1===s&&!this.IsMusic()||2===s,this._instUid=-1,this._fadeEndTime=-1,this._stopOnFadeEnd=!1}Release(){this._audioDomHandler=null,this._buffer=null,this._pannerNode&&(this._pannerNode.disconnect(),this._pannerNode=null),this._stereoPannerNode&&(this._stereoPannerNode.disconnect(),this._stereoPannerNode=null),this._gainNode.disconnect(),this._gainNode=null}GetAudioContext(){return this._audioDomHandler.GetAudioContext()}SetTags(e){this._tags=e}GetTags(){return this._tags}GetEffectTag(){return 0<this._tags.length?this._tags[0]:""}GetDestinationNode(){return this._audioDomHandler.GetDestinationForTag(this.GetEffectTag())}GetCurrentTime(){return this._isTimescaled?this._audioDomHandler.GetGameTime():performance.now()/1e3}GetOriginalUrl(){return this._buffer.GetOriginalUrl()}GetUrl(){return this._buffer.GetUrl()}GetContentType(){return this._buffer.GetContentType()}GetBuffer(){return this._buffer}IsMusic(){return this._buffer.IsMusic()}GetAiId(){return this._aiId}HasEnded(){}CanBeRecycled(){}IsPlaying(){return!this._isStopped&&!this._isPaused&&!this.HasEnded()}IsActive(){return!this._isStopped&&!this.HasEnded()}GetPlaybackTime(){}GetDuration(e){let t=this._buffer.GetDuration();return e&&(t/=this._playbackRate||.001),t}Play(e,t,i,s){}Stop(){}Pause(){}IsPaused(){return this._isPaused}Resume(){}SetVolume(e){this._volume=e,this._gainNode.gain.cancelScheduledValues(0),this._fadeEndTime=-1,this._gainNode.gain.value=this.GetOutputVolume()}FadeVolume(e,t,i){if(!this.IsMuted()){const s=this._gainNode.gain,n=(s.cancelScheduledValues(0),this._audioDomHandler.GetAudioCurrentTime()),o=n+t;s.setValueAtTime(s.value,n),s.linearRampToValueAtTime(e,o),this._volume=e,this._fadeEndTime=o,this._stopOnFadeEnd=i}}_UpdateVolume(){this.SetVolume(this._volume)}Tick(e){-1!==this._fadeEndTime&&e>=this._fadeEndTime&&(this._fadeEndTime=-1,this._stopOnFadeEnd&&this.Stop(),this._audioDomHandler.PostTrigger("fade-ended",this._tags,this._aiId))}GetOutputVolume(){const e=this._volume;return isFinite(e)?e:0}SetMuted(e){this._isMuted!==(e=!!e)&&(this._isMuted=e,this._UpdateMuted())}IsMuted(){return this._isMuted}IsSilent(){return this._audioDomHandler.IsSilent()}_UpdateMuted(){}SetLooping(e){}IsLooping(){return this._isLooping}SetPlaybackRate(e){this._playbackRate!==e&&(this._playbackRate=e,this._UpdatePlaybackRate())}_UpdatePlaybackRate(){}GetPlaybackRate(){return this._playbackRate}Seek(e){}SetSuspended(e){}SetPannerEnabled(e){this._isPannerEnabled!==(e=!!e)&&(this._isPannerEnabled=e,(this._isPannerEnabled?(this.SetStereoPannerEnabled(!1),this._pannerNode||(this._pannerNode=this.GetAudioContext().createPanner(),this._pannerNode.panningModel=this._audioDomHandler.GetPanningModel(),this._pannerNode.distanceModel=this._audioDomHandler.GetDistanceModel(),this._pannerNode.refDistance=this._audioDomHandler.GetReferenceDistance(),this._pannerNode.maxDistance=this._audioDomHandler.GetMaxDistance(),this._pannerNode.rolloffFactor=this._audioDomHandler.GetRolloffFactor()),this._gainNode.disconnect(),this._gainNode.connect(this._pannerNode),this._pannerNode):(this._pannerNode.disconnect(),this._gainNode.disconnect(),this._gainNode)).connect(this.GetDestinationNode()))}SetPan(e,t,i,s,n,o,a){if(this._isPannerEnabled){this.SetPanXYZA(e,t,i,s);const r=self.AudioDOMHandler.ToDegrees;this._pannerConeParams[0]!==r(n)&&(this._pannerConeParams[0]=r(n),this._pannerNode.coneInnerAngle=r(n)),this._pannerConeParams[1]!==r(o)&&(this._pannerConeParams[1]=r(o),this._pannerNode.coneOuterAngle=r(o)),this._pannerConeParams[2]!==a&&(this._pannerConeParams[2]=a,this._pannerNode.coneOuterGain=a)}}SetPanXYZA(e,t,i,s){if(this._isPannerEnabled){const n=this._pannerPosition,o=this._pannerOrientation,a=Math.cos(s),r=Math.sin(s);n[0]===e&&n[1]===t&&n[2]===i||(n[0]=e,n[1]=t,n[2]=i,this._pannerNode.setPosition(...n)),o[0]===a&&o[1]===r&&0===o[2]||(o[0]=a,o[1]=r,o[2]=0,this._pannerNode.setOrientation(...o))}}SetStereoPannerEnabled(e){this._isStereoPannerEnabled!==(e=!!e)&&(this._isStereoPannerEnabled=e,(this._isStereoPannerEnabled?(this.SetPannerEnabled(!1),this._stereoPannerNode=this.GetAudioContext().createStereoPanner(),this._gainNode.disconnect(),this._gainNode.connect(this._stereoPannerNode),this._stereoPannerNode):(this._stereoPannerNode.disconnect(),this._stereoPannerNode=null,this._gainNode.disconnect(),this._gainNode)).connect(this.GetDestinationNode()))}SetStereoPan(e){this._isStereoPannerEnabled&&this._stereoPan!==e&&(this._stereoPannerNode.pan.value=e,this._stereoPan=e)}SetUID(e){this._instUid=e}GetUID(){return this._instUid}GetResumePosition(){}Reconnect(e){const t=this._stereoPannerNode||this._pannerNode||this._gainNode;t.disconnect(),t.connect(e)}GetState(){return{aiid:this.GetAiId(),tags:this._tags,duration:this.GetDuration(),volume:-1===this._fadeEndTime?this._volume:this._gainNode.gain.value,isPlaying:this.IsPlaying(),playbackTime:this.GetPlaybackTime(),playbackRate:this.GetPlaybackRate(),uid:this._instUid,bufferOriginalUrl:this.GetOriginalUrl(),bufferUrl:"",bufferType:this.GetContentType(),isMusic:this.IsMusic(),isLooping:this.IsLooping(),isMuted:this.IsMuted(),resumePosition:this.GetResumePosition(),pan:this.GetPanState(),stereoPan:this.GetStereoPanState()}}_LoadAdditionalState(e){this.SetPlaybackRate(e.playbackRate),this.SetMuted(e.isMuted)}GetPanState(){if(!this._pannerNode)return null;const e=this._pannerNode;return{pos:this._pannerPosition,orient:this._pannerOrientation,cia:e.coneInnerAngle,coa:e.coneOuterAngle,cog:e.coneOuterGain,uid:this._instUid}}LoadPanState(e){if(e){this.SetPannerEnabled(!0);const t=this._pannerNode,i=e.pos,s=(this._pannerPosition[0]=i[0],this._pannerPosition[1]=i[1],this._pannerPosition[2]=i[2],e.orient);this._pannerOrientation[0]=s[0],this._pannerOrientation[1]=s[1],this._pannerOrientation[2]=s[2],t.setPosition(...this._pannerPosition),t.setOrientation(...this._pannerOrientation),this._pannerConeParams[0]=e.cia,this._pannerConeParams[1]=e.coa,this._pannerConeParams[2]=e.cog,t.coneInnerAngle=e.cia,t.coneOuterAngle=e.coa,t.coneOuterGain=e.cog,this._instUid=e.uid}else this.SetPannerEnabled(!1)}GetStereoPanState(){return this._stereoPannerNode?this._stereoPan:null}LoadStereoPanState(e){"number"!=typeof e?this.SetStereoPannerEnabled(!1):(this.SetStereoPannerEnabled(!0),this.SetStereoPan(e))}}}self.C3Html5AudioInstance=class extends self.C3AudioInstance{constructor(e,t,i){super(e,t,i),this._buffer.GetOutputNode().connect(this._gainNode),this._buffer.onended=()=>this._OnEnded()}Release(){this.Stop(),this._buffer.GetOutputNode().disconnect(),super.Release()}GetAudioElement(){return this._buffer.GetAudioElement()}_OnEnded(){this._isStopped=!0,this._instUid=-1,this._audioDomHandler.PostTrigger("ended",this._tags,this._aiId)}HasEnded(){return this.GetAudioElement().ended}CanBeRecycled(){return!!this._isStopped||this.HasEnded()}GetPlaybackTime(){let e=this.GetAudioElement().currentTime;return this._isLooping?e:Math.min(e,this.GetDuration())}Play(e,t,i,s){const n=this.GetAudioElement();if(1!==n.playbackRate&&(n.playbackRate=1),n.loop!==e&&(n.loop=e),this.SetVolume(t),this._isMuted=!1,n.muted&&(n.muted=!1),n.currentTime!==i)try{n.currentTime=i}catch(e){console.warn(`[Construct] Exception seeking audio '${this._buffer.GetUrl()}' to position '${i}': `,e)}this._audioDomHandler.TryPlayMedia(n),this._isStopped=!1,this._isPaused=!1,this._isLooping=e,this._playbackRate=1}Stop(){const e=this.GetAudioElement();e.paused||e.pause(),this._audioDomHandler.RemovePendingPlay(e),this._isStopped=!0,this._isPaused=!1,this._instUid=-1}Pause(){if(!(this._isPaused||this._isStopped||this.HasEnded())){const e=this.GetAudioElement();e.paused||e.pause(),this._audioDomHandler.RemovePendingPlay(e),this._isPaused=!0}}Resume(){!this._isPaused||this._isStopped||this.HasEnded()||(this._audioDomHandler.TryPlayMedia(this.GetAudioElement()),this._isPaused=!1)}_UpdateMuted(){this.GetAudioElement().muted=this._isMuted||this.IsSilent()}SetLooping(e){this._isLooping!==(e=!!e)&&(this._isLooping=e,this.GetAudioElement().loop=e)}_UpdatePlaybackRate(){let t=this._playbackRate;this._isTimescaled&&(t*=this._audioDomHandler.GetTimeScale());try{this.GetAudioElement().playbackRate=t}catch(e){console.warn(`[Construct] Unable to set playback rate '${t}':`,e)}}Seek(t){if(!this._isStopped&&!this.HasEnded())try{this.GetAudioElement().currentTime=t}catch(e){console.warn(`[Construct] Error seeking audio to '${t}': `,e)}}GetResumePosition(){return this.GetPlaybackTime()}SetSuspended(e){e?this.IsPlaying()?(this.GetAudioElement().pause(),this._resumeMe=!0):this._resumeMe=!1:this._resumeMe&&(this._audioDomHandler.TryPlayMedia(this.GetAudioElement()),this._resumeMe=!1)}},self.C3WebAudioInstance=class extends self.C3AudioInstance{constructor(e,t,i){super(e,t,i),this._bufferSource=null,this._onended_handler=e=>this._OnEnded(e),this._hasPlaybackEnded=!0,this._activeSource=null,this._playStartTime=0,this._playFromSeekPos=0,this._resumePosition=0,this._muteVol=1}Release(){this.Stop(),this._ReleaseBufferSource(),this._onended_handler=null,super.Release()}_ReleaseBufferSource(){this._bufferSource&&(this._bufferSource.onended=null,this._bufferSource.disconnect(),this._bufferSource.buffer=null),this._bufferSource=null,this._activeSource=null}_OnEnded(e){this._isPaused||this._resumeMe||e.target===this._activeSource&&(this._hasPlaybackEnded=!0,this._isStopped=!0,this._instUid=-1,this._ReleaseBufferSource(),this._audioDomHandler.PostTrigger("ended",this._tags,this._aiId))}HasEnded(){return!(!this._isStopped&&this._bufferSource&&this._bufferSource.loop||this._isPaused)&&this._hasPlaybackEnded}CanBeRecycled(){return!(this._bufferSource&&!this._isStopped)||this.HasEnded()}GetPlaybackTime(){let e=0;return e=this._isPaused?this._resumePosition:this._playFromSeekPos+(this.GetCurrentTime()-this._playStartTime)*this._playbackRate,this._isLooping?e:Math.min(e,this.GetDuration())}Play(e,t,i,s){this._isMuted=!1,this._muteVol=1,this.SetVolume(t),this._ReleaseBufferSource(),this._bufferSource=this.GetAudioContext().createBufferSource(),this._bufferSource.buffer=this._buffer.GetAudioBuffer(),this._bufferSource.connect(this._gainNode),this._activeSource=this._bufferSource,this._bufferSource.onended=this._onended_handler,this._bufferSource.loop=e,this._bufferSource.start(s,i),this._hasPlaybackEnded=!1,this._isStopped=!1,this._isPaused=!1,this._isLooping=e,this._playbackRate=1,this._playStartTime=this.GetCurrentTime(),this._playFromSeekPos=i}Stop(){if(this._bufferSource)try{this._bufferSource.stop(0)}catch(e){}this._isStopped=!0,this._isPaused=!1,this._instUid=-1}Pause(){this._isPaused||this._isStopped||this.HasEnded()||(this._resumePosition=this.GetPlaybackTime(),this._isLooping&&(this._resumePosition%=this.GetDuration()),this._isPaused=!0,this._bufferSource.stop(0))}Resume(){!this._isPaused||this._isStopped||this.HasEnded()||(this._ReleaseBufferSource(),this._bufferSource=this.GetAudioContext().createBufferSource(),this._bufferSource.buffer=this._buffer.GetAudioBuffer(),this._bufferSource.connect(this._gainNode),this._activeSource=this._bufferSource,this._bufferSource.onended=this._onended_handler,this._bufferSource.loop=this._isLooping,this._UpdateVolume(),this._UpdatePlaybackRate(),this._bufferSource.start(0,this._resumePosition),this._playStartTime=this.GetCurrentTime(),this._playFromSeekPos=this._resumePosition,this._isPaused=!1)}GetOutputVolume(){return super.GetOutputVolume()*this._muteVol}_UpdateMuted(){this._muteVol=this._isMuted||this.IsSilent()?0:1,this._UpdateVolume()}SetLooping(e){this._isLooping!==(e=!!e)&&(this._isLooping=e,this._bufferSource)&&(this._bufferSource.loop=e)}_UpdatePlaybackRate(){let e=this._playbackRate;this._isTimescaled&&(e*=this._audioDomHandler.GetTimeScale()),this._bufferSource&&(this._bufferSource.playbackRate.value=e)}Seek(e){this._isStopped||this.HasEnded()||(this._isPaused?this._resumePosition=e:(this.Pause(),this._resumePosition=e,this.Resume()))}GetResumePosition(){return this._resumePosition}SetSuspended(e){e?this.IsPlaying()?(this._resumeMe=!0,this._resumePosition=this.GetPlaybackTime(),this._isLooping&&(this._resumePosition%=this.GetDuration()),this._bufferSource.stop(0)):this._resumeMe=!1:this._resumeMe&&(this._ReleaseBufferSource(),this._bufferSource=this.GetAudioContext().createBufferSource(),this._bufferSource.buffer=this._buffer.GetAudioBuffer(),this._bufferSource.connect(this._gainNode),this._activeSource=this._bufferSource,this._bufferSource.onended=this._onended_handler,this._bufferSource.loop=this._isLooping,this._UpdateVolume(),this._UpdatePlaybackRate(),this._bufferSource.start(0,this._resumePosition),this._playStartTime=this.GetCurrentTime(),this._playFromSeekPos=this._resumePosition,this._resumeMe=!1)}_LoadAdditionalState(e){super._LoadAdditionalState(e),this._resumePosition=e.resumePosition}};{class el{constructor(e){this._audioDomHandler=e,this._audioContext=e.GetAudioContext(),this._index=-1,this._tag="",this._type="",this._params=null}Release(){this._audioContext=null}_SetIndex(e){this._index=e}GetIndex(){return this._index}_SetTag(e){this._tag=e}GetTag(){return this._tag}CreateGain(){return this._audioContext.createGain()}GetInputNode(){}ConnectTo(e){}SetAudioParam(e,t,i,s){if(e.cancelScheduledValues(0),0===s)e.value=t;else{const n=this._audioContext.currentTime;switch(s+=n,i){case 0:e.setValueAtTime(t,s);break;case 1:e.setValueAtTime(e.value,n),e.linearRampToValueAtTime(t,s);break;case 2:e.setValueAtTime(e.value,n),e.exponentialRampToValueAtTime(t,s)}}}GetState(){return{type:this._type,tag:this._tag,params:this._params}}}self.C3AudioFilterFX=class extends el{constructor(e,t,i,s,n,o,a){super(e),this._type="filter",this._params=[t,i,s,n,o,a],this._inputNode=this.CreateGain(),this._wetNode=this.CreateGain(),this._wetNode.gain.value=a,this._dryNode=this.CreateGain(),this._dryNode.gain.value=1-a,this._filterNode=this._audioContext.createBiquadFilter(),this._filterNode.type=t,this._filterNode.frequency.value=i,this._filterNode.detune.value=s,this._filterNode.Q.value=n,this._filterNode.gain.vlaue=o,this._inputNode.connect(this._filterNode),this._inputNode.connect(this._dryNode),this._filterNode.connect(this._wetNode)}Release(){this._inputNode.disconnect(),this._filterNode.disconnect(),this._wetNode.disconnect(),this._dryNode.disconnect(),super.Release()}ConnectTo(e){this._wetNode.disconnect(),this._wetNode.connect(e),this._dryNode.disconnect(),this._dryNode.connect(e)}GetInputNode(){return this._inputNode}SetParam(e,t,i,s){switch(e){case 0:t=Math.max(Math.min(t/100,1),0),this._params[5]=t,this.SetAudioParam(this._wetNode.gain,t,i,s),this.SetAudioParam(this._dryNode.gain,1-t,i,s);break;case 1:this._params[1]=t,this.SetAudioParam(this._filterNode.frequency,t,i,s);break;case 2:this._params[2]=t,this.SetAudioParam(this._filterNode.detune,t,i,s);break;case 3:this._params[3]=t,this.SetAudioParam(this._filterNode.Q,t,i,s);break;case 4:this._params[4]=t,this.SetAudioParam(this._filterNode.gain,t,i,s)}}},self.C3AudioDelayFX=class extends el{constructor(e,t,i,s){super(e),this._type="delay",this._params=[t,i,s],this._inputNode=this.CreateGain(),this._wetNode=this.CreateGain(),this._wetNode.gain.value=s,this._dryNode=this.CreateGain(),this._dryNode.gain.value=1-s,this._mainNode=this.CreateGain(),this._delayNode=this._audioContext.createDelay(t),this._delayNode.delayTime.value=t,this._delayGainNode=this.CreateGain(),this._delayGainNode.gain.value=i,this._inputNode.connect(this._mainNode),this._inputNode.connect(this._dryNode),this._mainNode.connect(this._wetNode),this._mainNode.connect(this._delayNode),this._delayNode.connect(this._delayGainNode),this._delayGainNode.connect(this._mainNode)}Release(){this._inputNode.disconnect(),this._wetNode.disconnect(),this._dryNode.disconnect(),this._mainNode.disconnect(),this._delayNode.disconnect(),this._delayGainNode.disconnect(),super.Release()}ConnectTo(e){this._wetNode.disconnect(),this._wetNode.connect(e),this._dryNode.disconnect(),this._dryNode.connect(e)}GetInputNode(){return this._inputNode}SetParam(e,t,i,s){const n=self.AudioDOMHandler.DbToLinear;switch(e){case 0:t=Math.max(Math.min(t/100,1),0),this._params[2]=t,this.SetAudioParam(this._wetNode.gain,t,i,s),this.SetAudioParam(this._dryNode.gain,1-t,i,s);break;case 4:this._params[1]=n(t),this.SetAudioParam(this._delayGainNode.gain,n(t),i,s);break;case 5:this._params[0]=t,this.SetAudioParam(this._delayNode.delayTime,t,i,s)}}},self.C3AudioConvolveFX=class extends el{constructor(e,t,i,s){super(e),this._type="convolution",this._params=[i,s],this._bufferOriginalUrl="",this._bufferUrl="",this._bufferType="",this._inputNode=this.CreateGain(),this._wetNode=this.CreateGain(),this._wetNode.gain.value=s,this._dryNode=this.CreateGain(),this._dryNode.gain.value=1-s,this._convolveNode=this._audioContext.createConvolver(),this._convolveNode.normalize=i,this._convolveNode.buffer=t,this._inputNode.connect(this._convolveNode),this._inputNode.connect(this._dryNode),this._convolveNode.connect(this._wetNode)}Release(){this._inputNode.disconnect(),this._convolveNode.disconnect(),this._wetNode.disconnect(),this._dryNode.disconnect(),super.Release()}ConnectTo(e){this._wetNode.disconnect(),this._wetNode.connect(e),this._dryNode.disconnect(),this._dryNode.connect(e)}GetInputNode(){return this._inputNode}SetParam(e,t,i,s){0===e&&(t=Math.max(Math.min(t/100,1),0),this._params[1]=t,this.SetAudioParam(this._wetNode.gain,t,i,s),this.SetAudioParam(this._dryNode.gain,1-t,i,s))}_SetBufferInfo(e,t,i){this._bufferOriginalUrl=e,this._bufferUrl=t,this._bufferType=i}GetState(){const e=super.GetState();return e.bufferOriginalUrl=this._bufferOriginalUrl,e.bufferUrl="",e.bufferType=this._bufferType,e}},self.C3AudioFlangerFX=class extends el{constructor(e,t,i,s,n,o){super(e),this._type="flanger",this._params=[t,i,s,n,o],this._inputNode=this.CreateGain(),this._dryNode=this.CreateGain(),this._dryNode.gain.value=1-o/2,this._wetNode=this.CreateGain(),this._wetNode.gain.value=o/2,this._feedbackNode=this.CreateGain(),this._feedbackNode.gain.value=n,this._delayNode=this._audioContext.createDelay(t+i),this._delayNode.delayTime.value=t,this._oscNode=this._audioContext.createOscillator(),this._oscNode.frequency.value=s,this._oscGainNode=this.CreateGain(),this._oscGainNode.gain.value=i,this._inputNode.connect(this._delayNode),this._inputNode.connect(this._dryNode),this._delayNode.connect(this._wetNode),this._delayNode.connect(this._feedbackNode),this._feedbackNode.connect(this._delayNode),this._oscNode.connect(this._oscGainNode),this._oscGainNode.connect(this._delayNode.delayTime),this._oscNode.start(0)}Release(){this._oscNode.stop(0),this._inputNode.disconnect(),this._delayNode.disconnect(),this._oscNode.disconnect(),this._oscGainNode.disconnect(),this._dryNode.disconnect(),this._wetNode.disconnect(),this._feedbackNode.disconnect(),super.Release()}ConnectTo(e){this._wetNode.disconnect(),this._wetNode.connect(e),this._dryNode.disconnect(),this._dryNode.connect(e)}GetInputNode(){return this._inputNode}SetParam(e,t,i,s){switch(e){case 0:t=Math.max(Math.min(t/100,1),0),this._params[4]=t,this.SetAudioParam(this._wetNode.gain,t/2,i,s),this.SetAudioParam(this._dryNode.gain,1-t/2,i,s);break;case 6:this._params[1]=t/1e3,this.SetAudioParam(this._oscGainNode.gain,t/1e3,i,s);break;case 7:this._params[2]=t,this.SetAudioParam(this._oscNode.frequency,t,i,s);break;case 8:this._params[3]=t/100,this.SetAudioParam(this._feedbackNode.gain,t/100,i,s)}}},self.C3AudioPhaserFX=class extends el{constructor(e,t,i,s,n,o,a){super(e),this._type="phaser",this._params=[t,i,s,n,o,a],this._inputNode=this.CreateGain(),this._dryNode=this.CreateGain(),this._dryNode.gain.value=1-a/2,this._wetNode=this.CreateGain(),this._wetNode.gain.value=a/2,this._filterNode=this._audioContext.createBiquadFilter(),this._filterNode.type="allpass",this._filterNode.frequency.value=t,this._filterNode.detune.value=i,this._filterNode.Q.value=s,this._oscNode=this._audioContext.createOscillator(),this._oscNode.frequency.value=o,this._oscGainNode=this.CreateGain(),this._oscGainNode.gain.value=n,this._inputNode.connect(this._filterNode),this._inputNode.connect(this._dryNode),this._filterNode.connect(this._wetNode),this._oscNode.connect(this._oscGainNode),this._oscGainNode.connect(this._filterNode.frequency),this._oscNode.start(0)}Release(){this._oscNode.stop(0),this._inputNode.disconnect(),this._filterNode.disconnect(),this._oscNode.disconnect(),this._oscGainNode.disconnect(),this._dryNode.disconnect(),this._wetNode.disconnect(),super.Release()}ConnectTo(e){this._wetNode.disconnect(),this._wetNode.connect(e),this._dryNode.disconnect(),this._dryNode.connect(e)}GetInputNode(){return this._inputNode}SetParam(e,t,i,s){switch(e){case 0:t=Math.max(Math.min(t/100,1),0),this._params[5]=t,this.SetAudioParam(this._wetNode.gain,t/2,i,s),this.SetAudioParam(this._dryNode.gain,1-t/2,i,s);break;case 1:this._params[0]=t,this.SetAudioParam(this._filterNode.frequency,t,i,s);break;case 2:this._params[1]=t,this.SetAudioParam(this._filterNode.detune,t,i,s);break;case 3:this._params[2]=t,this.SetAudioParam(this._filterNode.Q,t,i,s);break;case 6:this._params[3]=t,this.SetAudioParam(this._oscGainNode.gain,t,i,s);break;case 7:this._params[4]=t,this.SetAudioParam(this._oscNode.frequency,t,i,s)}}},self.C3AudioGainFX=class extends el{constructor(e,t){super(e),this._type="gain",this._params=[t],this._node=this.CreateGain(),this._node.gain.value=t}Release(){this._node.disconnect(),super.Release()}ConnectTo(e){this._node.disconnect(),this._node.connect(e)}GetInputNode(){return this._node}SetParam(e,t,i,s){const n=self.AudioDOMHandler.DbToLinear;4===e&&(this._params[0]=n(t),this.SetAudioParam(this._node.gain,n(t),i,s))}},self.C3AudioStereoPanFX=class extends el{constructor(e,t){super(e),this._type="stereopan",this._params=[t],this._node=this._audioContext.createStereoPanner(),this._node.pan.value=t}Release(){this._node.disconnect(),super.Release()}ConnectTo(e){this._node.disconnect(),this._node.connect(e)}GetInputNode(){return this._node}SetParam(e,t,i,s){t=Math.min(Math.max(t/100,-1),1),9===e&&(this._params[0]=t,this.SetAudioParam(this._node.pan,t,i,s))}},self.C3AudioTremoloFX=class extends el{constructor(e,t,i){super(e),this._type="tremolo",this._params=[t,i],this._node=this.CreateGain(),this._node.gain.value=1-i/2,this._oscNode=this._audioContext.createOscillator(),this._oscNode.frequency.value=t,this._oscGainNode=this.CreateGain(),this._oscGainNode.gain.value=i/2,this._oscNode.connect(this._oscGainNode),this._oscGainNode.connect(this._node.gain),this._oscNode.start(0)}Release(){this._oscNode.stop(0),this._oscNode.disconnect(),this._oscGainNode.disconnect(),this._node.disconnect(),super.Release()}ConnectTo(e){this._node.disconnect(),this._node.connect(e)}GetInputNode(){return this._node}SetParam(e,t,i,s){switch(e){case 0:t=Math.max(Math.min(t/100,1),0),this._params[1]=t,this.SetAudioParam(this._node.gain,1-t/2,i,s),this.SetAudioParam(this._oscGainNode.gain,t/2,i,s);break;case 7:this._params[0]=t,this.SetAudioParam(this._oscNode.frequency,t,i,s)}}},self.C3AudioRingModFX=class extends el{constructor(e,t,i){super(e),this._type="ringmod",this._params=[t,i],this._inputNode=this.CreateGain(),this._wetNode=this.CreateGain(),this._wetNode.gain.value=i,this._dryNode=this.CreateGain(),this._dryNode.gain.value=1-i,this._ringNode=this.CreateGain(),this._ringNode.gain.value=0,this._oscNode=this._audioContext.createOscillator(),this._oscNode.frequency.value=t,this._oscNode.connect(this._ringNode.gain),this._oscNode.start(0),this._inputNode.connect(this._ringNode),this._inputNode.connect(this._dryNode),this._ringNode.connect(this._wetNode)}Release(){this._oscNode.stop(0),this._oscNode.disconnect(),this._ringNode.disconnect(),this._inputNode.disconnect(),this._wetNode.disconnect(),this._dryNode.disconnect(),super.Release()}ConnectTo(e){this._wetNode.disconnect(),this._wetNode.connect(e),this._dryNode.disconnect(),this._dryNode.connect(e)}GetInputNode(){return this._inputNode}SetParam(e,t,i,s){switch(e){case 0:t=Math.max(Math.min(t/100,1),0),this._params[1]=t,this.SetAudioParam(this._wetNode.gain,t,i,s),this.SetAudioParam(this._dryNode.gain,1-t,i,s);break;case 7:this._params[0]=t,this.SetAudioParam(this._oscNode.frequency,t,i,s)}}},self.C3AudioDistortionFX=class extends el{constructor(e,t,i,s,n,o){super(e),this._type="distortion",this._params=[t,i,s,n,o],this._inputNode=this.CreateGain(),this._preGain=this.CreateGain(),this._postGain=this.CreateGain(),this._SetDrive(s,n),this._wetNode=this.CreateGain(),this._wetNode.gain.value=o,this._dryNode=this.CreateGain(),this._dryNode.gain.value=1-o,this._waveShaper=this._audioContext.createWaveShaper(),this._curve=new Float32Array(65536),this._GenerateColortouchCurve(t,i),this._waveShaper.curve=this._curve,this._inputNode.connect(this._preGain),this._inputNode.connect(this._dryNode),this._preGain.connect(this._waveShaper),this._waveShaper.connect(this._postGain),this._postGain.connect(this._wetNode)}Release(){this._inputNode.disconnect(),this._preGain.disconnect(),this._waveShaper.disconnect(),this._postGain.disconnect(),this._wetNode.disconnect(),this._dryNode.disconnect(),super.Release()}_SetDrive(e,t){this._preGain.gain.value=e=e<.01?.01:e,this._postGain.gain.value=Math.pow(1/e,.6)*t}_GenerateColortouchCurve(i,s){const n=32768;for(let t=0;t<n;++t){let e=t/n;e=this._Shape(e,i,s),this._curve[n+t]=e,this._curve[n-t-1]=-e}}_Shape(e,t,i){const s=1.05*i*t,n=s-t,o=e<0?-1:1,a=e<0?-e:e;let r=a<t?a:t+n*self.AudioDOMHandler.e4(a-t,1/n);return r*o}ConnectTo(e){this._wetNode.disconnect(),this._wetNode.connect(e),this._dryNode.disconnect(),this._dryNode.connect(e)}GetInputNode(){return this._inputNode}SetParam(e,t,i,s){0===e&&(t=Math.max(Math.min(t/100,1),0),this._params[4]=t,this.SetAudioParam(this._wetNode.gain,t,i,s),this.SetAudioParam(this._dryNode.gain,1-t,i,s))}},self.C3AudioCompressorFX=class extends el{constructor(e,t,i,s,n,o){super(e),this._type="compressor",this._params=[t,i,s,n,o],this._node=this._audioContext.createDynamicsCompressor(),this._node.threshold.value=t,this._node.knee.value=i,this._node.ratio.value=s,this._node.attack.value=n,this._node.release.value=o}Release(){this._node.disconnect(),super.Release()}ConnectTo(e){this._node.disconnect(),this._node.connect(e)}GetInputNode(){return this._node}SetParam(e,t,i,s){}},self.C3AudioAnalyserFX=class extends el{constructor(e,t,i){super(e),this._type="analyser",this._params=[t,i],this._node=this._audioContext.createAnalyser(),this._node.fftSize=t,this._node.smoothingTimeConstant=i,this._freqBins=new Float32Array(this._node.frequencyBinCount),this._signal=new Uint8Array(t),this._peak=0,this._rms=0,this._audioDomHandler._AddAnalyser(this)}Release(){this._audioDomHandler._RemoveAnalyser(this),this._node.disconnect(),super.Release()}Tick(){this._node.getFloatFrequencyData(this._freqBins),this._node.getByteTimeDomainData(this._signal);const e=this._node.fftSize;let i=this._peak=0;for(let t=0;t<e;++t){let e=(this._signal[t]-128)/128;e<0&&(e=-e),this._peak<e&&(this._peak=e),i+=e*e}const t=self.AudioDOMHandler.LinearToDb;this._peak=t(this._peak),this._rms=t(Math.sqrt(i/e))}ConnectTo(e){this._node.disconnect(),this._node.connect(e)}GetInputNode(){return this._node}SetParam(e,t,i,s){}GetData(){return{tag:this.GetTag(),index:this.GetIndex(),peak:this._peak,rms:this._rms,binCount:this._node.frequencyBinCount,freqBins:this._freqBins}}}}if(window.C3_Is_Supported){const Un=!0;window.c3_runtimeInterface=new self.RuntimeInterface({useWorker:Un,workerMainUrl:"workermain.js",runtimeScriptList:["scripts/c3main.js"],scriptFolder:"scripts/",exportType:"html5"})}
| ver. 1.4 |
Github
|
.
| PHP 8.2.29 | Генераци� �траницы: 0 |
proxy
|
phpinfo
|
�а�тройка