engine.js 9.2 KB

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