export_plugin.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945
  1. /**************************************************************************/
  2. /* export_plugin.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "export_plugin.h"
  31. #include "logo_svg.gen.h"
  32. #include "run_icon_svg.gen.h"
  33. #include "core/config/project_settings.h"
  34. #include "editor/editor_string_names.h"
  35. #include "editor/export/editor_export.h"
  36. #include "editor/import/resource_importer_texture_settings.h"
  37. #include "editor/settings/editor_settings.h"
  38. #include "editor/themes/editor_scale.h"
  39. #include "scene/resources/image_texture.h"
  40. #include "modules/modules_enabled.gen.h" // For mono.
  41. #include "modules/svg/image_loader_svg.h"
  42. Error EditorExportPlatformWeb::_extract_template(const String &p_template, const String &p_dir, const String &p_name, bool pwa) {
  43. Ref<FileAccess> io_fa;
  44. zlib_filefunc_def io = zipio_create_io(&io_fa);
  45. unzFile pkg = unzOpen2(p_template.utf8().get_data(), &io);
  46. if (!pkg) {
  47. add_message(EXPORT_MESSAGE_ERROR, TTR("Prepare Templates"), vformat(TTR("Could not open template for export: \"%s\"."), p_template));
  48. return ERR_FILE_NOT_FOUND;
  49. }
  50. if (unzGoToFirstFile(pkg) != UNZ_OK) {
  51. add_message(EXPORT_MESSAGE_ERROR, TTR("Prepare Templates"), vformat(TTR("Invalid export template: \"%s\"."), p_template));
  52. unzClose(pkg);
  53. return ERR_FILE_CORRUPT;
  54. }
  55. do {
  56. //get filename
  57. unz_file_info info;
  58. char fname[16384];
  59. unzGetCurrentFileInfo(pkg, &info, fname, 16384, nullptr, 0, nullptr, 0);
  60. String file = String::utf8(fname);
  61. // Skip folders.
  62. if (file.ends_with("/")) {
  63. continue;
  64. }
  65. // Skip service worker and offline page if not exporting pwa.
  66. if (!pwa && (file == "godot.service.worker.js" || file == "godot.offline.html")) {
  67. continue;
  68. }
  69. Vector<uint8_t> data;
  70. data.resize(info.uncompressed_size);
  71. //read
  72. unzOpenCurrentFile(pkg);
  73. unzReadCurrentFile(pkg, data.ptrw(), data.size());
  74. unzCloseCurrentFile(pkg);
  75. //write
  76. String dst = p_dir.path_join(file.replace("godot", p_name));
  77. Ref<FileAccess> f = FileAccess::open(dst, FileAccess::WRITE);
  78. if (f.is_null()) {
  79. add_message(EXPORT_MESSAGE_ERROR, TTR("Prepare Templates"), vformat(TTR("Could not write file: \"%s\"."), dst));
  80. unzClose(pkg);
  81. return ERR_FILE_CANT_WRITE;
  82. }
  83. f->store_buffer(data.ptr(), data.size());
  84. } while (unzGoToNextFile(pkg) == UNZ_OK);
  85. unzClose(pkg);
  86. return OK;
  87. }
  88. Error EditorExportPlatformWeb::_write_or_error(const uint8_t *p_content, int p_size, String p_path) {
  89. Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::WRITE);
  90. if (f.is_null()) {
  91. add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), vformat(TTR("Could not write file: \"%s\"."), p_path));
  92. return ERR_FILE_CANT_WRITE;
  93. }
  94. f->store_buffer(p_content, p_size);
  95. return OK;
  96. }
  97. void EditorExportPlatformWeb::_replace_strings(const HashMap<String, String> &p_replaces, Vector<uint8_t> &r_template) {
  98. String str_template = String::utf8(reinterpret_cast<const char *>(r_template.ptr()), r_template.size());
  99. String out;
  100. Vector<String> lines = str_template.split("\n");
  101. for (int i = 0; i < lines.size(); i++) {
  102. String current_line = lines[i];
  103. for (const KeyValue<String, String> &E : p_replaces) {
  104. current_line = current_line.replace(E.key, E.value);
  105. }
  106. out += current_line + "\n";
  107. }
  108. CharString cs = out.utf8();
  109. r_template.resize(cs.length());
  110. for (int i = 0; i < cs.length(); i++) {
  111. r_template.write[i] = cs[i];
  112. }
  113. }
  114. void EditorExportPlatformWeb::_fix_html(Vector<uint8_t> &p_html, const Ref<EditorExportPreset> &p_preset, const String &p_name, bool p_debug, BitField<EditorExportPlatform::DebugFlags> p_flags, const Vector<SharedObject> p_shared_objects, const Dictionary &p_file_sizes) {
  115. // Engine.js config
  116. Dictionary config;
  117. Array libs;
  118. for (int i = 0; i < p_shared_objects.size(); i++) {
  119. libs.push_back(p_shared_objects[i].path.get_file());
  120. }
  121. Vector<String> flags = gen_export_flags(p_flags & (~DEBUG_FLAG_DUMB_CLIENT));
  122. Array args;
  123. for (int i = 0; i < flags.size(); i++) {
  124. args.push_back(flags[i]);
  125. }
  126. config["canvasResizePolicy"] = p_preset->get("html/canvas_resize_policy");
  127. config["experimentalVK"] = p_preset->get("html/experimental_virtual_keyboard");
  128. config["focusCanvas"] = p_preset->get("html/focus_canvas_on_start");
  129. config["gdextensionLibs"] = libs;
  130. config["executable"] = p_name;
  131. config["args"] = args;
  132. config["fileSizes"] = p_file_sizes;
  133. config["ensureCrossOriginIsolationHeaders"] = (bool)p_preset->get("progressive_web_app/ensure_cross_origin_isolation_headers");
  134. config["godotPoolSize"] = p_preset->get("threads/godot_pool_size");
  135. config["emscriptenPoolSize"] = p_preset->get("threads/emscripten_pool_size");
  136. String head_include;
  137. if (p_preset->get("html/export_icon")) {
  138. head_include += "<link id=\"-gd-engine-icon\" rel=\"icon\" type=\"image/png\" href=\"" + p_name + ".icon.png\" />\n";
  139. head_include += "<link rel=\"apple-touch-icon\" href=\"" + p_name + ".apple-touch-icon.png\"/>\n";
  140. }
  141. if (p_preset->get("progressive_web_app/enabled")) {
  142. head_include += "<link rel=\"manifest\" href=\"" + p_name + ".manifest.json\">\n";
  143. config["serviceWorker"] = p_name + ".service.worker.js";
  144. }
  145. // Replaces HTML string
  146. const String str_config = Variant(config).to_json_string();
  147. const String custom_head_include = p_preset->get("html/head_include");
  148. HashMap<String, String> replaces;
  149. replaces["$GODOT_URL"] = p_name + ".js";
  150. replaces["$GODOT_PROJECT_NAME"] = get_project_setting(p_preset, "application/config/name");
  151. replaces["$GODOT_HEAD_INCLUDE"] = head_include + custom_head_include;
  152. replaces["$GODOT_CONFIG"] = str_config;
  153. replaces["$GODOT_SPLASH_COLOR"] = "#" + Color(get_project_setting(p_preset, "application/boot_splash/bg_color")).to_html(false);
  154. LocalVector<String> godot_splash_classes;
  155. godot_splash_classes.push_back("show-image--" + String(get_project_setting(p_preset, "application/boot_splash/show_image")));
  156. godot_splash_classes.push_back("fullsize--" + String(get_project_setting(p_preset, "application/boot_splash/fullsize")));
  157. godot_splash_classes.push_back("use-filter--" + String(get_project_setting(p_preset, "application/boot_splash/use_filter")));
  158. replaces["$GODOT_SPLASH_CLASSES"] = String(" ").join(godot_splash_classes);
  159. replaces["$GODOT_SPLASH"] = p_name + ".png";
  160. if (p_preset->get("variant/thread_support")) {
  161. replaces["$GODOT_THREADS_ENABLED"] = "true";
  162. } else {
  163. replaces["$GODOT_THREADS_ENABLED"] = "false";
  164. }
  165. _replace_strings(replaces, p_html);
  166. }
  167. Error EditorExportPlatformWeb::_add_manifest_icon(const Ref<EditorExportPreset> &p_preset, const String &p_path, const String &p_icon, int p_size, Array &r_arr) {
  168. const String name = p_path.get_file().get_basename();
  169. const String icon_name = vformat("%s.%dx%d.png", name, p_size, p_size);
  170. const String icon_dest = p_path.get_base_dir().path_join(icon_name);
  171. Ref<Image> icon;
  172. if (!p_icon.is_empty()) {
  173. Error err = OK;
  174. icon = _load_icon_or_splash_image(p_icon, &err);
  175. if (err != OK || icon.is_null() || icon->is_empty()) {
  176. add_message(EXPORT_MESSAGE_ERROR, TTR("Icon Creation"), vformat(TTR("Could not read file: \"%s\"."), p_icon));
  177. return err;
  178. }
  179. if (icon->get_width() != p_size || icon->get_height() != p_size) {
  180. icon->resize(p_size, p_size);
  181. }
  182. } else {
  183. icon = _get_project_icon(p_preset);
  184. icon->resize(p_size, p_size);
  185. }
  186. const Error err = icon->save_png(icon_dest);
  187. if (err != OK) {
  188. add_message(EXPORT_MESSAGE_ERROR, TTR("Icon Creation"), vformat(TTR("Could not write file: \"%s\"."), icon_dest));
  189. return err;
  190. }
  191. Dictionary icon_dict;
  192. icon_dict["sizes"] = vformat("%dx%d", p_size, p_size);
  193. icon_dict["type"] = "image/png";
  194. icon_dict["src"] = icon_name;
  195. r_arr.push_back(icon_dict);
  196. return err;
  197. }
  198. Error EditorExportPlatformWeb::_build_pwa(const Ref<EditorExportPreset> &p_preset, const String p_path, const Vector<SharedObject> &p_shared_objects) {
  199. String proj_name = get_project_setting(p_preset, "application/config/name");
  200. if (proj_name.is_empty()) {
  201. proj_name = "Godot Game";
  202. }
  203. // Service worker
  204. const String dir = p_path.get_base_dir();
  205. const String name = p_path.get_file().get_basename();
  206. bool extensions = (bool)p_preset->get("variant/extensions_support");
  207. bool ensure_crossorigin_isolation_headers = (bool)p_preset->get("progressive_web_app/ensure_cross_origin_isolation_headers");
  208. HashMap<String, String> replaces;
  209. replaces["___GODOT_VERSION___"] = String::num_int64(OS::get_singleton()->get_unix_time()) + "|" + String::num_int64(OS::get_singleton()->get_ticks_usec());
  210. replaces["___GODOT_NAME___"] = proj_name.substr(0, 16);
  211. replaces["___GODOT_OFFLINE_PAGE___"] = name + ".offline.html";
  212. replaces["___GODOT_ENSURE_CROSSORIGIN_ISOLATION_HEADERS___"] = ensure_crossorigin_isolation_headers ? "true" : "false";
  213. // Files cached during worker install.
  214. Array cache_files = {
  215. name + ".html",
  216. name + ".js",
  217. name + ".offline.html"
  218. };
  219. if (p_preset->get("html/export_icon")) {
  220. cache_files.push_back(name + ".icon.png");
  221. cache_files.push_back(name + ".apple-touch-icon.png");
  222. }
  223. cache_files.push_back(name + ".audio.worklet.js");
  224. cache_files.push_back(name + ".audio.position.worklet.js");
  225. replaces["___GODOT_CACHE___"] = Variant(cache_files).to_json_string();
  226. // Heavy files that are cached on demand.
  227. Array opt_cache_files = {
  228. name + ".wasm",
  229. name + ".pck"
  230. };
  231. if (extensions) {
  232. opt_cache_files.push_back(name + ".side.wasm");
  233. for (int i = 0; i < p_shared_objects.size(); i++) {
  234. opt_cache_files.push_back(p_shared_objects[i].path.get_file());
  235. }
  236. }
  237. replaces["___GODOT_OPT_CACHE___"] = Variant(opt_cache_files).to_json_string();
  238. const String sw_path = dir.path_join(name + ".service.worker.js");
  239. Vector<uint8_t> sw;
  240. {
  241. Ref<FileAccess> f = FileAccess::open(sw_path, FileAccess::READ);
  242. if (f.is_null()) {
  243. add_message(EXPORT_MESSAGE_ERROR, TTR("PWA"), vformat(TTR("Could not read file: \"%s\"."), sw_path));
  244. return ERR_FILE_CANT_READ;
  245. }
  246. sw.resize(f->get_length());
  247. f->get_buffer(sw.ptrw(), sw.size());
  248. }
  249. _replace_strings(replaces, sw);
  250. Error err = _write_or_error(sw.ptr(), sw.size(), dir.path_join(name + ".service.worker.js"));
  251. if (err != OK) {
  252. // Message is supplied by the subroutine method.
  253. return err;
  254. }
  255. // Custom offline page
  256. const String offline_page = p_preset->get("progressive_web_app/offline_page");
  257. if (!offline_page.is_empty()) {
  258. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  259. const String offline_dest = dir.path_join(name + ".offline.html");
  260. err = da->copy(ProjectSettings::get_singleton()->globalize_path(offline_page), offline_dest);
  261. if (err != OK) {
  262. add_message(EXPORT_MESSAGE_ERROR, TTR("PWA"), vformat(TTR("Could not read file: \"%s\"."), offline_dest));
  263. return err;
  264. }
  265. }
  266. // Manifest
  267. const char *modes[4] = { "fullscreen", "standalone", "minimal-ui", "browser" };
  268. const char *orientations[3] = { "any", "landscape", "portrait" };
  269. const int display = CLAMP(int(p_preset->get("progressive_web_app/display")), 0, 4);
  270. const int orientation = CLAMP(int(p_preset->get("progressive_web_app/orientation")), 0, 3);
  271. Dictionary manifest;
  272. manifest["name"] = proj_name;
  273. manifest["start_url"] = "./" + name + ".html";
  274. manifest["display"] = String::utf8(modes[display]);
  275. manifest["orientation"] = String::utf8(orientations[orientation]);
  276. manifest["background_color"] = "#" + p_preset->get("progressive_web_app/background_color").operator Color().to_html(false);
  277. Array icons_arr;
  278. const String icon144_path = p_preset->get("progressive_web_app/icon_144x144");
  279. err = _add_manifest_icon(p_preset, p_path, icon144_path, 144, icons_arr);
  280. if (err != OK) {
  281. // Message is supplied by the subroutine method.
  282. return err;
  283. }
  284. const String icon180_path = p_preset->get("progressive_web_app/icon_180x180");
  285. err = _add_manifest_icon(p_preset, p_path, icon180_path, 180, icons_arr);
  286. if (err != OK) {
  287. // Message is supplied by the subroutine method.
  288. return err;
  289. }
  290. const String icon512_path = p_preset->get("progressive_web_app/icon_512x512");
  291. err = _add_manifest_icon(p_preset, p_path, icon512_path, 512, icons_arr);
  292. if (err != OK) {
  293. // Message is supplied by the subroutine method.
  294. return err;
  295. }
  296. manifest["icons"] = icons_arr;
  297. CharString cs = Variant(manifest).to_json_string().utf8();
  298. err = _write_or_error((const uint8_t *)cs.get_data(), cs.length(), dir.path_join(name + ".manifest.json"));
  299. if (err != OK) {
  300. // Message is supplied by the subroutine method.
  301. return err;
  302. }
  303. return OK;
  304. }
  305. void EditorExportPlatformWeb::get_preset_features(const Ref<EditorExportPreset> &p_preset, List<String> *r_features) const {
  306. if (p_preset->get("vram_texture_compression/for_desktop")) {
  307. r_features->push_back("s3tc");
  308. r_features->push_back("bptc");
  309. }
  310. if (p_preset->get("vram_texture_compression/for_mobile")) {
  311. r_features->push_back("etc2");
  312. r_features->push_back("astc");
  313. }
  314. if (p_preset->get("variant/thread_support").operator bool()) {
  315. r_features->push_back("threads");
  316. } else {
  317. r_features->push_back("nothreads");
  318. }
  319. if (p_preset->get("variant/extensions_support").operator bool()) {
  320. r_features->push_back("web_extensions");
  321. } else {
  322. r_features->push_back("web_noextensions");
  323. }
  324. r_features->push_back("wasm32");
  325. }
  326. void EditorExportPlatformWeb::get_export_options(List<ExportOption> *r_options) const {
  327. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/debug", PROPERTY_HINT_GLOBAL_FILE, "*.zip"), ""));
  328. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/release", PROPERTY_HINT_GLOBAL_FILE, "*.zip"), ""));
  329. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "variant/extensions_support"), false)); // GDExtension support.
  330. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "variant/thread_support"), false, true)); // Thread support (i.e. run with or without COEP/COOP headers).
  331. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "vram_texture_compression/for_desktop"), true)); // S3TC
  332. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "vram_texture_compression/for_mobile"), false)); // ETC or ETC2, depending on renderer
  333. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "html/export_icon"), true));
  334. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "html/custom_html_shell", PROPERTY_HINT_FILE, "*.html"), ""));
  335. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "html/head_include", PROPERTY_HINT_MULTILINE_TEXT), ""));
  336. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "html/canvas_resize_policy", PROPERTY_HINT_ENUM, "None,Project,Adaptive"), 2));
  337. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "html/focus_canvas_on_start"), true));
  338. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "html/experimental_virtual_keyboard"), false));
  339. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "progressive_web_app/enabled"), false));
  340. r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "progressive_web_app/ensure_cross_origin_isolation_headers"), true));
  341. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "progressive_web_app/offline_page", PROPERTY_HINT_FILE, "*.html"), ""));
  342. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "progressive_web_app/display", PROPERTY_HINT_ENUM, "Fullscreen,Standalone,Minimal UI,Browser"), 1));
  343. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "progressive_web_app/orientation", PROPERTY_HINT_ENUM, "Any,Landscape,Portrait"), 0));
  344. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "progressive_web_app/icon_144x144", PROPERTY_HINT_FILE, "*.png,*.webp,*.svg"), ""));
  345. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "progressive_web_app/icon_180x180", PROPERTY_HINT_FILE, "*.png,*.webp,*.svg"), ""));
  346. r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "progressive_web_app/icon_512x512", PROPERTY_HINT_FILE, "*.png,*.webp,*.svg"), ""));
  347. r_options->push_back(ExportOption(PropertyInfo(Variant::COLOR, "progressive_web_app/background_color", PROPERTY_HINT_COLOR_NO_ALPHA), Color()));
  348. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "threads/emscripten_pool_size"), 8));
  349. r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "threads/godot_pool_size"), 4));
  350. }
  351. bool EditorExportPlatformWeb::get_export_option_visibility(const EditorExportPreset *p_preset, const String &p_option) const {
  352. bool advanced_options_enabled = p_preset->are_advanced_options_enabled();
  353. if (p_option == "custom_template/debug" || p_option == "custom_template/release") {
  354. return advanced_options_enabled;
  355. }
  356. if (p_option == "threads/godot_pool_size" || p_option == "threads/emscripten_pool_size") {
  357. return p_preset->get("variant/thread_support").operator bool();
  358. }
  359. return true;
  360. }
  361. String EditorExportPlatformWeb::get_name() const {
  362. return "Web";
  363. }
  364. String EditorExportPlatformWeb::get_os_name() const {
  365. return "Web";
  366. }
  367. Ref<Texture2D> EditorExportPlatformWeb::get_logo() const {
  368. return logo;
  369. }
  370. bool EditorExportPlatformWeb::has_valid_export_configuration(const Ref<EditorExportPreset> &p_preset, String &r_error, bool &r_missing_templates, bool p_debug) const {
  371. #ifdef MODULE_MONO_ENABLED
  372. // Don't check for additional errors, as this particular error cannot be resolved.
  373. r_error += TTR("Exporting to Web is currently not supported in Godot 4 when using C#/.NET. Use Godot 3 to target Web with C#/Mono instead.") + "\n";
  374. r_error += TTR("If this project does not use C#, use a non-C# editor build to export the project.") + "\n";
  375. return false;
  376. #else
  377. String err;
  378. bool valid = false;
  379. bool extensions = (bool)p_preset->get("variant/extensions_support");
  380. bool thread_support = (bool)p_preset->get("variant/thread_support");
  381. // Look for export templates (first official, and if defined custom templates).
  382. bool dvalid = exists_export_template(_get_template_name(extensions, thread_support, true), &err);
  383. bool rvalid = exists_export_template(_get_template_name(extensions, thread_support, false), &err);
  384. if (p_preset->get("custom_template/debug") != "") {
  385. dvalid = FileAccess::exists(p_preset->get("custom_template/debug"));
  386. if (!dvalid) {
  387. err += TTR("Custom debug template not found.") + "\n";
  388. }
  389. }
  390. if (p_preset->get("custom_template/release") != "") {
  391. rvalid = FileAccess::exists(p_preset->get("custom_template/release"));
  392. if (!rvalid) {
  393. err += TTR("Custom release template not found.") + "\n";
  394. }
  395. }
  396. valid = dvalid || rvalid;
  397. r_missing_templates = !valid;
  398. if (!err.is_empty()) {
  399. r_error = err;
  400. }
  401. return valid;
  402. #endif // !MODULE_MONO_ENABLED
  403. }
  404. bool EditorExportPlatformWeb::has_valid_project_configuration(const Ref<EditorExportPreset> &p_preset, String &r_error) const {
  405. String err;
  406. bool valid = true;
  407. // Validate the project configuration.
  408. if (p_preset->get("vram_texture_compression/for_mobile")) {
  409. if (!ResourceImporterTextureSettings::should_import_etc2_astc()) {
  410. valid = false;
  411. }
  412. }
  413. if (!err.is_empty()) {
  414. r_error = err;
  415. }
  416. return valid;
  417. }
  418. List<String> EditorExportPlatformWeb::get_binary_extensions(const Ref<EditorExportPreset> &p_preset) const {
  419. List<String> list;
  420. list.push_back("html");
  421. return list;
  422. }
  423. Error EditorExportPlatformWeb::export_project(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, BitField<EditorExportPlatform::DebugFlags> p_flags) {
  424. ExportNotifier notifier(*this, p_preset, p_debug, p_path, p_flags);
  425. const String custom_debug = p_preset->get("custom_template/debug");
  426. const String custom_release = p_preset->get("custom_template/release");
  427. const String custom_html = p_preset->get("html/custom_html_shell");
  428. const bool export_icon = p_preset->get("html/export_icon");
  429. const bool pwa = p_preset->get("progressive_web_app/enabled");
  430. const String base_dir = p_path.get_base_dir();
  431. const String base_path = p_path.get_basename();
  432. const String base_name = p_path.get_file().get_basename();
  433. if (!DirAccess::exists(base_dir)) {
  434. add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), vformat(TTR("Target folder does not exist or is inaccessible: \"%s\""), base_dir));
  435. return ERR_FILE_BAD_PATH;
  436. }
  437. // Find the correct template
  438. String template_path = p_debug ? custom_debug : custom_release;
  439. template_path = template_path.strip_edges();
  440. if (template_path.is_empty()) {
  441. bool extensions = (bool)p_preset->get("variant/extensions_support");
  442. bool thread_support = (bool)p_preset->get("variant/thread_support");
  443. template_path = find_export_template(_get_template_name(extensions, thread_support, p_debug));
  444. }
  445. if (!template_path.is_empty() && !FileAccess::exists(template_path)) {
  446. add_message(EXPORT_MESSAGE_ERROR, TTR("Prepare Templates"), vformat(TTR("Template file not found: \"%s\"."), template_path));
  447. return ERR_FILE_NOT_FOUND;
  448. }
  449. // Export pck and shared objects
  450. Vector<SharedObject> shared_objects;
  451. String pck_path = base_path + ".pck";
  452. Error error = save_pack(p_preset, p_debug, pck_path, &shared_objects);
  453. if (error != OK) {
  454. add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), vformat(TTR("Could not write file: \"%s\"."), pck_path));
  455. return error;
  456. }
  457. {
  458. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  459. for (int i = 0; i < shared_objects.size(); i++) {
  460. String dst = base_dir.path_join(shared_objects[i].path.get_file());
  461. error = da->copy(shared_objects[i].path, dst);
  462. if (error != OK) {
  463. add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), vformat(TTR("Could not write file: \"%s\"."), shared_objects[i].path.get_file()));
  464. return error;
  465. }
  466. }
  467. }
  468. // Extract templates.
  469. error = _extract_template(template_path, base_dir, base_name, pwa);
  470. if (error) {
  471. // Message is supplied by the subroutine method.
  472. return error;
  473. }
  474. // Parse generated file sizes (pck and wasm, to help show a meaningful loading bar).
  475. Dictionary file_sizes;
  476. Ref<FileAccess> f = FileAccess::open(pck_path, FileAccess::READ);
  477. if (f.is_valid()) {
  478. file_sizes[pck_path.get_file()] = (uint64_t)f->get_length();
  479. }
  480. f = FileAccess::open(base_path + ".wasm", FileAccess::READ);
  481. if (f.is_valid()) {
  482. file_sizes[base_name + ".wasm"] = (uint64_t)f->get_length();
  483. }
  484. // Read the HTML shell file (custom or from template).
  485. const String html_path = custom_html.is_empty() ? base_path + ".html" : custom_html;
  486. Vector<uint8_t> html;
  487. f = FileAccess::open(html_path, FileAccess::READ);
  488. if (f.is_null()) {
  489. add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), vformat(TTR("Could not read HTML shell: \"%s\"."), html_path));
  490. return ERR_FILE_CANT_READ;
  491. }
  492. html.resize(f->get_length());
  493. f->get_buffer(html.ptrw(), html.size());
  494. f.unref(); // close file.
  495. // Generate HTML file with replaced strings.
  496. _fix_html(html, p_preset, base_name, p_debug, p_flags, shared_objects, file_sizes);
  497. Error err = _write_or_error(html.ptr(), html.size(), p_path);
  498. if (err != OK) {
  499. // Message is supplied by the subroutine method.
  500. return err;
  501. }
  502. html.resize(0);
  503. // Export splash (why?)
  504. Ref<Image> splash = _get_project_splash(p_preset);
  505. const String splash_png_path = base_path + ".png";
  506. if (splash->save_png(splash_png_path) != OK) {
  507. add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), vformat(TTR("Could not write file: \"%s\"."), splash_png_path));
  508. return ERR_FILE_CANT_WRITE;
  509. }
  510. // Save a favicon that can be accessed without waiting for the project to finish loading.
  511. // This way, the favicon can be displayed immediately when loading the page.
  512. if (export_icon) {
  513. Ref<Image> favicon = _get_project_icon(p_preset);
  514. const String favicon_png_path = base_path + ".icon.png";
  515. if (favicon->save_png(favicon_png_path) != OK) {
  516. add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), vformat(TTR("Could not write file: \"%s\"."), favicon_png_path));
  517. return ERR_FILE_CANT_WRITE;
  518. }
  519. favicon->resize(180, 180);
  520. const String apple_icon_png_path = base_path + ".apple-touch-icon.png";
  521. if (favicon->save_png(apple_icon_png_path) != OK) {
  522. add_message(EXPORT_MESSAGE_ERROR, TTR("Export"), vformat(TTR("Could not write file: \"%s\"."), apple_icon_png_path));
  523. return ERR_FILE_CANT_WRITE;
  524. }
  525. }
  526. // Generate the PWA worker and manifest
  527. if (pwa) {
  528. err = _build_pwa(p_preset, p_path, shared_objects);
  529. if (err != OK) {
  530. // Message is supplied by the subroutine method.
  531. return err;
  532. }
  533. }
  534. return OK;
  535. }
  536. bool EditorExportPlatformWeb::poll_export() {
  537. Ref<EditorExportPreset> preset;
  538. for (int i = 0; i < EditorExport::get_singleton()->get_export_preset_count(); i++) {
  539. Ref<EditorExportPreset> ep = EditorExport::get_singleton()->get_export_preset(i);
  540. if (ep->is_runnable() && ep->get_platform() == this) {
  541. preset = ep;
  542. break;
  543. }
  544. }
  545. RemoteDebugState prev_remote_debug_state = remote_debug_state;
  546. remote_debug_state = REMOTE_DEBUG_STATE_UNAVAILABLE;
  547. if (preset.is_valid()) {
  548. const bool debug = true;
  549. // Throwaway variables to pass to `can_export`.
  550. String err;
  551. bool missing_templates;
  552. if (can_export(preset, err, missing_templates, debug)) {
  553. if (server->is_listening()) {
  554. remote_debug_state = REMOTE_DEBUG_STATE_SERVING;
  555. } else {
  556. remote_debug_state = REMOTE_DEBUG_STATE_AVAILABLE;
  557. }
  558. }
  559. }
  560. if (remote_debug_state != REMOTE_DEBUG_STATE_SERVING && server->is_listening()) {
  561. server->stop();
  562. }
  563. return remote_debug_state != prev_remote_debug_state;
  564. }
  565. Ref<ImageTexture> EditorExportPlatformWeb::get_option_icon(int p_index) const {
  566. Ref<ImageTexture> play_icon = EditorExportPlatform::get_option_icon(p_index);
  567. switch (remote_debug_state) {
  568. case REMOTE_DEBUG_STATE_UNAVAILABLE: {
  569. return nullptr;
  570. } break;
  571. case REMOTE_DEBUG_STATE_AVAILABLE: {
  572. switch (p_index) {
  573. case 0:
  574. case 1:
  575. return play_icon;
  576. default:
  577. ERR_FAIL_V(nullptr);
  578. }
  579. } break;
  580. case REMOTE_DEBUG_STATE_SERVING: {
  581. switch (p_index) {
  582. case 0:
  583. return play_icon;
  584. case 1:
  585. return restart_icon;
  586. case 2:
  587. return stop_icon;
  588. default:
  589. ERR_FAIL_V(nullptr);
  590. }
  591. } break;
  592. }
  593. return nullptr;
  594. }
  595. int EditorExportPlatformWeb::get_options_count() const {
  596. switch (remote_debug_state) {
  597. case REMOTE_DEBUG_STATE_UNAVAILABLE: {
  598. return 0;
  599. } break;
  600. case REMOTE_DEBUG_STATE_AVAILABLE: {
  601. return 2;
  602. } break;
  603. case REMOTE_DEBUG_STATE_SERVING: {
  604. return 3;
  605. } break;
  606. }
  607. return 0;
  608. }
  609. String EditorExportPlatformWeb::get_option_label(int p_index) const {
  610. String run_in_browser = TTR("Run in Browser");
  611. String start_http_server = TTR("Start HTTP Server");
  612. String reexport_project = TTR("Re-export Project");
  613. String stop_http_server = TTR("Stop HTTP Server");
  614. switch (remote_debug_state) {
  615. case REMOTE_DEBUG_STATE_UNAVAILABLE:
  616. return "";
  617. case REMOTE_DEBUG_STATE_AVAILABLE: {
  618. switch (p_index) {
  619. case 0:
  620. return run_in_browser;
  621. case 1:
  622. return start_http_server;
  623. default:
  624. ERR_FAIL_V("");
  625. }
  626. } break;
  627. case REMOTE_DEBUG_STATE_SERVING: {
  628. switch (p_index) {
  629. case 0:
  630. return run_in_browser;
  631. case 1:
  632. return reexport_project;
  633. case 2:
  634. return stop_http_server;
  635. default:
  636. ERR_FAIL_V("");
  637. }
  638. } break;
  639. }
  640. return "";
  641. }
  642. String EditorExportPlatformWeb::get_option_tooltip(int p_index) const {
  643. String run_in_browser = TTR("Run exported HTML in the system's default browser.");
  644. String start_http_server = TTR("Start the HTTP server.");
  645. String reexport_project = TTR("Export project again to account for updates.");
  646. String stop_http_server = TTR("Stop the HTTP server.");
  647. switch (remote_debug_state) {
  648. case REMOTE_DEBUG_STATE_UNAVAILABLE:
  649. return "";
  650. case REMOTE_DEBUG_STATE_AVAILABLE: {
  651. switch (p_index) {
  652. case 0:
  653. return run_in_browser;
  654. case 1:
  655. return start_http_server;
  656. default:
  657. ERR_FAIL_V("");
  658. }
  659. } break;
  660. case REMOTE_DEBUG_STATE_SERVING: {
  661. switch (p_index) {
  662. case 0:
  663. return run_in_browser;
  664. case 1:
  665. return reexport_project;
  666. case 2:
  667. return stop_http_server;
  668. default:
  669. ERR_FAIL_V("");
  670. }
  671. } break;
  672. }
  673. return "";
  674. }
  675. Error EditorExportPlatformWeb::run(const Ref<EditorExportPreset> &p_preset, int p_option, BitField<EditorExportPlatform::DebugFlags> p_debug_flags) {
  676. const uint16_t bind_port = EDITOR_GET("export/web/http_port");
  677. // Resolve host if needed.
  678. const String bind_host = EDITOR_GET("export/web/http_host");
  679. const bool use_tls = EDITOR_GET("export/web/use_tls");
  680. switch (remote_debug_state) {
  681. case REMOTE_DEBUG_STATE_UNAVAILABLE: {
  682. return FAILED;
  683. } break;
  684. case REMOTE_DEBUG_STATE_AVAILABLE: {
  685. switch (p_option) {
  686. // Run in Browser.
  687. case 0: {
  688. Error err = _export_project(p_preset, p_debug_flags);
  689. if (err != OK) {
  690. return err;
  691. }
  692. err = _start_server(bind_host, bind_port, use_tls);
  693. if (err != OK) {
  694. return err;
  695. }
  696. return _launch_browser(bind_host, bind_port, use_tls);
  697. } break;
  698. // Start HTTP Server.
  699. case 1: {
  700. Error err = _export_project(p_preset, p_debug_flags);
  701. if (err != OK) {
  702. return err;
  703. }
  704. return _start_server(bind_host, bind_port, use_tls);
  705. } break;
  706. default: {
  707. ERR_FAIL_V_MSG(FAILED, vformat(R"(Invalid option "%s" for the current state.)", p_option));
  708. }
  709. }
  710. } break;
  711. case REMOTE_DEBUG_STATE_SERVING: {
  712. switch (p_option) {
  713. // Run in Browser.
  714. case 0: {
  715. Error err = _export_project(p_preset, p_debug_flags);
  716. if (err != OK) {
  717. return err;
  718. }
  719. return _launch_browser(bind_host, bind_port, use_tls);
  720. } break;
  721. // Re-export Project.
  722. case 1: {
  723. return _export_project(p_preset, p_debug_flags);
  724. } break;
  725. // Stop HTTP Server.
  726. case 2: {
  727. return _stop_server();
  728. } break;
  729. default: {
  730. ERR_FAIL_V_MSG(FAILED, vformat(R"(Invalid option "%s" for the current state.)", p_option));
  731. }
  732. }
  733. } break;
  734. }
  735. return FAILED;
  736. }
  737. Error EditorExportPlatformWeb::_export_project(const Ref<EditorExportPreset> &p_preset, int p_debug_flags) {
  738. const String dest = EditorPaths::get_singleton()->get_temp_dir().path_join("web");
  739. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  740. if (!da->dir_exists(dest)) {
  741. Error err = da->make_dir_recursive(dest);
  742. if (err != OK) {
  743. add_message(EXPORT_MESSAGE_ERROR, TTR("Run"), vformat(TTR("Could not create HTTP server directory: %s."), dest));
  744. return err;
  745. }
  746. }
  747. const String basepath = dest.path_join("tmp_js_export");
  748. Error err = export_project(p_preset, true, basepath + ".html", p_debug_flags);
  749. if (err != OK) {
  750. // Export generates several files, clean them up on failure.
  751. DirAccess::remove_file_or_error(basepath + ".html");
  752. DirAccess::remove_file_or_error(basepath + ".offline.html");
  753. DirAccess::remove_file_or_error(basepath + ".js");
  754. DirAccess::remove_file_or_error(basepath + ".audio.worklet.js");
  755. DirAccess::remove_file_or_error(basepath + ".audio.position.worklet.js");
  756. DirAccess::remove_file_or_error(basepath + ".service.worker.js");
  757. DirAccess::remove_file_or_error(basepath + ".pck");
  758. DirAccess::remove_file_or_error(basepath + ".png");
  759. DirAccess::remove_file_or_error(basepath + ".side.wasm");
  760. DirAccess::remove_file_or_error(basepath + ".wasm");
  761. DirAccess::remove_file_or_error(basepath + ".icon.png");
  762. DirAccess::remove_file_or_error(basepath + ".apple-touch-icon.png");
  763. }
  764. return err;
  765. }
  766. Error EditorExportPlatformWeb::_launch_browser(const String &p_bind_host, const uint16_t p_bind_port, const bool p_use_tls) {
  767. OS::get_singleton()->shell_open(String((p_use_tls ? "https://" : "http://") + p_bind_host + ":" + itos(p_bind_port) + "/tmp_js_export.html"));
  768. // FIXME: Find out how to clean up export files after running the successfully
  769. // exported game. Might not be trivial.
  770. return OK;
  771. }
  772. Error EditorExportPlatformWeb::_start_server(const String &p_bind_host, const uint16_t p_bind_port, const bool p_use_tls) {
  773. IPAddress bind_ip;
  774. if (p_bind_host.is_valid_ip_address()) {
  775. bind_ip = p_bind_host;
  776. } else {
  777. bind_ip = IP::get_singleton()->resolve_hostname(p_bind_host);
  778. }
  779. ERR_FAIL_COND_V_MSG(!bind_ip.is_valid(), ERR_INVALID_PARAMETER, "Invalid editor setting 'export/web/http_host': '" + p_bind_host + "'. Try using '127.0.0.1'.");
  780. const String tls_key = EDITOR_GET("export/web/tls_key");
  781. const String tls_cert = EDITOR_GET("export/web/tls_certificate");
  782. // Restart server.
  783. server->stop();
  784. Error err = server->listen(p_bind_port, bind_ip, p_use_tls, tls_key, tls_cert);
  785. if (err != OK) {
  786. add_message(EXPORT_MESSAGE_ERROR, TTR("Run"), vformat(TTR("Error starting HTTP server: %d."), err));
  787. }
  788. return err;
  789. }
  790. Error EditorExportPlatformWeb::_stop_server() {
  791. server->stop();
  792. return OK;
  793. }
  794. Ref<Texture2D> EditorExportPlatformWeb::get_run_icon() const {
  795. return run_icon;
  796. }
  797. EditorExportPlatformWeb::EditorExportPlatformWeb() {
  798. if (EditorNode::get_singleton()) {
  799. server.instantiate();
  800. Ref<Image> img = memnew(Image);
  801. const bool upsample = !Math::is_equal_approx(Math::round(EDSCALE), EDSCALE);
  802. ImageLoaderSVG::create_image_from_string(img, _web_logo_svg, EDSCALE, upsample, false);
  803. logo = ImageTexture::create_from_image(img);
  804. ImageLoaderSVG::create_image_from_string(img, _web_run_icon_svg, EDSCALE, upsample, false);
  805. run_icon = ImageTexture::create_from_image(img);
  806. Ref<Theme> theme = EditorNode::get_singleton()->get_editor_theme();
  807. if (theme.is_valid()) {
  808. stop_icon = theme->get_icon(SNAME("Stop"), EditorStringName(EditorIcons));
  809. restart_icon = theme->get_icon(SNAME("Reload"), EditorStringName(EditorIcons));
  810. } else {
  811. stop_icon.instantiate();
  812. restart_icon.instantiate();
  813. }
  814. }
  815. }
  816. EditorExportPlatformWeb::~EditorExportPlatformWeb() {
  817. }