customizing_html5_shell.rst 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. .. _doc_customizing_html5_shell:
  2. Custom HTML page for Web export
  3. ====================================
  4. While Web export templates provide a default HTML page fully capable of launching
  5. the project without any further customization, it may be beneficial to create a custom
  6. HTML page. While the game itself cannot easily be directly controlled from the outside yet,
  7. such page allows to customize the initialization process for the engine.
  8. Some use-cases where customizing the default page is useful include:
  9. - Loading files from a different directory than the page;
  10. - Loading a ``.zip`` file instead of a ``.pck`` file as the main pack;
  11. - Loading the engine from a different directory than the main pack file;
  12. - Adding a click-to-play button so that games can be started in the fullscreen mode;
  13. - Loading some extra files before the engine starts, making them available in
  14. the project file system as soon as possible;
  15. - Passing custom command line arguments, e.g. ``-s`` to start a ``MainLoop`` script.
  16. The default HTML page is available in the Godot Engine repository at
  17. `/misc/dist/html/full-size.html <https://github.com/godotengine/godot/blob/master/misc/dist/html/full-size.html>`__
  18. but the following template can be used as a much simpler example:
  19. .. code-block:: html
  20. <!DOCTYPE html>
  21. <html>
  22. <head>
  23. <title>My Template</title>
  24. <meta charset="UTF-8">
  25. </head>
  26. <body>
  27. <canvas id="canvas"></canvas>
  28. <script src="$GODOT_URL"></script>
  29. <script>
  30. var engine = new Engine($GODOT_CONFIG);
  31. engine.startGame();
  32. </script>
  33. </body>
  34. </html>
  35. Setup
  36. -----
  37. As shown by the example above, it is mostly a regular HTML document, with few placeholders
  38. which needs to be replaced during export, an html ``<canvas>`` element, and some simple
  39. JavaScript code that calls the :js:class:`Engine` class.
  40. The only required placeholders are:
  41. - ``$GODOT_URL``:
  42. The name of the main JavaScript file, which provides the :js:class:`Engine` class required
  43. to start the engine and that must be included in the HTML as a ``<script>``.
  44. The name is generated from the *Export Path* during the export process.
  45. - ``$GODOT_CONFIG``:
  46. A JavaScript object, containing the export options and can be later overridden.
  47. See :js:attr:`EngineConfig` for the full list of overrides.
  48. The following optional placeholders will enable some extra features in your custom HTML template.
  49. - ``$GODOT_PROJECT_NAME``:
  50. The project name as defined in the Project Settings. It is a good idea to use it as a ``<title>``
  51. in your template.
  52. - ``$GODOT_HEAD_INCLUDE``:
  53. A custom string to include in the HTML document just before the end of the ``<head>`` tag. It
  54. is customized in the export options under the *Html / Head Include* section. While you fully
  55. control the HTML page you create, this variable can be useful for configuring parts of the
  56. HTML ``head`` element from the Godot Editor, e.g. for different Web export presets.
  57. When the custom page is ready, it can be selected in the export options under the *Html / Custom Html Shell*
  58. section.
  59. .. image:: img/html5_export_options.png
  60. Starting the project
  61. --------------------
  62. To be able to start the game, you need to write a script that initializes the engine — the control
  63. code. This process consists of three steps, though as shown most of them can be skipped depending on
  64. how much customization is needed (or be left to a default behavior).
  65. See the :ref:`HTML5 shell class reference <doc_html5_shell_classref>`, for the full list of methods and options available.
  66. First, the engine must be loaded, then it needs to be initialized, and after this the project
  67. can finally be started. You can perform every of these steps manually and with great control.
  68. However, in the simplest case all you need to do is to create an instance of the :js:class:`Engine`
  69. class with the exported configuration, and then call the :js:meth:`engine.startGame <Engine.prototype.startGame>` method
  70. optionally overriding any :js:attr:`EngineConfig` parameters.
  71. .. code-block:: js
  72. const engine = new Engine($GODOT_CONFIG);
  73. engine.startGame({
  74. /* optional override configuration, eg. */
  75. // unloadAfterInit: false,
  76. // canvasResizePolicy: 0,
  77. // ...
  78. });
  79. This snippet of code automatically loads and initializes the engine before starting the game.
  80. It uses the given configuration to to load the engine. The :js:meth:`engine.startGame <Engine.prototype.startGame>`
  81. method is asynchronous and returns a ``Promise``. This allows your control code to track if
  82. the game was loaded correctly without blocking execution or relying on polling.
  83. In case your project needs to have special control over the start arguments and dependency files,
  84. the :js:meth:`engine.start <Engine.prototype.start>` method can be used instead. Note, that this method do not
  85. automatically preload the ``pck`` file, so you will probably want to manually preload it
  86. (and any other extra file) via the :js:meth:`engine.preloadFile <Engine.prototype.preloadFile>` method.
  87. Optionally, you can also manually :js:meth:`engine.init <Engine.prototype.init>` to perform specific actions after
  88. the module initialization, but before the engine starts.
  89. This process is a bit more complex, but gives you full control over the engine startup process.
  90. .. code-block:: js
  91. const myWasm = 'mygame.wasm';
  92. const myPck = 'mygame.pck';
  93. const engine = new Engine();
  94. Promise.all([
  95. // Load and init the engine
  96. engine.init(myWasm),
  97. // And the pck concurrently
  98. engine.preloadFile(myPck),
  99. ]).then(() => {
  100. // Now start the engine.
  101. return engine.start({ args: ['--main-pack', myPck] });
  102. }).then(() => {
  103. console.log('Engine has started!');
  104. });
  105. To load the engine manually the :js:meth:`Engine.load` static method must be called. As
  106. this method is static, multiple engine instances can be spawned if the share the same ``wasm``.
  107. .. note:: Multiple instances cannot be spawned by default, as the engine is immediately unloaded after it is initialized.
  108. To prevent this from happening see the :js:attr:`unloadAfterInit` override option. It is still possible
  109. to unload the engine manually afterwards by calling the :js:meth:`Engine.unload` static method. Unloading the engine
  110. frees browser memory by unloading files that are no longer needed once the instance is initialized.
  111. Customizing the behavior
  112. ------------------------
  113. In the Web environment several methods can be used to guarantee that the game will work as intended.
  114. If you target a specific version of WebGL, or just want to check if WebGL is available at all,
  115. you can call the :js:meth:`Engine.isWebGLAvailable` method. It optionally takes an argument that
  116. allows to test for a specific major version of WebGL.
  117. As the real executable file does not exist in the Web environment, the engine only stores a virtual
  118. filename formed from the base name of loaded engine files. This value affects the output of the
  119. :ref:`OS.get_executable_path() <class_OS_method_get_executable_path>` method and defines the name of
  120. the automatically started main pack. The :js:attr:`executable` override option can be
  121. used to override this value.
  122. Customizing the presentation
  123. ----------------------------
  124. Several configuration options can be used to further customize the look and behavior of the game on your page.
  125. By default, the first canvas element on the page is used for rendering. To use a different canvas
  126. element the :js:attr:`canvas` override option can be used. It requires a reference to the DOM
  127. element itself.
  128. .. code-block:: js
  129. const canvasElement = document.querySelector("#my-canvas-element");
  130. engine.startGame({ canvas: canvasElement });
  131. The way the engine resize the canvas can be configured via the :js:attr:`canvasResizePolicy`
  132. override option.
  133. If your game takes some time to load, it may be useful to display a custom loading UI which tracks
  134. the progress. This can be achieved with the :js:attr:`onProgress` callback option, which
  135. allows to set up a callback function that will be called regularly as the engine loads new bytes.
  136. .. code-block:: js
  137. function printProgress(current, total) {
  138. console.log("Loaded " + current + " of " + total + " bytes");
  139. }
  140. engine.startGame({ onProgress: printProgress });
  141. Be aware that in some cases ``total`` can be ``0``. This means that it cannot be calculated.
  142. If your game supports multiple languages, the :js:attr:`locale` override option can be used to
  143. force a specific locale, provided you have a valid language code string. It may be good to use server-side
  144. logic to determine which languages a user may prefer. This way the language code can be taken from the
  145. ``Accept-Language`` HTTP header, or determined by a GeoIP service.
  146. Debugging
  147. ---------
  148. To debug exported projects, it may be useful to read the standard output and error streams generated
  149. by the engine. This is similar to the output shown in the editor console window. By default, standard
  150. ``console.log`` and ``console.warn`` are used for the output and error streams respectively. This
  151. behavior can be customized by setting your own functions to handle messages.
  152. Use the :js:attr:`onPrint` override option to set a callback function for the output stream,
  153. and the :js:attr:`onPrintError` override option to set a callback function for the error stream.
  154. .. code-block:: js
  155. function print(text) {
  156. console.log(text);
  157. }
  158. function printError(text) {
  159. console.warn(text);
  160. }
  161. engine.startGame({ onPrint: print, onPrintError: printError });
  162. When handling the engine output keep in mind, that it may not be desirable to print it out in the
  163. finished product.