engine.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. /**
  2. * Projects exported for the Web expose the :js:class:`Engine` class to the JavaScript environment, that allows
  3. * fine control over the engine's start-up process.
  4. *
  5. * This API is built in an asynchronous manner and requires basic understanding
  6. * of `Promises <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises>`__.
  7. *
  8. * @module Engine
  9. * @header HTML5 shell class reference
  10. */
  11. const Engine = (function () {
  12. const preloader = new Preloader();
  13. let loadPromise = null;
  14. let loadPath = '';
  15. let initPromise = null;
  16. /**
  17. * @classdesc The ``Engine`` class provides methods for loading and starting exported projects on the Web. For default export
  18. * settings, this is already part of the exported HTML page. To understand practical use of the ``Engine`` class,
  19. * see :ref:`Custom HTML page for Web export <doc_customizing_html5_shell>`.
  20. *
  21. * @description Create a new Engine instance with the given configuration.
  22. *
  23. * @global
  24. * @constructor
  25. * @param {EngineConfig} initConfig The initial config for this instance.
  26. */
  27. function Engine(initConfig) { // eslint-disable-line no-shadow
  28. this.config = new InternalConfig(initConfig);
  29. this.rtenv = null;
  30. }
  31. /**
  32. * Load the engine from the specified base path.
  33. *
  34. * @param {string} basePath Base path of the engine to load.
  35. * @param {number=} [size=0] The file size if known.
  36. * @returns {Promise} A Promise that resolves once the engine is loaded.
  37. *
  38. * @function Engine.load
  39. */
  40. Engine.load = function (basePath, size) {
  41. if (loadPromise == null) {
  42. loadPath = basePath;
  43. loadPromise = preloader.loadPromise(`${loadPath}.wasm`, size, true);
  44. requestAnimationFrame(preloader.animateProgress);
  45. }
  46. return loadPromise;
  47. };
  48. /**
  49. * Unload the engine to free memory.
  50. *
  51. * This method will be called automatically depending on the configuration. See :js:attr:`unloadAfterInit`.
  52. *
  53. * @function Engine.unload
  54. */
  55. Engine.unload = function () {
  56. loadPromise = null;
  57. };
  58. /**
  59. * Check whether WebGL is available. Optionally, specify a particular version of WebGL to check for.
  60. *
  61. * @param {number=} [majorVersion=1] The major WebGL version to check for.
  62. * @returns {boolean} If the given major version of WebGL is available.
  63. * @function Engine.isWebGLAvailable
  64. */
  65. Engine.isWebGLAvailable = function (majorVersion = 1) {
  66. try {
  67. return !!document.createElement('canvas').getContext(['webgl', 'webgl2'][majorVersion - 1]);
  68. } catch (e) { /* Not available */ }
  69. return false;
  70. };
  71. /**
  72. * Safe Engine constructor, creates a new prototype for every new instance to avoid prototype pollution.
  73. * @ignore
  74. * @constructor
  75. */
  76. function SafeEngine(initConfig) {
  77. const proto = /** @lends Engine.prototype */ {
  78. /**
  79. * Initialize the engine instance. Optionally, pass the base path to the engine to load it,
  80. * if it hasn't been loaded yet. See :js:meth:`Engine.load`.
  81. *
  82. * @param {string=} basePath Base path of the engine to load.
  83. * @return {Promise} A ``Promise`` that resolves once the engine is loaded and initialized.
  84. */
  85. init: function (basePath) {
  86. if (initPromise) {
  87. return initPromise;
  88. }
  89. if (loadPromise == null) {
  90. if (!basePath) {
  91. initPromise = Promise.reject(new Error('A base path must be provided when calling `init` and the engine is not loaded.'));
  92. return initPromise;
  93. }
  94. Engine.load(basePath, this.config.fileSizes[`${basePath}.wasm`]);
  95. }
  96. const me = this;
  97. function doInit(promise) {
  98. return promise.then(function (response) {
  99. return Godot(me.config.getModuleConfig(loadPath, response.clone()));
  100. }).then(function (module) {
  101. const paths = me.config.persistentPaths;
  102. return module['initFS'](paths).then(function (err) {
  103. return Promise.resolve(module);
  104. });
  105. }).then(function (module) {
  106. me.rtenv = module;
  107. if (me.config.unloadAfterInit) {
  108. Engine.unload();
  109. }
  110. return Promise.resolve();
  111. });
  112. }
  113. preloader.setProgressFunc(this.config.onProgress);
  114. initPromise = doInit(loadPromise);
  115. return initPromise;
  116. },
  117. /**
  118. * Load a file so it is available in the instance's file system once it runs. Must be called **before** starting the
  119. * instance.
  120. *
  121. * If not provided, the ``path`` is derived from the URL of the loaded file.
  122. *
  123. * @param {string|ArrayBuffer} file The file to preload.
  124. *
  125. * If a ``string`` the file will be loaded from that path.
  126. *
  127. * If an ``ArrayBuffer`` or a view on one, the buffer will used as the content of the file.
  128. *
  129. * @param {string=} path Path by which the file will be accessible. Required, if ``file`` is not a string.
  130. *
  131. * @returns {Promise} A Promise that resolves once the file is loaded.
  132. */
  133. preloadFile: function (file, path) {
  134. return preloader.preload(file, path, this.config.fileSizes[file]);
  135. },
  136. /**
  137. * Start the engine instance using the given override configuration (if any).
  138. * :js:meth:`startGame <Engine.prototype.startGame>` can be used in typical cases instead.
  139. *
  140. * This will initialize the instance if it is not initialized. For manual initialization, see :js:meth:`init <Engine.prototype.init>`.
  141. * The engine must be loaded beforehand.
  142. *
  143. * Fails if a canvas cannot be found on the page, or not specified in the configuration.
  144. *
  145. * @param {EngineConfig} override An optional configuration override.
  146. * @return {Promise} Promise that resolves once the engine started.
  147. */
  148. start: function (override) {
  149. this.config.update(override);
  150. const me = this;
  151. return me.init().then(function () {
  152. if (!me.rtenv) {
  153. return Promise.reject(new Error('The engine must be initialized before it can be started'));
  154. }
  155. let config = {};
  156. try {
  157. config = me.config.getGodotConfig(function () {
  158. me.rtenv = null;
  159. });
  160. } catch (e) {
  161. return Promise.reject(e);
  162. }
  163. // Godot configuration.
  164. me.rtenv['initConfig'](config);
  165. // Preload GDNative libraries.
  166. const libs = [];
  167. me.config.gdnativeLibs.forEach(function (lib) {
  168. libs.push(me.rtenv['loadDynamicLibrary'](lib, { 'loadAsync': true }));
  169. });
  170. return Promise.all(libs).then(function () {
  171. return new Promise(function (resolve, reject) {
  172. preloader.preloadedFiles.forEach(function (file) {
  173. me.rtenv['copyToFS'](file.path, file.buffer);
  174. });
  175. preloader.preloadedFiles.length = 0; // Clear memory
  176. me.rtenv['callMain'](me.config.args);
  177. initPromise = null;
  178. resolve();
  179. });
  180. });
  181. });
  182. },
  183. /**
  184. * Start the game instance using the given configuration override (if any).
  185. *
  186. * This will initialize the instance if it is not initialized. For manual initialization, see :js:meth:`init <Engine.prototype.init>`.
  187. *
  188. * This will load the engine if it is not loaded, and preload the main pck.
  189. *
  190. * This method expects the initial config (or the override) to have both the :js:attr:`executable` and :js:attr:`mainPack`
  191. * properties set (normally done by the editor during export).
  192. *
  193. * @param {EngineConfig} override An optional configuration override.
  194. * @return {Promise} Promise that resolves once the game started.
  195. */
  196. startGame: function (override) {
  197. this.config.update(override);
  198. // Add main-pack argument.
  199. const exe = this.config.executable;
  200. const pack = this.config.mainPack || `${exe}.pck`;
  201. this.config.args = ['--main-pack', pack].concat(this.config.args);
  202. // Start and init with execName as loadPath if not inited.
  203. const me = this;
  204. return Promise.all([
  205. this.init(exe),
  206. this.preloadFile(pack, pack),
  207. ]).then(function () {
  208. return me.start.apply(me);
  209. });
  210. },
  211. /**
  212. * Create a file at the specified ``path`` with the passed as ``buffer`` in the instance's file system.
  213. *
  214. * @param {string} path The location where the file will be created.
  215. * @param {ArrayBuffer} buffer The content of the file.
  216. */
  217. copyToFS: function (path, buffer) {
  218. if (this.rtenv == null) {
  219. throw new Error('Engine must be inited before copying files');
  220. }
  221. this.rtenv['copyToFS'](path, buffer);
  222. },
  223. /**
  224. * Request that the current instance quit.
  225. *
  226. * This is akin the user pressing the close button in the window manager, and will
  227. * have no effect if the engine has crashed, or is stuck in a loop.
  228. *
  229. */
  230. requestQuit: function () {
  231. if (this.rtenv) {
  232. this.rtenv['request_quit']();
  233. }
  234. },
  235. };
  236. Engine.prototype = proto;
  237. // Closure compiler exported instance methods.
  238. Engine.prototype['init'] = Engine.prototype.init;
  239. Engine.prototype['preloadFile'] = Engine.prototype.preloadFile;
  240. Engine.prototype['start'] = Engine.prototype.start;
  241. Engine.prototype['startGame'] = Engine.prototype.startGame;
  242. Engine.prototype['copyToFS'] = Engine.prototype.copyToFS;
  243. Engine.prototype['requestQuit'] = Engine.prototype.requestQuit;
  244. // Also expose static methods as instance methods
  245. Engine.prototype['load'] = Engine.load;
  246. Engine.prototype['unload'] = Engine.unload;
  247. Engine.prototype['isWebGLAvailable'] = Engine.isWebGLAvailable;
  248. return new Engine(initConfig);
  249. }
  250. // Closure compiler exported static methods.
  251. SafeEngine['load'] = Engine.load;
  252. SafeEngine['unload'] = Engine.unload;
  253. SafeEngine['isWebGLAvailable'] = Engine.isWebGLAvailable;
  254. return SafeEngine;
  255. }());
  256. if (typeof window !== 'undefined') {
  257. window['Engine'] = Engine;
  258. }