engine.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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. // Care! Promise chaining is bogus with old emscripten versions.
  99. // This caused a regression with the Mono build (which uses an older emscripten version).
  100. // Make sure to test that when refactoring.
  101. return new Promise(function (resolve, reject) {
  102. promise.then(function (response) {
  103. const cloned = new Response(response.clone().body, { 'headers': [['content-type', 'application/wasm']] });
  104. Godot(me.config.getModuleConfig(loadPath, cloned)).then(function (module) {
  105. const paths = me.config.persistentPaths;
  106. module['initFS'](paths).then(function (err) {
  107. me.rtenv = module;
  108. if (me.config.unloadAfterInit) {
  109. Engine.unload();
  110. }
  111. resolve();
  112. });
  113. });
  114. });
  115. });
  116. }
  117. preloader.setProgressFunc(this.config.onProgress);
  118. initPromise = doInit(loadPromise);
  119. return initPromise;
  120. },
  121. /**
  122. * Load a file so it is available in the instance's file system once it runs. Must be called **before** starting the
  123. * instance.
  124. *
  125. * If not provided, the ``path`` is derived from the URL of the loaded file.
  126. *
  127. * @param {string|ArrayBuffer} file The file to preload.
  128. *
  129. * If a ``string`` the file will be loaded from that path.
  130. *
  131. * If an ``ArrayBuffer`` or a view on one, the buffer will used as the content of the file.
  132. *
  133. * @param {string=} path Path by which the file will be accessible. Required, if ``file`` is not a string.
  134. *
  135. * @returns {Promise} A Promise that resolves once the file is loaded.
  136. */
  137. preloadFile: function (file, path) {
  138. return preloader.preload(file, path, this.config.fileSizes[file]);
  139. },
  140. /**
  141. * Start the engine instance using the given override configuration (if any).
  142. * :js:meth:`startGame <Engine.prototype.startGame>` can be used in typical cases instead.
  143. *
  144. * This will initialize the instance if it is not initialized. For manual initialization, see :js:meth:`init <Engine.prototype.init>`.
  145. * The engine must be loaded beforehand.
  146. *
  147. * Fails if a canvas cannot be found on the page, or not specified in the configuration.
  148. *
  149. * @param {EngineConfig} override An optional configuration override.
  150. * @return {Promise} Promise that resolves once the engine started.
  151. */
  152. start: function (override) {
  153. this.config.update(override);
  154. const me = this;
  155. return me.init().then(function () {
  156. if (!me.rtenv) {
  157. return Promise.reject(new Error('The engine must be initialized before it can be started'));
  158. }
  159. let config = {};
  160. try {
  161. config = me.config.getGodotConfig(function () {
  162. me.rtenv = null;
  163. });
  164. } catch (e) {
  165. return Promise.reject(e);
  166. }
  167. // Godot configuration.
  168. me.rtenv['initConfig'](config);
  169. // Preload GDNative libraries.
  170. const libs = [];
  171. me.config.gdnativeLibs.forEach(function (lib) {
  172. libs.push(me.rtenv['loadDynamicLibrary'](lib, { 'loadAsync': true }));
  173. });
  174. return Promise.all(libs).then(function () {
  175. return new Promise(function (resolve, reject) {
  176. preloader.preloadedFiles.forEach(function (file) {
  177. me.rtenv['copyToFS'](file.path, file.buffer);
  178. });
  179. preloader.preloadedFiles.length = 0; // Clear memory
  180. me.rtenv['callMain'](me.config.args);
  181. initPromise = null;
  182. if (me.config.serviceWorker && 'serviceWorker' in navigator) {
  183. navigator.serviceWorker.register(me.config.serviceWorker);
  184. }
  185. resolve();
  186. });
  187. });
  188. });
  189. },
  190. /**
  191. * Start the game instance using the given configuration override (if any).
  192. *
  193. * This will initialize the instance if it is not initialized. For manual initialization, see :js:meth:`init <Engine.prototype.init>`.
  194. *
  195. * This will load the engine if it is not loaded, and preload the main pck.
  196. *
  197. * This method expects the initial config (or the override) to have both the :js:attr:`executable` and :js:attr:`mainPack`
  198. * properties set (normally done by the editor during export).
  199. *
  200. * @param {EngineConfig} override An optional configuration override.
  201. * @return {Promise} Promise that resolves once the game started.
  202. */
  203. startGame: function (override) {
  204. this.config.update(override);
  205. // Add main-pack argument.
  206. const exe = this.config.executable;
  207. const pack = this.config.mainPack || `${exe}.pck`;
  208. this.config.args = ['--main-pack', pack].concat(this.config.args);
  209. // Start and init with execName as loadPath if not inited.
  210. const me = this;
  211. return Promise.all([
  212. this.init(exe),
  213. this.preloadFile(pack, pack),
  214. ]).then(function () {
  215. return me.start.apply(me);
  216. });
  217. },
  218. /**
  219. * Create a file at the specified ``path`` with the passed as ``buffer`` in the instance's file system.
  220. *
  221. * @param {string} path The location where the file will be created.
  222. * @param {ArrayBuffer} buffer The content of the file.
  223. */
  224. copyToFS: function (path, buffer) {
  225. if (this.rtenv == null) {
  226. throw new Error('Engine must be inited before copying files');
  227. }
  228. this.rtenv['copyToFS'](path, buffer);
  229. },
  230. /**
  231. * Request that the current instance quit.
  232. *
  233. * This is akin the user pressing the close button in the window manager, and will
  234. * have no effect if the engine has crashed, or is stuck in a loop.
  235. *
  236. */
  237. requestQuit: function () {
  238. if (this.rtenv) {
  239. this.rtenv['request_quit']();
  240. }
  241. },
  242. };
  243. Engine.prototype = proto;
  244. // Closure compiler exported instance methods.
  245. Engine.prototype['init'] = Engine.prototype.init;
  246. Engine.prototype['preloadFile'] = Engine.prototype.preloadFile;
  247. Engine.prototype['start'] = Engine.prototype.start;
  248. Engine.prototype['startGame'] = Engine.prototype.startGame;
  249. Engine.prototype['copyToFS'] = Engine.prototype.copyToFS;
  250. Engine.prototype['requestQuit'] = Engine.prototype.requestQuit;
  251. // Also expose static methods as instance methods
  252. Engine.prototype['load'] = Engine.load;
  253. Engine.prototype['unload'] = Engine.unload;
  254. Engine.prototype['isWebGLAvailable'] = Engine.isWebGLAvailable;
  255. return new Engine(initConfig);
  256. }
  257. // Closure compiler exported static methods.
  258. SafeEngine['load'] = Engine.load;
  259. SafeEngine['unload'] = Engine.unload;
  260. SafeEngine['isWebGLAvailable'] = Engine.isWebGLAvailable;
  261. return SafeEngine;
  262. }());
  263. if (typeof window !== 'undefined') {
  264. window['Engine'] = Engine;
  265. }