var gdjs;(function(n){const c=new n.Logger("Game manager"),h=u=>new Promise(e=>setTimeout(e,u)),g=u=>u.usedResources.map(e=>e.name);let l=null;const m=()=>{if(l)return l;l=[];try{new CompressionStream("gzip"),l.push("cs:gzip")}catch{}try{new CompressionStream("deflate"),l.push("cs:deflate")}catch{}return l},p=()=>{try{const e=new URL(location.href).searchParams.get("runtimeGameStatus");if(!e)return null;const t=JSON.parse(e);return{isPaused:!!t.isPaused,isInGameEdition:!!t.isInGameEdition,sceneName:""+t.sceneName,injectedExternalLayoutName:""+t.injectedExternalLayoutName,skipCreatingInstancesFromScene:!!t.skipCreatingInstancesFromScene,eventsBasedObjectType:t.eventsBasedObjectType,eventsBasedObjectVariantName:t.eventsBasedObjectVariantName,editorId:t.editorId,editorCamera3D:t.editorCamera3D}}catch{return null}};class _{constructor(e,t){this._sceneAndExtensionsData=[];this._displayedLoadingScreen=null;this._notifyScenesForGameResolutionResize=!1;this._paused=!1;this._hasJustResumed=!1;this._sessionMetricsInitialized=!1;this._disableMetrics=!1;this._wasDisposed=!1;this.getPlatformInfo=()=>({isCordova:!!window.cordova,devicePlatform:typeof device!="undefined"&&device.platform||"",navigatorPlatform:typeof navigator!="undefined"?navigator.platform:"",hasTouch:typeof navigator!="undefined"?!!navigator.maxTouchPoints&&navigator.maxTouchPoints>2:!1,supportedCompressionMethods:m()});if(this._options=t||{},this._isPreview=this._options.isPreview||!1,this._isPreview){const s=p();s&&(this._options.initialRuntimeGameStatus=s)}this._isInGameEdition=this._options.initialRuntimeGameStatus?.isInGameEdition||!1,this._variables=new n.VariablesContainer(e.variables),this._variablesByExtensionName=new Map;for(const s of e.eventsFunctionsExtensions)s.globalVariables.length>0&&this._variablesByExtensionName.set(s.name,new n.VariablesContainer(s.globalVariables));this._eventsBasedObjectDatas=new Map,this._data=e,this._updateSceneAndExtensionsData(),n.Variable.useDeprecatedZeroAsDefaultStringVariable=!!e.properties.useDeprecatedZeroAsDefaultStringVariable,this._sceneResourcesPreloading=this._data.properties.sceneResourcesPreloading||"at-startup",this._sceneResourcesUnloading=this._data.properties.sceneResourcesUnloading||"never",this._resourcesLoader=new n.ResourceLoader(this,e.resources.resources,g(e),e.layouts),this._inGameEditor=this._isInGameEdition?new n.InGameEditor(this,e,this._options.inGameEditorSettings||null):null,this._debuggerClient=n.DebuggerClient?new n.DebuggerClient(this):null,this._effectsManager=new n.EffectsManager,this._maxFPS=this._data.properties.maxFPS,this._minFPS=this._data.properties.minFPS,this._gameResolutionWidth=this._data.properties.windowWidth,this._gameResolutionHeight=this._data.properties.windowHeight,this._originalWidth=this._gameResolutionWidth,this._originalHeight=this._gameResolutionHeight,this._resizeMode=this._data.properties.sizeOnStartupMode,this._adaptGameResolutionAtRuntime=this._data.properties.adaptGameResolutionAtRuntime,this._scaleMode=e.properties.scaleMode||"linear",this._pixelsRounding=this._data.properties.pixelsRounding,this._antialiasingMode=this._data.properties.antialiasingMode,this._isAntialisingEnabledOnMobile=this._data.properties.antialisingEnabledOnMobile,this._renderer=new n.RuntimeGameRenderer(this,this._options.forceFullscreen||!1),this._watermark=new n.watermark.RuntimeWatermark(this,e.properties.authorUsernames,this._data.properties.watermark),this._sceneStack=new n.SceneStack(this),this._inputManager=new n.InputManager,this._captureManager=n.CaptureManager?new n.CaptureManager(this._renderer,this._options.captureOptions||{}):null,this._sessionId=null,this._playerId=null,this._embeddedResourcesMappings=new Map,this._updateEmbeddedResourcesMappings(),this.isUsingGDevelopDevelopmentEnvironment()&&c.info("This game will run on the development version of GDevelop APIs.")}setProjectData(e){this._inGameEditor&&this._inGameEditor.onProjectDataChange(e),this._data=e,this._updateEmbeddedResourcesMappings(),this._updateSceneAndExtensionsData(),this._resourcesLoader.setResources(e.resources.resources,g(e),e.layouts)}_updateSceneAndExtensionsData(){const e=this._data.eventsFunctionsExtensions.filter(t=>t.sceneVariables.length>0);if(this._sceneAndExtensionsData=this._data.layouts.map(t=>({sceneData:t,usedExtensionsWithVariablesData:e})),this._eventsBasedObjectDatas.clear(),this._data.eventsFunctionsExtensions)for(const t of this._data.eventsFunctionsExtensions)for(const s of t.eventsBasedObjects)this._eventsBasedObjectDatas.set(t.name+"::"+s.name,s)}_updateEmbeddedResourcesMappings(){this._embeddedResourcesMappings.clear();for(const e of this._data.resources.resources)if(!!e.metadata)try{const t=JSON.parse(e.metadata);t?.embeddedResourcesMapping&&this._embeddedResourcesMappings.set(e.name,t.embeddedResourcesMapping)}catch{c.error("Some metadata of resources can not be successfully parsed.")}}getAdditionalOptions(){return this._options}getRenderer(){return this._renderer}getVariables(){return this._variables}getVariablesForExtension(e){return this._variablesByExtensionName.get(e)||null}getResourceLoader(){return this._resourcesLoader}getSoundManager(){return this._resourcesLoader.getSoundManager()}getImageManager(){return this._resourcesLoader.getImageManager()}getFontManager(){return this._resourcesLoader.getFontManager()}getBitmapFontManager(){return this._resourcesLoader.getBitmapFontManager()}getJsonManager(){return this._resourcesLoader.getJsonManager()}getModel3DManager(){return this._resourcesLoader.getModel3DManager()}getSpineManager(){return this._resourcesLoader.getSpineManager()}getSpineAtlasManager(){return this._resourcesLoader.getSpineAtlasManager()}getInputManager(){return this._inputManager}getEffectsManager(){return this._effectsManager}getGameData(){return this._data}getEventsBasedObjectData(e){const t=this._eventsBasedObjectDatas.get(e);return t||(c.error('The game has no events-based object of the type "'+e+'"'),null)}getEventsBasedObjectVariantData(e,t){const s=this.getEventsBasedObjectData(e);return s?n.RuntimeGame._getEventsBasedObjectVariantData(s,t):null}static _getEventsBasedObjectVariantData(e,t){if(e.defaultVariant||(e.defaultVariant={...e,name:""}),e.defaultVariant.instances.length==0)return e.defaultVariant;let i=e.defaultVariant;for(let a=0;a{await this._resourcesLoader.loadGlobalAndFirstSceneResources(e,i),this._resourcesLoader.loadAllSceneInBackground()},t),n.getAllAsynchronouslyLoadingLibraryPromise()])}catch(s){throw this._debuggerClient&&this._debuggerClient.onUncaughtException(s),s}}async loadSceneAssets(e,t){await this._loadAssetsWithLoadingScreen(!1,async s=>{await this._resourcesLoader.loadAndProcessSceneResources(e,s)},t)}async _loadAssetsWithLoadingScreen(e,t,s){this.pause(!0);const i=new n.LoadingScreenRenderer(this.getRenderer(),this._resourcesLoader.getImageManager(),this._data.properties.loadingScreen,this._data.properties.watermark.showWatermark,e);this._displayedLoadingScreen=i,await t(async(r,o)=>{const d=Math.floor(100*r/o);i.setPercent(d),s&&s(d),i.renderIfNeeded()&&await h(1)}),await i.unload(),this._displayedLoadingScreen=null,this._isInGameEdition||this.pause(!1)}_getFirstSceneName(){const e=this._options.initialRuntimeGameStatus?.sceneName||this._data.firstLayout;return this.hasScene(e)?e:this.getSceneAndExtensionsData().sceneData.name}startGameLoop(){this._throwIfDisposed();try{if(!this.hasScene()){c.error("The game has no scene.");return}this._forceGameResolutionUpdate();const e=this._getFirstSceneName(),t=this._options.initialRuntimeGameStatus?.injectedExternalLayoutName||null;if(this._inGameEditor){const a=this._options.initialRuntimeGameStatus?.eventsBasedObjectType||null,r=this._options.initialRuntimeGameStatus?.eventsBasedObjectVariantName||null,o=this._options.initialRuntimeGameStatus?.editorId||null,d=this._options.initialRuntimeGameStatus?.editorCamera3D||null;this._inGameEditor.switchToSceneOrVariant(o,e,t,a,r,d)}else e&&this.getSceneStack().replace({sceneName:e,externalLayoutName:t===null?void 0:t,clear:!0});this._watermark.displayAtStartup(),this._setupGameVisibilityEvents(),n.inAppTutorialMessage&&n.inAppTutorialMessage.displayInAppTutorialMessage(this,this._options.inAppTutorialMessageInPreview,this._options.inAppTutorialMessagePositionInPreview||"");let s=null,i=0;this._hasJustResumed=!1,this._renderer.startGameLoop(a=>{try{if(this._debuggerClient){const o=(this._inGameEditor||this.getSceneStack()).getCurrentScene();o&&o.getName()!==s&&(s=o.getName(),this._debuggerClient.sendRuntimeGameStatus())}if(this._paused&&this._inGameEditor&&this._inGameEditor.updateTargetFramerate(a),i+=a,this._maxFPS>0&&1e3/i>this._maxFPS+7)return!0;const r=i;if(i=0,this._notifyScenesForGameResolutionResize&&(this._inGameEditor?this._inGameEditor.onGameResolutionResized():this._sceneStack.onGameResolutionResized(),this._notifyScenesForGameResolutionResize=!1),this._paused)this._inGameEditor?this._displayedLoadingScreen||this._inGameEditor.updateAndRender():this._sceneStack.renderWithoutStep();else{if(!this._sceneStack.step(r))return!1;this._hasJustResumed=!1}return this.getInputManager().onFrameEnded(),!0}catch(r){throw this._debuggerClient&&this._debuggerClient.onUncaughtException(r),r}}),setTimeout(()=>{this._setupSessionMetrics()},4e3),this._captureManager&&this._captureManager.setupCaptureOptions(this._isPreview)}catch(e){throw this._debuggerClient&&this._debuggerClient.onUncaughtException(e),e}}dispose(e){this._inGameEditor&&this._inGameEditor.dispose(),this._renderer.stopGameLoop(),this._sceneStack.dispose(),this._renderer.dispose(e),this._resourcesLoader.dispose(),this._wasDisposed=!0}enableMetrics(e){this._disableMetrics=!e,e&&this._setupSessionMetrics()}_setupGameVisibilityEvents(){typeof navigator!="undefined"&&typeof document!="undefined"&&(document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&(this._hasJustResumed=!0)}),window.addEventListener("resume",()=>{this._hasJustResumed=!0},!1))}_setupSessionMetrics(){if(this._sessionMetricsInitialized||this._disableMetrics||this.isPreview()||typeof fetch=="undefined"||!this._data.properties.projectUuid)return;const e="https://api.gdevelop-app.com/analytics";this._playerId=this._makePlayerUuid();let t=0,s=0,i=Date.now();const a=this.getPlatformInfo();fetch(e+"/session",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({gameId:this._data.properties.projectUuid,playerId:this._playerId,game:{name:this._data.properties.name||"",packageName:this._data.properties.packageName||"",version:this._data.properties.version||"",location:window.location.href},platform:{isCordova:a.isCordova,devicePlatform:a.devicePlatform,navigatorPlatform:a.navigatorPlatform,hasTouch:a.hasTouch}})}).then(o=>{if(!o.ok)throw console.error("Error while creating the session",o),new Error("Error while creating the session");return o}).then(o=>o.text()).then(o=>{this._sessionId=o}).catch(()=>{});const r=()=>{if(!this._sessionId)return;const o=Date.now();if(s+=o-i,i=o,s<5*1e3)return;const d=Math.floor(s/1e3)*1e3;t+=d,s-=d,navigator.sendBeacon(e+"/session-hit",JSON.stringify({gameId:this._data.properties.projectUuid,playerId:this._playerId,sessionId:this._sessionId,duration:Math.floor(t/1e3)}))};if(typeof navigator!="undefined"&&typeof document!="undefined"){document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"?i=Date.now():r()}),window.addEventListener("pagehide",r,!1),window.addEventListener("pause",r,!1),window.addEventListener("resume",()=>{i=Date.now()},!1);const o=typeof safari=="object"&&safari.pushNotification,d=/electron/i.test(navigator.userAgent);(o||d)&&window.addEventListener("beforeunload",()=>{r()})}this._sessionMetricsInitialized=!0,this._sessionId=this._sessionId}_makePlayerUuid(){try{const e="GDJS-internal-player-uuid",t=localStorage.getItem(e);if(t)return t;const s=n.makeUuid();return localStorage.setItem(e,s),s}catch{return n.makeUuid()}}getSessionId(){return this._sessionId}getPlayerId(){return this._playerId}onWindowInnerSizeChanged(){this._forceGameResolutionUpdate()}_forceGameResolutionUpdate(){this.setGameResolutionSize(this._gameResolutionWidth,this._gameResolutionHeight)}startCurrentSceneProfiler(e){this._throwIfDisposed();const t=this._sceneStack.getCurrentScene();return t?(t.startProfiler(e),!0):!1}stopCurrentSceneProfiler(){this._throwIfDisposed();const e=this._sceneStack.getCurrentScene();!e||e.stopProfiler()}wasFirstSceneLoaded(){return this._sceneStack.wasFirstSceneLoaded()}getSceneStack(){return this._sceneStack}isPreview(){return this._isPreview}isPaused(){return this._paused}isInGameEdition(){return this._isInGameEdition}getInGameEditor(){return this._inGameEditor}isBehaviorActivatedByDefaultInEditor(e){return this._data.activatedByDefaultInEditorBehaviors?this._data.activatedByDefaultInEditorBehaviors.includes(e):!1}setMaximumFps(e){this._maxFPS=e}isUsingGDevelopDevelopmentEnvironment(){return this._options.environment==="dev"}getExtensionProperty(e,t){for(let s of this._data.properties.extensionProperties)if(s.extension===e&&s.property===t)return s.value;return null}resolveEmbeddedResource(e,t){const s=this._embeddedResourcesMappings.get(e);return s&&s[t]?s[t]:t}getEmbeddedResourcesNames(e){return this._embeddedResourcesMappings.has(e)?Object.keys(this._embeddedResourcesMappings.get(e)):[]}getNetworkSyncData(e){const t={var:e.syncGameVariables===!1?void 0:this._variables.getNetworkSyncData(e),sm:e.syncSounds?this.getSoundManager().getNetworkSyncData():void 0,ss:this._sceneStack.getNetworkSyncData(e)||void 0};if(e.syncGameVariables!==!1){const s={};this._variablesByExtensionName.forEach((i,a)=>{const r=i.getNetworkSyncData(e);r.length&&(s[a]=r)}),t.extVar=s}return(!t.var||t.var.length===0)&&!t.ss&&(!t.extVar||Object.keys(t.extVar).length===0)?null:t}updateFromNetworkSyncData(e,t){if(this._throwIfDisposed(),e.var&&this._variables.updateFromNetworkSyncData(e.var,t),e.sm&&this.getSoundManager().updateFromNetworkSyncData(e.sm),e.ss&&this._sceneStack.updateFromNetworkSyncData(e.ss),e.extVar)for(const s in e.extVar){if(!e.extVar.hasOwnProperty(s))continue;const i=e.extVar[s],a=this.getVariablesForExtension(s);a&&a.updateFromNetworkSyncData(i,t)}}_throwIfDisposed(){if(this._wasDisposed)throw"The RuntimeGame has been disposed and should not be used anymore."}}n.RuntimeGame=_})(gdjs||(gdjs={})); //# sourceMappingURL=runtimegame.js.map