config.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. /**
  2. * An object used to configure the Engine instance based on godot export options, and to override those in custom HTML
  3. * templates if needed.
  4. *
  5. * @header Engine configuration
  6. * @summary The Engine configuration object. This is just a typedef, create it like a regular object, e.g.:
  7. *
  8. * ``const MyConfig = { executable: 'godot', unloadAfterInit: false }``
  9. *
  10. * @typedef {Object} EngineConfig
  11. */
  12. const EngineConfig = {}; // eslint-disable-line no-unused-vars
  13. /**
  14. * @struct
  15. * @constructor
  16. * @ignore
  17. */
  18. const InternalConfig = function (initConfig) { // eslint-disable-line no-unused-vars
  19. const cfg = /** @lends {InternalConfig.prototype} */ {
  20. /**
  21. * Whether the unload the engine automatically after the instance is initialized.
  22. *
  23. * @memberof EngineConfig
  24. * @default
  25. * @type {boolean}
  26. */
  27. unloadAfterInit: true,
  28. /**
  29. * The HTML DOM Canvas object to use.
  30. *
  31. * By default, the first canvas element in the document will be used is none is specified.
  32. *
  33. * @memberof EngineConfig
  34. * @default
  35. * @type {?HTMLCanvasElement}
  36. */
  37. canvas: null,
  38. /**
  39. * The name of the WASM file without the extension. (Set by Godot Editor export process).
  40. *
  41. * @memberof EngineConfig
  42. * @default
  43. * @type {string}
  44. */
  45. executable: '',
  46. /**
  47. * An alternative name for the game pck to load. The executable name is used otherwise.
  48. *
  49. * @memberof EngineConfig
  50. * @default
  51. * @type {?string}
  52. */
  53. mainPack: null,
  54. /**
  55. * Specify a language code to select the proper localization for the game.
  56. *
  57. * The browser locale will be used if none is specified. See complete list of
  58. * :ref:`supported locales <doc_locales>`.
  59. *
  60. * @memberof EngineConfig
  61. * @type {?string}
  62. * @default
  63. */
  64. locale: null,
  65. /**
  66. * The canvas resize policy determines how the canvas should be resized by Godot.
  67. *
  68. * ``0`` means Godot won't do any resizing. This is useful if you want to control the canvas size from
  69. * javascript code in your template.
  70. *
  71. * ``1`` means Godot will resize the canvas on start, and when changing window size via engine functions.
  72. *
  73. * ``2`` means Godot will adapt the canvas size to match the whole browser window.
  74. *
  75. * @memberof EngineConfig
  76. * @type {number}
  77. * @default
  78. */
  79. canvasResizePolicy: 2,
  80. /**
  81. * The arguments to be passed as command line arguments on startup.
  82. *
  83. * See :ref:`command line tutorial <doc_command_line_tutorial>`.
  84. *
  85. * **Note**: :js:meth:`startGame <Engine.prototype.startGame>` will always add the ``--main-pack`` argument.
  86. *
  87. * @memberof EngineConfig
  88. * @type {Array<string>}
  89. * @default
  90. */
  91. args: [],
  92. /**
  93. * @ignore
  94. * @type {Array.<string>}
  95. */
  96. persistentPaths: ['/userfs'],
  97. /**
  98. * @ignore
  99. * @type {Array.<string>}
  100. */
  101. gdnativeLibs: [],
  102. /**
  103. * A callback function for handling Godot's ``OS.execute`` calls.
  104. *
  105. * This is for example used in the Web Editor template to switch between project manager and editor, and for running the game.
  106. *
  107. * @callback EngineConfig.onExecute
  108. * @param {string} path The path that Godot's wants executed.
  109. * @param {Array.<string>} args The arguments of the "command" to execute.
  110. */
  111. /**
  112. * @ignore
  113. * @type {?function(string, Array.<string>)}
  114. */
  115. onExecute: null,
  116. /**
  117. * A callback function for being notified when the Godot instance quits.
  118. *
  119. * **Note**: This function will not be called if the engine crashes or become unresponsive.
  120. *
  121. * @callback EngineConfig.onExit
  122. * @param {number} status_code The status code returned by Godot on exit.
  123. */
  124. /**
  125. * @ignore
  126. * @type {?function(number)}
  127. */
  128. onExit: null,
  129. /**
  130. * A callback function for displaying download progress.
  131. *
  132. * The function is called once per frame while downloading files, so the usage of ``requestAnimationFrame()``
  133. * is not necessary.
  134. *
  135. * If the callback function receives a total amount of bytes as 0, this means that it is impossible to calculate.
  136. * Possible reasons include:
  137. *
  138. * - Files are delivered with server-side chunked compression
  139. * - Files are delivered with server-side compression on Chromium
  140. * - Not all file downloads have started yet (usually on servers without multi-threading)
  141. *
  142. * @callback EngineConfig.onProgress
  143. * @param {number} current The current amount of downloaded bytes so far.
  144. * @param {number} total The total amount of bytes to be downloaded.
  145. */
  146. /**
  147. * @ignore
  148. * @type {?function(number, number)}
  149. */
  150. onProgress: null,
  151. /**
  152. * A callback function for handling the standard output stream. This method should usually only be used in debug pages.
  153. *
  154. * By default, ``console.log()`` is used.
  155. *
  156. * @callback EngineConfig.onPrint
  157. * @param {...*} [var_args] A variadic number of arguments to be printed.
  158. */
  159. /**
  160. * @ignore
  161. * @type {?function(...*)}
  162. */
  163. onPrint: function () {
  164. console.log.apply(console, Array.from(arguments)); // eslint-disable-line no-console
  165. },
  166. /**
  167. * A callback function for handling the standard error stream. This method should usually only be used in debug pages.
  168. *
  169. * By default, ``console.error()`` is used.
  170. *
  171. * @callback EngineConfig.onPrintError
  172. * @param {...*} [var_args] A variadic number of arguments to be printed as errors.
  173. */
  174. /**
  175. * @ignore
  176. * @type {?function(...*)}
  177. */
  178. onPrintError: function (var_args) {
  179. console.error.apply(console, Array.from(arguments)); // eslint-disable-line no-console
  180. },
  181. };
  182. /**
  183. * @ignore
  184. * @struct
  185. * @constructor
  186. * @param {EngineConfig} opts
  187. */
  188. function Config(opts) {
  189. this.update(opts);
  190. }
  191. Config.prototype = cfg;
  192. /**
  193. * @ignore
  194. * @param {EngineConfig} opts
  195. */
  196. Config.prototype.update = function (opts) {
  197. const config = opts || {};
  198. function parse(key, def) {
  199. if (typeof (config[key]) === 'undefined') {
  200. return def;
  201. }
  202. return config[key];
  203. }
  204. // Module config
  205. this.unloadAfterInit = parse('unloadAfterInit', this.unloadAfterInit);
  206. this.onPrintError = parse('onPrintError', this.onPrintError);
  207. this.onPrint = parse('onPrint', this.onPrint);
  208. this.onProgress = parse('onProgress', this.onProgress);
  209. // Godot config
  210. this.canvas = parse('canvas', this.canvas);
  211. this.executable = parse('executable', this.executable);
  212. this.mainPack = parse('mainPack', this.mainPack);
  213. this.locale = parse('locale', this.locale);
  214. this.canvasResizePolicy = parse('canvasResizePolicy', this.canvasResizePolicy);
  215. this.persistentPaths = parse('persistentPaths', this.persistentPaths);
  216. this.gdnativeLibs = parse('gdnativeLibs', this.gdnativeLibs);
  217. this.args = parse('args', this.args);
  218. this.onExecute = parse('onExecute', this.onExecute);
  219. this.onExit = parse('onExit', this.onExit);
  220. };
  221. /**
  222. * @ignore
  223. * @param {string} loadPath
  224. * @param {Response} response
  225. */
  226. Config.prototype.getModuleConfig = function (loadPath, response) {
  227. let r = response;
  228. return {
  229. 'print': this.onPrint,
  230. 'printErr': this.onPrintError,
  231. 'thisProgram': this.executable,
  232. 'noExitRuntime': true,
  233. 'dynamicLibraries': [`${loadPath}.side.wasm`],
  234. 'instantiateWasm': function (imports, onSuccess) {
  235. function done(result) {
  236. onSuccess(result['instance'], result['module']);
  237. }
  238. if (typeof (WebAssembly.instantiateStreaming) !== 'undefined') {
  239. WebAssembly.instantiateStreaming(Promise.resolve(r), imports).then(done);
  240. } else {
  241. r.arrayBuffer().then(function (buffer) {
  242. WebAssembly.instantiate(buffer, imports).then(done);
  243. });
  244. }
  245. r = null;
  246. return {};
  247. },
  248. 'locateFile': function (path) {
  249. if (path.endsWith('.worker.js')) {
  250. return `${loadPath}.worker.js`;
  251. } else if (path.endsWith('.audio.worklet.js')) {
  252. return `${loadPath}.audio.worklet.js`;
  253. } else if (path.endsWith('.js')) {
  254. return `${loadPath}.js`;
  255. } else if (path.endsWith('.side.wasm')) {
  256. return `${loadPath}.side.wasm`;
  257. } else if (path.endsWith('.wasm')) {
  258. return `${loadPath}.wasm`;
  259. }
  260. return path;
  261. },
  262. };
  263. };
  264. /**
  265. * @ignore
  266. * @param {function()} cleanup
  267. */
  268. Config.prototype.getGodotConfig = function (cleanup) {
  269. // Try to find a canvas
  270. if (!(this.canvas instanceof HTMLCanvasElement)) {
  271. const nodes = document.getElementsByTagName('canvas');
  272. if (nodes.length && nodes[0] instanceof HTMLCanvasElement) {
  273. this.canvas = nodes[0];
  274. }
  275. if (!this.canvas) {
  276. throw new Error('No canvas found in page');
  277. }
  278. }
  279. // Canvas can grab focus on click, or key events won't work.
  280. if (this.canvas.tabIndex < 0) {
  281. this.canvas.tabIndex = 0;
  282. }
  283. // Browser locale, or custom one if defined.
  284. let locale = this.locale;
  285. if (!locale) {
  286. locale = navigator.languages ? navigator.languages[0] : navigator.language;
  287. locale = locale.split('.')[0];
  288. }
  289. const onExit = this.onExit;
  290. // Godot configuration.
  291. return {
  292. 'canvas': this.canvas,
  293. 'canvasResizePolicy': this.canvasResizePolicy,
  294. 'locale': locale,
  295. 'onExecute': this.onExecute,
  296. 'onExit': function (p_code) {
  297. cleanup(); // We always need to call the cleanup callback to free memory.
  298. if (typeof (onExit) === 'function') {
  299. onExit(p_code);
  300. }
  301. },
  302. };
  303. };
  304. return new Config(initConfig);
  305. };