engine.js 9.1 KB

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