export_plugin.cpp 35 KB

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