gdcore-tools 2.0.0-gd-v5.5.232-autobuild → 2.0.0-gd-v5.5.234-autobuild
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Runtime/Extensions/3D/Cube3DRuntimeObject.js +1 -1
- package/dist/Runtime/Extensions/3D/Cube3DRuntimeObject.js.map +2 -2
- package/dist/Runtime/Extensions/3D/Cube3DRuntimeObjectPixiRenderer.js +1 -1
- package/dist/Runtime/Extensions/3D/Cube3DRuntimeObjectPixiRenderer.js.map +2 -2
- package/dist/Runtime/Extensions/3D/DirectionalLight.js +1 -1
- package/dist/Runtime/Extensions/3D/DirectionalLight.js.map +2 -2
- package/dist/Runtime/Extensions/3D/JsExtension.js +60 -9
- package/dist/Runtime/Extensions/3D/Model3DRuntimeObject.js +1 -1
- package/dist/Runtime/Extensions/3D/Model3DRuntimeObject.js.map +2 -2
- package/dist/Runtime/Extensions/3D/Model3DRuntimeObject3DRenderer.js +1 -1
- package/dist/Runtime/Extensions/3D/Model3DRuntimeObject3DRenderer.js.map +2 -2
- package/dist/Runtime/Extensions/BBText/JsExtension.js +6 -6
- package/dist/Runtime/Extensions/BitmapText/JsExtension.js +6 -6
- package/dist/Runtime/Extensions/Physics2Behavior/JsExtension.js +10 -10
- package/dist/Runtime/Extensions/Physics3DBehavior/JsExtension.js +20 -7
- package/dist/Runtime/Extensions/Physics3DBehavior/Physics3DRuntimeBehavior.js +1 -1
- package/dist/Runtime/Extensions/Physics3DBehavior/Physics3DRuntimeBehavior.js.map +2 -2
- package/dist/Runtime/Extensions/Physics3DBehavior/PhysicsCar3DRuntimeBehavior.js +1 -1
- package/dist/Runtime/Extensions/Physics3DBehavior/PhysicsCar3DRuntimeBehavior.js.map +2 -2
- package/dist/Runtime/Extensions/PlatformBehavior/platformerobjectruntimebehavior.js +1 -1
- package/dist/Runtime/Extensions/PlatformBehavior/platformerobjectruntimebehavior.js.map +2 -2
- package/dist/Runtime/Extensions/Spine/managers/pixi-spine-atlas-manager.js +1 -1
- package/dist/Runtime/Extensions/Spine/managers/pixi-spine-atlas-manager.js.map +2 -2
- package/dist/Runtime/Extensions/Spine/managers/pixi-spine-manager.js +1 -1
- package/dist/Runtime/Extensions/Spine/managers/pixi-spine-manager.js.map +2 -2
- package/dist/Runtime/Extensions/TextInput/JsExtension.js +11 -11
- package/dist/Runtime/Extensions/TileMap/JsExtension.js +3 -3
- package/dist/Runtime/Model3DManager.js +1 -1
- package/dist/Runtime/Model3DManager.js.map +2 -2
- package/dist/Runtime/ResourceLoader.js +1 -1
- package/dist/Runtime/ResourceLoader.js.map +2 -2
- package/dist/Runtime/RuntimeLayer.js +1 -1
- package/dist/Runtime/RuntimeLayer.js.map +2 -2
- package/dist/Runtime/events-tools/objecttools.js +1 -1
- package/dist/Runtime/events-tools/objecttools.js.map +2 -2
- package/dist/Runtime/fontfaceobserver-font-manager/fontfaceobserver-font-manager.js +1 -1
- package/dist/Runtime/fontfaceobserver-font-manager/fontfaceobserver-font-manager.js.map +2 -2
- package/dist/Runtime/howler-sound-manager/howler-sound-manager.js +1 -1
- package/dist/Runtime/howler-sound-manager/howler-sound-manager.js.map +2 -2
- package/dist/Runtime/jsonmanager.js +1 -1
- package/dist/Runtime/jsonmanager.js.map +2 -2
- package/dist/Runtime/logger.js +1 -1
- package/dist/Runtime/logger.js.map +2 -2
- package/dist/Runtime/pixi-renderers/pixi-bitmapfont-manager.js +1 -1
- package/dist/Runtime/pixi-renderers/pixi-bitmapfont-manager.js.map +2 -2
- package/dist/Runtime/pixi-renderers/pixi-effects-manager.js.map +2 -2
- package/dist/Runtime/pixi-renderers/pixi-image-manager.js +1 -1
- package/dist/Runtime/pixi-renderers/pixi-image-manager.js.map +2 -2
- package/dist/Runtime/pixi-renderers/runtimegame-pixi-renderer.js +1 -1
- package/dist/Runtime/pixi-renderers/runtimegame-pixi-renderer.js.map +2 -2
- package/dist/Runtime/runtimegame.js +1 -1
- package/dist/Runtime/runtimegame.js.map +2 -2
- package/dist/Runtime/runtimescene.js +1 -1
- package/dist/Runtime/runtimescene.js.map +2 -2
- package/dist/Runtime/scenestack.js +1 -1
- package/dist/Runtime/scenestack.js.map +2 -2
- package/dist/Runtime/types/project-data.d.ts +6 -1
- package/dist/lib/libGD.cjs +1 -1
- package/dist/lib/libGD.wasm +0 -0
- package/gd.d.ts +21 -0
- package/package.json +1 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../GDevelop/GDJS/Runtime/runtimegame.ts"],
|
|
4
|
-
"sourcesContent": ["/*\n * GDevelop JS Platform\n * Copyright 2013-2016 Florian Rival (Florian.Rival@gmail.com). All rights reserved.\n * This project is released under the MIT License.\n */\nnamespace gdjs {\n const logger = new gdjs.Logger('Game manager');\n\n const sleep = (ms: float) =>\n new Promise((resolve) => setTimeout(resolve, ms));\n\n /** Identify a script file, with its content hash (useful for hot-reloading). */\n export type RuntimeGameOptionsScriptFile = {\n /** The path for this script file. */\n path: string;\n /** The hash of the script file content. */\n hash: number;\n };\n\n const getGlobalResourceNames = (projectData: ProjectData): Array<string> =>\n projectData.usedResources.map((resource) => resource.name);\n\n let supportedCompressionMethods: ('cs:gzip' | 'cs:deflate')[] | null = null;\n const getSupportedCompressionMethods = (): ('cs:gzip' | 'cs:deflate')[] => {\n if (!!supportedCompressionMethods) {\n return supportedCompressionMethods;\n }\n supportedCompressionMethods = [];\n\n try {\n // @ts-ignore - We are checking if the CompressionStream is available.\n new CompressionStream('gzip');\n supportedCompressionMethods.push('cs:gzip');\n } catch (e) {}\n try {\n // @ts-ignore - We are checking if the CompressionStream is available.\n new CompressionStream('deflate');\n supportedCompressionMethods.push('cs:deflate');\n } catch (e) {}\n\n return supportedCompressionMethods;\n };\n\n /** Options given to the game at startup. */\n export type RuntimeGameOptions = {\n /** if true, force fullscreen. */\n forceFullscreen?: boolean;\n /** if true, game is run as a preview launched from an editor. */\n isPreview?: boolean;\n /** The name of the external layout to create in the scene at position 0;0. */\n injectExternalLayout?: string;\n /** Script files, used for hot-reloading. */\n scriptFiles?: Array<RuntimeGameOptionsScriptFile>;\n /** if true, export is a partial preview without events. */\n projectDataOnlyExport?: boolean;\n /** if true, preview is launched from GDevelop native mobile app. */\n nativeMobileApp?: boolean;\n /** The address of the debugger server, to reach out using WebSocket. */\n websocketDebuggerServerAddress?: string;\n /** The port of the debugger server, to reach out using WebSocket. */\n websocketDebuggerServerPort?: string;\n\n /**\n * The path to require `@electron/remote` module.\n * This is only useful in a preview, where this can't be required from\n * `@electron/remote` directly as previews don't have any node_modules.\n * On the contrary, a game packaged with Electron as a standalone app\n * has its node_modules.\n * This can be removed once there are no more dependencies on\n * `@electron/remote` in the game engine and extensions.\n */\n electronRemoteRequirePath?: string;\n\n /**\n * The token to use by the game engine when requiring any resource stored on\n * GDevelop Cloud buckets. Note that this is only useful during previews.\n */\n gdevelopResourceToken?: string;\n\n /**\n * Check if, in some exceptional cases, we allow authentication\n * to be done through a iframe.\n * This is usually discouraged as the user can't verify that the authentication\n * window is a genuine one. It's only to be used in trusted contexts.\n */\n allowAuthenticationUsingIframeForPreview?: boolean;\n\n /** If set, the game will send crash reports to GDevelop APIs. */\n crashReportUploadLevel?: 'all' | 'exclude-javascript-code-events' | 'none';\n\n /** Arbitrary string explaining in which context the game is being played. */\n previewContext?: string;\n\n /** The GDevelop version used to build the game. */\n gdevelopVersionWithHash?: string;\n\n /** The template slug that was used to create the project. */\n projectTemplateSlug?: string;\n\n /** The source game id that was used to create the project. */\n sourceGameId?: string;\n\n /** Any capture that should be done during the preview. */\n captureOptions?: CaptureOptions;\n\n /** Message to display to the user during an in-app tutorial. */\n inAppTutorialMessageInPreview?: string;\n inAppTutorialMessagePositionInPreview?: string;\n\n /**\n * If set, this data is used to authenticate automatically when launching the game.\n * This is only useful during previews.\n */\n playerUsername?: string;\n playerId?: string;\n playerToken?: string;\n\n /**\n * If set, the game should use the specified environment for making calls\n * to GDevelop APIs (\"dev\" = development APIs).\n */\n environment?: 'dev';\n };\n\n /**\n * Represents a game being played.\n */\n export class RuntimeGame {\n _resourcesLoader: gdjs.ResourceLoader;\n _variables: VariablesContainer;\n _variablesByExtensionName: Map<string, gdjs.VariablesContainer>;\n _data: ProjectData;\n _sceneAndExtensionsData: Array<SceneAndExtensionsData> = [];\n _eventsBasedObjectDatas: Map<String, EventsBasedObjectData>;\n _effectsManager: EffectsManager;\n _maxFPS: integer;\n _minFPS: integer;\n _gameResolutionWidth: integer;\n _gameResolutionHeight: integer;\n _originalWidth: float;\n _originalHeight: float;\n _resizeMode: 'adaptWidth' | 'adaptHeight' | string;\n _adaptGameResolutionAtRuntime: boolean;\n _scaleMode: 'linear' | 'nearest';\n _pixelsRounding: boolean;\n _antialiasingMode: 'none' | 'MSAA';\n _isAntialisingEnabledOnMobile: boolean;\n /**\n * Game loop management (see startGameLoop method)\n */\n _renderer: RuntimeGameRenderer;\n _sessionId: string | null;\n _playerId: string | null;\n _watermark: watermark.RuntimeWatermark;\n\n _sceneStack: SceneStack;\n /**\n * When set to true, the scenes are notified that game resolution size changed.\n */\n _notifyScenesForGameResolutionResize: boolean = false;\n\n /**\n * When paused, the game won't step and will be freezed. Useful for debugging.\n */\n _paused: boolean = false;\n\n /**\n * True during the first frame the game is back from being hidden.\n * This has nothing to do with `_paused`.\n */\n _hasJustResumed: boolean = false;\n\n //Inputs :\n _inputManager: InputManager;\n\n /**\n * Allow to specify an external layout to insert in the first scene.\n */\n _injectExternalLayout: any;\n _options: RuntimeGameOptions;\n\n /**\n * The mappings for embedded resources\n */\n _embeddedResourcesMappings: Map<string, Record<string, string>>;\n\n /**\n * Optional client to connect to a debugger server.\n */\n _debuggerClient: gdjs.AbstractDebuggerClient | null;\n _sessionMetricsInitialized: boolean = false;\n _disableMetrics: boolean = false;\n _isPreview: boolean;\n\n /**\n * The capture manager, used to manage captures (screenshots, videos, etc...).\n */\n _captureManager: CaptureManager | null;\n\n /** True if the RuntimeGame has been disposed and should not be used anymore. */\n _wasDisposed: boolean = false;\n\n /**\n * @param data The object (usually stored in data.json) containing the full project data\n * @param options The game options\n */\n constructor(data: ProjectData, options?: RuntimeGameOptions) {\n this._options = options || {};\n this._variables = new gdjs.VariablesContainer(data.variables);\n this._variablesByExtensionName = new Map<\n string,\n gdjs.VariablesContainer\n >();\n for (const extensionData of data.eventsFunctionsExtensions) {\n if (extensionData.globalVariables.length > 0) {\n this._variablesByExtensionName.set(\n extensionData.name,\n new gdjs.VariablesContainer(extensionData.globalVariables)\n );\n }\n }\n this._eventsBasedObjectDatas = new Map<String, EventsBasedObjectData>();\n this._data = data;\n this._updateSceneAndExtensionsData();\n\n this._resourcesLoader = new gdjs.ResourceLoader(\n this,\n data.resources.resources,\n getGlobalResourceNames(data),\n data.layouts\n );\n\n this._effectsManager = new gdjs.EffectsManager();\n this._maxFPS = this._data.properties.maxFPS;\n this._minFPS = this._data.properties.minFPS;\n this._gameResolutionWidth = this._data.properties.windowWidth;\n this._gameResolutionHeight = this._data.properties.windowHeight;\n this._originalWidth = this._gameResolutionWidth;\n this._originalHeight = this._gameResolutionHeight;\n this._resizeMode = this._data.properties.sizeOnStartupMode;\n this._adaptGameResolutionAtRuntime =\n this._data.properties.adaptGameResolutionAtRuntime;\n this._scaleMode = data.properties.scaleMode || 'linear';\n this._pixelsRounding = this._data.properties.pixelsRounding;\n this._antialiasingMode = this._data.properties.antialiasingMode;\n this._isAntialisingEnabledOnMobile =\n this._data.properties.antialisingEnabledOnMobile;\n this._renderer = new gdjs.RuntimeGameRenderer(\n this,\n this._options.forceFullscreen || false\n );\n this._watermark = new gdjs.watermark.RuntimeWatermark(\n this,\n data.properties.authorUsernames,\n this._data.properties.watermark\n );\n this._sceneStack = new gdjs.SceneStack(this);\n this._inputManager = new gdjs.InputManager();\n this._injectExternalLayout = this._options.injectExternalLayout || '';\n this._debuggerClient = gdjs.DebuggerClient\n ? new gdjs.DebuggerClient(this)\n : null;\n this._captureManager = gdjs.CaptureManager\n ? new gdjs.CaptureManager(\n this._renderer,\n this._options.captureOptions || {}\n )\n : null;\n this._isPreview = this._options.isPreview || false;\n this._sessionId = null;\n this._playerId = null;\n\n this._embeddedResourcesMappings = new Map();\n for (const resource of this._data.resources.resources) {\n if (resource.metadata) {\n try {\n const metadata = JSON.parse(resource.metadata);\n if (metadata?.embeddedResourcesMapping) {\n this._embeddedResourcesMappings.set(\n resource.name,\n metadata.embeddedResourcesMapping\n );\n }\n } catch {\n logger.error(\n 'Some metadata of resources can not be successfully parsed.'\n );\n }\n }\n }\n\n if (this.isUsingGDevelopDevelopmentEnvironment()) {\n logger.info(\n 'This game will run on the development version of GDevelop APIs.'\n );\n }\n }\n\n /**\n * Update the project data. Useful for hot-reloading, should not be used otherwise.\n *\n * @param projectData The object (usually stored in data.json) containing the full project data\n */\n setProjectData(projectData: ProjectData): void {\n this._data = projectData;\n this._updateSceneAndExtensionsData();\n this._resourcesLoader.setResources(\n projectData.resources.resources,\n getGlobalResourceNames(projectData),\n projectData.layouts\n );\n }\n\n private _updateSceneAndExtensionsData(): void {\n const usedExtensionsWithVariablesData =\n this._data.eventsFunctionsExtensions.filter(\n (extensionData) => extensionData.sceneVariables.length > 0\n );\n this._sceneAndExtensionsData = this._data.layouts.map((sceneData) => ({\n sceneData,\n usedExtensionsWithVariablesData,\n }));\n\n this._eventsBasedObjectDatas.clear();\n if (this._data.eventsFunctionsExtensions) {\n for (const extension of this._data.eventsFunctionsExtensions) {\n for (const eventsBasedObject of extension.eventsBasedObjects) {\n this._eventsBasedObjectDatas.set(\n extension.name + '::' + eventsBasedObject.name,\n eventsBasedObject\n );\n }\n }\n }\n }\n\n /**\n * Return the additional options passed to the RuntimeGame when created.\n * @returns The additional options, if any.\n */\n getAdditionalOptions(): RuntimeGameOptions {\n return this._options;\n }\n\n getRenderer(): gdjs.RuntimeGameRenderer {\n return this._renderer;\n }\n\n /**\n * Get the variables of the RuntimeGame.\n * @return The global variables\n */\n getVariables(): gdjs.VariablesContainer {\n return this._variables;\n }\n\n /**\n * Get the extension's global variables.\n * @param extensionName The extension name.\n * @returns The extension's global variables.\n */\n getVariablesForExtension(extensionName: string) {\n return this._variablesByExtensionName.get(extensionName) || null;\n }\n\n /**\n * Get the gdjs.SoundManager of the RuntimeGame.\n * @return The sound manager.\n */\n getSoundManager(): gdjs.HowlerSoundManager {\n return this._resourcesLoader.getSoundManager();\n }\n\n /**\n * Get the gdjs.ImageManager of the RuntimeGame.\n * @return The image manager.\n */\n getImageManager(): gdjs.PixiImageManager {\n return this._resourcesLoader.getImageManager();\n }\n\n /**\n * Get the gdjs.FontManager of the RuntimeGame.\n * @return The font manager.\n */\n getFontManager(): gdjs.FontFaceObserverFontManager {\n return this._resourcesLoader.getFontManager();\n }\n\n /**\n * Get the gdjs.BitmapFontManager of the RuntimeGame.\n * @return The bitmap font manager.\n */\n getBitmapFontManager(): gdjs.BitmapFontManager {\n return this._resourcesLoader.getBitmapFontManager();\n }\n\n /**\n * Get the JSON manager of the game, used to load JSON from game\n * resources.\n * @return The json manager for the game\n */\n getJsonManager(): gdjs.JsonManager {\n return this._resourcesLoader.getJsonManager();\n }\n\n /**\n * Get the 3D model manager of the game, used to load 3D model from game\n * resources.\n * @return The 3D model manager for the game\n */\n getModel3DManager(): gdjs.Model3DManager {\n return this._resourcesLoader.getModel3DManager();\n }\n\n /**\n * Get the Spine manager of the game, used to load and construct spine skeletons from game\n * resources.\n * @return The Spine manager for the game\n */\n getSpineManager(): gdjs.SpineManager | null {\n return this._resourcesLoader.getSpineManager();\n }\n\n /**\n * Get the Spine Atlas manager of the game, used to load atlases from game\n * resources.\n * @return The Spine Atlas manager for the game\n */\n getSpineAtlasManager(): gdjs.SpineAtlasManager | null {\n return this._resourcesLoader.getSpineAtlasManager();\n }\n\n /**\n * Get the input manager of the game, storing mouse, keyboard\n * and touches states.\n * @return The input manager owned by the game\n */\n getInputManager(): gdjs.InputManager {\n return this._inputManager;\n }\n\n /**\n * Get the effects manager of the game, which allows to manage\n * effects on runtime objects or runtime layers.\n * @return The effects manager for the game\n */\n getEffectsManager(): gdjs.EffectsManager {\n return this._effectsManager;\n }\n\n /**\n * Get the object containing the game data\n * @return The object associated to the game.\n */\n getGameData(): ProjectData {\n return this._data;\n }\n\n getEventsBasedObjectData(type: string): EventsBasedObjectData | null {\n const eventsBasedObjectData = this._eventsBasedObjectDatas.get(type);\n if (!eventsBasedObjectData) {\n logger.error(\n 'The game has no events-based object of the type \"' + type + '\"'\n );\n return null;\n }\n return eventsBasedObjectData;\n }\n\n /**\n * Get the data associated to a scene.\n *\n * @param sceneName The name of the scene. If not defined, the first scene will be returned.\n * @return The data associated to the scene.\n */\n getSceneAndExtensionsData(\n sceneName?: string\n ): SceneAndExtensionsData | null {\n for (let i = 0, len = this._sceneAndExtensionsData.length; i < len; ++i) {\n const sceneAndExtensionsData = this._sceneAndExtensionsData[i];\n if (\n sceneName === undefined ||\n sceneAndExtensionsData.sceneData.name === sceneName\n ) {\n return sceneAndExtensionsData;\n }\n }\n logger.error('The game has no scene called \"' + sceneName + '\"');\n return null;\n }\n\n /**\n * Check if a scene exists\n *\n * @param sceneName The name of the scene to search.\n * @return true if the scene exists. If sceneName is undefined, true if the game has a scene.\n */\n hasScene(sceneName?: string): boolean {\n for (let i = 0, len = this._data.layouts.length; i < len; ++i) {\n const sceneData = this._data.layouts[i];\n if (sceneName === undefined || sceneData.name == sceneName) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Get the data associated to an external layout.\n *\n * @param name The name of the external layout.\n * @return The data associated to the external layout or null if not found.\n */\n getExternalLayoutData(name: string): ExternalLayoutData | null {\n let externalLayout: ExternalLayoutData | null = null;\n for (let i = 0, len = this._data.externalLayouts.length; i < len; ++i) {\n const layoutData = this._data.externalLayouts[i];\n if (layoutData.name === name) {\n externalLayout = layoutData;\n break;\n }\n }\n return externalLayout;\n }\n\n /**\n * Get the data representing all the global objects of the game.\n * @return The data associated to the global objects.\n */\n getInitialObjectsData(): ObjectData[] {\n return this._data.objects || [];\n }\n\n /**\n * Get the original width of the game, as set on the startup of the game.\n *\n * This is guaranteed to never change, even if the size of the game is changed afterwards.\n */\n getOriginalWidth(): float {\n return this._originalWidth;\n }\n\n /**\n * Get the original height of the game, as set on the startup of the game.\n *\n * This is guaranteed to never change, even if the size of the game is changed afterwards.\n */\n getOriginalHeight(): float {\n return this._originalHeight;\n }\n\n /**\n * Get the game resolution (the size at which the game is played and rendered) width.\n * @returns The game resolution width, in pixels.\n */\n getGameResolutionWidth(): float {\n return this._gameResolutionWidth;\n }\n\n /**\n * Get the game resolution (the size at which the game is played and rendered) height.\n * @returns The game resolution height, in pixels.\n */\n getGameResolutionHeight(): float {\n return this._gameResolutionHeight;\n }\n\n /**\n * Change the game resolution.\n *\n * @param width The new width\n * @param height The new height\n */\n setGameResolutionSize(width: float, height: float): void {\n this._throwIfDisposed();\n\n this._gameResolutionWidth = width;\n this._gameResolutionHeight = height;\n if (this._adaptGameResolutionAtRuntime) {\n if (\n gdjs.RuntimeGameRenderer &&\n gdjs.RuntimeGameRenderer.getWindowInnerWidth &&\n gdjs.RuntimeGameRenderer.getWindowInnerHeight\n ) {\n const windowInnerWidth =\n gdjs.RuntimeGameRenderer.getWindowInnerWidth();\n const windowInnerHeight =\n gdjs.RuntimeGameRenderer.getWindowInnerHeight();\n\n // Enlarge either the width or the eight to fill the inner window space.\n if (this._resizeMode === 'adaptWidth') {\n this._gameResolutionWidth =\n (this._gameResolutionHeight * windowInnerWidth) /\n windowInnerHeight;\n } else if (this._resizeMode === 'adaptHeight') {\n this._gameResolutionHeight =\n (this._gameResolutionWidth * windowInnerHeight) /\n windowInnerWidth;\n } else if (this._resizeMode === 'scaleOuter') {\n const widthFactor = windowInnerWidth / this._originalWidth;\n const heightFactor = windowInnerHeight / this._originalHeight;\n\n if (widthFactor < heightFactor) {\n this._gameResolutionWidth = this._originalWidth;\n this._gameResolutionHeight = Math.floor(\n windowInnerHeight / widthFactor\n );\n } else {\n this._gameResolutionWidth = Math.floor(\n windowInnerWidth / heightFactor\n );\n this._gameResolutionHeight = this._originalHeight;\n }\n }\n }\n }\n\n // Don't alter the game resolution. The renderer\n // will maybe adapt the size of the canvas or whatever is used to render the\n // game in the window, but this does not change the \"game resolution\".\n\n // Notify the renderer that game resolution changed (so that the renderer size\n // can be updated, and maybe other things like the canvas size), and let the\n // scenes know too.\n this._renderer.updateRendererSize();\n this._notifyScenesForGameResolutionResize = true;\n }\n\n /**\n * Set if the width or the height of the game resolution\n * should be changed to fit the game window - or if the game\n * resolution should not be updated automatically.\n *\n * @param resizeMode Either \"\" (don't change game resolution), \"adaptWidth\" or \"adaptHeight\".\n */\n setGameResolutionResizeMode(resizeMode: string): void {\n this._resizeMode = resizeMode;\n this._forceGameResolutionUpdate();\n }\n\n /**\n * Returns if the width or the height of the game resolution\n * should be changed to fit the game window - or if the game\n * resolution should not be updated automatically (empty string).\n *\n * @returns Either \"\" (don't change game resolution), \"adaptWidth\" or \"adaptHeight\".\n */\n getGameResolutionResizeMode(): string {\n return this._resizeMode;\n }\n\n /**\n * Set if the game resolution should be automatically adapted\n * when the game window or screen size change. This will only\n * be the case if the game resolution resize mode is\n * configured to adapt the width or the height of the game.\n * @param enable true to change the game resolution according to the window/screen size.\n */\n setAdaptGameResolutionAtRuntime(enable: boolean): void {\n this._adaptGameResolutionAtRuntime = enable;\n this._forceGameResolutionUpdate();\n }\n\n /**\n * Returns if the game resolution should be automatically adapted\n * when the game window or screen size change. This will only\n * be the case if the game resolution resize mode is\n * configured to adapt the width or the height of the game.\n * @returns true if the game resolution is automatically changed according to the window/screen size.\n */\n getAdaptGameResolutionAtRuntime(): boolean {\n return this._adaptGameResolutionAtRuntime;\n }\n\n /**\n * Return the minimal fps that must be guaranteed by the game\n * (otherwise, game is slowed down).\n */\n getMinimalFramerate(): integer {\n return this._minFPS;\n }\n\n /**\n * Return the scale mode of the game (\"linear\" or \"nearest\").\n */\n getScaleMode(): 'linear' | 'nearest' {\n return this._scaleMode;\n }\n\n /**\n * Return if the game is rounding pixels when rendering.\n */\n getPixelsRounding(): boolean {\n return this._pixelsRounding;\n }\n\n /**\n * Return the antialiasing mode used by the game (\"none\" or \"MSAA\").\n */\n getAntialiasingMode(): 'none' | 'MSAA' {\n return this._antialiasingMode;\n }\n\n /**\n * Return true if antialising is enabled on mobiles.\n */\n isAntialisingEnabledOnMobile(): boolean {\n return this._isAntialisingEnabledOnMobile;\n }\n\n /**\n * Set or unset the game as paused.\n * When paused, the game won't step and will be freezed. Useful for debugging.\n * @param enable true to pause the game, false to unpause\n */\n pause(enable: boolean) {\n if (this._paused === enable) return;\n\n this._paused = enable;\n if (this._debuggerClient) {\n if (this._paused) this._debuggerClient.sendGamePaused();\n else this._debuggerClient.sendGameResumed();\n }\n }\n\n /**\n * @returns true during the first frame the game is back from being hidden.\n * This has nothing to do with `_paused`.\n */\n hasJustResumed() {\n return this._hasJustResumed;\n }\n\n /**\n * Preload a scene assets as soon as possible in background.\n */\n prioritizeLoadingOfScene(sceneName: string) {\n // Don't await the scene assets to be loaded.\n this._resourcesLoader.loadSceneResources(sceneName);\n }\n\n /**\n * @return The progress of assets loading in background for a scene\n * (between 0 and 1).\n */\n getSceneLoadingProgress(sceneName: string): number {\n return this._resourcesLoader.getSceneLoadingProgress(sceneName);\n }\n\n /**\n * @returns true when all the resources of the given scene are loaded\n * (but maybe not parsed).\n */\n areSceneAssetsLoaded(sceneName: string): boolean {\n return this._resourcesLoader.areSceneAssetsLoaded(sceneName);\n }\n\n /**\n * @returns true when all the resources of the given scene are loaded and\n * parsed.\n */\n areSceneAssetsReady(sceneName: string): boolean {\n return this._resourcesLoader.areSceneAssetsReady(sceneName);\n }\n\n /**\n * Load all assets needed to display the 1st scene, displaying progress in\n * renderer.\n */\n loadAllAssets(\n callback: () => void,\n progressCallback?: (progress: float) => void\n ) {\n this._throwIfDisposed();\n this.loadFirstAssetsAndStartBackgroundLoading(\n this._getFirstSceneName(),\n progressCallback\n ).then(callback);\n }\n\n /**\n * Load all assets needed to display the 1st scene, displaying progress in\n * renderer.\n *\n * When a game is hot-reload, this method can be called with the current\n * scene.\n */\n async loadFirstAssetsAndStartBackgroundLoading(\n firstSceneName: string,\n progressCallback?: (progress: float) => void\n ): Promise<void> {\n try {\n // Download the loading screen background image first to be able to\n // display the loading screen as soon as possible.\n const backgroundImageResourceName =\n this._data.properties.loadingScreen.backgroundImageResourceName;\n if (backgroundImageResourceName) {\n await this._resourcesLoader\n .getImageManager()\n .loadResource(backgroundImageResourceName);\n }\n await Promise.all([\n this._loadAssetsWithLoadingScreen(\n /* isFirstScene = */ true,\n async (onProgress) => {\n // TODO Is a setting needed?\n if (false) {\n await this._resourcesLoader.loadAllResources(onProgress);\n } else {\n await this._resourcesLoader.loadGlobalAndFirstSceneResources(\n firstSceneName,\n onProgress\n );\n // Don't await as it must not block the first scene from starting.\n this._resourcesLoader.loadAllSceneInBackground();\n }\n },\n progressCallback\n ),\n // TODO This is probably not necessary in case of hot reload.\n gdjs.getAllAsynchronouslyLoadingLibraryPromise(),\n ]);\n } catch (e) {\n if (this._debuggerClient) this._debuggerClient.onUncaughtException(e);\n\n throw e;\n }\n }\n\n /**\n * Load all assets for a given scene, displaying progress in renderer.\n */\n async loadSceneAssets(\n sceneName: string,\n progressCallback?: (progress: float) => void\n ): Promise<void> {\n await this._loadAssetsWithLoadingScreen(\n /* isFirstLayout = */ false,\n async (onProgress) => {\n await this._resourcesLoader.loadAndProcessSceneResources(\n sceneName,\n onProgress\n );\n },\n progressCallback\n );\n }\n\n /**\n * Load assets, displaying progress in renderer.\n */\n private async _loadAssetsWithLoadingScreen(\n isFirstScene: boolean,\n loadAssets: (\n onProgress: (count: integer, total: integer) => Promise<void>\n ) => Promise<void>,\n progressCallback?: (progress: float) => void\n ): Promise<void> {\n this.pause(true);\n const loadingScreen = new gdjs.LoadingScreenRenderer(\n this.getRenderer(),\n this._resourcesLoader.getImageManager(),\n this._data.properties.loadingScreen,\n this._data.properties.watermark.showWatermark,\n isFirstScene\n );\n\n const onProgress = async (count: integer, total: integer) => {\n const percent = Math.floor((100 * count) / total);\n loadingScreen.setPercent(percent);\n if (progressCallback) {\n progressCallback(percent);\n }\n const hasRendered = loadingScreen.renderIfNeeded();\n if (hasRendered) {\n // Give a chance to draw calls from the renderer to be handled.\n await sleep(1);\n }\n };\n await loadAssets(onProgress);\n\n await loadingScreen.unload();\n this.pause(false);\n }\n\n private _getFirstSceneName(): string {\n const firstSceneName = this._data.firstLayout;\n return this.hasScene(firstSceneName)\n ? firstSceneName\n : // There is always at least a scene\n this.getSceneAndExtensionsData()!.sceneData.name;\n }\n\n /**\n * Start the game loop, to be called once assets are loaded.\n */\n startGameLoop() {\n this._throwIfDisposed();\n try {\n if (!this.hasScene()) {\n logger.error('The game has no scene.');\n return;\n }\n this._forceGameResolutionUpdate();\n\n // Load the first scene\n this._sceneStack.push(\n this._getFirstSceneName(),\n this._injectExternalLayout\n );\n this._watermark.displayAtStartup();\n\n //Uncomment to profile the first x frames of the game.\n // var x = 500;\n // var startTime = Date.now();\n // console.profile(\"Stepping for \" + x + \" frames\")\n // for(var i = 0; i < x; ++i) {\n // this._sceneStack.step(16);\n // }\n // console.profileEnd();\n // var time = Date.now() - startTime;\n // logger.log(\"Took\", time, \"ms\");\n // return;\n\n this._setupGameVisibilityEvents();\n\n if (gdjs.inAppTutorialMessage) {\n gdjs.inAppTutorialMessage.displayInAppTutorialMessage(\n this,\n this._options.inAppTutorialMessageInPreview,\n this._options.inAppTutorialMessagePositionInPreview || ''\n );\n }\n\n // The standard game loop\n let accumulatedElapsedTime = 0;\n this._hasJustResumed = false;\n this._renderer.startGameLoop((lastCallElapsedTime) => {\n try {\n if (this._paused) {\n return true;\n }\n\n // Skip the frame if we rendering frames too fast\n accumulatedElapsedTime += lastCallElapsedTime;\n if (\n this._maxFPS > 0 &&\n 1000.0 / accumulatedElapsedTime > this._maxFPS + 7\n ) {\n // Only skip frame if the framerate is 7 frames above the maximum framerate.\n // Most browser/engines will try to run at slightly more than 60 frames per second.\n // If game is set to have a maximum FPS to 60, then one out of two frames will be dropped.\n // Hence, we use a 7 frames margin to ensure that we're not skipping frames too much.\n return true;\n }\n const elapsedTime = accumulatedElapsedTime;\n accumulatedElapsedTime = 0;\n\n // Manage resize events.\n if (this._notifyScenesForGameResolutionResize) {\n this._sceneStack.onGameResolutionResized();\n this._notifyScenesForGameResolutionResize = false;\n }\n\n // Render and step the scene.\n if (this._sceneStack.step(elapsedTime)) {\n this.getInputManager().onFrameEnded();\n this._hasJustResumed = false;\n return true;\n }\n return false;\n } catch (e) {\n if (this._debuggerClient)\n this._debuggerClient.onUncaughtException(e);\n\n throw e;\n }\n });\n setTimeout(() => {\n this._setupSessionMetrics();\n }, 4000);\n if (this._captureManager) {\n this._captureManager.setupCaptureOptions(this._isPreview);\n }\n } catch (e) {\n if (this._debuggerClient) this._debuggerClient.onUncaughtException(e);\n\n throw e;\n }\n }\n\n /**\n * Stop game loop, unload all scenes, dispose renderer and resources.\n * After calling this method, the RuntimeGame should not be used anymore.\n * @param removeCanvas If true, the canvas will be removed from the DOM.\n */\n dispose(removeCanvas?: boolean): void {\n this._renderer.stopGameLoop();\n this._sceneStack.dispose();\n this._renderer.dispose(removeCanvas);\n this._resourcesLoader.dispose();\n\n this._wasDisposed = true;\n }\n\n /**\n * Set if the session should be registered.\n */\n enableMetrics(enable: boolean): void {\n this._disableMetrics = !enable;\n if (enable) {\n this._setupSessionMetrics();\n }\n }\n\n /**\n * Helper function to get information about the platform running the game.\n */\n getPlatformInfo = () => {\n return {\n // @ts-ignore\n isCordova: !!window.cordova,\n devicePlatform:\n // @ts-ignore\n typeof device !== 'undefined' ? device.platform || '' : '',\n navigatorPlatform:\n typeof navigator !== 'undefined' ? navigator.platform : '',\n hasTouch:\n typeof navigator !== 'undefined'\n ? !!navigator.maxTouchPoints && navigator.maxTouchPoints > 2\n : false,\n supportedCompressionMethods: getSupportedCompressionMethods(),\n };\n };\n\n _setupGameVisibilityEvents() {\n if (typeof navigator !== 'undefined' && typeof document !== 'undefined') {\n document.addEventListener('visibilitychange', () => {\n if (document.visibilityState === 'visible') {\n this._hasJustResumed = true;\n }\n });\n window.addEventListener(\n 'resume',\n () => {\n this._hasJustResumed = true;\n },\n false\n );\n }\n }\n\n /**\n * Register a new session for the game, and set up listeners to follow the session\n * time.\n */\n _setupSessionMetrics() {\n if (this._sessionMetricsInitialized) {\n return;\n }\n if (this._disableMetrics) {\n return;\n }\n if (this.isPreview()) {\n return;\n }\n if (typeof fetch === 'undefined') {\n return;\n }\n if (!this._data.properties.projectUuid) {\n return;\n }\n const baseUrl = 'https://api.gdevelop-app.com/analytics';\n this._playerId = this._makePlayerUuid();\n /**\n * The duration that is already sent to the service\n * (in milliseconds).\n **/\n let sentDuration = 0;\n /**\n * The duration that is not yet sent to the service to avoid flooding\n * (in milliseconds).\n **/\n let notYetSentDuration = 0;\n /**\n * The last time when duration has been counted\n * either in sendedDuration or notYetSentDuration.\n **/\n let lastSessionResumeTime = Date.now();\n const platform = this.getPlatformInfo();\n fetch(baseUrl + '/session', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n // It's important to ensure that the data sent here does not contain\n // any personal information from the player or that would allow to\n // precisely identify someone.\n body: JSON.stringify({\n gameId: this._data.properties.projectUuid,\n playerId: this._playerId,\n game: {\n name: this._data.properties.name || '',\n packageName: this._data.properties.packageName || '',\n version: this._data.properties.version || '',\n location: window.location.href,\n },\n platform: {\n isCordova: platform.isCordova,\n devicePlatform: platform.devicePlatform,\n navigatorPlatform: platform.navigatorPlatform,\n hasTouch: platform.hasTouch,\n },\n }),\n })\n .then((response) => {\n // Ensure the session is correctly created to avoid sending hits that will fail.\n if (!response.ok) {\n console.error('Error while creating the session', response);\n throw new Error('Error while creating the session');\n }\n return response;\n })\n .then((response) => response.text())\n .then((returnedSessionId) => {\n this._sessionId = returnedSessionId;\n })\n .catch(() => {});\n\n /* Ignore any error */\n const sendSessionHit = () => {\n if (!this._sessionId) {\n return;\n }\n\n const now = Date.now();\n notYetSentDuration += now - lastSessionResumeTime;\n lastSessionResumeTime = now;\n\n // Group repeated calls to sendSessionHit - which could\n // happen because of multiple event listeners being fired.\n if (notYetSentDuration < 5 * 1000) {\n return;\n }\n // The backend use seconds for duration.\n // The milliseconds will stay in notYetSentDuration.\n const toBeSentDuration = Math.floor(notYetSentDuration / 1000) * 1000;\n sentDuration += toBeSentDuration;\n notYetSentDuration -= toBeSentDuration;\n\n navigator.sendBeacon(\n baseUrl + '/session-hit',\n JSON.stringify({\n gameId: this._data.properties.projectUuid,\n playerId: this._playerId,\n sessionId: this._sessionId,\n duration: Math.floor(sentDuration / 1000),\n })\n );\n };\n if (typeof navigator !== 'undefined' && typeof document !== 'undefined') {\n document.addEventListener('visibilitychange', () => {\n if (document.visibilityState === 'visible') {\n // Skip the duration the game was hidden.\n lastSessionResumeTime = Date.now();\n } else {\n sendSessionHit();\n }\n });\n window.addEventListener('pagehide', sendSessionHit, false);\n // Cordova events\n window.addEventListener('pause', sendSessionHit, false);\n window.addEventListener(\n 'resume',\n () => {\n // Skip the duration the game was hidden.\n lastSessionResumeTime = Date.now();\n },\n false\n );\n\n // Detect Safari to work around Safari-specific bugs:\n // - https://bugs.webkit.org/show_bug.cgi?id=151610\n // - https://bugs.webkit.org/show_bug.cgi?id=151234\n // @ts-ignore\n const isSafari = typeof safari === 'object' && safari.pushNotification;\n const isElectron = /electron/i.test(navigator.userAgent);\n if (isSafari || isElectron) {\n window.addEventListener('beforeunload', () => {\n sendSessionHit();\n });\n }\n }\n this._sessionMetricsInitialized = true;\n this._sessionId = this._sessionId;\n }\n\n /**\n * Generate an anonymous unique identifier to differentiate\n * the player from others in the game metrics.\n */\n _makePlayerUuid(): string {\n try {\n const key = 'GDJS-internal-player-uuid';\n const existingPlayerUuid = localStorage.getItem(key);\n if (existingPlayerUuid) {\n return existingPlayerUuid;\n }\n const newPlayerUuid = gdjs.makeUuid();\n localStorage.setItem(key, newPlayerUuid);\n return newPlayerUuid;\n } catch (err) {\n return gdjs.makeUuid();\n }\n }\n\n getSessionId(): string | null {\n return this._sessionId;\n }\n\n getPlayerId(): string | null {\n return this._playerId;\n }\n\n /**\n * Called by the game renderer when the window containing the game\n * has changed size (this can result from a resize of the window,\n * but also other factors like a device orientation change on mobile).\n */\n onWindowInnerSizeChanged() {\n this._forceGameResolutionUpdate();\n }\n\n /**\n * Enlarge/reduce the width (or the height) of the game to fill the inner window.\n */\n private _forceGameResolutionUpdate() {\n this.setGameResolutionSize(\n this._gameResolutionWidth,\n this._gameResolutionHeight\n );\n }\n\n /**\n * Start a profiler for the currently running scene.\n * @param onProfilerStopped Function to be called when the profiler is stopped. Will be passed the profiler as argument.\n */\n startCurrentSceneProfiler(\n onProfilerStopped: (oldProfiler: Profiler) => void\n ) {\n this._throwIfDisposed();\n const currentScene = this._sceneStack.getCurrentScene();\n if (!currentScene) {\n return false;\n }\n currentScene.startProfiler(onProfilerStopped);\n return true;\n }\n\n /**\n * Stop the profiler for the currently running scene.\n */\n stopCurrentSceneProfiler() {\n this._throwIfDisposed();\n const currentScene = this._sceneStack.getCurrentScene();\n if (!currentScene) {\n return;\n }\n currentScene.stopProfiler();\n }\n\n /**\n * Return true if a scene was loaded, false otherwise (i.e: game not yet started).\n */\n wasFirstSceneLoaded(): boolean {\n return this._sceneStack.wasFirstSceneLoaded();\n }\n\n /**\n * Return the stack of {@link gdjs.RuntimeScene} being played.\n */\n getSceneStack(): gdjs.SceneStack {\n return this._sceneStack;\n }\n\n /**\n * Check if the game is running as a preview, launched from an editor.\n * @returns true if the current game is a preview.\n */\n isPreview(): boolean {\n return this._isPreview;\n }\n\n /**\n * Check if the game should call GDevelop development APIs or not.\n *\n * Unless you are contributing to GDevelop, avoid using this.\n */\n isUsingGDevelopDevelopmentEnvironment(): boolean {\n return this._options.environment === 'dev';\n }\n\n /**\n * Gets an extension property from the project data.\n * @param extensionName The extension name.\n * @param propertyName The property name.\n * @return The property value.\n */\n getExtensionProperty(\n extensionName: string,\n propertyName: string\n ): string | null {\n for (let property of this._data.properties.extensionProperties) {\n if (\n property.extension === extensionName &&\n property.property === propertyName\n ) {\n return property.value;\n }\n }\n return null;\n }\n\n /**\n * Resolves the name of an embedded resource.\n * @param mainResourceName The name of the resource containing the embedded resource.\n * @param embeddedResourceName The name of the embedded resource.\n * @return The resource name.\n */\n resolveEmbeddedResource(\n mainResourceName: string,\n embeddedResourceName: string\n ): string {\n const mapping = this._embeddedResourcesMappings.get(mainResourceName);\n return mapping && mapping[embeddedResourceName]\n ? mapping[embeddedResourceName]\n : embeddedResourceName;\n }\n\n /**\n * Returns the array of resources that are embedded to passed one.\n * @param resourceName The name of resource to find embedded resources of.\n * @returns The array of related resources names.\n */\n getEmbeddedResourcesNames(resourceName: string): string[] {\n return this._embeddedResourcesMappings.has(resourceName)\n ? Object.keys(this._embeddedResourcesMappings.get(resourceName)!)\n : [];\n }\n\n getNetworkSyncData(\n syncOptions: GetNetworkSyncDataOptions\n ): GameNetworkSyncData | null {\n const syncData: GameNetworkSyncData = {\n var: this._variables.getNetworkSyncData(syncOptions),\n ss: this._sceneStack.getNetworkSyncData(syncOptions) || undefined,\n };\n\n const extensionsVariablesSyncData = {};\n this._variablesByExtensionName.forEach((variables, extensionName) => {\n const extensionVariablesSyncData =\n variables.getNetworkSyncData(syncOptions);\n // If there is no variables to sync, don't include the extension in the sync data.\n if (extensionVariablesSyncData.length) {\n extensionsVariablesSyncData[extensionName] =\n extensionVariablesSyncData;\n }\n });\n syncData.extVar = extensionsVariablesSyncData;\n\n if (\n (!syncData.var || syncData.var.length === 0) &&\n !syncData.ss &&\n (!syncData.extVar || Object.keys(syncData.extVar).length === 0)\n ) {\n // Nothing to sync.\n return null;\n }\n\n return syncData;\n }\n\n updateFromNetworkSyncData(syncData: GameNetworkSyncData) {\n this._throwIfDisposed();\n if (syncData.var) {\n this._variables.updateFromNetworkSyncData(syncData.var);\n }\n if (syncData.ss) {\n this._sceneStack.updateFromNetworkSyncData(syncData.ss);\n }\n if (syncData.extVar) {\n for (const extensionName in syncData.extVar) {\n if (!syncData.extVar.hasOwnProperty(extensionName)) {\n continue;\n }\n const extensionVariablesData = syncData.extVar[extensionName];\n const extensionVariables =\n this.getVariablesForExtension(extensionName);\n if (extensionVariables) {\n extensionVariables.updateFromNetworkSyncData(\n extensionVariablesData\n );\n }\n }\n }\n }\n\n private _throwIfDisposed(): void {\n if (this._wasDisposed) {\n throw 'The RuntimeGame has been disposed and should not be used anymore.';\n }\n }\n }\n}\n"],
|
|
5
|
-
"mappings": "AAKA,GAAU,MAAV,UAAU,EAAV,CACE,KAAM,GAAS,GAAI,GAAK,OAAO,gBAEzB,EAAQ,AAAC,GACb,GAAI,SAAQ,AAAC,GAAY,WAAW,EAAS,IAUzC,EAAyB,AAAC,GAC9B,EAAY,cAAc,IAAI,AAAC,GAAa,EAAS,MAEvD,GAAI,GAAmE,KACvE,KAAM,GAAiC,IAAoC,CACzE,GAAM,EACJ,MAAO,GAET,EAA8B,GAE9B,GAAI,CAEF,GAAI,mBAAkB,QACtB,EAA4B,KAAK,gBACjC,EACF,GAAI,CAEF,GAAI,mBAAkB,WACtB,EAA4B,KAAK,mBACjC,EAEF,MAAO,IAuFF,OAAkB,
|
|
4
|
+
"sourcesContent": ["/*\n * GDevelop JS Platform\n * Copyright 2013-2016 Florian Rival (Florian.Rival@gmail.com). All rights reserved.\n * This project is released under the MIT License.\n */\nnamespace gdjs {\n const logger = new gdjs.Logger('Game manager');\n\n const sleep = (ms: float) =>\n new Promise((resolve) => setTimeout(resolve, ms));\n\n /** Identify a script file, with its content hash (useful for hot-reloading). */\n export type RuntimeGameOptionsScriptFile = {\n /** The path for this script file. */\n path: string;\n /** The hash of the script file content. */\n hash: number;\n };\n\n const getGlobalResourceNames = (projectData: ProjectData): Array<string> =>\n projectData.usedResources.map((resource) => resource.name);\n\n let supportedCompressionMethods: ('cs:gzip' | 'cs:deflate')[] | null = null;\n const getSupportedCompressionMethods = (): ('cs:gzip' | 'cs:deflate')[] => {\n if (!!supportedCompressionMethods) {\n return supportedCompressionMethods;\n }\n supportedCompressionMethods = [];\n\n try {\n // @ts-ignore - We are checking if the CompressionStream is available.\n new CompressionStream('gzip');\n supportedCompressionMethods.push('cs:gzip');\n } catch (e) {}\n try {\n // @ts-ignore - We are checking if the CompressionStream is available.\n new CompressionStream('deflate');\n supportedCompressionMethods.push('cs:deflate');\n } catch (e) {}\n\n return supportedCompressionMethods;\n };\n\n /** Options given to the game at startup. */\n export type RuntimeGameOptions = {\n /** if true, force fullscreen. */\n forceFullscreen?: boolean;\n /** if true, game is run as a preview launched from an editor. */\n isPreview?: boolean;\n /** The name of the external layout to create in the scene at position 0;0. */\n injectExternalLayout?: string;\n /** Script files, used for hot-reloading. */\n scriptFiles?: Array<RuntimeGameOptionsScriptFile>;\n /** if true, export is a partial preview without events. */\n projectDataOnlyExport?: boolean;\n /** if true, preview is launched from GDevelop native mobile app. */\n nativeMobileApp?: boolean;\n /** The address of the debugger server, to reach out using WebSocket. */\n websocketDebuggerServerAddress?: string;\n /** The port of the debugger server, to reach out using WebSocket. */\n websocketDebuggerServerPort?: string;\n\n /**\n * The path to require `@electron/remote` module.\n * This is only useful in a preview, where this can't be required from\n * `@electron/remote` directly as previews don't have any node_modules.\n * On the contrary, a game packaged with Electron as a standalone app\n * has its node_modules.\n * This can be removed once there are no more dependencies on\n * `@electron/remote` in the game engine and extensions.\n */\n electronRemoteRequirePath?: string;\n\n /**\n * The token to use by the game engine when requiring any resource stored on\n * GDevelop Cloud buckets. Note that this is only useful during previews.\n */\n gdevelopResourceToken?: string;\n\n /**\n * Check if, in some exceptional cases, we allow authentication\n * to be done through a iframe.\n * This is usually discouraged as the user can't verify that the authentication\n * window is a genuine one. It's only to be used in trusted contexts.\n */\n allowAuthenticationUsingIframeForPreview?: boolean;\n\n /** If set, the game will send crash reports to GDevelop APIs. */\n crashReportUploadLevel?: 'all' | 'exclude-javascript-code-events' | 'none';\n\n /** Arbitrary string explaining in which context the game is being played. */\n previewContext?: string;\n\n /** The GDevelop version used to build the game. */\n gdevelopVersionWithHash?: string;\n\n /** The template slug that was used to create the project. */\n projectTemplateSlug?: string;\n\n /** The source game id that was used to create the project. */\n sourceGameId?: string;\n\n /** Any capture that should be done during the preview. */\n captureOptions?: CaptureOptions;\n\n /** Message to display to the user during an in-app tutorial. */\n inAppTutorialMessageInPreview?: string;\n inAppTutorialMessagePositionInPreview?: string;\n\n /**\n * If set, this data is used to authenticate automatically when launching the game.\n * This is only useful during previews.\n */\n playerUsername?: string;\n playerId?: string;\n playerToken?: string;\n\n /**\n * If set, the game should use the specified environment for making calls\n * to GDevelop APIs (\"dev\" = development APIs).\n */\n environment?: 'dev';\n };\n\n /**\n * Represents a game being played.\n */\n export class RuntimeGame {\n _resourcesLoader: gdjs.ResourceLoader;\n _variables: VariablesContainer;\n _variablesByExtensionName: Map<string, gdjs.VariablesContainer>;\n _data: ProjectData;\n _sceneAndExtensionsData: Array<SceneAndExtensionsData> = [];\n _eventsBasedObjectDatas: Map<String, EventsBasedObjectData>;\n _effectsManager: EffectsManager;\n _maxFPS: integer;\n _minFPS: integer;\n _gameResolutionWidth: integer;\n _gameResolutionHeight: integer;\n _originalWidth: float;\n _originalHeight: float;\n _resizeMode: 'adaptWidth' | 'adaptHeight' | string;\n _adaptGameResolutionAtRuntime: boolean;\n _scaleMode: 'linear' | 'nearest';\n _pixelsRounding: boolean;\n _antialiasingMode: 'none' | 'MSAA';\n _isAntialisingEnabledOnMobile: boolean;\n /**\n * Game loop management (see startGameLoop method)\n */\n _renderer: RuntimeGameRenderer;\n _sessionId: string | null;\n _playerId: string | null;\n _watermark: watermark.RuntimeWatermark;\n\n _sceneStack: SceneStack;\n /**\n * When set to true, the scenes are notified that game resolution size changed.\n */\n _notifyScenesForGameResolutionResize: boolean = false;\n\n /**\n * When paused, the game won't step and will be freezed. Useful for debugging.\n */\n _paused: boolean = false;\n\n /**\n * True during the first frame the game is back from being hidden.\n * This has nothing to do with `_paused`.\n */\n _hasJustResumed: boolean = false;\n\n //Inputs :\n _inputManager: InputManager;\n\n /**\n * Allow to specify an external layout to insert in the first scene.\n */\n _injectExternalLayout: any;\n _options: RuntimeGameOptions;\n\n /**\n * The mappings for embedded resources\n */\n _embeddedResourcesMappings: Map<string, Record<string, string>>;\n\n _sceneResourcesPreloading: 'at-startup' | 'never';\n _sceneResourcesUnloading: 'at-scene-exit' | 'never';\n\n /**\n * Optional client to connect to a debugger server.\n */\n _debuggerClient: gdjs.AbstractDebuggerClient | null;\n _sessionMetricsInitialized: boolean = false;\n _disableMetrics: boolean = false;\n _isPreview: boolean;\n\n /**\n * The capture manager, used to manage captures (screenshots, videos, etc...).\n */\n _captureManager: CaptureManager | null;\n\n /** True if the RuntimeGame has been disposed and should not be used anymore. */\n _wasDisposed: boolean = false;\n\n /**\n * @param data The object (usually stored in data.json) containing the full project data\n * @param options The game options\n */\n constructor(data: ProjectData, options?: RuntimeGameOptions) {\n this._options = options || {};\n this._variables = new gdjs.VariablesContainer(data.variables);\n this._variablesByExtensionName = new Map<\n string,\n gdjs.VariablesContainer\n >();\n for (const extensionData of data.eventsFunctionsExtensions) {\n if (extensionData.globalVariables.length > 0) {\n this._variablesByExtensionName.set(\n extensionData.name,\n new gdjs.VariablesContainer(extensionData.globalVariables)\n );\n }\n }\n this._eventsBasedObjectDatas = new Map<String, EventsBasedObjectData>();\n this._data = data;\n this._updateSceneAndExtensionsData();\n\n this._sceneResourcesPreloading =\n this._data.properties.sceneResourcesPreloading || 'at-startup';\n this._sceneResourcesUnloading =\n this._data.properties.sceneResourcesUnloading || 'never';\n\n this._resourcesLoader = new gdjs.ResourceLoader(\n this,\n data.resources.resources,\n getGlobalResourceNames(data),\n data.layouts\n );\n\n this._effectsManager = new gdjs.EffectsManager();\n this._maxFPS = this._data.properties.maxFPS;\n this._minFPS = this._data.properties.minFPS;\n this._gameResolutionWidth = this._data.properties.windowWidth;\n this._gameResolutionHeight = this._data.properties.windowHeight;\n this._originalWidth = this._gameResolutionWidth;\n this._originalHeight = this._gameResolutionHeight;\n this._resizeMode = this._data.properties.sizeOnStartupMode;\n this._adaptGameResolutionAtRuntime =\n this._data.properties.adaptGameResolutionAtRuntime;\n this._scaleMode = data.properties.scaleMode || 'linear';\n this._pixelsRounding = this._data.properties.pixelsRounding;\n this._antialiasingMode = this._data.properties.antialiasingMode;\n this._isAntialisingEnabledOnMobile =\n this._data.properties.antialisingEnabledOnMobile;\n\n this._renderer = new gdjs.RuntimeGameRenderer(\n this,\n this._options.forceFullscreen || false\n );\n this._watermark = new gdjs.watermark.RuntimeWatermark(\n this,\n data.properties.authorUsernames,\n this._data.properties.watermark\n );\n this._sceneStack = new gdjs.SceneStack(this);\n this._inputManager = new gdjs.InputManager();\n this._injectExternalLayout = this._options.injectExternalLayout || '';\n this._debuggerClient = gdjs.DebuggerClient\n ? new gdjs.DebuggerClient(this)\n : null;\n this._captureManager = gdjs.CaptureManager\n ? new gdjs.CaptureManager(\n this._renderer,\n this._options.captureOptions || {}\n )\n : null;\n this._isPreview = this._options.isPreview || false;\n this._sessionId = null;\n this._playerId = null;\n\n this._embeddedResourcesMappings = new Map();\n for (const resource of this._data.resources.resources) {\n if (resource.metadata) {\n try {\n const metadata = JSON.parse(resource.metadata);\n if (metadata?.embeddedResourcesMapping) {\n this._embeddedResourcesMappings.set(\n resource.name,\n metadata.embeddedResourcesMapping\n );\n }\n } catch {\n logger.error(\n 'Some metadata of resources can not be successfully parsed.'\n );\n }\n }\n }\n\n if (this.isUsingGDevelopDevelopmentEnvironment()) {\n logger.info(\n 'This game will run on the development version of GDevelop APIs.'\n );\n }\n }\n\n /**\n * Update the project data. Useful for hot-reloading, should not be used otherwise.\n *\n * @param projectData The object (usually stored in data.json) containing the full project data\n */\n setProjectData(projectData: ProjectData): void {\n this._data = projectData;\n this._updateSceneAndExtensionsData();\n this._resourcesLoader.setResources(\n projectData.resources.resources,\n getGlobalResourceNames(projectData),\n projectData.layouts\n );\n }\n\n private _updateSceneAndExtensionsData(): void {\n const usedExtensionsWithVariablesData =\n this._data.eventsFunctionsExtensions.filter(\n (extensionData) => extensionData.sceneVariables.length > 0\n );\n this._sceneAndExtensionsData = this._data.layouts.map((sceneData) => ({\n sceneData,\n usedExtensionsWithVariablesData,\n }));\n\n this._eventsBasedObjectDatas.clear();\n if (this._data.eventsFunctionsExtensions) {\n for (const extension of this._data.eventsFunctionsExtensions) {\n for (const eventsBasedObject of extension.eventsBasedObjects) {\n this._eventsBasedObjectDatas.set(\n extension.name + '::' + eventsBasedObject.name,\n eventsBasedObject\n );\n }\n }\n }\n }\n\n /**\n * Return the additional options passed to the RuntimeGame when created.\n * @returns The additional options, if any.\n */\n getAdditionalOptions(): RuntimeGameOptions {\n return this._options;\n }\n\n getRenderer(): gdjs.RuntimeGameRenderer {\n return this._renderer;\n }\n\n /**\n * Get the variables of the RuntimeGame.\n * @return The global variables\n */\n getVariables(): gdjs.VariablesContainer {\n return this._variables;\n }\n\n /**\n * Get the extension's global variables.\n * @param extensionName The extension name.\n * @returns The extension's global variables.\n */\n getVariablesForExtension(extensionName: string) {\n return this._variablesByExtensionName.get(extensionName) || null;\n }\n\n /**\n * Get the gdjs.ResourceLoader of the RuntimeGame.\n * @return The resource loader.\n */\n getResourceLoader(): gdjs.ResourceLoader {\n return this._resourcesLoader;\n }\n\n /**\n * Get the gdjs.SoundManager of the RuntimeGame.\n * @return The sound manager.\n */\n getSoundManager(): gdjs.HowlerSoundManager {\n return this._resourcesLoader.getSoundManager();\n }\n\n /**\n * Get the gdjs.ImageManager of the RuntimeGame.\n * @return The image manager.\n */\n getImageManager(): gdjs.PixiImageManager {\n return this._resourcesLoader.getImageManager();\n }\n\n /**\n * Get the gdjs.FontManager of the RuntimeGame.\n * @return The font manager.\n */\n getFontManager(): gdjs.FontFaceObserverFontManager {\n return this._resourcesLoader.getFontManager();\n }\n\n /**\n * Get the gdjs.BitmapFontManager of the RuntimeGame.\n * @return The bitmap font manager.\n */\n getBitmapFontManager(): gdjs.BitmapFontManager {\n return this._resourcesLoader.getBitmapFontManager();\n }\n\n /**\n * Get the JSON manager of the game, used to load JSON from game\n * resources.\n * @return The json manager for the game\n */\n getJsonManager(): gdjs.JsonManager {\n return this._resourcesLoader.getJsonManager();\n }\n\n /**\n * Get the 3D model manager of the game, used to load 3D model from game\n * resources.\n * @return The 3D model manager for the game\n */\n getModel3DManager(): gdjs.Model3DManager {\n return this._resourcesLoader.getModel3DManager();\n }\n\n /**\n * Get the Spine manager of the game, used to load and construct spine skeletons from game\n * resources.\n * @return The Spine manager for the game\n */\n getSpineManager(): gdjs.SpineManager | null {\n return this._resourcesLoader.getSpineManager();\n }\n\n /**\n * Get the Spine Atlas manager of the game, used to load atlases from game\n * resources.\n * @return The Spine Atlas manager for the game\n */\n getSpineAtlasManager(): gdjs.SpineAtlasManager | null {\n return this._resourcesLoader.getSpineAtlasManager();\n }\n\n /**\n * Get the input manager of the game, storing mouse, keyboard\n * and touches states.\n * @return The input manager owned by the game\n */\n getInputManager(): gdjs.InputManager {\n return this._inputManager;\n }\n\n /**\n * Get the effects manager of the game, which allows to manage\n * effects on runtime objects or runtime layers.\n * @return The effects manager for the game\n */\n getEffectsManager(): gdjs.EffectsManager {\n return this._effectsManager;\n }\n\n /**\n * Get the object containing the game data\n * @return The object associated to the game.\n */\n getGameData(): ProjectData {\n return this._data;\n }\n\n getEventsBasedObjectData(type: string): EventsBasedObjectData | null {\n const eventsBasedObjectData = this._eventsBasedObjectDatas.get(type);\n if (!eventsBasedObjectData) {\n logger.error(\n 'The game has no events-based object of the type \"' + type + '\"'\n );\n return null;\n }\n return eventsBasedObjectData;\n }\n\n /**\n * Get the data associated to a scene.\n *\n * @param sceneName The name of the scene. If not defined, the first scene will be returned.\n * @return The data associated to the scene.\n */\n getSceneAndExtensionsData(\n sceneName?: string\n ): SceneAndExtensionsData | null {\n for (let i = 0, len = this._sceneAndExtensionsData.length; i < len; ++i) {\n const sceneAndExtensionsData = this._sceneAndExtensionsData[i];\n if (\n sceneName === undefined ||\n sceneAndExtensionsData.sceneData.name === sceneName\n ) {\n return sceneAndExtensionsData;\n }\n }\n logger.error('The game has no scene called \"' + sceneName + '\"');\n return null;\n }\n\n /**\n * Check if a scene exists\n *\n * @param sceneName The name of the scene to search.\n * @return true if the scene exists. If sceneName is undefined, true if the game has a scene.\n */\n hasScene(sceneName?: string): boolean {\n for (let i = 0, len = this._data.layouts.length; i < len; ++i) {\n const sceneData = this._data.layouts[i];\n if (sceneName === undefined || sceneData.name == sceneName) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Get the data associated to an external layout.\n *\n * @param name The name of the external layout.\n * @return The data associated to the external layout or null if not found.\n */\n getExternalLayoutData(name: string): ExternalLayoutData | null {\n let externalLayout: ExternalLayoutData | null = null;\n for (let i = 0, len = this._data.externalLayouts.length; i < len; ++i) {\n const layoutData = this._data.externalLayouts[i];\n if (layoutData.name === name) {\n externalLayout = layoutData;\n break;\n }\n }\n return externalLayout;\n }\n\n /**\n * Get the data representing all the global objects of the game.\n * @return The data associated to the global objects.\n */\n getInitialObjectsData(): ObjectData[] {\n return this._data.objects || [];\n }\n\n /**\n * Get the original width of the game, as set on the startup of the game.\n *\n * This is guaranteed to never change, even if the size of the game is changed afterwards.\n */\n getOriginalWidth(): float {\n return this._originalWidth;\n }\n\n /**\n * Get the original height of the game, as set on the startup of the game.\n *\n * This is guaranteed to never change, even if the size of the game is changed afterwards.\n */\n getOriginalHeight(): float {\n return this._originalHeight;\n }\n\n /**\n * Get the game resolution (the size at which the game is played and rendered) width.\n * @returns The game resolution width, in pixels.\n */\n getGameResolutionWidth(): float {\n return this._gameResolutionWidth;\n }\n\n /**\n * Get the game resolution (the size at which the game is played and rendered) height.\n * @returns The game resolution height, in pixels.\n */\n getGameResolutionHeight(): float {\n return this._gameResolutionHeight;\n }\n\n /**\n * Change the game resolution.\n *\n * @param width The new width\n * @param height The new height\n */\n setGameResolutionSize(width: float, height: float): void {\n this._throwIfDisposed();\n\n this._gameResolutionWidth = width;\n this._gameResolutionHeight = height;\n if (this._adaptGameResolutionAtRuntime) {\n if (\n gdjs.RuntimeGameRenderer &&\n gdjs.RuntimeGameRenderer.getWindowInnerWidth &&\n gdjs.RuntimeGameRenderer.getWindowInnerHeight\n ) {\n const windowInnerWidth =\n gdjs.RuntimeGameRenderer.getWindowInnerWidth();\n const windowInnerHeight =\n gdjs.RuntimeGameRenderer.getWindowInnerHeight();\n\n // Enlarge either the width or the eight to fill the inner window space.\n if (this._resizeMode === 'adaptWidth') {\n this._gameResolutionWidth =\n (this._gameResolutionHeight * windowInnerWidth) /\n windowInnerHeight;\n } else if (this._resizeMode === 'adaptHeight') {\n this._gameResolutionHeight =\n (this._gameResolutionWidth * windowInnerHeight) /\n windowInnerWidth;\n } else if (this._resizeMode === 'scaleOuter') {\n const widthFactor = windowInnerWidth / this._originalWidth;\n const heightFactor = windowInnerHeight / this._originalHeight;\n\n if (widthFactor < heightFactor) {\n this._gameResolutionWidth = this._originalWidth;\n this._gameResolutionHeight = Math.floor(\n windowInnerHeight / widthFactor\n );\n } else {\n this._gameResolutionWidth = Math.floor(\n windowInnerWidth / heightFactor\n );\n this._gameResolutionHeight = this._originalHeight;\n }\n }\n }\n }\n\n // Don't alter the game resolution. The renderer\n // will maybe adapt the size of the canvas or whatever is used to render the\n // game in the window, but this does not change the \"game resolution\".\n\n // Notify the renderer that game resolution changed (so that the renderer size\n // can be updated, and maybe other things like the canvas size), and let the\n // scenes know too.\n this._renderer.updateRendererSize();\n this._notifyScenesForGameResolutionResize = true;\n }\n\n /**\n * Set if the width or the height of the game resolution\n * should be changed to fit the game window - or if the game\n * resolution should not be updated automatically.\n *\n * @param resizeMode Either \"\" (don't change game resolution), \"adaptWidth\" or \"adaptHeight\".\n */\n setGameResolutionResizeMode(resizeMode: string): void {\n this._resizeMode = resizeMode;\n this._forceGameResolutionUpdate();\n }\n\n /**\n * Returns if the width or the height of the game resolution\n * should be changed to fit the game window - or if the game\n * resolution should not be updated automatically (empty string).\n *\n * @returns Either \"\" (don't change game resolution), \"adaptWidth\" or \"adaptHeight\".\n */\n getGameResolutionResizeMode(): string {\n return this._resizeMode;\n }\n\n /**\n * Set if the game resolution should be automatically adapted\n * when the game window or screen size change. This will only\n * be the case if the game resolution resize mode is\n * configured to adapt the width or the height of the game.\n * @param enable true to change the game resolution according to the window/screen size.\n */\n setAdaptGameResolutionAtRuntime(enable: boolean): void {\n this._adaptGameResolutionAtRuntime = enable;\n this._forceGameResolutionUpdate();\n }\n\n /**\n * Returns if the game resolution should be automatically adapted\n * when the game window or screen size change. This will only\n * be the case if the game resolution resize mode is\n * configured to adapt the width or the height of the game.\n * @returns true if the game resolution is automatically changed according to the window/screen size.\n */\n getAdaptGameResolutionAtRuntime(): boolean {\n return this._adaptGameResolutionAtRuntime;\n }\n\n /**\n * Return the minimal fps that must be guaranteed by the game\n * (otherwise, game is slowed down).\n */\n getMinimalFramerate(): integer {\n return this._minFPS;\n }\n\n /**\n * Return the scale mode of the game (\"linear\" or \"nearest\").\n */\n getScaleMode(): 'linear' | 'nearest' {\n return this._scaleMode;\n }\n\n /**\n * Return if the game is rounding pixels when rendering.\n */\n getPixelsRounding(): boolean {\n return this._pixelsRounding;\n }\n\n /**\n * Return the antialiasing mode used by the game (\"none\" or \"MSAA\").\n */\n getAntialiasingMode(): 'none' | 'MSAA' {\n return this._antialiasingMode;\n }\n\n /**\n * Return true if antialising is enabled on mobiles.\n */\n isAntialisingEnabledOnMobile(): boolean {\n return this._isAntialisingEnabledOnMobile;\n }\n\n /**\n * Set or unset the game as paused.\n * When paused, the game won't step and will be freezed. Useful for debugging.\n * @param enable true to pause the game, false to unpause\n */\n pause(enable: boolean) {\n if (this._paused === enable) return;\n\n this._paused = enable;\n if (this._debuggerClient) {\n if (this._paused) this._debuggerClient.sendGamePaused();\n else this._debuggerClient.sendGameResumed();\n }\n }\n\n /**\n * @returns true during the first frame the game is back from being hidden.\n * This has nothing to do with `_paused`.\n */\n hasJustResumed() {\n return this._hasJustResumed;\n }\n\n /**\n * Preload a scene assets as soon as possible in background.\n */\n prioritizeLoadingOfScene(sceneName: string) {\n // Don't await the scene assets to be loaded.\n this._resourcesLoader.loadSceneResources(sceneName);\n }\n\n /**\n * @return The progress of assets loading in background for a scene\n * (between 0 and 1).\n */\n getSceneLoadingProgress(sceneName: string): number {\n return this._resourcesLoader.getSceneLoadingProgress(sceneName);\n }\n\n /**\n * @returns true when all the resources of the given scene are loaded\n * (but maybe not parsed).\n */\n areSceneAssetsLoaded(sceneName: string): boolean {\n return this._resourcesLoader.areSceneAssetsLoaded(sceneName);\n }\n\n /**\n * @returns true when all the resources of the given scene are loaded and\n * parsed.\n */\n areSceneAssetsReady(sceneName: string): boolean {\n return this._resourcesLoader.areSceneAssetsReady(sceneName);\n }\n\n /**\n * Returns the scene resources preloading mode.\n * It can be overriden by each scene.\n */\n getSceneResourcesPreloading(): 'at-startup' | 'never' {\n return this._sceneResourcesPreloading;\n }\n\n /**\n * Returns the scene resources unloading mode.\n * It can be overriden by each scene.\n */\n getSceneResourcesUnloading(): 'at-scene-exit' | 'never' {\n return this._sceneResourcesUnloading;\n }\n\n /**\n * Load all assets needed to display the 1st scene, displaying progress in\n * renderer.\n */\n loadAllAssets(\n callback: () => void,\n progressCallback?: (progress: float) => void\n ) {\n this._throwIfDisposed();\n this.loadFirstAssetsAndStartBackgroundLoading(\n this._getFirstSceneName(),\n progressCallback\n ).then(callback);\n }\n\n /**\n * Load all assets needed to display the 1st scene, displaying progress in\n * renderer.\n *\n * When a game is hot-reload, this method can be called with the current\n * scene.\n */\n async loadFirstAssetsAndStartBackgroundLoading(\n firstSceneName: string,\n progressCallback?: (progress: float) => void\n ): Promise<void> {\n try {\n // Download the loading screen background image first to be able to\n // display the loading screen as soon as possible.\n const backgroundImageResourceName =\n this._data.properties.loadingScreen.backgroundImageResourceName;\n if (backgroundImageResourceName) {\n await this._resourcesLoader\n .getImageManager()\n .loadResource(backgroundImageResourceName);\n }\n await Promise.all([\n this._loadAssetsWithLoadingScreen(\n /* isFirstScene = */ true,\n async (onProgress) => {\n // TODO Is a setting needed?\n if (false) {\n await this._resourcesLoader.loadAllResources(onProgress);\n } else {\n await this._resourcesLoader.loadGlobalAndFirstSceneResources(\n firstSceneName,\n onProgress\n );\n // Don't await as it must not block the first scene from starting.\n this._resourcesLoader.loadAllSceneInBackground();\n }\n },\n progressCallback\n ),\n // TODO This is probably not necessary in case of hot reload.\n gdjs.getAllAsynchronouslyLoadingLibraryPromise(),\n ]);\n } catch (e) {\n if (this._debuggerClient) this._debuggerClient.onUncaughtException(e);\n\n throw e;\n }\n }\n\n /**\n * Load all assets for a given scene, displaying progress in renderer.\n */\n async loadSceneAssets(\n sceneName: string,\n progressCallback?: (progress: float) => void\n ): Promise<void> {\n await this._loadAssetsWithLoadingScreen(\n /* isFirstLayout = */ false,\n async (onProgress) => {\n await this._resourcesLoader.loadAndProcessSceneResources(\n sceneName,\n onProgress\n );\n },\n progressCallback\n );\n }\n\n /**\n * Load assets, displaying progress in renderer.\n */\n private async _loadAssetsWithLoadingScreen(\n isFirstScene: boolean,\n loadAssets: (\n onProgress: (count: integer, total: integer) => Promise<void>\n ) => Promise<void>,\n progressCallback?: (progress: float) => void\n ): Promise<void> {\n this.pause(true);\n const loadingScreen = new gdjs.LoadingScreenRenderer(\n this.getRenderer(),\n this._resourcesLoader.getImageManager(),\n this._data.properties.loadingScreen,\n this._data.properties.watermark.showWatermark,\n isFirstScene\n );\n\n const onProgress = async (count: integer, total: integer) => {\n const percent = Math.floor((100 * count) / total);\n loadingScreen.setPercent(percent);\n if (progressCallback) {\n progressCallback(percent);\n }\n const hasRendered = loadingScreen.renderIfNeeded();\n if (hasRendered) {\n // Give a chance to draw calls from the renderer to be handled.\n await sleep(1);\n }\n };\n await loadAssets(onProgress);\n\n await loadingScreen.unload();\n this.pause(false);\n }\n\n private _getFirstSceneName(): string {\n const firstSceneName = this._data.firstLayout;\n return this.hasScene(firstSceneName)\n ? firstSceneName\n : // There is always at least a scene\n this.getSceneAndExtensionsData()!.sceneData.name;\n }\n\n /**\n * Start the game loop, to be called once assets are loaded.\n */\n startGameLoop() {\n this._throwIfDisposed();\n try {\n if (!this.hasScene()) {\n logger.error('The game has no scene.');\n return;\n }\n this._forceGameResolutionUpdate();\n\n // Load the first scene\n this._sceneStack.push(\n this._getFirstSceneName(),\n this._injectExternalLayout\n );\n this._watermark.displayAtStartup();\n\n //Uncomment to profile the first x frames of the game.\n // var x = 500;\n // var startTime = Date.now();\n // console.profile(\"Stepping for \" + x + \" frames\")\n // for(var i = 0; i < x; ++i) {\n // this._sceneStack.step(16);\n // }\n // console.profileEnd();\n // var time = Date.now() - startTime;\n // logger.log(\"Took\", time, \"ms\");\n // return;\n\n this._setupGameVisibilityEvents();\n\n if (gdjs.inAppTutorialMessage) {\n gdjs.inAppTutorialMessage.displayInAppTutorialMessage(\n this,\n this._options.inAppTutorialMessageInPreview,\n this._options.inAppTutorialMessagePositionInPreview || ''\n );\n }\n\n // The standard game loop\n let accumulatedElapsedTime = 0;\n this._hasJustResumed = false;\n this._renderer.startGameLoop((lastCallElapsedTime) => {\n try {\n if (this._paused) {\n return true;\n }\n\n // Skip the frame if we rendering frames too fast\n accumulatedElapsedTime += lastCallElapsedTime;\n if (\n this._maxFPS > 0 &&\n 1000.0 / accumulatedElapsedTime > this._maxFPS + 7\n ) {\n // Only skip frame if the framerate is 7 frames above the maximum framerate.\n // Most browser/engines will try to run at slightly more than 60 frames per second.\n // If game is set to have a maximum FPS to 60, then one out of two frames will be dropped.\n // Hence, we use a 7 frames margin to ensure that we're not skipping frames too much.\n return true;\n }\n const elapsedTime = accumulatedElapsedTime;\n accumulatedElapsedTime = 0;\n\n // Manage resize events.\n if (this._notifyScenesForGameResolutionResize) {\n this._sceneStack.onGameResolutionResized();\n this._notifyScenesForGameResolutionResize = false;\n }\n\n // Render and step the scene.\n if (this._sceneStack.step(elapsedTime)) {\n this.getInputManager().onFrameEnded();\n this._hasJustResumed = false;\n return true;\n }\n return false;\n } catch (e) {\n if (this._debuggerClient)\n this._debuggerClient.onUncaughtException(e);\n\n throw e;\n }\n });\n setTimeout(() => {\n this._setupSessionMetrics();\n }, 4000);\n if (this._captureManager) {\n this._captureManager.setupCaptureOptions(this._isPreview);\n }\n } catch (e) {\n if (this._debuggerClient) this._debuggerClient.onUncaughtException(e);\n\n throw e;\n }\n }\n\n /**\n * Stop game loop, unload all scenes, dispose renderer and resources.\n * After calling this method, the RuntimeGame should not be used anymore.\n * @param removeCanvas If true, the canvas will be removed from the DOM.\n */\n dispose(removeCanvas?: boolean): void {\n this._renderer.stopGameLoop();\n this._sceneStack.dispose();\n this._renderer.dispose(removeCanvas);\n this._resourcesLoader.dispose();\n\n this._wasDisposed = true;\n }\n\n /**\n * Set if the session should be registered.\n */\n enableMetrics(enable: boolean): void {\n this._disableMetrics = !enable;\n if (enable) {\n this._setupSessionMetrics();\n }\n }\n\n /**\n * Helper function to get information about the platform running the game.\n */\n getPlatformInfo = () => {\n return {\n // @ts-ignore\n isCordova: !!window.cordova,\n devicePlatform:\n // @ts-ignore\n typeof device !== 'undefined' ? device.platform || '' : '',\n navigatorPlatform:\n typeof navigator !== 'undefined' ? navigator.platform : '',\n hasTouch:\n typeof navigator !== 'undefined'\n ? !!navigator.maxTouchPoints && navigator.maxTouchPoints > 2\n : false,\n supportedCompressionMethods: getSupportedCompressionMethods(),\n };\n };\n\n _setupGameVisibilityEvents() {\n if (typeof navigator !== 'undefined' && typeof document !== 'undefined') {\n document.addEventListener('visibilitychange', () => {\n if (document.visibilityState === 'visible') {\n this._hasJustResumed = true;\n }\n });\n window.addEventListener(\n 'resume',\n () => {\n this._hasJustResumed = true;\n },\n false\n );\n }\n }\n\n /**\n * Register a new session for the game, and set up listeners to follow the session\n * time.\n */\n _setupSessionMetrics() {\n if (this._sessionMetricsInitialized) {\n return;\n }\n if (this._disableMetrics) {\n return;\n }\n if (this.isPreview()) {\n return;\n }\n if (typeof fetch === 'undefined') {\n return;\n }\n if (!this._data.properties.projectUuid) {\n return;\n }\n const baseUrl = 'https://api.gdevelop-app.com/analytics';\n this._playerId = this._makePlayerUuid();\n /**\n * The duration that is already sent to the service\n * (in milliseconds).\n **/\n let sentDuration = 0;\n /**\n * The duration that is not yet sent to the service to avoid flooding\n * (in milliseconds).\n **/\n let notYetSentDuration = 0;\n /**\n * The last time when duration has been counted\n * either in sendedDuration or notYetSentDuration.\n **/\n let lastSessionResumeTime = Date.now();\n const platform = this.getPlatformInfo();\n fetch(baseUrl + '/session', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n // It's important to ensure that the data sent here does not contain\n // any personal information from the player or that would allow to\n // precisely identify someone.\n body: JSON.stringify({\n gameId: this._data.properties.projectUuid,\n playerId: this._playerId,\n game: {\n name: this._data.properties.name || '',\n packageName: this._data.properties.packageName || '',\n version: this._data.properties.version || '',\n location: window.location.href,\n },\n platform: {\n isCordova: platform.isCordova,\n devicePlatform: platform.devicePlatform,\n navigatorPlatform: platform.navigatorPlatform,\n hasTouch: platform.hasTouch,\n },\n }),\n })\n .then((response) => {\n // Ensure the session is correctly created to avoid sending hits that will fail.\n if (!response.ok) {\n console.error('Error while creating the session', response);\n throw new Error('Error while creating the session');\n }\n return response;\n })\n .then((response) => response.text())\n .then((returnedSessionId) => {\n this._sessionId = returnedSessionId;\n })\n .catch(() => {});\n\n /* Ignore any error */\n const sendSessionHit = () => {\n if (!this._sessionId) {\n return;\n }\n\n const now = Date.now();\n notYetSentDuration += now - lastSessionResumeTime;\n lastSessionResumeTime = now;\n\n // Group repeated calls to sendSessionHit - which could\n // happen because of multiple event listeners being fired.\n if (notYetSentDuration < 5 * 1000) {\n return;\n }\n // The backend use seconds for duration.\n // The milliseconds will stay in notYetSentDuration.\n const toBeSentDuration = Math.floor(notYetSentDuration / 1000) * 1000;\n sentDuration += toBeSentDuration;\n notYetSentDuration -= toBeSentDuration;\n\n navigator.sendBeacon(\n baseUrl + '/session-hit',\n JSON.stringify({\n gameId: this._data.properties.projectUuid,\n playerId: this._playerId,\n sessionId: this._sessionId,\n duration: Math.floor(sentDuration / 1000),\n })\n );\n };\n if (typeof navigator !== 'undefined' && typeof document !== 'undefined') {\n document.addEventListener('visibilitychange', () => {\n if (document.visibilityState === 'visible') {\n // Skip the duration the game was hidden.\n lastSessionResumeTime = Date.now();\n } else {\n sendSessionHit();\n }\n });\n window.addEventListener('pagehide', sendSessionHit, false);\n // Cordova events\n window.addEventListener('pause', sendSessionHit, false);\n window.addEventListener(\n 'resume',\n () => {\n // Skip the duration the game was hidden.\n lastSessionResumeTime = Date.now();\n },\n false\n );\n\n // Detect Safari to work around Safari-specific bugs:\n // - https://bugs.webkit.org/show_bug.cgi?id=151610\n // - https://bugs.webkit.org/show_bug.cgi?id=151234\n // @ts-ignore\n const isSafari = typeof safari === 'object' && safari.pushNotification;\n const isElectron = /electron/i.test(navigator.userAgent);\n if (isSafari || isElectron) {\n window.addEventListener('beforeunload', () => {\n sendSessionHit();\n });\n }\n }\n this._sessionMetricsInitialized = true;\n this._sessionId = this._sessionId;\n }\n\n /**\n * Generate an anonymous unique identifier to differentiate\n * the player from others in the game metrics.\n */\n _makePlayerUuid(): string {\n try {\n const key = 'GDJS-internal-player-uuid';\n const existingPlayerUuid = localStorage.getItem(key);\n if (existingPlayerUuid) {\n return existingPlayerUuid;\n }\n const newPlayerUuid = gdjs.makeUuid();\n localStorage.setItem(key, newPlayerUuid);\n return newPlayerUuid;\n } catch (err) {\n return gdjs.makeUuid();\n }\n }\n\n getSessionId(): string | null {\n return this._sessionId;\n }\n\n getPlayerId(): string | null {\n return this._playerId;\n }\n\n /**\n * Called by the game renderer when the window containing the game\n * has changed size (this can result from a resize of the window,\n * but also other factors like a device orientation change on mobile).\n */\n onWindowInnerSizeChanged() {\n this._forceGameResolutionUpdate();\n }\n\n /**\n * Enlarge/reduce the width (or the height) of the game to fill the inner window.\n */\n private _forceGameResolutionUpdate() {\n this.setGameResolutionSize(\n this._gameResolutionWidth,\n this._gameResolutionHeight\n );\n }\n\n /**\n * Start a profiler for the currently running scene.\n * @param onProfilerStopped Function to be called when the profiler is stopped. Will be passed the profiler as argument.\n */\n startCurrentSceneProfiler(\n onProfilerStopped: (oldProfiler: Profiler) => void\n ) {\n this._throwIfDisposed();\n const currentScene = this._sceneStack.getCurrentScene();\n if (!currentScene) {\n return false;\n }\n currentScene.startProfiler(onProfilerStopped);\n return true;\n }\n\n /**\n * Stop the profiler for the currently running scene.\n */\n stopCurrentSceneProfiler() {\n this._throwIfDisposed();\n const currentScene = this._sceneStack.getCurrentScene();\n if (!currentScene) {\n return;\n }\n currentScene.stopProfiler();\n }\n\n /**\n * Return true if a scene was loaded, false otherwise (i.e: game not yet started).\n */\n wasFirstSceneLoaded(): boolean {\n return this._sceneStack.wasFirstSceneLoaded();\n }\n\n /**\n * Return the stack of {@link gdjs.RuntimeScene} being played.\n */\n getSceneStack(): gdjs.SceneStack {\n return this._sceneStack;\n }\n\n /**\n * Check if the game is running as a preview, launched from an editor.\n * @returns true if the current game is a preview.\n */\n isPreview(): boolean {\n return this._isPreview;\n }\n\n /**\n * Check if the game should call GDevelop development APIs or not.\n *\n * Unless you are contributing to GDevelop, avoid using this.\n */\n isUsingGDevelopDevelopmentEnvironment(): boolean {\n return this._options.environment === 'dev';\n }\n\n /**\n * Gets an extension property from the project data.\n * @param extensionName The extension name.\n * @param propertyName The property name.\n * @return The property value.\n */\n getExtensionProperty(\n extensionName: string,\n propertyName: string\n ): string | null {\n for (let property of this._data.properties.extensionProperties) {\n if (\n property.extension === extensionName &&\n property.property === propertyName\n ) {\n return property.value;\n }\n }\n return null;\n }\n\n /**\n * Resolves the name of an embedded resource.\n * @param mainResourceName The name of the resource containing the embedded resource.\n * @param embeddedResourceName The name of the embedded resource.\n * @return The resource name.\n */\n resolveEmbeddedResource(\n mainResourceName: string,\n embeddedResourceName: string\n ): string {\n const mapping = this._embeddedResourcesMappings.get(mainResourceName);\n return mapping && mapping[embeddedResourceName]\n ? mapping[embeddedResourceName]\n : embeddedResourceName;\n }\n\n /**\n * Returns the array of resources that are embedded to passed one.\n * @param resourceName The name of resource to find embedded resources of.\n * @returns The array of related resources names.\n */\n getEmbeddedResourcesNames(resourceName: string): string[] {\n return this._embeddedResourcesMappings.has(resourceName)\n ? Object.keys(this._embeddedResourcesMappings.get(resourceName)!)\n : [];\n }\n\n getNetworkSyncData(\n syncOptions: GetNetworkSyncDataOptions\n ): GameNetworkSyncData | null {\n const syncData: GameNetworkSyncData = {\n var: this._variables.getNetworkSyncData(syncOptions),\n ss: this._sceneStack.getNetworkSyncData(syncOptions) || undefined,\n };\n\n const extensionsVariablesSyncData = {};\n this._variablesByExtensionName.forEach((variables, extensionName) => {\n const extensionVariablesSyncData =\n variables.getNetworkSyncData(syncOptions);\n // If there is no variables to sync, don't include the extension in the sync data.\n if (extensionVariablesSyncData.length) {\n extensionsVariablesSyncData[extensionName] =\n extensionVariablesSyncData;\n }\n });\n syncData.extVar = extensionsVariablesSyncData;\n\n if (\n (!syncData.var || syncData.var.length === 0) &&\n !syncData.ss &&\n (!syncData.extVar || Object.keys(syncData.extVar).length === 0)\n ) {\n // Nothing to sync.\n return null;\n }\n\n return syncData;\n }\n\n updateFromNetworkSyncData(syncData: GameNetworkSyncData) {\n this._throwIfDisposed();\n if (syncData.var) {\n this._variables.updateFromNetworkSyncData(syncData.var);\n }\n if (syncData.ss) {\n this._sceneStack.updateFromNetworkSyncData(syncData.ss);\n }\n if (syncData.extVar) {\n for (const extensionName in syncData.extVar) {\n if (!syncData.extVar.hasOwnProperty(extensionName)) {\n continue;\n }\n const extensionVariablesData = syncData.extVar[extensionName];\n const extensionVariables =\n this.getVariablesForExtension(extensionName);\n if (extensionVariables) {\n extensionVariables.updateFromNetworkSyncData(\n extensionVariablesData\n );\n }\n }\n }\n }\n\n private _throwIfDisposed(): void {\n if (this._wasDisposed) {\n throw 'The RuntimeGame has been disposed and should not be used anymore.';\n }\n }\n }\n}\n"],
|
|
5
|
+
"mappings": "AAKA,GAAU,MAAV,UAAU,EAAV,CACE,KAAM,GAAS,GAAI,GAAK,OAAO,gBAEzB,EAAQ,AAA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0BAA0B,EAAS,KAEjD,EAAS,IACX,KAAK,YAAY,0BAA0B,EAAS,IAElD,EAAS,OACX,SAAW,KAAiB,GAAS,OAAQ,CAC3C,GAAI,CAAC,EAAS,OAAO,eAAe,GAClC,SAEF,KAAM,GAAyB,EAAS,OAAO,GACzC,EACJ,KAAK,yBAAyB,GAChC,AAAI,GACF,EAAmB,0BACjB,IAOF,kBAAyB,CAC/B,GAAI,KAAK,aACP,KAAM,qEAlyCL,EAAM,gBA1HL",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var gdjs;(function(i){const h=new i.Logger("RuntimeScene"),d=new i.Logger("RuntimeScene (setup warnings)");class c extends i.RuntimeInstanceContainer{constructor(t){super();this._eventsFunction=null;this._lastId=0;this._name="";this._gameStopRequested=!1;this._requestedScene="";this._asyncTasksManager=new i.AsyncTasksManager;this._isLoaded=!1;this._isJustResumed=!1;this._backgroundColor=0;this._clearCanvas=!0;this._profiler=null;this._onProfilerStopped=null;this.networkId=null;this._runtimeGame=t,this._variables=new i.VariablesContainer,this._variablesByExtensionName=new Map,this._timeManager=new i.TimeManager,this._onceTriggers=new i.OnceTriggers,this._requestedChange=l.CONTINUE,this._cachedGameResolutionWidth=t?t.getGameResolutionWidth():0,this._cachedGameResolutionHeight=t?t.getGameResolutionHeight():0,this._renderer=new i.RuntimeSceneRenderer(this,t?t.getRenderer():null),this._debuggerRenderer=new i.DebuggerRenderer(this),this.onGameResolutionResized()}addLayer(t){const e=new i.Layer(t,this);this._layers.put(t.name,e),this._orderedLayers.push(e)}onGameResolutionResized(){const t=this.getViewportOriginX(),e=this.getViewportOriginY();this._cachedGameResolutionWidth=this._runtimeGame?this._runtimeGame.getGameResolutionWidth():0,this._cachedGameResolutionHeight=this._runtimeGame?this._runtimeGame.getGameResolutionHeight():0;for(const a in this._layers.items)this._layers.items.hasOwnProperty(a)&&this._layers.items[a].onGameResolutionResized(t,e);this._renderer.onGameResolutionResized()}loadFromScene(t){if(!t){h.error("loadFromScene was called without a scene");return}const{sceneData:e,usedExtensionsWithVariablesData:a}=t;this._isLoaded&&this.unloadScene(),this._runtimeGame&&this._runtimeGame.getRenderer().setWindowTitle(e.title),this._name=e.name,this.setBackgroundColor(e.r,e.v,e.b);for(let r=0,s=e.layers.length;r<s;++r)this.addLayer(e.layers[r]);this._variables=new i.VariablesContainer(e.variables);for(const r of a)this._variablesByExtensionName.set(r.name,new i.VariablesContainer(r.sceneVariables));for(let r=0,s=e.behaviorsSharedData.length;r<s;++r){const o=e.behaviorsSharedData[r];this.setInitialSharedDataForBehavior(o.name,o)}const n=this.getGame().getInitialObjectsData();for(let r=0,s=n.length;r<s;++r)this.registerObject(n[r]);for(let r=0,s=e.objects.length;r<s;++r)this.registerObject(e.objects[r]);if(this.createObjectsFrom(e.instances,0,0,0,!0),this._setLayerDefaultZOrders(),this.setEventsGeneratedCodeFunction(e),this._onceTriggers=new i.OnceTriggers,this._runtimeGame&&!this._runtimeGame.wasFirstSceneLoaded())for(let r=0;r<i.callbacksFirstRuntimeSceneLoaded.length;++r)i.callbacksFirstRuntimeSceneLoaded[r](this);for(let r=0;r<i.callbacksRuntimeSceneLoaded.length;++r)i.callbacksRuntimeSceneLoaded[r](this);e.stopSoundsOnStartup&&this._runtimeGame&&this._runtimeGame.getSoundManager().clearAll(),this._isLoaded=!0,this._timeManager.reset()}getInitialSharedDataForBehavior(t){const e=super.getInitialSharedDataForBehavior(t);return e||h.error("Can't find shared data for behavior with name: "+t),e}onPause(){const t=this.getAdhocListOfAllInstances();for(let e=0,a=t.length;e<a;++e)t[e].onScenePaused(this);for(let e=0;e<i.callbacksRuntimeScenePaused.length;++e)i.callbacksRuntimeScenePaused[e](this)}onResume(){this._isJustResumed=!0;const t=this.getAdhocListOfAllInstances();for(let e=0,a=t.length;e<a;++e)t[e].onSceneResumed(this);for(let e=0;e<i.callbacksRuntimeSceneResumed.length;++e)i.callbacksRuntimeSceneResumed[e](this)}unloadScene(){if(!this._isLoaded)return;this._profiler&&this.stopProfiler();for(let e=0;e<i.callbacksRuntimeSceneUnloading.length;++e)i.callbacksRuntimeSceneUnloading[e](this);const t=this.getAdhocListOfAllInstances();for(let e=0,a=t.length;e<a;++e){const n=t[e];n.onDeletedFromScene(),n.onDestroyed()}this._renderer&&this._renderer.onSceneUnloaded();for(let e=0;e<i.callbacksRuntimeSceneUnloaded.length;++e)i.callbacksRuntimeSceneUnloaded[e](this);this._destroy(),this._isLoaded=!1,this.onGameResolutionResized()}_destroy(){super._destroy(),this._variables=new i.VariablesContainer,this._variablesByExtensionName=new Map,this._initialBehaviorSharedData=new Hashtable,this._eventsFunction=null,this._lastId=0,this.networkId=null,this._onceTriggers=null}setEventsGeneratedCodeFunction(t){const e=i[t.mangledName+"Code"];e&&e.func?this._eventsFunction=e.func:(d.warn("No function found for running logic of scene "+this._name),this._eventsFunction=function(){})}setEventsFunction(t){this._eventsFunction=t}renderAndStep(t){this._profiler&&this._profiler.beginFrame(),this._requestedChange=l.CONTINUE,this._timeManager.update(t,this._runtimeGame.getMinimalFramerate()),this._profiler&&this._profiler.begin("asynchronous actions (wait action, etc...)"),this._asyncTasksManager.processTasks(this),this._profiler&&this._profiler.end("asynchronous actions (wait action, etc...)"),this._profiler&&this._profiler.begin("objects (pre-events)"),this._updateObjectsPreEvents(),this._profiler&&this._profiler.end("objects (pre-events)"),this._profiler&&this._profiler.begin("callbacks and extensions (pre-events)");for(let e=0;e<i.callbacksRuntimeScenePreEvents.length;++e)i.callbacksRuntimeScenePreEvents[e](this);this._profiler&&this._profiler.end("callbacks and extensions (pre-events)"),this._profiler&&this._profiler.begin("events"),this._eventsFunction!==null&&this._eventsFunction(this),this._profiler&&this._profiler.end("events"),this._profiler&&this._profiler.begin("objects (post-events)"),this._updateObjectsPostEvents(),this._profiler&&this._profiler.end("objects (post-events)"),this._profiler&&this._profiler.begin("callbacks and extensions (post-events)");for(let e=0;e<i.callbacksRuntimeScenePostEvents.length;++e)i.callbacksRuntimeScenePostEvents[e](this);return this._profiler&&this._profiler.end("callbacks and extensions (post-events)"),this._profiler&&this._profiler.begin("objects (pre-render, effects update)"),this._updateObjectsPreRender(),this._profiler&&this._profiler.end("objects (pre-render, effects update)"),this._profiler&&this._profiler.begin("layers (effects update)"),this._updateLayersPreRender(),this._profiler&&this._profiler.end("layers (effects update)"),this._profiler&&this._profiler.begin("render"),this._debugDrawEnabled&&this._debuggerRenderer.renderDebugDraw(this.getAdhocListOfAllInstances(),this._debugDrawShowHiddenInstances,this._debugDrawShowPointsNames,this._debugDrawShowCustomPoints),this._isJustResumed=!1,this.render(),this._profiler&&this._profiler.end("render"),this._profiler&&this._profiler.endFrame(),!!this.getRequestedChange()}render(){this._renderer.render()}_updateObjectsPreRender(){if(this._timeManager.isFirstFrame()){super._updateObjectsPreRender();return}else{this._updateLayersCameraCoordinates(2);const t=this.getAdhocListOfAllInstances();for(let e=0,a=t.length;e<a;++e){const n=t[e],r=n.getRendererObject();if(r){if(n.isHidden())r.visible=!1;else{const s=this._layersCameraCoordinates[n.getLayer()];if(!s)continue;const o=n.getVisibilityAABB();r.visible=!o||!(o.min[0]>s[2]||o.min[1]>s[3]||o.max[0]<s[0]||o.max[1]<s[1])}r.visible&&(this._runtimeGame.getEffectsManager().updatePreRender(n.getRendererEffects(),n),n.updatePreRender(this))}else n.updatePreRender(this)}}}setBackgroundColor(t,e,a){this._backgroundColor=parseInt(i.rgbToHex(t,e,a),16)}getBackgroundColor(){return this._backgroundColor}setClearCanvas(t){this._clearCanvas=t}getClearCanvas(){return this._clearCanvas}getName(){return this._name}createNewUniqueId(){return this._lastId++,this._lastId}getRenderer(){return this._renderer}getDebuggerRenderer(){return this._debuggerRenderer}getGame(){return this._runtimeGame}getScene(){return this}getUnrotatedViewportMinX(){return 0}getUnrotatedViewportMinY(){return 0}getUnrotatedViewportMaxX(){return this._cachedGameResolutionWidth}getUnrotatedViewportMaxY(){return this._cachedGameResolutionHeight}getInitialUnrotatedViewportMinX(){return 0}getInitialUnrotatedViewportMinY(){return 0}getInitialUnrotatedViewportMaxX(){return this.getGame().getOriginalWidth()}getInitialUnrotatedViewportMaxY(){return this.getGame().getOriginalHeight()}getViewportWidth(){return this._cachedGameResolutionWidth}getViewportHeight(){return this._cachedGameResolutionHeight}getViewportOriginX(){return this._cachedGameResolutionWidth/2}getViewportOriginY(){return this._cachedGameResolutionHeight/2}convertCoords(t,e,a){const n=a||[0,0];return n[0]=t,n[1]=e,n}convertInverseCoords(t,e,a){const n=a||[0,0];return n[0]=t,n[1]=e,n}onChildrenLocationChanged(){}getVariables(){return this._variables}getVariablesForExtension(t){return this._variablesByExtensionName.get(t)||null}getTimeManager(){return this._timeManager}getElapsedTime(){return this._timeManager.getElapsedTime()}getSoundManager(){return this._runtimeGame.getSoundManager()}getAsyncTasksManager(){return this._asyncTasksManager}getRequestedChange(){return this._requestedChange}getRequestedScene(){return this._requestedScene}requestChange(t,e){this._requestedChange=t,e&&(this._requestedScene=e)}getProfiler(){return this._profiler}startProfiler(t){this._profiler||(this._profiler=new i.Profiler,this._onProfilerStopped=t)}stopProfiler(){if(!this._profiler)return;const t=this._profiler,e=this._onProfilerStopped;this._profiler=null,this._onProfilerStopped=null,e&&e(t)}getOnceTriggers(){return this._onceTriggers}sceneJustResumed(){return this._isJustResumed}getNetworkSyncData(t){const e=t.playerNumber,a=this._variables.getNetworkSyncData(t),n={};return this._variablesByExtensionName.forEach((r,s)=>{const o=r.getNetworkSyncData(t);o&&(n[s]=o)}),e!==void 0&&e!==1&&(!this.networkId||a.length===0&&!Object.keys(n).length)?null:{var:a,extVar:n,id:this.getOrCreateNetworkId()}}updateFromNetworkSyncData(t){if(t.var&&this._variables.updateFromNetworkSyncData(t.var),t.extVar)for(const e in t.extVar){if(!t.extVar.hasOwnProperty(e))continue;const a=t.extVar[e],n=this._variablesByExtensionName.get(e);n&&n.updateFromNetworkSyncData(a)}}getOrCreateNetworkId(){if(!this.networkId){const t=i.makeUuid().substring(0,8);this.networkId=t}return this.networkId}}i.RuntimeScene=c;let l;(function(s){s[s.CONTINUE=0]="CONTINUE",s[s.PUSH_SCENE=1]="PUSH_SCENE",s[s.POP_SCENE=2]="POP_SCENE",s[s.REPLACE_SCENE=3]="REPLACE_SCENE",s[s.CLEAR_SCENES=4]="CLEAR_SCENES",s[s.STOP_GAME=5]="STOP_GAME"})(l=i.SceneChangeRequest||(i.SceneChangeRequest={}))})(gdjs||(gdjs={}));
|
|
1
|
+
var gdjs;(function(i){const h=new i.Logger("RuntimeScene"),d=new i.Logger("RuntimeScene (setup warnings)");class c extends i.RuntimeInstanceContainer{constructor(t){super();this._eventsFunction=null;this._lastId=0;this._name="";this._gameStopRequested=!1;this._requestedScene="";this._resourcesUnloading="inherit";this._asyncTasksManager=new i.AsyncTasksManager;this._isLoaded=!1;this._isJustResumed=!1;this._backgroundColor=0;this._clearCanvas=!0;this._profiler=null;this._onProfilerStopped=null;this.networkId=null;this._runtimeGame=t,this._variables=new i.VariablesContainer,this._variablesByExtensionName=new Map,this._timeManager=new i.TimeManager,this._onceTriggers=new i.OnceTriggers,this._requestedChange=l.CONTINUE,this._cachedGameResolutionWidth=t?t.getGameResolutionWidth():0,this._cachedGameResolutionHeight=t?t.getGameResolutionHeight():0,this._renderer=new i.RuntimeSceneRenderer(this,t?t.getRenderer():null),this._debuggerRenderer=new i.DebuggerRenderer(this),this.onGameResolutionResized()}addLayer(t){const e=new i.Layer(t,this);this._layers.put(t.name,e),this._orderedLayers.push(e)}onGameResolutionResized(){const t=this.getViewportOriginX(),e=this.getViewportOriginY();this._cachedGameResolutionWidth=this._runtimeGame?this._runtimeGame.getGameResolutionWidth():0,this._cachedGameResolutionHeight=this._runtimeGame?this._runtimeGame.getGameResolutionHeight():0;for(const a in this._layers.items)this._layers.items.hasOwnProperty(a)&&this._layers.items[a].onGameResolutionResized(t,e);this._renderer.onGameResolutionResized()}loadFromScene(t){if(!t){h.error("loadFromScene was called without a scene");return}const{sceneData:e,usedExtensionsWithVariablesData:a}=t;this._isLoaded&&this.unloadScene(),this._runtimeGame&&this._runtimeGame.getRenderer().setWindowTitle(e.title),this._name=e.name,this._resourcesUnloading=e.resourcesUnloading||"inherit",this.setBackgroundColor(e.r,e.v,e.b);for(let r=0,s=e.layers.length;r<s;++r)this.addLayer(e.layers[r]);this._variables=new i.VariablesContainer(e.variables);for(const r of a)this._variablesByExtensionName.set(r.name,new i.VariablesContainer(r.sceneVariables));for(let r=0,s=e.behaviorsSharedData.length;r<s;++r){const o=e.behaviorsSharedData[r];this.setInitialSharedDataForBehavior(o.name,o)}const n=this.getGame().getInitialObjectsData();for(let r=0,s=n.length;r<s;++r)this.registerObject(n[r]);for(let r=0,s=e.objects.length;r<s;++r)this.registerObject(e.objects[r]);if(this.createObjectsFrom(e.instances,0,0,0,!0),this._setLayerDefaultZOrders(),this.setEventsGeneratedCodeFunction(e),this._onceTriggers=new i.OnceTriggers,this._runtimeGame&&!this._runtimeGame.wasFirstSceneLoaded())for(let r=0;r<i.callbacksFirstRuntimeSceneLoaded.length;++r)i.callbacksFirstRuntimeSceneLoaded[r](this);for(let r=0;r<i.callbacksRuntimeSceneLoaded.length;++r)i.callbacksRuntimeSceneLoaded[r](this);e.stopSoundsOnStartup&&this._runtimeGame&&this._runtimeGame.getSoundManager().clearAll(),this._isLoaded=!0,this._timeManager.reset()}getInitialSharedDataForBehavior(t){const e=super.getInitialSharedDataForBehavior(t);return e||h.error("Can't find shared data for behavior with name: "+t),e}onPause(){const t=this.getAdhocListOfAllInstances();for(let e=0,a=t.length;e<a;++e)t[e].onScenePaused(this);for(let e=0;e<i.callbacksRuntimeScenePaused.length;++e)i.callbacksRuntimeScenePaused[e](this)}onResume(){this._isJustResumed=!0;const t=this.getAdhocListOfAllInstances();for(let e=0,a=t.length;e<a;++e)t[e].onSceneResumed(this);for(let e=0;e<i.callbacksRuntimeSceneResumed.length;++e)i.callbacksRuntimeSceneResumed[e](this)}unloadScene(){if(!this._isLoaded)return;this._profiler&&this.stopProfiler();for(let e=0;e<i.callbacksRuntimeSceneUnloading.length;++e)i.callbacksRuntimeSceneUnloading[e](this);const t=this.getAdhocListOfAllInstances();for(let e=0,a=t.length;e<a;++e){const n=t[e];n.onDeletedFromScene(),n.onDestroyed()}this._renderer&&this._renderer.onSceneUnloaded();for(let e=0;e<i.callbacksRuntimeSceneUnloaded.length;++e)i.callbacksRuntimeSceneUnloaded[e](this);this._destroy(),this._isLoaded=!1,this.onGameResolutionResized()}_destroy(){super._destroy(),this._variables=new i.VariablesContainer,this._variablesByExtensionName=new Map,this._initialBehaviorSharedData=new Hashtable,this._eventsFunction=null,this._lastId=0,this.networkId=null,this._onceTriggers=null}setEventsGeneratedCodeFunction(t){const e=i[t.mangledName+"Code"];e&&e.func?this._eventsFunction=e.func:(d.warn("No function found for running logic of scene "+this._name),this._eventsFunction=function(){})}setEventsFunction(t){this._eventsFunction=t}renderAndStep(t){this._profiler&&this._profiler.beginFrame(),this._requestedChange=l.CONTINUE,this._timeManager.update(t,this._runtimeGame.getMinimalFramerate()),this._profiler&&this._profiler.begin("asynchronous actions (wait action, etc...)"),this._asyncTasksManager.processTasks(this),this._profiler&&this._profiler.end("asynchronous actions (wait action, etc...)"),this._profiler&&this._profiler.begin("objects (pre-events)"),this._updateObjectsPreEvents(),this._profiler&&this._profiler.end("objects (pre-events)"),this._profiler&&this._profiler.begin("callbacks and extensions (pre-events)");for(let e=0;e<i.callbacksRuntimeScenePreEvents.length;++e)i.callbacksRuntimeScenePreEvents[e](this);this._profiler&&this._profiler.end("callbacks and extensions (pre-events)"),this._profiler&&this._profiler.begin("events"),this._eventsFunction!==null&&this._eventsFunction(this),this._profiler&&this._profiler.end("events"),this._profiler&&this._profiler.begin("objects (post-events)"),this._updateObjectsPostEvents(),this._profiler&&this._profiler.end("objects (post-events)"),this._profiler&&this._profiler.begin("callbacks and extensions (post-events)");for(let e=0;e<i.callbacksRuntimeScenePostEvents.length;++e)i.callbacksRuntimeScenePostEvents[e](this);return this._profiler&&this._profiler.end("callbacks and extensions (post-events)"),this._profiler&&this._profiler.begin("objects (pre-render, effects update)"),this._updateObjectsPreRender(),this._profiler&&this._profiler.end("objects (pre-render, effects update)"),this._profiler&&this._profiler.begin("layers (effects update)"),this._updateLayersPreRender(),this._profiler&&this._profiler.end("layers (effects update)"),this._profiler&&this._profiler.begin("render"),this._debugDrawEnabled&&this._debuggerRenderer.renderDebugDraw(this.getAdhocListOfAllInstances(),this._debugDrawShowHiddenInstances,this._debugDrawShowPointsNames,this._debugDrawShowCustomPoints),this._isJustResumed=!1,this.render(),this._profiler&&this._profiler.end("render"),this._profiler&&this._profiler.endFrame(),!!this.getRequestedChange()}render(){this._renderer.render()}_updateObjectsPreRender(){if(this._timeManager.isFirstFrame()){super._updateObjectsPreRender();return}else{this._updateLayersCameraCoordinates(2);const t=this.getAdhocListOfAllInstances();for(let e=0,a=t.length;e<a;++e){const n=t[e],r=n.getRendererObject();if(r){if(n.isHidden())r.visible=!1;else{const s=this._layersCameraCoordinates[n.getLayer()];if(!s)continue;const o=n.getVisibilityAABB();r.visible=!o||!(o.min[0]>s[2]||o.min[1]>s[3]||o.max[0]<s[0]||o.max[1]<s[1])}r.visible&&(this._runtimeGame.getEffectsManager().updatePreRender(n.getRendererEffects(),n),n.updatePreRender(this))}else n.updatePreRender(this)}}}setBackgroundColor(t,e,a){this._backgroundColor=parseInt(i.rgbToHex(t,e,a),16)}getBackgroundColor(){return this._backgroundColor}setClearCanvas(t){this._clearCanvas=t}getClearCanvas(){return this._clearCanvas}getName(){return this._name}getResourcesUnloading(){return this._resourcesUnloading}createNewUniqueId(){return this._lastId++,this._lastId}getRenderer(){return this._renderer}getDebuggerRenderer(){return this._debuggerRenderer}getGame(){return this._runtimeGame}getScene(){return this}getUnrotatedViewportMinX(){return 0}getUnrotatedViewportMinY(){return 0}getUnrotatedViewportMaxX(){return this._cachedGameResolutionWidth}getUnrotatedViewportMaxY(){return this._cachedGameResolutionHeight}getInitialUnrotatedViewportMinX(){return 0}getInitialUnrotatedViewportMinY(){return 0}getInitialUnrotatedViewportMaxX(){return this.getGame().getOriginalWidth()}getInitialUnrotatedViewportMaxY(){return this.getGame().getOriginalHeight()}getViewportWidth(){return this._cachedGameResolutionWidth}getViewportHeight(){return this._cachedGameResolutionHeight}getViewportOriginX(){return this._cachedGameResolutionWidth/2}getViewportOriginY(){return this._cachedGameResolutionHeight/2}convertCoords(t,e,a){const n=a||[0,0];return n[0]=t,n[1]=e,n}convertInverseCoords(t,e,a){const n=a||[0,0];return n[0]=t,n[1]=e,n}onChildrenLocationChanged(){}getVariables(){return this._variables}getVariablesForExtension(t){return this._variablesByExtensionName.get(t)||null}getTimeManager(){return this._timeManager}getElapsedTime(){return this._timeManager.getElapsedTime()}getSoundManager(){return this._runtimeGame.getSoundManager()}getAsyncTasksManager(){return this._asyncTasksManager}getRequestedChange(){return this._requestedChange}getRequestedScene(){return this._requestedScene}requestChange(t,e){this._requestedChange=t,e&&(this._requestedScene=e)}getProfiler(){return this._profiler}startProfiler(t){this._profiler||(this._profiler=new i.Profiler,this._onProfilerStopped=t)}stopProfiler(){if(!this._profiler)return;const t=this._profiler,e=this._onProfilerStopped;this._profiler=null,this._onProfilerStopped=null,e&&e(t)}getOnceTriggers(){return this._onceTriggers}sceneJustResumed(){return this._isJustResumed}getNetworkSyncData(t){const e=t.playerNumber,a=this._variables.getNetworkSyncData(t),n={};return this._variablesByExtensionName.forEach((r,s)=>{const o=r.getNetworkSyncData(t);o&&(n[s]=o)}),e!==void 0&&e!==1&&(!this.networkId||a.length===0&&!Object.keys(n).length)?null:{var:a,extVar:n,id:this.getOrCreateNetworkId()}}updateFromNetworkSyncData(t){if(t.var&&this._variables.updateFromNetworkSyncData(t.var),t.extVar)for(const e in t.extVar){if(!t.extVar.hasOwnProperty(e))continue;const a=t.extVar[e],n=this._variablesByExtensionName.get(e);n&&n.updateFromNetworkSyncData(a)}}getOrCreateNetworkId(){if(!this.networkId){const t=i.makeUuid().substring(0,8);this.networkId=t}return this.networkId}}i.RuntimeScene=c;let l;(function(s){s[s.CONTINUE=0]="CONTINUE",s[s.PUSH_SCENE=1]="PUSH_SCENE",s[s.POP_SCENE=2]="POP_SCENE",s[s.REPLACE_SCENE=3]="REPLACE_SCENE",s[s.CLEAR_SCENES=4]="CLEAR_SCENES",s[s.STOP_GAME=5]="STOP_GAME"})(l=i.SceneChangeRequest||(i.SceneChangeRequest={}))})(gdjs||(gdjs={}));
|
|
2
2
|
//# sourceMappingURL=runtimescene.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../GDevelop/GDJS/Runtime/runtimescene.ts"],
|
|
4
|
-
"sourcesContent": ["/*\n * GDevelop JS Platform\n * Copyright 2013-2016 Florian Rival (Florian.Rival@gmail.com). All rights reserved.\n * This project is released under the MIT License.\n */\nnamespace gdjs {\n const logger = new gdjs.Logger('RuntimeScene');\n const setupWarningLogger = new gdjs.Logger('RuntimeScene (setup warnings)');\n\n /**\n * A scene being played, containing instances of objects rendered on screen.\n */\n export class RuntimeScene extends gdjs.RuntimeInstanceContainer {\n _eventsFunction: null | ((runtimeScene: RuntimeScene) => void) = null;\n\n _renderer: RuntimeSceneRenderer;\n _debuggerRenderer: gdjs.DebuggerRenderer;\n _variables: gdjs.VariablesContainer;\n _variablesByExtensionName: Map<string, gdjs.VariablesContainer>;\n _runtimeGame: gdjs.RuntimeGame;\n _lastId: integer = 0;\n _name: string = '';\n _timeManager: TimeManager;\n _gameStopRequested: boolean = false;\n _requestedScene: string = '';\n private _asyncTasksManager = new gdjs.AsyncTasksManager();\n\n /** True if loadFromScene was called and the scene is being played. */\n _isLoaded: boolean = false;\n /** True in the first frame after resuming the paused scene */\n _isJustResumed: boolean = false;\n\n _requestedChange: SceneChangeRequest;\n /** Black background by default. */\n _backgroundColor: integer = 0;\n\n /** Should the canvas be cleared before this scene rendering. */\n _clearCanvas: boolean = true;\n\n _onceTriggers: OnceTriggers;\n _profiler: gdjs.Profiler | null = null;\n\n // Set to `new gdjs.Profiler()` to have profiling done on the scene.\n _onProfilerStopped: null | ((oldProfiler: gdjs.Profiler) => void) = null;\n\n _cachedGameResolutionWidth: integer;\n _cachedGameResolutionHeight: integer;\n\n /**\n * A network ID associated to the scene to be used\n * for multiplayer, to identify the scene across peers.\n * A scene can have its networkId re-generated during the game, meaning\n * that the scene is re-created on every peer.\n */\n networkId: string | null = null;\n\n /**\n * @param runtimeGame The game associated to this scene.\n */\n constructor(runtimeGame: gdjs.RuntimeGame) {\n super();\n this._runtimeGame = runtimeGame;\n this._variables = new gdjs.VariablesContainer();\n this._variablesByExtensionName = new Map<\n string,\n gdjs.VariablesContainer\n >();\n this._timeManager = new gdjs.TimeManager();\n this._onceTriggers = new gdjs.OnceTriggers();\n this._requestedChange = SceneChangeRequest.CONTINUE;\n this._cachedGameResolutionWidth = runtimeGame\n ? runtimeGame.getGameResolutionWidth()\n : 0;\n this._cachedGameResolutionHeight = runtimeGame\n ? runtimeGame.getGameResolutionHeight()\n : 0;\n\n this._renderer = new gdjs.RuntimeSceneRenderer(\n this,\n // @ts-ignore This is needed because of test. They should mock RuntimeGame instead.\n runtimeGame ? runtimeGame.getRenderer() : null\n );\n this._debuggerRenderer = new gdjs.DebuggerRenderer(this);\n\n // What to do after the frame is rendered.\n\n // The callback function to call when the profiler is stopped.\n this.onGameResolutionResized();\n }\n\n addLayer(layerData: LayerData) {\n const layer = new gdjs.Layer(layerData, this);\n this._layers.put(layerData.name, layer);\n this._orderedLayers.push(layer);\n }\n\n /**\n * Should be called when the canvas where the scene is rendered has been resized.\n * See gdjs.RuntimeGame.startGameLoop in particular.\n */\n onGameResolutionResized() {\n const oldGameResolutionOriginX = this.getViewportOriginX();\n const oldGameResolutionOriginY = this.getViewportOriginY();\n this._cachedGameResolutionWidth = this._runtimeGame\n ? this._runtimeGame.getGameResolutionWidth()\n : 0;\n this._cachedGameResolutionHeight = this._runtimeGame\n ? this._runtimeGame.getGameResolutionHeight()\n : 0;\n for (const name in this._layers.items) {\n if (this._layers.items.hasOwnProperty(name)) {\n const theLayer: gdjs.RuntimeLayer = this._layers.items[name];\n theLayer.onGameResolutionResized(\n oldGameResolutionOriginX,\n oldGameResolutionOriginY\n );\n }\n }\n this._renderer.onGameResolutionResized();\n }\n\n /**\n * Load the runtime scene from the given scene.\n * @param sceneAndExtensionsData An object containing the scene data.\n * @see gdjs.RuntimeGame#getSceneAndExtensionsData\n */\n loadFromScene(sceneAndExtensionsData: SceneAndExtensionsData | null) {\n if (!sceneAndExtensionsData) {\n logger.error('loadFromScene was called without a scene');\n return;\n }\n const { sceneData, usedExtensionsWithVariablesData } =\n sceneAndExtensionsData;\n\n if (this._isLoaded) {\n this.unloadScene();\n }\n\n //Setup main properties\n if (this._runtimeGame) {\n this._runtimeGame.getRenderer().setWindowTitle(sceneData.title);\n }\n this._name = sceneData.name;\n this.setBackgroundColor(sceneData.r, sceneData.v, sceneData.b);\n\n //Load layers\n for (let i = 0, len = sceneData.layers.length; i < len; ++i) {\n this.addLayer(sceneData.layers[i]);\n }\n\n // Load variables\n this._variables = new gdjs.VariablesContainer(sceneData.variables);\n for (const extensionData of usedExtensionsWithVariablesData) {\n this._variablesByExtensionName.set(\n extensionData.name,\n new gdjs.VariablesContainer(extensionData.sceneVariables)\n );\n }\n\n //Cache the initial shared data of the behaviors\n for (\n let i = 0, len = sceneData.behaviorsSharedData.length;\n i < len;\n ++i\n ) {\n const behaviorSharedData = sceneData.behaviorsSharedData[i];\n this.setInitialSharedDataForBehavior(\n behaviorSharedData.name,\n behaviorSharedData\n );\n }\n\n //Registering objects: Global objects first...\n const initialGlobalObjectsData = this.getGame().getInitialObjectsData();\n for (let i = 0, len = initialGlobalObjectsData.length; i < len; ++i) {\n this.registerObject(initialGlobalObjectsData[i]);\n }\n\n //...then the scene objects\n for (let i = 0, len = sceneData.objects.length; i < len; ++i) {\n this.registerObject(sceneData.objects[i]);\n }\n\n //Create initial instances of objects\n this.createObjectsFrom(\n sceneData.instances,\n 0,\n 0,\n 0,\n /*trackByPersistentUuid=*/\n true\n );\n\n // Set up the default z order (for objects created from events)\n this._setLayerDefaultZOrders();\n\n //Set up the function to be executed at each tick\n this.setEventsGeneratedCodeFunction(sceneData);\n this._onceTriggers = new gdjs.OnceTriggers();\n\n // Notify the global callbacks\n if (this._runtimeGame && !this._runtimeGame.wasFirstSceneLoaded()) {\n for (let i = 0; i < gdjs.callbacksFirstRuntimeSceneLoaded.length; ++i) {\n gdjs.callbacksFirstRuntimeSceneLoaded[i](this);\n }\n }\n for (let i = 0; i < gdjs.callbacksRuntimeSceneLoaded.length; ++i) {\n gdjs.callbacksRuntimeSceneLoaded[i](this);\n }\n if (sceneData.stopSoundsOnStartup && this._runtimeGame) {\n this._runtimeGame.getSoundManager().clearAll();\n }\n this._isLoaded = true;\n this._timeManager.reset();\n }\n\n getInitialSharedDataForBehavior(name: string): BehaviorSharedData | null {\n // TODO Move this error in RuntimeInstanceContainer after deciding\n // what to do with shared data in custom object.\n const behaviorSharedData = super.getInitialSharedDataForBehavior(name);\n if (!behaviorSharedData) {\n logger.error(\"Can't find shared data for behavior with name: \" + name);\n }\n return behaviorSharedData;\n }\n\n /**\n * Called when a scene is \"paused\", i.e it will be not be rendered again\n * for some time, until it's resumed or unloaded.\n */\n onPause() {\n // Notify the objects that the scene is being paused. Objects should not\n // do anything special, but some object renderers might want to know about this.\n const allInstancesList = this.getAdhocListOfAllInstances();\n for (let i = 0, len = allInstancesList.length; i < len; ++i) {\n const object = allInstancesList[i];\n object.onScenePaused(this);\n }\n\n for (let i = 0; i < gdjs.callbacksRuntimeScenePaused.length; ++i) {\n gdjs.callbacksRuntimeScenePaused[i](this);\n }\n }\n\n /**\n * Called when a scene is \"resumed\", i.e it will be rendered again\n * on screen after having being paused.\n */\n onResume() {\n this._isJustResumed = true;\n\n // Notify the objects that the scene is being resumed. Objects should not\n // do anything special, but some object renderers might want to know about this.\n const allInstancesList = this.getAdhocListOfAllInstances();\n for (let i = 0, len = allInstancesList.length; i < len; ++i) {\n const object = allInstancesList[i];\n object.onSceneResumed(this);\n }\n\n for (let i = 0; i < gdjs.callbacksRuntimeSceneResumed.length; ++i) {\n gdjs.callbacksRuntimeSceneResumed[i](this);\n }\n }\n\n /**\n * Called before a scene is removed from the stack of scenes\n * rendered on the screen.\n */\n unloadScene() {\n if (!this._isLoaded) {\n return;\n }\n if (this._profiler) {\n this.stopProfiler();\n }\n\n // Notify the global callbacks (which should not release resources yet,\n // as other callbacks might still refer to the objects/scene).\n for (let i = 0; i < gdjs.callbacksRuntimeSceneUnloading.length; ++i) {\n gdjs.callbacksRuntimeSceneUnloading[i](this);\n }\n\n // Notify the objects they are being destroyed\n const allInstancesList = this.getAdhocListOfAllInstances();\n for (let i = 0, len = allInstancesList.length; i < len; ++i) {\n const object = allInstancesList[i];\n object.onDeletedFromScene();\n object.onDestroyed();\n }\n\n // Notify the renderer\n if (this._renderer) {\n this._renderer.onSceneUnloaded();\n }\n\n // Notify the global callbacks (after notifying objects and renderer, because\n // callbacks from extensions might want to free resources - which can't be done\n // safely before destroying objects and the renderer).\n for (let i = 0; i < gdjs.callbacksRuntimeSceneUnloaded.length; ++i) {\n gdjs.callbacksRuntimeSceneUnloaded[i](this);\n }\n\n this._destroy();\n\n this._isLoaded = false;\n this.onGameResolutionResized();\n }\n\n _destroy() {\n // It should not be necessary to reset these variables, but this help\n // ensuring that all memory related to the RuntimeScene is released immediately.\n super._destroy();\n this._variables = new gdjs.VariablesContainer();\n this._variablesByExtensionName = new Map<\n string,\n gdjs.VariablesContainer\n >();\n this._initialBehaviorSharedData = new Hashtable();\n this._eventsFunction = null;\n this._lastId = 0;\n this.networkId = null;\n // @ts-ignore We are deleting the object\n this._onceTriggers = null;\n }\n\n /**\n * Set the function called each time the scene is stepped to be the events generated code,\n * which is by convention assumed to be a function in `gdjs` with a name based on the scene\n * mangled name.\n *\n * @param sceneData The scene data, used to find where the code was generated.\n */\n setEventsGeneratedCodeFunction(sceneData: LayoutData): void {\n const module = gdjs[sceneData.mangledName + 'Code'];\n if (module && module.func) {\n this._eventsFunction = module.func;\n } else {\n setupWarningLogger.warn(\n 'No function found for running logic of scene ' + this._name\n );\n this._eventsFunction = function () {};\n }\n }\n\n /**\n * Set the function called each time the scene is stepped.\n * The function will be passed the `runtimeScene` as argument.\n *\n * Note that this is already set up by the gdjs.RuntimeScene constructor and that you should\n * not need to use this method.\n *\n * @param func The function to be called.\n */\n setEventsFunction(func: () => void): void {\n this._eventsFunction = func;\n }\n\n /**\n * Step and render the scene.\n * @param elapsedTime In milliseconds\n * @return true if the game loop should continue, false if a scene change/push/pop\n * or a game stop was requested.\n */\n renderAndStep(elapsedTime: float): boolean {\n if (this._profiler) {\n this._profiler.beginFrame();\n }\n this._requestedChange = SceneChangeRequest.CONTINUE;\n this._timeManager.update(\n elapsedTime,\n this._runtimeGame.getMinimalFramerate()\n );\n if (this._profiler) {\n this._profiler.begin('asynchronous actions (wait action, etc...)');\n }\n this._asyncTasksManager.processTasks(this);\n if (this._profiler) {\n this._profiler.end('asynchronous actions (wait action, etc...)');\n }\n if (this._profiler) {\n this._profiler.begin('objects (pre-events)');\n }\n this._updateObjectsPreEvents();\n if (this._profiler) {\n this._profiler.end('objects (pre-events)');\n }\n if (this._profiler) {\n this._profiler.begin('callbacks and extensions (pre-events)');\n }\n for (let i = 0; i < gdjs.callbacksRuntimeScenePreEvents.length; ++i) {\n gdjs.callbacksRuntimeScenePreEvents[i](this);\n }\n if (this._profiler) {\n this._profiler.end('callbacks and extensions (pre-events)');\n }\n if (this._profiler) {\n this._profiler.begin('events');\n }\n if (this._eventsFunction !== null) this._eventsFunction(this);\n if (this._profiler) {\n this._profiler.end('events');\n }\n if (this._profiler) {\n this._profiler.begin('objects (post-events)');\n }\n this._updateObjectsPostEvents();\n if (this._profiler) {\n this._profiler.end('objects (post-events)');\n }\n if (this._profiler) {\n this._profiler.begin('callbacks and extensions (post-events)');\n }\n for (let i = 0; i < gdjs.callbacksRuntimeScenePostEvents.length; ++i) {\n gdjs.callbacksRuntimeScenePostEvents[i](this);\n }\n if (this._profiler) {\n this._profiler.end('callbacks and extensions (post-events)');\n }\n if (this._profiler) {\n this._profiler.begin('objects (pre-render, effects update)');\n }\n this._updateObjectsPreRender();\n if (this._profiler) {\n this._profiler.end('objects (pre-render, effects update)');\n }\n if (this._profiler) {\n this._profiler.begin('layers (effects update)');\n }\n this._updateLayersPreRender();\n if (this._profiler) {\n this._profiler.end('layers (effects update)');\n }\n if (this._profiler) {\n this._profiler.begin('render');\n }\n\n // Set to true to enable debug rendering (look for the implementation in the renderer\n // to see what is rendered).\n if (this._debugDrawEnabled) {\n this._debuggerRenderer.renderDebugDraw(\n this.getAdhocListOfAllInstances(),\n this._debugDrawShowHiddenInstances,\n this._debugDrawShowPointsNames,\n this._debugDrawShowCustomPoints\n );\n }\n\n this._isJustResumed = false;\n this.render();\n if (this._profiler) {\n this._profiler.end('render');\n }\n if (this._profiler) {\n this._profiler.endFrame();\n }\n return !!this.getRequestedChange();\n }\n\n /**\n * Render the PIXI container associated to the runtimeScene.\n */\n render() {\n this._renderer.render();\n }\n\n /**\n * Called to update visibility of the renderers of objects\n * rendered on the scene (\"culling\"), update effects (of visible objects)\n * and give a last chance for objects to update before rendering.\n *\n * Visibility is set to false if object is hidden, or if\n * object is too far from the camera of its layer (\"culling\").\n */\n _updateObjectsPreRender() {\n if (this._timeManager.isFirstFrame()) {\n super._updateObjectsPreRender();\n return;\n } else {\n // After first frame, optimise rendering by setting only objects\n // near camera as visible.\n // TODO: For compatibility, pass a scale of `2`,\n // meaning that size of cameras will be multiplied by 2 and so objects\n // will be hidden if they are outside of this *larger* camera area.\n // This is useful for:\n // - objects not properly reporting their visibility AABB,\n // (so we have a \"safety margin\") but these objects should be fixed\n // instead.\n // - objects having effects rendering outside of their visibility AABB.\n\n // TODO (3D) culling - add support for 3D object culling?\n this._updateLayersCameraCoordinates(2);\n const allInstancesList = this.getAdhocListOfAllInstances();\n for (let i = 0, len = allInstancesList.length; i < len; ++i) {\n const object = allInstancesList[i];\n const rendererObject = object.getRendererObject();\n if (rendererObject) {\n if (object.isHidden()) {\n rendererObject.visible = false;\n } else {\n const cameraCoords =\n this._layersCameraCoordinates[object.getLayer()];\n if (!cameraCoords) {\n continue;\n }\n const aabb = object.getVisibilityAABB();\n rendererObject.visible =\n // If no AABB is returned, the object should always be visible\n !aabb ||\n // If an AABB is there, it must be at least partially inside\n // the camera bounds.\n !(\n aabb.min[0] > cameraCoords[2] ||\n aabb.min[1] > cameraCoords[3] ||\n aabb.max[0] < cameraCoords[0] ||\n aabb.max[1] < cameraCoords[1]\n );\n }\n\n // Update effects, only for visible objects.\n if (rendererObject.visible) {\n this._runtimeGame\n .getEffectsManager()\n .updatePreRender(object.getRendererEffects(), object);\n\n // Perform pre-render update only if the object is visible\n // (including if there is no visibility AABB returned previously).\n object.updatePreRender(this);\n }\n } else {\n // Perform pre-render update, always for objects not having an\n // associated renderer object (so it must handle visibility on its own).\n object.updatePreRender(this);\n }\n }\n }\n }\n\n /**\n * Change the background color, by setting the RGB components.\n * Internally, the color is stored as an hexadecimal number.\n *\n * @param r The color red component (0-255).\n * @param g The color green component (0-255).\n * @param b The color blue component (0-255).\n */\n setBackgroundColor(r: integer, g: integer, b: integer): void {\n this._backgroundColor = parseInt(gdjs.rgbToHex(r, g, b), 16);\n }\n\n /**\n * Get the background color, as an hexadecimal number.\n * @returns The current background color.\n */\n getBackgroundColor(): number {\n return this._backgroundColor;\n }\n\n /**\n * Set whether the canvas should be cleared before this scene rendering.\n * This is experimental: if possible, try to avoid relying on this and use\n * custom objects to build complex scenes.\n */\n setClearCanvas(shouldClearCanvas: boolean): void {\n this._clearCanvas = shouldClearCanvas;\n }\n\n /**\n * Get whether the canvas should be cleared before this scene rendering.\n */\n getClearCanvas(): boolean {\n return this._clearCanvas;\n }\n\n /**\n * Get the name of the scene.\n */\n getName(): string {\n return this._name;\n }\n\n /**\n * Create an identifier for a new object of the scene.\n */\n createNewUniqueId(): integer {\n this._lastId++;\n return this._lastId;\n }\n\n getRenderer(): gdjs.RuntimeScenePixiRenderer {\n return this._renderer;\n }\n\n getDebuggerRenderer() {\n return this._debuggerRenderer;\n }\n\n getGame() {\n return this._runtimeGame;\n }\n\n getScene() {\n return this;\n }\n\n getUnrotatedViewportMinX(): float {\n return 0;\n }\n\n getUnrotatedViewportMinY(): float {\n return 0;\n }\n\n getUnrotatedViewportMaxX(): float {\n return this._cachedGameResolutionWidth;\n }\n\n getUnrotatedViewportMaxY(): float {\n return this._cachedGameResolutionHeight;\n }\n\n getInitialUnrotatedViewportMinX(): float {\n return 0;\n }\n\n getInitialUnrotatedViewportMinY(): float {\n return 0;\n }\n\n getInitialUnrotatedViewportMaxX(): float {\n return this.getGame().getOriginalWidth();\n }\n\n getInitialUnrotatedViewportMaxY(): float {\n return this.getGame().getOriginalHeight();\n }\n\n getViewportWidth(): float {\n return this._cachedGameResolutionWidth;\n }\n\n getViewportHeight(): float {\n return this._cachedGameResolutionHeight;\n }\n\n getViewportOriginX(): float {\n return this._cachedGameResolutionWidth / 2;\n }\n\n getViewportOriginY(): float {\n return this._cachedGameResolutionHeight / 2;\n }\n\n convertCoords(x: float, y: float, result: FloatPoint): FloatPoint {\n // The result parameter used to be optional.\n const point = result || [0, 0];\n point[0] = x;\n point[1] = y;\n return point;\n }\n\n convertInverseCoords(\n sceneX: float,\n sceneY: float,\n result: FloatPoint\n ): FloatPoint {\n const point = result || [0, 0];\n point[0] = sceneX;\n point[1] = sceneY;\n return point;\n }\n\n onChildrenLocationChanged(): void {\n // Scenes don't maintain bounds.\n }\n\n /**\n * Get the variables of the runtimeScene.\n * @return The container holding the variables of the scene.\n */\n getVariables() {\n return this._variables;\n }\n\n /**\n * Get the extension's variables for this scene.\n * @param extensionName The extension name.\n * @returns The extension's variables for this scene.\n */\n getVariablesForExtension(extensionName: string) {\n return this._variablesByExtensionName.get(extensionName) || null;\n }\n\n /**\n * Get the TimeManager of the scene.\n * @return The gdjs.TimeManager of the scene.\n */\n getTimeManager(): gdjs.TimeManager {\n return this._timeManager;\n }\n\n /**\n * Return the time elapsed since the last frame,\n * in milliseconds, for objects on the layer.\n */\n getElapsedTime(): float {\n return this._timeManager.getElapsedTime();\n }\n\n /**\n * Shortcut to get the SoundManager of the game.\n * @return The gdjs.SoundManager of the game.\n */\n getSoundManager(): gdjs.SoundManager {\n return this._runtimeGame.getSoundManager();\n }\n\n /**\n * @returns The scene's async tasks manager.\n */\n getAsyncTasksManager() {\n return this._asyncTasksManager;\n }\n\n /**\n * Return the value of the scene change that is requested.\n */\n getRequestedChange(): SceneChangeRequest {\n return this._requestedChange;\n }\n\n /**\n * Return the name of the new scene to be launched.\n *\n * See requestChange.\n */\n getRequestedScene(): string {\n return this._requestedScene;\n }\n\n /**\n * Request a scene change to be made. The change is handled externally (see gdjs.SceneStack)\n * thanks to getRequestedChange and getRequestedScene methods.\n * @param change One of RuntimeScene.CONTINUE|PUSH_SCENE|POP_SCENE|REPLACE_SCENE|CLEAR_SCENES|STOP_GAME.\n * @param sceneName The name of the new scene to launch, if applicable.\n */\n requestChange(change: SceneChangeRequest, sceneName?: string) {\n this._requestedChange = change;\n if (sceneName) this._requestedScene = sceneName;\n }\n\n /**\n * Get the profiler associated with the scene, or null if none.\n */\n getProfiler(): gdjs.Profiler | null {\n return this._profiler;\n }\n\n /**\n * Start a new profiler to measures the time passed in sections of the engine\n * in the scene.\n * @param onProfilerStopped Function to be called when the profiler is stopped. Will be passed the profiler as argument.\n */\n startProfiler(onProfilerStopped: (oldProfiler: gdjs.Profiler) => void) {\n if (this._profiler) {\n return;\n }\n this._profiler = new gdjs.Profiler();\n this._onProfilerStopped = onProfilerStopped;\n }\n\n /**\n * Stop the profiler being run on the scene.\n */\n stopProfiler() {\n if (!this._profiler) {\n return;\n }\n const oldProfiler = this._profiler;\n const onProfilerStopped = this._onProfilerStopped;\n this._profiler = null;\n this._onProfilerStopped = null;\n if (onProfilerStopped) {\n onProfilerStopped(oldProfiler);\n }\n }\n\n /**\n * Get the structure containing the triggers for \"Trigger once\" conditions.\n */\n getOnceTriggers() {\n return this._onceTriggers;\n }\n\n /**\n * Check if the scene was just resumed.\n * This is true during the first frame after the scene has been unpaused.\n *\n * @returns true if the scene was just resumed\n */\n sceneJustResumed(): boolean {\n return this._isJustResumed;\n }\n\n getNetworkSyncData(\n syncOptions: GetNetworkSyncDataOptions\n ): LayoutNetworkSyncData | null {\n const syncedPlayerNumber = syncOptions.playerNumber;\n const variablesNetworkSyncData =\n this._variables.getNetworkSyncData(syncOptions);\n const extensionsVariablesSyncData = {};\n this._variablesByExtensionName.forEach((variables, extensionName) => {\n const extensionVariablesSyncData =\n variables.getNetworkSyncData(syncOptions);\n // If there is no variables to sync, don't include the extension in the sync data.\n if (extensionVariablesSyncData) {\n extensionsVariablesSyncData[extensionName] =\n extensionVariablesSyncData;\n }\n });\n\n if (\n syncedPlayerNumber !== undefined &&\n syncedPlayerNumber !== 1 &&\n (!this.networkId ||\n (variablesNetworkSyncData.length === 0 &&\n !Object.keys(extensionsVariablesSyncData).length))\n ) {\n // If we are getting sync data for a specific player,\n // and they are not the host, there is no sync data to send if:\n // - The scene has no networkId (it's either not a multiplayer scene or the scene is not yet networked).\n // - There are no variables to sync in the scene or extensions.\n return null;\n }\n\n return {\n var: variablesNetworkSyncData,\n extVar: extensionsVariablesSyncData,\n id: this.getOrCreateNetworkId(),\n };\n }\n\n updateFromNetworkSyncData(syncData: LayoutNetworkSyncData) {\n if (syncData.var) {\n this._variables.updateFromNetworkSyncData(syncData.var);\n }\n if (syncData.extVar) {\n for (const extensionName in syncData.extVar) {\n if (!syncData.extVar.hasOwnProperty(extensionName)) {\n continue;\n }\n const extensionVariablesData = syncData.extVar[extensionName];\n const extensionVariables =\n this._variablesByExtensionName.get(extensionName);\n if (extensionVariables) {\n extensionVariables.updateFromNetworkSyncData(\n extensionVariablesData\n );\n }\n }\n }\n }\n\n getOrCreateNetworkId(): string {\n if (!this.networkId) {\n const newNetworkId = gdjs.makeUuid().substring(0, 8);\n this.networkId = newNetworkId;\n }\n return this.networkId;\n }\n }\n\n //The flags to describe the change request by a scene:\n export enum SceneChangeRequest {\n CONTINUE,\n PUSH_SCENE,\n POP_SCENE,\n REPLACE_SCENE,\n CLEAR_SCENES,\n STOP_GAME,\n }\n}\n"],
|
|
5
|
-
"mappings": "AAKA,GAAU,MAAV,UAAU,EAAV,CACE,KAAM,GAAS,GAAI,GAAK,OAAO,gBACzB,EAAqB,GAAI,GAAK,OAAO,iCAKpC,eAA2B,GAAK,wBAAyB,
|
|
4
|
+
"sourcesContent": ["/*\n * GDevelop JS Platform\n * Copyright 2013-2016 Florian Rival (Florian.Rival@gmail.com). All rights reserved.\n * This project is released under the MIT License.\n */\nnamespace gdjs {\n const logger = new gdjs.Logger('RuntimeScene');\n const setupWarningLogger = new gdjs.Logger('RuntimeScene (setup warnings)');\n\n /**\n * A scene being played, containing instances of objects rendered on screen.\n */\n export class RuntimeScene extends gdjs.RuntimeInstanceContainer {\n _eventsFunction: null | ((runtimeScene: RuntimeScene) => void) = null;\n\n _renderer: RuntimeSceneRenderer;\n _debuggerRenderer: gdjs.DebuggerRenderer;\n _variables: gdjs.VariablesContainer;\n _variablesByExtensionName: Map<string, gdjs.VariablesContainer>;\n _runtimeGame: gdjs.RuntimeGame;\n _lastId: integer = 0;\n _name: string = '';\n _timeManager: TimeManager;\n _gameStopRequested: boolean = false;\n _requestedScene: string = '';\n _resourcesUnloading: 'at-scene-exit' | 'never' | 'inherit' = 'inherit';\n private _asyncTasksManager = new gdjs.AsyncTasksManager();\n\n /** True if loadFromScene was called and the scene is being played. */\n _isLoaded: boolean = false;\n /** True in the first frame after resuming the paused scene */\n _isJustResumed: boolean = false;\n\n _requestedChange: SceneChangeRequest;\n /** Black background by default. */\n _backgroundColor: integer = 0;\n\n /** Should the canvas be cleared before this scene rendering. */\n _clearCanvas: boolean = true;\n\n _onceTriggers: OnceTriggers;\n _profiler: gdjs.Profiler | null = null;\n\n // Set to `new gdjs.Profiler()` to have profiling done on the scene.\n _onProfilerStopped: null | ((oldProfiler: gdjs.Profiler) => void) = null;\n\n _cachedGameResolutionWidth: integer;\n _cachedGameResolutionHeight: integer;\n\n /**\n * A network ID associated to the scene to be used\n * for multiplayer, to identify the scene across peers.\n * A scene can have its networkId re-generated during the game, meaning\n * that the scene is re-created on every peer.\n */\n networkId: string | null = null;\n\n /**\n * @param runtimeGame The game associated to this scene.\n */\n constructor(runtimeGame: gdjs.RuntimeGame) {\n super();\n this._runtimeGame = runtimeGame;\n this._variables = new gdjs.VariablesContainer();\n this._variablesByExtensionName = new Map<\n string,\n gdjs.VariablesContainer\n >();\n this._timeManager = new gdjs.TimeManager();\n this._onceTriggers = new gdjs.OnceTriggers();\n this._requestedChange = SceneChangeRequest.CONTINUE;\n this._cachedGameResolutionWidth = runtimeGame\n ? runtimeGame.getGameResolutionWidth()\n : 0;\n this._cachedGameResolutionHeight = runtimeGame\n ? runtimeGame.getGameResolutionHeight()\n : 0;\n\n this._renderer = new gdjs.RuntimeSceneRenderer(\n this,\n // @ts-ignore This is needed because of test. They should mock RuntimeGame instead.\n runtimeGame ? runtimeGame.getRenderer() : null\n );\n this._debuggerRenderer = new gdjs.DebuggerRenderer(this);\n\n // What to do after the frame is rendered.\n\n // The callback function to call when the profiler is stopped.\n this.onGameResolutionResized();\n }\n\n addLayer(layerData: LayerData) {\n const layer = new gdjs.Layer(layerData, this);\n this._layers.put(layerData.name, layer);\n this._orderedLayers.push(layer);\n }\n\n /**\n * Should be called when the canvas where the scene is rendered has been resized.\n * See gdjs.RuntimeGame.startGameLoop in particular.\n */\n onGameResolutionResized() {\n const oldGameResolutionOriginX = this.getViewportOriginX();\n const oldGameResolutionOriginY = this.getViewportOriginY();\n this._cachedGameResolutionWidth = this._runtimeGame\n ? this._runtimeGame.getGameResolutionWidth()\n : 0;\n this._cachedGameResolutionHeight = this._runtimeGame\n ? this._runtimeGame.getGameResolutionHeight()\n : 0;\n for (const name in this._layers.items) {\n if (this._layers.items.hasOwnProperty(name)) {\n const theLayer: gdjs.RuntimeLayer = this._layers.items[name];\n theLayer.onGameResolutionResized(\n oldGameResolutionOriginX,\n oldGameResolutionOriginY\n );\n }\n }\n this._renderer.onGameResolutionResized();\n }\n\n /**\n * Load the runtime scene from the given scene.\n * @param sceneAndExtensionsData An object containing the scene data.\n * @see gdjs.RuntimeGame#getSceneAndExtensionsData\n */\n loadFromScene(sceneAndExtensionsData: SceneAndExtensionsData | null) {\n if (!sceneAndExtensionsData) {\n logger.error('loadFromScene was called without a scene');\n return;\n }\n const { sceneData, usedExtensionsWithVariablesData } =\n sceneAndExtensionsData;\n\n if (this._isLoaded) {\n this.unloadScene();\n }\n\n //Setup main properties\n if (this._runtimeGame) {\n this._runtimeGame.getRenderer().setWindowTitle(sceneData.title);\n }\n this._name = sceneData.name;\n this._resourcesUnloading = sceneData.resourcesUnloading || 'inherit';\n this.setBackgroundColor(sceneData.r, sceneData.v, sceneData.b);\n\n //Load layers\n for (let i = 0, len = sceneData.layers.length; i < len; ++i) {\n this.addLayer(sceneData.layers[i]);\n }\n\n // Load variables\n this._variables = new gdjs.VariablesContainer(sceneData.variables);\n for (const extensionData of usedExtensionsWithVariablesData) {\n this._variablesByExtensionName.set(\n extensionData.name,\n new gdjs.VariablesContainer(extensionData.sceneVariables)\n );\n }\n\n //Cache the initial shared data of the behaviors\n for (\n let i = 0, len = sceneData.behaviorsSharedData.length;\n i < len;\n ++i\n ) {\n const behaviorSharedData = sceneData.behaviorsSharedData[i];\n this.setInitialSharedDataForBehavior(\n behaviorSharedData.name,\n behaviorSharedData\n );\n }\n\n //Registering objects: Global objects first...\n const initialGlobalObjectsData = this.getGame().getInitialObjectsData();\n for (let i = 0, len = initialGlobalObjectsData.length; i < len; ++i) {\n this.registerObject(initialGlobalObjectsData[i]);\n }\n\n //...then the scene objects\n for (let i = 0, len = sceneData.objects.length; i < len; ++i) {\n this.registerObject(sceneData.objects[i]);\n }\n\n //Create initial instances of objects\n this.createObjectsFrom(\n sceneData.instances,\n 0,\n 0,\n 0,\n /*trackByPersistentUuid=*/\n true\n );\n\n // Set up the default z order (for objects created from events)\n this._setLayerDefaultZOrders();\n\n //Set up the function to be executed at each tick\n this.setEventsGeneratedCodeFunction(sceneData);\n this._onceTriggers = new gdjs.OnceTriggers();\n\n // Notify the global callbacks\n if (this._runtimeGame && !this._runtimeGame.wasFirstSceneLoaded()) {\n for (let i = 0; i < gdjs.callbacksFirstRuntimeSceneLoaded.length; ++i) {\n gdjs.callbacksFirstRuntimeSceneLoaded[i](this);\n }\n }\n for (let i = 0; i < gdjs.callbacksRuntimeSceneLoaded.length; ++i) {\n gdjs.callbacksRuntimeSceneLoaded[i](this);\n }\n if (sceneData.stopSoundsOnStartup && this._runtimeGame) {\n this._runtimeGame.getSoundManager().clearAll();\n }\n this._isLoaded = true;\n this._timeManager.reset();\n }\n\n getInitialSharedDataForBehavior(name: string): BehaviorSharedData | null {\n // TODO Move this error in RuntimeInstanceContainer after deciding\n // what to do with shared data in custom object.\n const behaviorSharedData = super.getInitialSharedDataForBehavior(name);\n if (!behaviorSharedData) {\n logger.error(\"Can't find shared data for behavior with name: \" + name);\n }\n return behaviorSharedData;\n }\n\n /**\n * Called when a scene is \"paused\", i.e it will be not be rendered again\n * for some time, until it's resumed or unloaded.\n */\n onPause() {\n // Notify the objects that the scene is being paused. Objects should not\n // do anything special, but some object renderers might want to know about this.\n const allInstancesList = this.getAdhocListOfAllInstances();\n for (let i = 0, len = allInstancesList.length; i < len; ++i) {\n const object = allInstancesList[i];\n object.onScenePaused(this);\n }\n\n for (let i = 0; i < gdjs.callbacksRuntimeScenePaused.length; ++i) {\n gdjs.callbacksRuntimeScenePaused[i](this);\n }\n }\n\n /**\n * Called when a scene is \"resumed\", i.e it will be rendered again\n * on screen after having being paused.\n */\n onResume() {\n this._isJustResumed = true;\n\n // Notify the objects that the scene is being resumed. Objects should not\n // do anything special, but some object renderers might want to know about this.\n const allInstancesList = this.getAdhocListOfAllInstances();\n for (let i = 0, len = allInstancesList.length; i < len; ++i) {\n const object = allInstancesList[i];\n object.onSceneResumed(this);\n }\n\n for (let i = 0; i < gdjs.callbacksRuntimeSceneResumed.length; ++i) {\n gdjs.callbacksRuntimeSceneResumed[i](this);\n }\n }\n\n /**\n * Called before a scene is removed from the stack of scenes\n * rendered on the screen.\n */\n unloadScene() {\n if (!this._isLoaded) {\n return;\n }\n if (this._profiler) {\n this.stopProfiler();\n }\n\n // Notify the global callbacks (which should not release resources yet,\n // as other callbacks might still refer to the objects/scene).\n for (let i = 0; i < gdjs.callbacksRuntimeSceneUnloading.length; ++i) {\n gdjs.callbacksRuntimeSceneUnloading[i](this);\n }\n\n // Notify the objects they are being destroyed\n const allInstancesList = this.getAdhocListOfAllInstances();\n for (let i = 0, len = allInstancesList.length; i < len; ++i) {\n const object = allInstancesList[i];\n object.onDeletedFromScene();\n object.onDestroyed();\n }\n\n // Notify the renderer\n if (this._renderer) {\n this._renderer.onSceneUnloaded();\n }\n\n // Notify the global callbacks (after notifying objects and renderer, because\n // callbacks from extensions might want to free resources - which can't be done\n // safely before destroying objects and the renderer).\n for (let i = 0; i < gdjs.callbacksRuntimeSceneUnloaded.length; ++i) {\n gdjs.callbacksRuntimeSceneUnloaded[i](this);\n }\n\n this._destroy();\n\n this._isLoaded = false;\n this.onGameResolutionResized();\n }\n\n _destroy() {\n // It should not be necessary to reset these variables, but this help\n // ensuring that all memory related to the RuntimeScene is released immediately.\n super._destroy();\n this._variables = new gdjs.VariablesContainer();\n this._variablesByExtensionName = new Map<\n string,\n gdjs.VariablesContainer\n >();\n this._initialBehaviorSharedData = new Hashtable();\n this._eventsFunction = null;\n this._lastId = 0;\n this.networkId = null;\n // @ts-ignore We are deleting the object\n this._onceTriggers = null;\n }\n\n /**\n * Set the function called each time the scene is stepped to be the events generated code,\n * which is by convention assumed to be a function in `gdjs` with a name based on the scene\n * mangled name.\n *\n * @param sceneData The scene data, used to find where the code was generated.\n */\n setEventsGeneratedCodeFunction(sceneData: LayoutData): void {\n const module = gdjs[sceneData.mangledName + 'Code'];\n if (module && module.func) {\n this._eventsFunction = module.func;\n } else {\n setupWarningLogger.warn(\n 'No function found for running logic of scene ' + this._name\n );\n this._eventsFunction = function () {};\n }\n }\n\n /**\n * Set the function called each time the scene is stepped.\n * The function will be passed the `runtimeScene` as argument.\n *\n * Note that this is already set up by the gdjs.RuntimeScene constructor and that you should\n * not need to use this method.\n *\n * @param func The function to be called.\n */\n setEventsFunction(func: () => void): void {\n this._eventsFunction = func;\n }\n\n /**\n * Step and render the scene.\n * @param elapsedTime In milliseconds\n * @return true if the game loop should continue, false if a scene change/push/pop\n * or a game stop was requested.\n */\n renderAndStep(elapsedTime: float): boolean {\n if (this._profiler) {\n this._profiler.beginFrame();\n }\n this._requestedChange = SceneChangeRequest.CONTINUE;\n this._timeManager.update(\n elapsedTime,\n this._runtimeGame.getMinimalFramerate()\n );\n if (this._profiler) {\n this._profiler.begin('asynchronous actions (wait action, etc...)');\n }\n this._asyncTasksManager.processTasks(this);\n if (this._profiler) {\n this._profiler.end('asynchronous actions (wait action, etc...)');\n }\n if (this._profiler) {\n this._profiler.begin('objects (pre-events)');\n }\n this._updateObjectsPreEvents();\n if (this._profiler) {\n this._profiler.end('objects (pre-events)');\n }\n if (this._profiler) {\n this._profiler.begin('callbacks and extensions (pre-events)');\n }\n for (let i = 0; i < gdjs.callbacksRuntimeScenePreEvents.length; ++i) {\n gdjs.callbacksRuntimeScenePreEvents[i](this);\n }\n if (this._profiler) {\n this._profiler.end('callbacks and extensions (pre-events)');\n }\n if (this._profiler) {\n this._profiler.begin('events');\n }\n if (this._eventsFunction !== null) this._eventsFunction(this);\n if (this._profiler) {\n this._profiler.end('events');\n }\n if (this._profiler) {\n this._profiler.begin('objects (post-events)');\n }\n this._updateObjectsPostEvents();\n if (this._profiler) {\n this._profiler.end('objects (post-events)');\n }\n if (this._profiler) {\n this._profiler.begin('callbacks and extensions (post-events)');\n }\n for (let i = 0; i < gdjs.callbacksRuntimeScenePostEvents.length; ++i) {\n gdjs.callbacksRuntimeScenePostEvents[i](this);\n }\n if (this._profiler) {\n this._profiler.end('callbacks and extensions (post-events)');\n }\n if (this._profiler) {\n this._profiler.begin('objects (pre-render, effects update)');\n }\n this._updateObjectsPreRender();\n if (this._profiler) {\n this._profiler.end('objects (pre-render, effects update)');\n }\n if (this._profiler) {\n this._profiler.begin('layers (effects update)');\n }\n this._updateLayersPreRender();\n if (this._profiler) {\n this._profiler.end('layers (effects update)');\n }\n if (this._profiler) {\n this._profiler.begin('render');\n }\n\n // Set to true to enable debug rendering (look for the implementation in the renderer\n // to see what is rendered).\n if (this._debugDrawEnabled) {\n this._debuggerRenderer.renderDebugDraw(\n this.getAdhocListOfAllInstances(),\n this._debugDrawShowHiddenInstances,\n this._debugDrawShowPointsNames,\n this._debugDrawShowCustomPoints\n );\n }\n\n this._isJustResumed = false;\n this.render();\n if (this._profiler) {\n this._profiler.end('render');\n }\n if (this._profiler) {\n this._profiler.endFrame();\n }\n return !!this.getRequestedChange();\n }\n\n /**\n * Render the PIXI container associated to the runtimeScene.\n */\n render() {\n this._renderer.render();\n }\n\n /**\n * Called to update visibility of the renderers of objects\n * rendered on the scene (\"culling\"), update effects (of visible objects)\n * and give a last chance for objects to update before rendering.\n *\n * Visibility is set to false if object is hidden, or if\n * object is too far from the camera of its layer (\"culling\").\n */\n _updateObjectsPreRender() {\n if (this._timeManager.isFirstFrame()) {\n super._updateObjectsPreRender();\n return;\n } else {\n // After first frame, optimise rendering by setting only objects\n // near camera as visible.\n // TODO: For compatibility, pass a scale of `2`,\n // meaning that size of cameras will be multiplied by 2 and so objects\n // will be hidden if they are outside of this *larger* camera area.\n // This is useful for:\n // - objects not properly reporting their visibility AABB,\n // (so we have a \"safety margin\") but these objects should be fixed\n // instead.\n // - objects having effects rendering outside of their visibility AABB.\n\n // TODO (3D) culling - add support for 3D object culling?\n this._updateLayersCameraCoordinates(2);\n const allInstancesList = this.getAdhocListOfAllInstances();\n for (let i = 0, len = allInstancesList.length; i < len; ++i) {\n const object = allInstancesList[i];\n const rendererObject = object.getRendererObject();\n if (rendererObject) {\n if (object.isHidden()) {\n rendererObject.visible = false;\n } else {\n const cameraCoords =\n this._layersCameraCoordinates[object.getLayer()];\n if (!cameraCoords) {\n continue;\n }\n const aabb = object.getVisibilityAABB();\n rendererObject.visible =\n // If no AABB is returned, the object should always be visible\n !aabb ||\n // If an AABB is there, it must be at least partially inside\n // the camera bounds.\n !(\n aabb.min[0] > cameraCoords[2] ||\n aabb.min[1] > cameraCoords[3] ||\n aabb.max[0] < cameraCoords[0] ||\n aabb.max[1] < cameraCoords[1]\n );\n }\n\n // Update effects, only for visible objects.\n if (rendererObject.visible) {\n this._runtimeGame\n .getEffectsManager()\n .updatePreRender(object.getRendererEffects(), object);\n\n // Perform pre-render update only if the object is visible\n // (including if there is no visibility AABB returned previously).\n object.updatePreRender(this);\n }\n } else {\n // Perform pre-render update, always for objects not having an\n // associated renderer object (so it must handle visibility on its own).\n object.updatePreRender(this);\n }\n }\n }\n }\n\n /**\n * Change the background color, by setting the RGB components.\n * Internally, the color is stored as an hexadecimal number.\n *\n * @param r The color red component (0-255).\n * @param g The color green component (0-255).\n * @param b The color blue component (0-255).\n */\n setBackgroundColor(r: integer, g: integer, b: integer): void {\n this._backgroundColor = parseInt(gdjs.rgbToHex(r, g, b), 16);\n }\n\n /**\n * Get the background color, as an hexadecimal number.\n * @returns The current background color.\n */\n getBackgroundColor(): number {\n return this._backgroundColor;\n }\n\n /**\n * Set whether the canvas should be cleared before this scene rendering.\n * This is experimental: if possible, try to avoid relying on this and use\n * custom objects to build complex scenes.\n */\n setClearCanvas(shouldClearCanvas: boolean): void {\n this._clearCanvas = shouldClearCanvas;\n }\n\n /**\n * Get whether the canvas should be cleared before this scene rendering.\n */\n getClearCanvas(): boolean {\n return this._clearCanvas;\n }\n\n /**\n * Get the name of the scene.\n */\n getName(): string {\n return this._name;\n }\n\n /**\n * Get the strategy to unload resources of this scene.\n */\n getResourcesUnloading(): 'at-scene-exit' | 'never' | 'inherit' {\n return this._resourcesUnloading;\n }\n\n /**\n * Create an identifier for a new object of the scene.\n */\n createNewUniqueId(): integer {\n this._lastId++;\n return this._lastId;\n }\n\n getRenderer(): gdjs.RuntimeScenePixiRenderer {\n return this._renderer;\n }\n\n getDebuggerRenderer() {\n return this._debuggerRenderer;\n }\n\n getGame() {\n return this._runtimeGame;\n }\n\n getScene() {\n return this;\n }\n\n getUnrotatedViewportMinX(): float {\n return 0;\n }\n\n getUnrotatedViewportMinY(): float {\n return 0;\n }\n\n getUnrotatedViewportMaxX(): float {\n return this._cachedGameResolutionWidth;\n }\n\n getUnrotatedViewportMaxY(): float {\n return this._cachedGameResolutionHeight;\n }\n\n getInitialUnrotatedViewportMinX(): float {\n return 0;\n }\n\n getInitialUnrotatedViewportMinY(): float {\n return 0;\n }\n\n getInitialUnrotatedViewportMaxX(): float {\n return this.getGame().getOriginalWidth();\n }\n\n getInitialUnrotatedViewportMaxY(): float {\n return this.getGame().getOriginalHeight();\n }\n\n getViewportWidth(): float {\n return this._cachedGameResolutionWidth;\n }\n\n getViewportHeight(): float {\n return this._cachedGameResolutionHeight;\n }\n\n getViewportOriginX(): float {\n return this._cachedGameResolutionWidth / 2;\n }\n\n getViewportOriginY(): float {\n return this._cachedGameResolutionHeight / 2;\n }\n\n convertCoords(x: float, y: float, result: FloatPoint): FloatPoint {\n // The result parameter used to be optional.\n const point = result || [0, 0];\n point[0] = x;\n point[1] = y;\n return point;\n }\n\n convertInverseCoords(\n sceneX: float,\n sceneY: float,\n result: FloatPoint\n ): FloatPoint {\n const point = result || [0, 0];\n point[0] = sceneX;\n point[1] = sceneY;\n return point;\n }\n\n onChildrenLocationChanged(): void {\n // Scenes don't maintain bounds.\n }\n\n /**\n * Get the variables of the runtimeScene.\n * @return The container holding the variables of the scene.\n */\n getVariables() {\n return this._variables;\n }\n\n /**\n * Get the extension's variables for this scene.\n * @param extensionName The extension name.\n * @returns The extension's variables for this scene.\n */\n getVariablesForExtension(extensionName: string) {\n return this._variablesByExtensionName.get(extensionName) || null;\n }\n\n /**\n * Get the TimeManager of the scene.\n * @return The gdjs.TimeManager of the scene.\n */\n getTimeManager(): gdjs.TimeManager {\n return this._timeManager;\n }\n\n /**\n * Return the time elapsed since the last frame,\n * in milliseconds, for objects on the layer.\n */\n getElapsedTime(): float {\n return this._timeManager.getElapsedTime();\n }\n\n /**\n * Shortcut to get the SoundManager of the game.\n * @return The gdjs.SoundManager of the game.\n */\n getSoundManager(): gdjs.SoundManager {\n return this._runtimeGame.getSoundManager();\n }\n\n /**\n * @returns The scene's async tasks manager.\n */\n getAsyncTasksManager() {\n return this._asyncTasksManager;\n }\n\n /**\n * Return the value of the scene change that is requested.\n */\n getRequestedChange(): SceneChangeRequest {\n return this._requestedChange;\n }\n\n /**\n * Return the name of the new scene to be launched.\n *\n * See requestChange.\n */\n getRequestedScene(): string {\n return this._requestedScene;\n }\n\n /**\n * Request a scene change to be made. The change is handled externally (see gdjs.SceneStack)\n * thanks to getRequestedChange and getRequestedScene methods.\n * @param change One of RuntimeScene.CONTINUE|PUSH_SCENE|POP_SCENE|REPLACE_SCENE|CLEAR_SCENES|STOP_GAME.\n * @param sceneName The name of the new scene to launch, if applicable.\n */\n requestChange(change: SceneChangeRequest, sceneName?: string) {\n this._requestedChange = change;\n if (sceneName) this._requestedScene = sceneName;\n }\n\n /**\n * Get the profiler associated with the scene, or null if none.\n */\n getProfiler(): gdjs.Profiler | null {\n return this._profiler;\n }\n\n /**\n * Start a new profiler to measures the time passed in sections of the engine\n * in the scene.\n * @param onProfilerStopped Function to be called when the profiler is stopped. Will be passed the profiler as argument.\n */\n startProfiler(onProfilerStopped: (oldProfiler: gdjs.Profiler) => void) {\n if (this._profiler) {\n return;\n }\n this._profiler = new gdjs.Profiler();\n this._onProfilerStopped = onProfilerStopped;\n }\n\n /**\n * Stop the profiler being run on the scene.\n */\n stopProfiler() {\n if (!this._profiler) {\n return;\n }\n const oldProfiler = this._profiler;\n const onProfilerStopped = this._onProfilerStopped;\n this._profiler = null;\n this._onProfilerStopped = null;\n if (onProfilerStopped) {\n onProfilerStopped(oldProfiler);\n }\n }\n\n /**\n * Get the structure containing the triggers for \"Trigger once\" conditions.\n */\n getOnceTriggers() {\n return this._onceTriggers;\n }\n\n /**\n * Check if the scene was just resumed.\n * This is true during the first frame after the scene has been unpaused.\n *\n * @returns true if the scene was just resumed\n */\n sceneJustResumed(): boolean {\n return this._isJustResumed;\n }\n\n getNetworkSyncData(\n syncOptions: GetNetworkSyncDataOptions\n ): LayoutNetworkSyncData | null {\n const syncedPlayerNumber = syncOptions.playerNumber;\n const variablesNetworkSyncData =\n this._variables.getNetworkSyncData(syncOptions);\n const extensionsVariablesSyncData = {};\n this._variablesByExtensionName.forEach((variables, extensionName) => {\n const extensionVariablesSyncData =\n variables.getNetworkSyncData(syncOptions);\n // If there is no variables to sync, don't include the extension in the sync data.\n if (extensionVariablesSyncData) {\n extensionsVariablesSyncData[extensionName] =\n extensionVariablesSyncData;\n }\n });\n\n if (\n syncedPlayerNumber !== undefined &&\n syncedPlayerNumber !== 1 &&\n (!this.networkId ||\n (variablesNetworkSyncData.length === 0 &&\n !Object.keys(extensionsVariablesSyncData).length))\n ) {\n // If we are getting sync data for a specific player,\n // and they are not the host, there is no sync data to send if:\n // - The scene has no networkId (it's either not a multiplayer scene or the scene is not yet networked).\n // - There are no variables to sync in the scene or extensions.\n return null;\n }\n\n return {\n var: variablesNetworkSyncData,\n extVar: extensionsVariablesSyncData,\n id: this.getOrCreateNetworkId(),\n };\n }\n\n updateFromNetworkSyncData(syncData: LayoutNetworkSyncData) {\n if (syncData.var) {\n this._variables.updateFromNetworkSyncData(syncData.var);\n }\n if (syncData.extVar) {\n for (const extensionName in syncData.extVar) {\n if (!syncData.extVar.hasOwnProperty(extensionName)) {\n continue;\n }\n const extensionVariablesData = syncData.extVar[extensionName];\n const extensionVariables =\n this._variablesByExtensionName.get(extensionName);\n if (extensionVariables) {\n extensionVariables.updateFromNetworkSyncData(\n extensionVariablesData\n );\n }\n }\n }\n }\n\n getOrCreateNetworkId(): string {\n if (!this.networkId) {\n const newNetworkId = gdjs.makeUuid().substring(0, 8);\n this.networkId = newNetworkId;\n }\n return this.networkId;\n }\n }\n\n //The flags to describe the change request by a scene:\n export enum SceneChangeRequest {\n CONTINUE,\n PUSH_SCENE,\n POP_SCENE,\n REPLACE_SCENE,\n CLEAR_SCENES,\n STOP_GAME,\n }\n}\n"],
|
|
5
|
+
"mappings": "AAKA,GAAU,MAAV,UAAU,EAAV,CACE,KAAM,GAAS,GAAI,GAAK,OAAO,gBACzB,EAAqB,GAAI,GAAK,OAAO,iCAKpC,eAA2B,GAAK,wBAAyB,CAgD9D,YAAY,EAA+B,CACzC,QAhDF,qBAAiE,KAOjE,aAAmB,EACnB,WAAgB,GAEhB,wBAA8B,GAC9B,qBAA0B,GAC1B,yBAA6D,UACrD,wBAAqB,GAAI,GAAK,kBAGtC,eAAqB,GAErB,oBAA0B,GAI1B,sBAA4B,EAG5B,kBAAwB,GAGxB,eAAkC,KAGlC,wBAAoE,KAWpE,eAA2B,KAOzB,KAAK,aAAe,EACpB,KAAK,WAAa,GAAI,GAAK,mBAC3B,KAAK,0BAA4B,GAAI,KAIrC,KAAK,aAAe,GAAI,GAAK,YAC7B,KAAK,cAAgB,GAAI,GAAK,aAC9B,KAAK,iBAAmB,EAAmB,SAC3C,KAAK,2BAA6B,EAC9B,EAAY,yBACZ,EACJ,KAAK,4BAA8B,EAC/B,EAAY,0BACZ,EAEJ,KAAK,UAAY,GAAI,GAAK,qBACxB,KAEA,EAAc,EAAY,cAAgB,MAE5C,KAAK,kBAAoB,GAAI,GAAK,iBAAiB,MAKnD,KAAK,0BAGP,SAAS,EAAsB,CAC7B,KAAM,GAAQ,GAAI,GAAK,MAAM,EAAW,MACxC,KAAK,QAAQ,IAAI,EAAU,KAAM,GACjC,KAAK,eAAe,KAAK,GAO3B,yBAA0B,CACxB,KAAM,GAA2B,KAAK,qBAChC,EA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EAAK,WAAW,UAAU,EAAG,GAClD,KAAK,UAAY,EAEnB,MAAO,MAAK,WAh2BT,EAAM,eAq2BN,GAAK,GAAL,UAAK,EAAL,CACL,2BACA,+BACA,6BACA,qCACA,mCACA,+BANU,qDA52BJ",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var gdjs;(function(o){const r=new o.Logger("Scene stack"),c=new o.Logger("Multiplayer - Debug");class
|
|
1
|
+
var gdjs;(function(o){const r=new o.Logger("Scene stack"),c=new o.Logger("Multiplayer - Debug");class u{constructor(e){this._stack=[];this._wasFirstSceneLoaded=!1;this._isNextLayoutLoading=!1;this._sceneStackSyncDataToApply=null;this._wasDisposed=!1;if(!e)throw"SceneStack must be constructed with a gdjs.RuntimeGame.";this._runtimeGame=e}onGameResolutionResized(){for(let e=0;e<this._stack.length;++e)this._stack[e].onGameResolutionResized()}step(e){if(this._throwIfDisposed(),this._isNextLayoutLoading||this._stack.length===0)return!1;if(this.applyUpdateFromNetworkSyncDataIfAny())return c.info("Scene stack has been updated from network sync data, skipping step."),!0;const t=this._stack[this._stack.length-1];if(t.renderAndStep(e)){const n=t.getRequestedChange();if(n===o.SceneChangeRequest.STOP_GAME)return this._runtimeGame.getRenderer().stopGame(),!0;n===o.SceneChangeRequest.POP_SCENE?this.pop():n===o.SceneChangeRequest.PUSH_SCENE?this.push(t.getRequestedScene()):n===o.SceneChangeRequest.REPLACE_SCENE||n===o.SceneChangeRequest.CLEAR_SCENES?this.replace(t.getRequestedScene(),n===o.SceneChangeRequest.CLEAR_SCENES):r.error("Unrecognized change in scene stack: "+n)}return!0}renderWithoutStep(){return this._throwIfDisposed(),this._stack.length===0?!1:(this._stack[this._stack.length-1].render(),!0)}pop(e=1){this._throwIfDisposed();let s=!1;for(let t=0;t<e&&!(this._stack.length<=1);++t){s=!0;const n=this._stack.pop();if(!n)return;this._unloadSceneAndPossiblyResources({scene:n,newSceneName:null})}if(s){const t=this._stack[this._stack.length-1];t&&t.onResume()}}push(e,s){this._throwIfDisposed();const t=this._stack[this._stack.length-1];return t&&t.onPause(),this._runtimeGame.areSceneAssetsReady(e)?this._loadNewScene(e,s):(this._isNextLayoutLoading=!0,this._runtimeGame.loadSceneAssets(e).then(()=>{this._loadNewScene(e),this._isNextLayoutLoading=!1}),null)}_loadNewScene(e,s){this._throwIfDisposed();const t=new o.RuntimeScene(this._runtimeGame);if(t.loadFromScene(this._runtimeGame.getSceneAndExtensionsData(e)),this._wasFirstSceneLoaded=!0,s){const n=this._runtimeGame.getExternalLayoutData(s);n&&t.createObjectsFrom(n.instances,0,0,0,!0)}return this._stack.push(t),t}replace(e,s){if(this._throwIfDisposed(),s)for(;this._stack.length!==0;){let t=this._stack.pop();t&&this._unloadSceneAndPossiblyResources({scene:t,newSceneName:e})}else if(this._stack.length!==0){let t=this._stack.pop();t&&this._unloadSceneAndPossiblyResources({scene:t,newSceneName:e})}return this.push(e)}getCurrentScene(){return this._throwIfDisposed(),this._stack.length===0?null:this._stack[this._stack.length-1]}wasFirstSceneLoaded(){return this._wasFirstSceneLoaded}getAllSceneNames(){return this._throwIfDisposed(),this._stack.map(e=>e.getName())}getNetworkSyncData(e){const s=e.playerNumber,t=e.isHost;if(s!==void 0&&!t)return null;const n=[];for(let a=0;a<this._stack.length;++a){const i=this._stack[a];n.push({name:i.getName(),networkId:i.getOrCreateNetworkId()})}return n}updateFromNetworkSyncData(e){this._sceneStackSyncDataToApply=e}applyUpdateFromNetworkSyncDataIfAny(){this._throwIfDisposed();const e=this._sceneStackSyncDataToApply;let s=!1;if(!e)return s;this._sceneStackSyncDataToApply=null;for(let t=0;t<e.length;++t){const n=e[t],a=this._stack[t];if(!a){c.info(`Scene at position ${t} with name ${n.name} is missing from the stack, adding it.`);const i=this.push(n.name);i&&(i.networkId=n.networkId),s=!0;continue}if(a.getName()!==n.name){c.info(`Scene at position ${t} and name ${a.getName()} is not the same as the expected ${n.name}, replacing.`);const i=this.replace(n.name,!0);i&&(i.networkId=n.networkId),s=!0;continue}if(!a.networkId&&n.networkId&&n.name===a.getName()){c.info(`Scene at position ${t} and name ${a.getName()} has no networkId, let's assume it's the right one and reconcile it with the id ${n.networkId}.`),a.networkId=n.networkId;continue}if(a.networkId!==n.networkId){c.info(`Scene at position ${t} and name ${a.getName()} has a different networkId ${a.networkId} than the expected ${n.networkId}, replacing.`);const i=this.replace(n.name,!1);i&&(i.networkId=n.networkId),s=!0;continue}}if(this._stack.length>e.length){const t=this._stack.length-e.length;this.pop(t),s=!0}return s}dispose(){for(;this._stack.length>0;){const e=this._stack.pop();e&&this._unloadSceneAndPossiblyResources({scene:e,newSceneName:null})}this._wasDisposed=!0}_unloadSceneAndPossiblyResources({scene:e,newSceneName:s}){const t=e.getName(),n=e.getResourcesUnloading(),i=(n==="inherit"?this._runtimeGame.getSceneResourcesUnloading():n)==="at-scene-exit"&&s!==e.getName()&&this._stack.every(h=>h.getName()!==t);e.unloadScene(),i&&this._runtimeGame.getResourceLoader().unloadSceneResources({unloadedSceneName:t,newSceneName:s})}_throwIfDisposed(){if(this._wasDisposed)throw"The scene stack has been disposed and should not be used anymore."}}o.SceneStack=u})(gdjs||(gdjs={}));
|
|
2
2
|
//# sourceMappingURL=scenestack.js.map
|