mirror of
https://github.com/godotengine/godot.git
synced 2025-11-02 06:31:13 +00:00
[HTML5] Document Engine and EngineConfig (jsdoc).
This commit also removes the utils.js engine file, moving some of it's content to config.js and some to engine.js .
This commit is contained in:
parent
d02535f509
commit
018ee5a4dc
5 changed files with 547 additions and 273 deletions
|
|
@ -3,9 +3,8 @@ module.exports = {
|
||||||
"./.eslintrc.js",
|
"./.eslintrc.js",
|
||||||
],
|
],
|
||||||
"globals": {
|
"globals": {
|
||||||
"EngineConfig": true,
|
"InternalConfig": true,
|
||||||
"Godot": true,
|
"Godot": true,
|
||||||
"Preloader": true,
|
"Preloader": true,
|
||||||
"Utils": true,
|
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -73,7 +73,6 @@ sys_env.Depends(build[0], sys_env["JS_EXTERNS"])
|
||||||
|
|
||||||
engine = [
|
engine = [
|
||||||
"js/engine/preloader.js",
|
"js/engine/preloader.js",
|
||||||
"js/engine/utils.js",
|
|
||||||
"js/engine/config.js",
|
"js/engine/config.js",
|
||||||
"js/engine/engine.js",
|
"js/engine/engine.js",
|
||||||
]
|
]
|
||||||
|
|
|
||||||
|
|
@ -1,100 +1,309 @@
|
||||||
/** @constructor */
|
/**
|
||||||
function EngineConfig(opts) {
|
* An object used to configure the Engine instance based on godot export options, and to override those in custom HTML
|
||||||
// Module config
|
* templates if needed.
|
||||||
this.unloadAfterInit = true;
|
*
|
||||||
this.onPrintError = function () {
|
* @header Engine configuration
|
||||||
console.error.apply(console, Array.from(arguments)); // eslint-disable-line no-console
|
* @summary The Engine configuration object. This is just a typedef, create it like a regular object, e.g.:
|
||||||
};
|
*
|
||||||
this.onPrint = function () {
|
* ``const MyConfig = { executable: 'godot', unloadAfterInit: false }``
|
||||||
console.log.apply(console, Array.from(arguments)); // eslint-disable-line no-console
|
*
|
||||||
};
|
* @typedef {Object} EngineConfig
|
||||||
this.onProgress = null;
|
*/
|
||||||
|
const EngineConfig = {}; // eslint-disable-line no-unused-vars
|
||||||
|
|
||||||
// Godot Config
|
/**
|
||||||
this.canvas = null;
|
* @struct
|
||||||
this.executable = '';
|
* @constructor
|
||||||
this.mainPack = null;
|
* @ignore
|
||||||
this.locale = null;
|
*/
|
||||||
this.canvasResizePolicy = false;
|
const InternalConfig = function (initConfig) { // eslint-disable-line no-unused-vars
|
||||||
this.persistentPaths = ['/userfs'];
|
const cfg = /** @lends {InternalConfig.prototype} */ {
|
||||||
this.gdnativeLibs = [];
|
/**
|
||||||
this.args = [];
|
* Whether the unload the engine automatically after the instance is initialized.
|
||||||
this.onExecute = null;
|
*
|
||||||
this.onExit = null;
|
* @memberof EngineConfig
|
||||||
this.update(opts);
|
* @default
|
||||||
}
|
* @type {boolean}
|
||||||
|
*/
|
||||||
EngineConfig.prototype.update = function (opts) {
|
unloadAfterInit: true,
|
||||||
const config = opts || {};
|
/**
|
||||||
function parse(key, def) {
|
* The HTML DOM Canvas object to use.
|
||||||
if (typeof (config[key]) === 'undefined') {
|
*
|
||||||
return def;
|
* By default, the first canvas element in the document will be used is none is specified.
|
||||||
}
|
*
|
||||||
return config[key];
|
* @memberof EngineConfig
|
||||||
}
|
* @default
|
||||||
// Module config
|
* @type {?HTMLCanvasElement}
|
||||||
this.unloadAfterInit = parse('unloadAfterInit', this.unloadAfterInit);
|
*/
|
||||||
this.onPrintError = parse('onPrintError', this.onPrintError);
|
canvas: null,
|
||||||
this.onPrint = parse('onPrint', this.onPrint);
|
/**
|
||||||
this.onProgress = parse('onProgress', this.onProgress);
|
* The name of the WASM file without the extension. (Set by Godot Editor export process).
|
||||||
|
*
|
||||||
// Godot config
|
* @memberof EngineConfig
|
||||||
this.canvas = parse('canvas', this.canvas);
|
* @default
|
||||||
this.executable = parse('executable', this.executable);
|
* @type {string}
|
||||||
this.mainPack = parse('mainPack', this.mainPack);
|
*/
|
||||||
this.locale = parse('locale', this.locale);
|
executable: '',
|
||||||
this.canvasResizePolicy = parse('canvasResizePolicy', this.canvasResizePolicy);
|
/**
|
||||||
this.persistentPaths = parse('persistentPaths', this.persistentPaths);
|
* An alternative name for the game pck to load. The executable name is used otherwise.
|
||||||
this.gdnativeLibs = parse('gdnativeLibs', this.gdnativeLibs);
|
*
|
||||||
this.args = parse('args', this.args);
|
* @memberof EngineConfig
|
||||||
this.onExecute = parse('onExecute', this.onExecute);
|
* @default
|
||||||
this.onExit = parse('onExit', this.onExit);
|
* @type {?string}
|
||||||
};
|
*/
|
||||||
|
mainPack: null,
|
||||||
EngineConfig.prototype.getModuleConfig = function (loadPath, loadPromise) {
|
/**
|
||||||
const me = this;
|
* Specify a language code to select the proper localization for the game.
|
||||||
return {
|
*
|
||||||
'print': this.onPrint,
|
* The browser locale will be used if none is specified. See complete list of
|
||||||
'printErr': this.onPrintError,
|
* :ref:`supported locales <doc_locales>`.
|
||||||
'locateFile': Utils.createLocateRewrite(loadPath),
|
*
|
||||||
'instantiateWasm': Utils.createInstantiatePromise(loadPromise),
|
* @memberof EngineConfig
|
||||||
'thisProgram': me.executable,
|
* @type {?string}
|
||||||
'noExitRuntime': true,
|
* @default
|
||||||
'dynamicLibraries': [`${me.executable}.side.wasm`],
|
*/
|
||||||
};
|
locale: null,
|
||||||
};
|
/**
|
||||||
|
* The canvas resize policy determines how the canvas should be resized by Godot.
|
||||||
EngineConfig.prototype.getGodotConfig = function (cleanup) {
|
*
|
||||||
if (!(this.canvas instanceof HTMLCanvasElement)) {
|
* ``0`` means Godot won't do any resizing. This is useful if you want to control the canvas size from
|
||||||
this.canvas = Utils.findCanvas();
|
* javascript code in your template.
|
||||||
if (!this.canvas) {
|
*
|
||||||
throw new Error('No canvas found in page');
|
* ``1`` means Godot will resize the canvas on start, and when changing window size via engine functions.
|
||||||
}
|
*
|
||||||
}
|
* ``2`` means Godot will adapt the canvas size to match the whole browser window.
|
||||||
|
*
|
||||||
// Canvas can grab focus on click, or key events won't work.
|
* @memberof EngineConfig
|
||||||
if (this.canvas.tabIndex < 0) {
|
* @type {number}
|
||||||
this.canvas.tabIndex = 0;
|
* @default
|
||||||
}
|
*/
|
||||||
|
canvasResizePolicy: 2,
|
||||||
// Browser locale, or custom one if defined.
|
/**
|
||||||
let locale = this.locale;
|
* The arguments to be passed as command line arguments on startup.
|
||||||
if (!locale) {
|
*
|
||||||
locale = navigator.languages ? navigator.languages[0] : navigator.language;
|
* See :ref:`command line tutorial <doc_command_line_tutorial>`.
|
||||||
locale = locale.split('.')[0];
|
*
|
||||||
}
|
* **Note**: :js:meth:`startGame <Engine.prototype.startGame>` will always add the ``--main-pack`` argument.
|
||||||
const onExit = this.onExit;
|
*
|
||||||
// Godot configuration.
|
* @memberof EngineConfig
|
||||||
return {
|
* @type {Array<string>}
|
||||||
'canvas': this.canvas,
|
* @default
|
||||||
'canvasResizePolicy': this.canvasResizePolicy,
|
*/
|
||||||
'locale': locale,
|
args: [],
|
||||||
'onExecute': this.onExecute,
|
/**
|
||||||
'onExit': function (p_code) {
|
* @ignore
|
||||||
cleanup(); // We always need to call the cleanup callback to free memory.
|
* @type {Array.<string>}
|
||||||
if (typeof (onExit) === 'function') {
|
*/
|
||||||
onExit(p_code);
|
persistentPaths: ['/userfs'],
|
||||||
}
|
/**
|
||||||
|
* @ignore
|
||||||
|
* @type {Array.<string>}
|
||||||
|
*/
|
||||||
|
gdnativeLibs: [],
|
||||||
|
/**
|
||||||
|
* A callback function for handling Godot's ``OS.execute`` calls.
|
||||||
|
*
|
||||||
|
* This is for example used in the Web Editor template to switch between project manager and editor, and for running the game.
|
||||||
|
*
|
||||||
|
* @callback EngineConfig.onExecute
|
||||||
|
* @param {string} path The path that Godot's wants executed.
|
||||||
|
* @param {Array.<string>} args The arguments of the "command" to execute.
|
||||||
|
*/
|
||||||
|
/**
|
||||||
|
* @ignore
|
||||||
|
* @type {?function(string, Array.<string>)}
|
||||||
|
*/
|
||||||
|
onExecute: null,
|
||||||
|
/**
|
||||||
|
* A callback function for being notified when the Godot instance quits.
|
||||||
|
*
|
||||||
|
* **Note**: This function will not be called if the engine crashes or become unresponsive.
|
||||||
|
*
|
||||||
|
* @callback EngineConfig.onExit
|
||||||
|
* @param {number} status_code The status code returned by Godot on exit.
|
||||||
|
*/
|
||||||
|
/**
|
||||||
|
* @ignore
|
||||||
|
* @type {?function(number)}
|
||||||
|
*/
|
||||||
|
onExit: null,
|
||||||
|
/**
|
||||||
|
* A callback function for displaying download progress.
|
||||||
|
*
|
||||||
|
* The function is called once per frame while downloading files, so the usage of ``requestAnimationFrame()``
|
||||||
|
* is not necessary.
|
||||||
|
*
|
||||||
|
* If the callback function receives a total amount of bytes as 0, this means that it is impossible to calculate.
|
||||||
|
* Possible reasons include:
|
||||||
|
*
|
||||||
|
* - Files are delivered with server-side chunked compression
|
||||||
|
* - Files are delivered with server-side compression on Chromium
|
||||||
|
* - Not all file downloads have started yet (usually on servers without multi-threading)
|
||||||
|
*
|
||||||
|
* @callback EngineConfig.onProgress
|
||||||
|
* @param {number} current The current amount of downloaded bytes so far.
|
||||||
|
* @param {number} total The total amount of bytes to be downloaded.
|
||||||
|
*/
|
||||||
|
/**
|
||||||
|
* @ignore
|
||||||
|
* @type {?function(number, number)}
|
||||||
|
*/
|
||||||
|
onProgress: null,
|
||||||
|
/**
|
||||||
|
* A callback function for handling the standard output stream. This method should usually only be used in debug pages.
|
||||||
|
*
|
||||||
|
* By default, ``console.log()`` is used.
|
||||||
|
*
|
||||||
|
* @callback EngineConfig.onPrint
|
||||||
|
* @param {...*} [var_args] A variadic number of arguments to be printed.
|
||||||
|
*/
|
||||||
|
/**
|
||||||
|
* @ignore
|
||||||
|
* @type {?function(...*)}
|
||||||
|
*/
|
||||||
|
onPrint: function () {
|
||||||
|
console.log.apply(console, Array.from(arguments)); // eslint-disable-line no-console
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* A callback function for handling the standard error stream. This method should usually only be used in debug pages.
|
||||||
|
*
|
||||||
|
* By default, ``console.error()`` is used.
|
||||||
|
*
|
||||||
|
* @callback EngineConfig.onPrintError
|
||||||
|
* @param {...*} [var_args] A variadic number of arguments to be printed as errors.
|
||||||
|
*/
|
||||||
|
/**
|
||||||
|
* @ignore
|
||||||
|
* @type {?function(...*)}
|
||||||
|
*/
|
||||||
|
onPrintError: function (var_args) {
|
||||||
|
console.error.apply(console, Array.from(arguments)); // eslint-disable-line no-console
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @ignore
|
||||||
|
* @struct
|
||||||
|
* @constructor
|
||||||
|
* @param {EngineConfig} opts
|
||||||
|
*/
|
||||||
|
function Config(opts) {
|
||||||
|
this.update(opts);
|
||||||
|
}
|
||||||
|
|
||||||
|
Config.prototype = cfg;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @ignore
|
||||||
|
* @param {EngineConfig} opts
|
||||||
|
*/
|
||||||
|
Config.prototype.update = function (opts) {
|
||||||
|
const config = opts || {};
|
||||||
|
function parse(key, def) {
|
||||||
|
if (typeof (config[key]) === 'undefined') {
|
||||||
|
return def;
|
||||||
|
}
|
||||||
|
return config[key];
|
||||||
|
}
|
||||||
|
// Module config
|
||||||
|
this.unloadAfterInit = parse('unloadAfterInit', this.unloadAfterInit);
|
||||||
|
this.onPrintError = parse('onPrintError', this.onPrintError);
|
||||||
|
this.onPrint = parse('onPrint', this.onPrint);
|
||||||
|
this.onProgress = parse('onProgress', this.onProgress);
|
||||||
|
|
||||||
|
// Godot config
|
||||||
|
this.canvas = parse('canvas', this.canvas);
|
||||||
|
this.executable = parse('executable', this.executable);
|
||||||
|
this.mainPack = parse('mainPack', this.mainPack);
|
||||||
|
this.locale = parse('locale', this.locale);
|
||||||
|
this.canvasResizePolicy = parse('canvasResizePolicy', this.canvasResizePolicy);
|
||||||
|
this.persistentPaths = parse('persistentPaths', this.persistentPaths);
|
||||||
|
this.gdnativeLibs = parse('gdnativeLibs', this.gdnativeLibs);
|
||||||
|
this.args = parse('args', this.args);
|
||||||
|
this.onExecute = parse('onExecute', this.onExecute);
|
||||||
|
this.onExit = parse('onExit', this.onExit);
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @ignore
|
||||||
|
* @param {string} loadPath
|
||||||
|
* @param {Promise} loadPromise
|
||||||
|
*/
|
||||||
|
Config.prototype.getModuleConfig = function (loadPath, loadPromise) {
|
||||||
|
let loader = loadPromise;
|
||||||
|
return {
|
||||||
|
'print': this.onPrint,
|
||||||
|
'printErr': this.onPrintError,
|
||||||
|
'thisProgram': this.executable,
|
||||||
|
'noExitRuntime': true,
|
||||||
|
'dynamicLibraries': [`${loadPath}.side.wasm`],
|
||||||
|
'instantiateWasm': function (imports, onSuccess) {
|
||||||
|
loader.then(function (xhr) {
|
||||||
|
WebAssembly.instantiate(xhr.response, imports).then(function (result) {
|
||||||
|
onSuccess(result['instance'], result['module']);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
loader = null;
|
||||||
|
return {};
|
||||||
|
},
|
||||||
|
'locateFile': function (path) {
|
||||||
|
if (path.endsWith('.worker.js')) {
|
||||||
|
return `${loadPath}.worker.js`;
|
||||||
|
} else if (path.endsWith('.audio.worklet.js')) {
|
||||||
|
return `${loadPath}.audio.worklet.js`;
|
||||||
|
} else if (path.endsWith('.js')) {
|
||||||
|
return `${loadPath}.js`;
|
||||||
|
} else if (path.endsWith('.side.wasm')) {
|
||||||
|
return `${loadPath}.side.wasm`;
|
||||||
|
} else if (path.endsWith('.wasm')) {
|
||||||
|
return `${loadPath}.wasm`;
|
||||||
|
}
|
||||||
|
return path;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @ignore
|
||||||
|
* @param {function()} cleanup
|
||||||
|
*/
|
||||||
|
Config.prototype.getGodotConfig = function (cleanup) {
|
||||||
|
// Try to find a canvas
|
||||||
|
if (!(this.canvas instanceof HTMLCanvasElement)) {
|
||||||
|
const nodes = document.getElementsByTagName('canvas');
|
||||||
|
if (nodes.length && nodes[0] instanceof HTMLCanvasElement) {
|
||||||
|
this.canvas = nodes[0];
|
||||||
|
}
|
||||||
|
if (!this.canvas) {
|
||||||
|
throw new Error('No canvas found in page');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Canvas can grab focus on click, or key events won't work.
|
||||||
|
if (this.canvas.tabIndex < 0) {
|
||||||
|
this.canvas.tabIndex = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Browser locale, or custom one if defined.
|
||||||
|
let locale = this.locale;
|
||||||
|
if (!locale) {
|
||||||
|
locale = navigator.languages ? navigator.languages[0] : navigator.language;
|
||||||
|
locale = locale.split('.')[0];
|
||||||
|
}
|
||||||
|
const onExit = this.onExit;
|
||||||
|
|
||||||
|
// Godot configuration.
|
||||||
|
return {
|
||||||
|
'canvas': this.canvas,
|
||||||
|
'canvasResizePolicy': this.canvasResizePolicy,
|
||||||
|
'locale': locale,
|
||||||
|
'onExecute': this.onExecute,
|
||||||
|
'onExit': function (p_code) {
|
||||||
|
cleanup(); // We always need to call the cleanup callback to free memory.
|
||||||
|
if (typeof (onExit) === 'function') {
|
||||||
|
onExit(p_code);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
};
|
||||||
|
return new Config(initConfig);
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,13 @@
|
||||||
|
/**
|
||||||
|
* Projects exported for the Web expose the :js:class:`Engine` class to the JavaScript environment, that allows
|
||||||
|
* fine control over the engine's start-up process.
|
||||||
|
*
|
||||||
|
* This API is built in an asynchronous manner and requires basic understanding
|
||||||
|
* of `Promises <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises>`__.
|
||||||
|
*
|
||||||
|
* @module Engine
|
||||||
|
* @header HTML5 shell class reference
|
||||||
|
*/
|
||||||
const Engine = (function () {
|
const Engine = (function () {
|
||||||
const preloader = new Preloader();
|
const preloader = new Preloader();
|
||||||
|
|
||||||
|
|
@ -5,139 +15,254 @@ const Engine = (function () {
|
||||||
let loadPath = '';
|
let loadPath = '';
|
||||||
let initPromise = null;
|
let initPromise = null;
|
||||||
|
|
||||||
function load(basePath) {
|
/**
|
||||||
|
* @classdesc The ``Engine`` class provides methods for loading and starting exported projects on the Web. For default export
|
||||||
|
* settings, this is already part of the exported HTML page. To understand practical use of the ``Engine`` class,
|
||||||
|
* see :ref:`Custom HTML page for Web export <doc_customizing_html5_shell>`.
|
||||||
|
*
|
||||||
|
* @description Create a new Engine instance with the given configuration.
|
||||||
|
*
|
||||||
|
* @global
|
||||||
|
* @constructor
|
||||||
|
* @param {EngineConfig} initConfig The initial config for this instance.
|
||||||
|
*/
|
||||||
|
function Engine(initConfig) { // eslint-disable-line no-shadow
|
||||||
|
this.config = new InternalConfig(initConfig);
|
||||||
|
this.rtenv = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load the engine from the specified base path.
|
||||||
|
*
|
||||||
|
* @param {string} basePath Base path of the engine to load.
|
||||||
|
* @returns {Promise} A Promise that resolves once the engine is loaded.
|
||||||
|
*
|
||||||
|
* @function Engine.load
|
||||||
|
*/
|
||||||
|
Engine.load = function (basePath) {
|
||||||
if (loadPromise == null) {
|
if (loadPromise == null) {
|
||||||
loadPath = basePath;
|
loadPath = basePath;
|
||||||
loadPromise = preloader.loadPromise(`${loadPath}.wasm`);
|
loadPromise = preloader.loadPromise(`${loadPath}.wasm`);
|
||||||
requestAnimationFrame(preloader.animateProgress);
|
requestAnimationFrame(preloader.animateProgress);
|
||||||
}
|
}
|
||||||
return loadPromise;
|
return loadPromise;
|
||||||
}
|
};
|
||||||
|
|
||||||
function unload() {
|
/**
|
||||||
|
* Unload the engine to free memory.
|
||||||
|
*
|
||||||
|
* This method will be called automatically depending on the configuration. See :js:attr:`unloadAfterInit`.
|
||||||
|
*
|
||||||
|
* @function Engine.unload
|
||||||
|
*/
|
||||||
|
Engine.unload = function () {
|
||||||
loadPromise = null;
|
loadPromise = null;
|
||||||
}
|
};
|
||||||
|
|
||||||
/** @constructor */
|
/**
|
||||||
function Engine(opts) { // eslint-disable-line no-shadow
|
* Check whether WebGL is available. Optionally, specify a particular version of WebGL to check for.
|
||||||
this.config = new EngineConfig(opts);
|
*
|
||||||
this.rtenv = null;
|
* @param {number=} [majorVersion=1] The major WebGL version to check for.
|
||||||
}
|
* @returns {boolean} If the given major version of WebGL is available.
|
||||||
|
* @function Engine.isWebGLAvailable
|
||||||
|
*/
|
||||||
|
Engine.isWebGLAvailable = function (majorVersion = 1) {
|
||||||
|
try {
|
||||||
|
return !!document.createElement('canvas').getContext(['webgl', 'webgl2'][majorVersion - 1]);
|
||||||
|
} catch (e) { /* Not available */ }
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
Engine.prototype.init = /** @param {string=} basePath */ function (basePath) {
|
/**
|
||||||
if (initPromise) {
|
* Safe Engine constructor, creates a new prototype for every new instance to avoid prototype pollution.
|
||||||
return initPromise;
|
* @ignore
|
||||||
}
|
* @constructor
|
||||||
if (loadPromise == null) {
|
*/
|
||||||
if (!basePath) {
|
function SafeEngine(initConfig) {
|
||||||
initPromise = Promise.reject(new Error('A base path must be provided when calling `init` and the engine is not loaded.'));
|
const proto = /** @lends Engine.prototype */ {
|
||||||
return initPromise;
|
/**
|
||||||
}
|
* Initialize the engine instance. Optionally, pass the base path to the engine to load it,
|
||||||
load(basePath);
|
* if it hasn't been loaded yet. See :js:meth:`Engine.load`.
|
||||||
}
|
*
|
||||||
preloader.setProgressFunc(this.config.onProgress);
|
* @param {string=} basePath Base path of the engine to load.
|
||||||
let config = this.config.getModuleConfig(loadPath, loadPromise);
|
* @return {Promise} A ``Promise`` that resolves once the engine is loaded and initialized.
|
||||||
const me = this;
|
*/
|
||||||
initPromise = new Promise(function (resolve, reject) {
|
init: function (basePath) {
|
||||||
Godot(config).then(function (module) {
|
if (initPromise) {
|
||||||
module['initFS'](me.config.persistentPaths).then(function (fs_err) {
|
return initPromise;
|
||||||
me.rtenv = module;
|
}
|
||||||
if (me.config.unloadAfterInit) {
|
if (loadPromise == null) {
|
||||||
unload();
|
if (!basePath) {
|
||||||
|
initPromise = Promise.reject(new Error('A base path must be provided when calling `init` and the engine is not loaded.'));
|
||||||
|
return initPromise;
|
||||||
}
|
}
|
||||||
resolve();
|
Engine.load(basePath);
|
||||||
config = null;
|
}
|
||||||
});
|
preloader.setProgressFunc(this.config.onProgress);
|
||||||
});
|
let config = this.config.getModuleConfig(loadPath, loadPromise);
|
||||||
});
|
const me = this;
|
||||||
return initPromise;
|
initPromise = new Promise(function (resolve, reject) {
|
||||||
};
|
Godot(config).then(function (module) {
|
||||||
|
module['initFS'](me.config.persistentPaths).then(function (fs_err) {
|
||||||
/** @type {function(string, string):Object} */
|
me.rtenv = module;
|
||||||
Engine.prototype.preloadFile = function (file, path) {
|
if (me.config.unloadAfterInit) {
|
||||||
return preloader.preload(file, path);
|
Engine.unload();
|
||||||
};
|
}
|
||||||
|
resolve();
|
||||||
/** @type {function(...string):Object} */
|
config = null;
|
||||||
Engine.prototype.start = function (override) {
|
});
|
||||||
this.config.update(override);
|
|
||||||
const me = this;
|
|
||||||
return me.init().then(function () {
|
|
||||||
if (!me.rtenv) {
|
|
||||||
return Promise.reject(new Error('The engine must be initialized before it can be started'));
|
|
||||||
}
|
|
||||||
|
|
||||||
let config = {};
|
|
||||||
try {
|
|
||||||
config = me.config.getGodotConfig(function () {
|
|
||||||
me.rtenv = null;
|
|
||||||
});
|
|
||||||
} catch (e) {
|
|
||||||
return Promise.reject(e);
|
|
||||||
}
|
|
||||||
// Godot configuration.
|
|
||||||
me.rtenv['initConfig'](config);
|
|
||||||
|
|
||||||
// Preload GDNative libraries.
|
|
||||||
const libs = [];
|
|
||||||
me.config.gdnativeLibs.forEach(function (lib) {
|
|
||||||
libs.push(me.rtenv['loadDynamicLibrary'](lib, { 'loadAsync': true }));
|
|
||||||
});
|
|
||||||
return Promise.all(libs).then(function () {
|
|
||||||
return new Promise(function (resolve, reject) {
|
|
||||||
preloader.preloadedFiles.forEach(function (file) {
|
|
||||||
me.rtenv['copyToFS'](file.path, file.buffer);
|
|
||||||
});
|
});
|
||||||
preloader.preloadedFiles.length = 0; // Clear memory
|
|
||||||
me.rtenv['callMain'](me.config.args);
|
|
||||||
initPromise = null;
|
|
||||||
resolve();
|
|
||||||
});
|
});
|
||||||
});
|
return initPromise;
|
||||||
});
|
},
|
||||||
};
|
|
||||||
|
|
||||||
Engine.prototype.startGame = function (override) {
|
/**
|
||||||
this.config.update(override);
|
* Load a file so it is available in the instance's file system once it runs. Must be called **before** starting the
|
||||||
// Add main-pack argument.
|
* instance.
|
||||||
const exe = this.config.executable;
|
*
|
||||||
const pack = this.config.mainPack || `${exe}.pck`;
|
* If not provided, the ``path`` is derived from the URL of the loaded file.
|
||||||
this.config.args = ['--main-pack', pack].concat(this.config.args);
|
*
|
||||||
// Start and init with execName as loadPath if not inited.
|
* @param {string|ArrayBuffer} file The file to preload.
|
||||||
const me = this;
|
*
|
||||||
return Promise.all([
|
* If a ``string`` the file will be loaded from that path.
|
||||||
this.init(exe),
|
*
|
||||||
this.preloadFile(pack, pack),
|
* If an ``ArrayBuffer`` or a view on one, the buffer will used as the content of the file.
|
||||||
]).then(function () {
|
*
|
||||||
return me.start.apply(me);
|
* @param {string=} path Path by which the file will be accessible. Required, if ``file`` is not a string.
|
||||||
});
|
*
|
||||||
};
|
* @returns {Promise} A Promise that resolves once the file is loaded.
|
||||||
|
*/
|
||||||
|
preloadFile: function (file, path) {
|
||||||
|
return preloader.preload(file, path);
|
||||||
|
},
|
||||||
|
|
||||||
Engine.prototype.copyToFS = function (path, buffer) {
|
/**
|
||||||
if (this.rtenv == null) {
|
* Start the engine instance using the given override configuration (if any).
|
||||||
throw new Error('Engine must be inited before copying files');
|
* :js:meth:`startGame <Engine.prototype.startGame>` can be used in typical cases instead.
|
||||||
}
|
*
|
||||||
this.rtenv['copyToFS'](path, buffer);
|
* This will initialize the instance if it is not initialized. For manual initialization, see :js:meth:`init <Engine.prototype.init>`.
|
||||||
};
|
* The engine must be loaded beforehand.
|
||||||
|
*
|
||||||
|
* Fails if a canvas cannot be found on the page, or not specified in the configuration.
|
||||||
|
*
|
||||||
|
* @param {EngineConfig} override An optional configuration override.
|
||||||
|
* @return {Promise} Promise that resolves once the engine started.
|
||||||
|
*/
|
||||||
|
start: function (override) {
|
||||||
|
this.config.update(override);
|
||||||
|
const me = this;
|
||||||
|
return me.init().then(function () {
|
||||||
|
if (!me.rtenv) {
|
||||||
|
return Promise.reject(new Error('The engine must be initialized before it can be started'));
|
||||||
|
}
|
||||||
|
|
||||||
Engine.prototype.requestQuit = function () {
|
let config = {};
|
||||||
if (this.rtenv) {
|
try {
|
||||||
this.rtenv['request_quit']();
|
config = me.config.getGodotConfig(function () {
|
||||||
}
|
me.rtenv = null;
|
||||||
};
|
});
|
||||||
|
} catch (e) {
|
||||||
|
return Promise.reject(e);
|
||||||
|
}
|
||||||
|
// Godot configuration.
|
||||||
|
me.rtenv['initConfig'](config);
|
||||||
|
|
||||||
// Closure compiler exported engine methods.
|
// Preload GDNative libraries.
|
||||||
/** @export */
|
const libs = [];
|
||||||
Engine['isWebGLAvailable'] = Utils.isWebGLAvailable;
|
me.config.gdnativeLibs.forEach(function (lib) {
|
||||||
Engine['load'] = load;
|
libs.push(me.rtenv['loadDynamicLibrary'](lib, { 'loadAsync': true }));
|
||||||
Engine['unload'] = unload;
|
});
|
||||||
Engine.prototype['init'] = Engine.prototype.init;
|
return Promise.all(libs).then(function () {
|
||||||
Engine.prototype['preloadFile'] = Engine.prototype.preloadFile;
|
return new Promise(function (resolve, reject) {
|
||||||
Engine.prototype['start'] = Engine.prototype.start;
|
preloader.preloadedFiles.forEach(function (file) {
|
||||||
Engine.prototype['startGame'] = Engine.prototype.startGame;
|
me.rtenv['copyToFS'](file.path, file.buffer);
|
||||||
Engine.prototype['copyToFS'] = Engine.prototype.copyToFS;
|
});
|
||||||
Engine.prototype['requestQuit'] = Engine.prototype.requestQuit;
|
preloader.preloadedFiles.length = 0; // Clear memory
|
||||||
return Engine;
|
me.rtenv['callMain'](me.config.args);
|
||||||
|
initPromise = null;
|
||||||
|
resolve();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Start the game instance using the given configuration override (if any).
|
||||||
|
*
|
||||||
|
* This will initialize the instance if it is not initialized. For manual initialization, see :js:meth:`init <Engine.prototype.init>`.
|
||||||
|
*
|
||||||
|
* This will load the engine if it is not loaded, and preload the main pck.
|
||||||
|
*
|
||||||
|
* This method expects the initial config (or the override) to have both the :js:attr:`executable` and :js:attr:`mainPack`
|
||||||
|
* properties set (normally done by the editor during export).
|
||||||
|
*
|
||||||
|
* @param {EngineConfig} override An optional configuration override.
|
||||||
|
* @return {Promise} Promise that resolves once the game started.
|
||||||
|
*/
|
||||||
|
startGame: function (override) {
|
||||||
|
this.config.update(override);
|
||||||
|
// Add main-pack argument.
|
||||||
|
const exe = this.config.executable;
|
||||||
|
const pack = this.config.mainPack || `${exe}.pck`;
|
||||||
|
this.config.args = ['--main-pack', pack].concat(this.config.args);
|
||||||
|
// Start and init with execName as loadPath if not inited.
|
||||||
|
const me = this;
|
||||||
|
return Promise.all([
|
||||||
|
this.init(exe),
|
||||||
|
this.preloadFile(pack, pack),
|
||||||
|
]).then(function () {
|
||||||
|
return me.start.apply(me);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a file at the specified ``path`` with the passed as ``buffer`` in the instance's file system.
|
||||||
|
*
|
||||||
|
* @param {string} path The location where the file will be created.
|
||||||
|
* @param {ArrayBuffer} buffer The content of the file.
|
||||||
|
*/
|
||||||
|
copyToFS: function (path, buffer) {
|
||||||
|
if (this.rtenv == null) {
|
||||||
|
throw new Error('Engine must be inited before copying files');
|
||||||
|
}
|
||||||
|
this.rtenv['copyToFS'](path, buffer);
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Request that the current instance quit.
|
||||||
|
*
|
||||||
|
* This is akin the user pressing the close button in the window manager, and will
|
||||||
|
* have no effect if the engine has crashed, or is stuck in a loop.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
requestQuit: function () {
|
||||||
|
if (this.rtenv) {
|
||||||
|
this.rtenv['request_quit']();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
Engine.prototype = proto;
|
||||||
|
// Closure compiler exported instance methods.
|
||||||
|
Engine.prototype['init'] = Engine.prototype.init;
|
||||||
|
Engine.prototype['preloadFile'] = Engine.prototype.preloadFile;
|
||||||
|
Engine.prototype['start'] = Engine.prototype.start;
|
||||||
|
Engine.prototype['startGame'] = Engine.prototype.startGame;
|
||||||
|
Engine.prototype['copyToFS'] = Engine.prototype.copyToFS;
|
||||||
|
Engine.prototype['requestQuit'] = Engine.prototype.requestQuit;
|
||||||
|
// Also expose static methods as instance methods
|
||||||
|
Engine.prototype['load'] = Engine.load;
|
||||||
|
Engine.prototype['unload'] = Engine.unload;
|
||||||
|
Engine.prototype['isWebGLAvailable'] = Engine.isWebGLAvailable;
|
||||||
|
return new Engine(initConfig);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Closure compiler exported static methods.
|
||||||
|
SafeEngine['load'] = Engine.load;
|
||||||
|
SafeEngine['unload'] = Engine.unload;
|
||||||
|
SafeEngine['isWebGLAvailable'] = Engine.isWebGLAvailable;
|
||||||
|
|
||||||
|
return SafeEngine;
|
||||||
}());
|
}());
|
||||||
if (typeof window !== 'undefined') {
|
if (typeof window !== 'undefined') {
|
||||||
window['Engine'] = Engine;
|
window['Engine'] = Engine;
|
||||||
|
|
|
||||||
|
|
@ -1,58 +0,0 @@
|
||||||
const Utils = { // eslint-disable-line no-unused-vars
|
|
||||||
|
|
||||||
createLocateRewrite: function (execName) {
|
|
||||||
function rw(path) {
|
|
||||||
if (path.endsWith('.worker.js')) {
|
|
||||||
return `${execName}.worker.js`;
|
|
||||||
} else if (path.endsWith('.audio.worklet.js')) {
|
|
||||||
return `${execName}.audio.worklet.js`;
|
|
||||||
} else if (path.endsWith('.js')) {
|
|
||||||
return `${execName}.js`;
|
|
||||||
} else if (path.endsWith('.side.wasm')) {
|
|
||||||
return `${execName}.side.wasm`;
|
|
||||||
} else if (path.endsWith('.wasm')) {
|
|
||||||
return `${execName}.wasm`;
|
|
||||||
}
|
|
||||||
return path;
|
|
||||||
}
|
|
||||||
return rw;
|
|
||||||
},
|
|
||||||
|
|
||||||
createInstantiatePromise: function (wasmLoader) {
|
|
||||||
let loader = wasmLoader;
|
|
||||||
function instantiateWasm(imports, onSuccess) {
|
|
||||||
loader.then(function (xhr) {
|
|
||||||
WebAssembly.instantiate(xhr.response, imports).then(function (result) {
|
|
||||||
onSuccess(result['instance'], result['module']);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
loader = null;
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
|
|
||||||
return instantiateWasm;
|
|
||||||
},
|
|
||||||
|
|
||||||
findCanvas: function () {
|
|
||||||
const nodes = document.getElementsByTagName('canvas');
|
|
||||||
if (nodes.length && nodes[0] instanceof HTMLCanvasElement) {
|
|
||||||
return nodes[0];
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
},
|
|
||||||
|
|
||||||
isWebGLAvailable: function (majorVersion = 1) {
|
|
||||||
let testContext = false;
|
|
||||||
try {
|
|
||||||
const testCanvas = document.createElement('canvas');
|
|
||||||
if (majorVersion === 1) {
|
|
||||||
testContext = testCanvas.getContext('webgl') || testCanvas.getContext('experimental-webgl');
|
|
||||||
} else if (majorVersion === 2) {
|
|
||||||
testContext = testCanvas.getContext('webgl2') || testCanvas.getContext('experimental-webgl2');
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
// Not available
|
|
||||||
}
|
|
||||||
return !!testContext;
|
|
||||||
},
|
|
||||||
};
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue