engine.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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 Web export JavaScript 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. * Safe Engine constructor, creates a new prototype for every new instance to avoid prototype pollution.
  60. * @ignore
  61. * @constructor
  62. */
  63. function SafeEngine(initConfig) {
  64. const proto = /** @lends Engine.prototype */ {
  65. /**
  66. * Initialize the engine instance. Optionally, pass the base path to the engine to load it,
  67. * if it hasn't been loaded yet. See :js:meth:`Engine.load`.
  68. *
  69. * @param {string=} basePath Base path of the engine to load.
  70. * @return {Promise} A ``Promise`` that resolves once the engine is loaded and initialized.
  71. */
  72. init: function (basePath) {
  73. if (initPromise) {
  74. return initPromise;
  75. }
  76. if (loadPromise == null) {
  77. if (!basePath) {
  78. initPromise = Promise.reject(new Error('A base path must be provided when calling `init` and the engine is not loaded.'));
  79. return initPromise;
  80. }
  81. Engine.load(basePath, this.config.fileSizes[`${basePath}.wasm`]);
  82. }
  83. const me = this;
  84. function doInit(promise) {
  85. // Care! Promise chaining is bogus with old emscripten versions.
  86. // This caused a regression with the Mono build (which uses an older emscripten version).
  87. // Make sure to test that when refactoring.
  88. return new Promise(function (resolve, reject) {
  89. promise.then(function (response) {
  90. const cloned = new Response(response.clone().body, { 'headers': [['content-type', 'application/wasm']] });
  91. Godot(me.config.getModuleConfig(loadPath, cloned)).then(function (module) {
  92. const paths = me.config.persistentPaths;
  93. module['initFS'](paths).then(function (err) {
  94. me.rtenv = module;
  95. if (me.config.unloadAfterInit) {
  96. Engine.unload();
  97. }
  98. resolve();
  99. });
  100. });
  101. });
  102. });
  103. }
  104. preloader.setProgressFunc(this.config.onProgress);
  105. initPromise = doInit(loadPromise);
  106. return initPromise;
  107. },
  108. /**
  109. * Load a file so it is available in the instance's file system once it runs. Must be called **before** starting the
  110. * instance.
  111. *
  112. * If not provided, the ``path`` is derived from the URL of the loaded file.
  113. *
  114. * @param {string|ArrayBuffer} file The file to preload.
  115. *
  116. * If a ``string`` the file will be loaded from that path.
  117. *
  118. * If an ``ArrayBuffer`` or a view on one, the buffer will used as the content of the file.
  119. *
  120. * @param {string=} path Path by which the file will be accessible. Required, if ``file`` is not a string.
  121. *
  122. * @returns {Promise} A Promise that resolves once the file is loaded.
  123. */
  124. preloadFile: function (file, path) {
  125. return preloader.preload(file, path, this.config.fileSizes[file]);
  126. },
  127. /**
  128. * Start the engine instance using the given override configuration (if any).
  129. * :js:meth:`startGame <Engine.prototype.startGame>` can be used in typical cases instead.
  130. *
  131. * This will initialize the instance if it is not initialized. For manual initialization, see :js:meth:`init <Engine.prototype.init>`.
  132. * The engine must be loaded beforehand.
  133. *
  134. * Fails if a canvas cannot be found on the page, or not specified in the configuration.
  135. *
  136. * @param {EngineConfig} override An optional configuration override.
  137. * @return {Promise} Promise that resolves once the engine started.
  138. */
  139. start: function (override) {
  140. this.config.update(override);
  141. const me = this;
  142. return me.init().then(function () {
  143. if (!me.rtenv) {
  144. return Promise.reject(new Error('The engine must be initialized before it can be started'));
  145. }
  146. let config = {};
  147. try {
  148. config = me.config.getGodotConfig(function () {
  149. me.rtenv = null;
  150. });
  151. } catch (e) {
  152. return Promise.reject(e);
  153. }
  154. // Godot configuration.
  155. me.rtenv['initConfig'](config);
  156. // Preload GDExtension libraries.
  157. if (me.config.gdextensionLibs.length > 0 && !me.rtenv['loadDynamicLibrary']) {
  158. return Promise.reject(new Error('GDExtension libraries are not supported by this engine version. '
  159. + 'Enable "Extensions Support" for your export preset and/or build your custom template with "dlink_enabled=yes".'));
  160. }
  161. return new Promise(function (resolve, reject) {
  162. for (const file of preloader.preloadedFiles) {
  163. me.rtenv['copyToFS'](file.path, file.buffer);
  164. }
  165. preloader.preloadedFiles.length = 0; // Clear memory
  166. me.rtenv['callMain'](me.config.args);
  167. initPromise = null;
  168. me.installServiceWorker();
  169. resolve();
  170. });
  171. });
  172. },
  173. /**
  174. * Start the game instance using the given configuration override (if any).
  175. *
  176. * This will initialize the instance if it is not initialized. For manual initialization, see :js:meth:`init <Engine.prototype.init>`.
  177. *
  178. * This will load the engine if it is not loaded, and preload the main pck.
  179. *
  180. * This method expects the initial config (or the override) to have both the :js:attr:`executable` and :js:attr:`mainPack`
  181. * properties set (normally done by the editor during export).
  182. *
  183. * @param {EngineConfig} override An optional configuration override.
  184. * @return {Promise} Promise that resolves once the game started.
  185. */
  186. startGame: function (override) {
  187. this.config.update(override);
  188. // Add main-pack argument.
  189. const exe = this.config.executable;
  190. const pack = this.config.mainPack || `${exe}.pck`;
  191. this.config.args = ['--main-pack', pack].concat(this.config.args);
  192. // Start and init with execName as loadPath if not inited.
  193. const me = this;
  194. return Promise.all([
  195. this.init(exe),
  196. this.preloadFile(pack, pack),
  197. ]).then(function () {
  198. return me.start.apply(me);
  199. });
  200. },
  201. /**
  202. * Create a file at the specified ``path`` with the passed as ``buffer`` in the instance's file system.
  203. *
  204. * @param {string} path The location where the file will be created.
  205. * @param {ArrayBuffer} buffer The content of the file.
  206. */
  207. copyToFS: function (path, buffer) {
  208. if (this.rtenv == null) {
  209. throw new Error('Engine must be inited before copying files');
  210. }
  211. this.rtenv['copyToFS'](path, buffer);
  212. },
  213. /**
  214. * Request that the current instance quit.
  215. *
  216. * This is akin the user pressing the close button in the window manager, and will
  217. * have no effect if the engine has crashed, or is stuck in a loop.
  218. *
  219. */
  220. requestQuit: function () {
  221. if (this.rtenv) {
  222. this.rtenv['request_quit']();
  223. }
  224. },
  225. /**
  226. * Install the progressive-web app service worker.
  227. * @returns {Promise} The service worker registration promise.
  228. */
  229. installServiceWorker: function () {
  230. if (this.config.serviceWorker && 'serviceWorker' in navigator) {
  231. try {
  232. return navigator.serviceWorker.register(this.config.serviceWorker);
  233. } catch (e) {
  234. return Promise.reject(e);
  235. }
  236. }
  237. return Promise.resolve();
  238. },
  239. };
  240. Engine.prototype = proto;
  241. // Closure compiler exported instance methods.
  242. Engine.prototype['init'] = Engine.prototype.init;
  243. Engine.prototype['preloadFile'] = Engine.prototype.preloadFile;
  244. Engine.prototype['start'] = Engine.prototype.start;
  245. Engine.prototype['startGame'] = Engine.prototype.startGame;
  246. Engine.prototype['copyToFS'] = Engine.prototype.copyToFS;
  247. Engine.prototype['requestQuit'] = Engine.prototype.requestQuit;
  248. Engine.prototype['installServiceWorker'] = Engine.prototype.installServiceWorker;
  249. // Also expose static methods as instance methods
  250. Engine.prototype['load'] = Engine.load;
  251. Engine.prototype['unload'] = Engine.unload;
  252. return new Engine(initConfig);
  253. }
  254. // Closure compiler exported static methods.
  255. SafeEngine['load'] = Engine.load;
  256. SafeEngine['unload'] = Engine.unload;
  257. // Feature-detection utilities.
  258. SafeEngine['isWebGLAvailable'] = Features.isWebGLAvailable;
  259. SafeEngine['isFetchAvailable'] = Features.isFetchAvailable;
  260. SafeEngine['isSecureContext'] = Features.isSecureContext;
  261. SafeEngine['isCrossOriginIsolated'] = Features.isCrossOriginIsolated;
  262. SafeEngine['isSharedArrayBufferAvailable'] = Features.isSharedArrayBufferAvailable;
  263. SafeEngine['isAudioWorkletAvailable'] = Features.isAudioWorkletAvailable;
  264. SafeEngine['getMissingFeatures'] = Features.getMissingFeatures;
  265. return SafeEngine;
  266. }());
  267. if (typeof window !== 'undefined') {
  268. window['Engine'] = Engine;
  269. }