detect.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. import os
  2. import sys
  3. from typing import TYPE_CHECKING
  4. from emscripten_helpers import (
  5. add_js_externs,
  6. add_js_libraries,
  7. add_js_post,
  8. add_js_pre,
  9. create_engine_file,
  10. create_template_zip,
  11. get_template_zip_path,
  12. run_closure_compiler,
  13. )
  14. from SCons.Util import WhereIs
  15. from methods import get_compiler_version, print_error, print_info, print_warning
  16. from platform_methods import validate_arch
  17. if TYPE_CHECKING:
  18. from SCons.Script.SConscript import SConsEnvironment
  19. def get_name():
  20. return "Web"
  21. def can_build():
  22. return WhereIs("emcc") is not None
  23. def get_tools(env: "SConsEnvironment"):
  24. # Use generic POSIX build toolchain for Emscripten.
  25. return ["cc", "c++", "ar", "link", "textfile", "zip"]
  26. def get_opts():
  27. from SCons.Variables import BoolVariable
  28. return [
  29. ("initial_memory", "Initial WASM memory (in MiB)", 32),
  30. # Matches default values from before Emscripten 3.1.27. New defaults are too low for Godot.
  31. ("stack_size", "WASM stack size (in KiB)", 5120),
  32. ("default_pthread_stack_size", "WASM pthread default stack size (in KiB)", 2048),
  33. BoolVariable("use_assertions", "Use Emscripten runtime assertions", False),
  34. BoolVariable("use_ubsan", "Use Emscripten undefined behavior sanitizer (UBSAN)", False),
  35. BoolVariable("use_asan", "Use Emscripten address sanitizer (ASAN)", False),
  36. BoolVariable("use_lsan", "Use Emscripten leak sanitizer (LSAN)", False),
  37. BoolVariable("use_safe_heap", "Use Emscripten SAFE_HEAP sanitizer", False),
  38. # eval() can be a security concern, so it can be disabled.
  39. BoolVariable("javascript_eval", "Enable JavaScript eval interface", True),
  40. BoolVariable(
  41. "dlink_enabled", "Enable WebAssembly dynamic linking (GDExtension support). Produces bigger binaries", False
  42. ),
  43. BoolVariable("use_closure_compiler", "Use closure compiler to minimize JavaScript code", False),
  44. BoolVariable(
  45. "proxy_to_pthread",
  46. "Use Emscripten PROXY_TO_PTHREAD option to run the main application code to a separate thread",
  47. False,
  48. ),
  49. BoolVariable("wasm_simd", "Use WebAssembly SIMD to improve CPU performance", True),
  50. ]
  51. def get_doc_classes():
  52. return [
  53. "EditorExportPlatformWeb",
  54. ]
  55. def get_doc_path():
  56. return "doc_classes"
  57. def get_flags():
  58. return {
  59. "arch": "wasm32",
  60. "target": "template_debug",
  61. "builtin_pcre2_with_jit": False,
  62. "vulkan": False,
  63. # Embree is heavy and requires too much memory (GH-70621).
  64. "module_raycast_enabled": False,
  65. # Use -Os to prioritize optimizing for reduced file size. This is
  66. # particularly valuable for the web platform because it directly
  67. # decreases download time.
  68. # -Os reduces file size by around 5 MiB over -O3. -Oz only saves about
  69. # 100 KiB over -Os, which does not justify the negative impact on
  70. # run-time performance.
  71. # Note that this overrides the "auto" behavior for target/dev_build.
  72. "optimize": "size",
  73. }
  74. def library_emitter(target, source, env):
  75. # Make every source file dependent on the compiler version.
  76. # This makes sure that when emscripten is updated, that the cached files
  77. # aren't used and are recompiled instead.
  78. env.Depends(source, env.Value(get_compiler_version(env)))
  79. return target, source
  80. def configure(env: "SConsEnvironment"):
  81. env.Append(LIBEMITTER=[library_emitter])
  82. # Validate arch.
  83. supported_arches = ["wasm32"]
  84. validate_arch(env["arch"], get_name(), supported_arches)
  85. try:
  86. env["initial_memory"] = int(env["initial_memory"])
  87. except Exception:
  88. print_error("Initial memory must be a valid integer")
  89. sys.exit(255)
  90. ## Build type
  91. if env.debug_features:
  92. # Retain function names for backtraces at the cost of file size.
  93. env.Append(LINKFLAGS=["--profiling-funcs"])
  94. else:
  95. env["use_assertions"] = True
  96. if env["use_assertions"]:
  97. env.Append(LINKFLAGS=["-sASSERTIONS=1"])
  98. if env.editor_build and env["initial_memory"] < 64:
  99. print_info("Forcing `initial_memory=64` as it is required for the web editor.")
  100. env["initial_memory"] = 64
  101. env.Append(LINKFLAGS=["-sINITIAL_MEMORY=%sMB" % env["initial_memory"]])
  102. ## Copy env variables.
  103. env["ENV"] = os.environ
  104. # This makes `wasm-ld` treat all warnings as errors.
  105. if env["werror"]:
  106. env.Append(LINKFLAGS=["-Wl,--fatal-warnings"])
  107. # LTO
  108. if env["lto"] == "auto": # Enable LTO for production.
  109. env["lto"] = "thin"
  110. if env["lto"] != "none":
  111. if env["lto"] == "thin":
  112. env.Append(CCFLAGS=["-flto=thin"])
  113. env.Append(LINKFLAGS=["-flto=thin"])
  114. else:
  115. env.Append(CCFLAGS=["-flto"])
  116. env.Append(LINKFLAGS=["-flto"])
  117. # Sanitizers
  118. if env["use_ubsan"]:
  119. env.Append(CCFLAGS=["-fsanitize=undefined"])
  120. env.Append(LINKFLAGS=["-fsanitize=undefined"])
  121. if env["use_asan"]:
  122. env.Append(CCFLAGS=["-fsanitize=address"])
  123. env.Append(LINKFLAGS=["-fsanitize=address"])
  124. if env["use_lsan"]:
  125. env.Append(CCFLAGS=["-fsanitize=leak"])
  126. env.Append(LINKFLAGS=["-fsanitize=leak"])
  127. if env["use_safe_heap"]:
  128. env.Append(LINKFLAGS=["-sSAFE_HEAP=1"])
  129. # Closure compiler
  130. if env["use_closure_compiler"]:
  131. # For emscripten support code.
  132. env.Append(LINKFLAGS=["--closure", "1"])
  133. # Register builder for our Engine files
  134. jscc = env.Builder(generator=run_closure_compiler, suffix=".cc.js", src_suffix=".js")
  135. env.Append(BUILDERS={"BuildJS": jscc})
  136. # Add helper method for adding libraries, externs, pre-js, post-js.
  137. env["JS_LIBS"] = []
  138. env["JS_PRE"] = []
  139. env["JS_POST"] = []
  140. env["JS_EXTERNS"] = []
  141. env.AddMethod(add_js_libraries, "AddJSLibraries")
  142. env.AddMethod(add_js_pre, "AddJSPre")
  143. env.AddMethod(add_js_post, "AddJSPost")
  144. env.AddMethod(add_js_externs, "AddJSExterns")
  145. # Add method that joins/compiles our Engine files.
  146. env.AddMethod(create_engine_file, "CreateEngineFile")
  147. # Add method for getting the final zip path
  148. env.AddMethod(get_template_zip_path, "GetTemplateZipPath")
  149. # Add method for creating the final zip file
  150. env.AddMethod(create_template_zip, "CreateTemplateZip")
  151. env["CC"] = "emcc"
  152. env["CXX"] = "em++"
  153. env["AR"] = "emar"
  154. env["RANLIB"] = "emranlib"
  155. # Use TempFileMunge since some AR invocations are too long for cmd.exe.
  156. # Use POSIX-style paths, required with TempFileMunge.
  157. env["ARCOM_POSIX"] = env["ARCOM"].replace("$TARGET", "$TARGET.posix").replace("$SOURCES", "$SOURCES.posix")
  158. env["ARCOM"] = "${TEMPFILE('$ARCOM_POSIX','$ARCOMSTR')}"
  159. # All intermediate files are just object files.
  160. env["OBJPREFIX"] = ""
  161. env["OBJSUFFIX"] = ".o"
  162. env["PROGPREFIX"] = ""
  163. # Program() output consists of multiple files, so specify suffixes manually at builder.
  164. env["PROGSUFFIX"] = ""
  165. env["LIBPREFIX"] = "lib"
  166. env["LIBSUFFIX"] = ".a"
  167. env["LIBPREFIXES"] = ["$LIBPREFIX"]
  168. env["LIBSUFFIXES"] = ["$LIBSUFFIX"]
  169. # Get version info for checks below.
  170. cc_version = get_compiler_version(env)
  171. cc_semver = (cc_version["major"], cc_version["minor"], cc_version["patch"])
  172. # Minimum emscripten requirements.
  173. if cc_semver < (3, 1, 62):
  174. print_error("The minimum emscripten version to build Godot is 3.1.62, detected: %s.%s.%s" % cc_semver)
  175. sys.exit(255)
  176. env.Prepend(CPPPATH=["#platform/web"])
  177. env.Append(CPPDEFINES=["WEB_ENABLED", "UNIX_ENABLED", "UNIX_SOCKET_UNAVAILABLE"])
  178. if env["opengl3"]:
  179. env.AppendUnique(CPPDEFINES=["GLES3_ENABLED"])
  180. # This setting just makes WebGL 2 APIs available, it does NOT disable WebGL 1.
  181. env.Append(LINKFLAGS=["-sMAX_WEBGL_VERSION=2"])
  182. # Allow use to take control of swapping WebGL buffers.
  183. env.Append(LINKFLAGS=["-sOFFSCREEN_FRAMEBUFFER=1"])
  184. # Disables the use of *glGetProcAddress() which is inefficient.
  185. # See https://emscripten.org/docs/tools_reference/settings_reference.html#gl-enable-get-proc-address
  186. env.Append(LINKFLAGS=["-sGL_ENABLE_GET_PROC_ADDRESS=0"])
  187. if env["javascript_eval"]:
  188. env.Append(CPPDEFINES=["JAVASCRIPT_EVAL_ENABLED"])
  189. env.Append(LINKFLAGS=["-s%s=%sKB" % ("STACK_SIZE", env["stack_size"])])
  190. if env["threads"]:
  191. # Thread support (via SharedArrayBuffer).
  192. env.Append(CPPDEFINES=["PTHREAD_NO_RENAME"])
  193. env.Append(CCFLAGS=["-sUSE_PTHREADS=1"])
  194. env.Append(LINKFLAGS=["-sUSE_PTHREADS=1"])
  195. env.Append(LINKFLAGS=["-sDEFAULT_PTHREAD_STACK_SIZE=%sKB" % env["default_pthread_stack_size"]])
  196. env.Append(LINKFLAGS=["-sPTHREAD_POOL_SIZE=8"])
  197. env.Append(LINKFLAGS=["-sWASM_MEM_MAX=2048MB"])
  198. if not env["dlink_enabled"]:
  199. # Workaround https://github.com/emscripten-core/emscripten/issues/21844#issuecomment-2116936414.
  200. # Not needed (and potentially dangerous) when dlink_enabled=yes, since we set EXPORT_ALL=1 in that case.
  201. env.Append(LINKFLAGS=["-sEXPORTED_FUNCTIONS=['__emscripten_thread_crashed','_main']"])
  202. elif env["proxy_to_pthread"]:
  203. print_warning('"threads=no" support requires "proxy_to_pthread=no", disabling proxy to pthread.')
  204. env["proxy_to_pthread"] = False
  205. if env["lto"] != "none":
  206. # Workaround https://github.com/emscripten-core/emscripten/issues/16836.
  207. env.Append(LINKFLAGS=["-Wl,-u,_emscripten_run_callback_on_thread"])
  208. if env["dlink_enabled"]:
  209. if env["proxy_to_pthread"]:
  210. print_warning("GDExtension support requires proxy_to_pthread=no, disabling proxy to pthread.")
  211. env["proxy_to_pthread"] = False
  212. env.Append(CCFLAGS=["-sSIDE_MODULE=2"])
  213. env.Append(LINKFLAGS=["-sSIDE_MODULE=2"])
  214. env.Append(CCFLAGS=["-fvisibility=hidden"])
  215. env.Append(LINKFLAGS=["-fvisibility=hidden"])
  216. env.extra_suffix = ".dlink" + env.extra_suffix
  217. env.Append(LINKFLAGS=["-sWASM_BIGINT"])
  218. # Run the main application in a web worker
  219. if env["proxy_to_pthread"]:
  220. env.Append(LINKFLAGS=["-sPROXY_TO_PTHREAD=1"])
  221. env.Append(CPPDEFINES=["PROXY_TO_PTHREAD_ENABLED"])
  222. env.Append(LINKFLAGS=["-sEXPORTED_RUNTIME_METHODS=['_emscripten_proxy_main']"])
  223. # https://github.com/emscripten-core/emscripten/issues/18034#issuecomment-1277561925
  224. env.Append(LINKFLAGS=["-sTEXTDECODER=0"])
  225. # Enable WebAssembly SIMD
  226. if env["wasm_simd"]:
  227. env.Append(CCFLAGS=["-msimd128"])
  228. # Reduce code size by generating less support code (e.g. skip NodeJS support).
  229. env.Append(LINKFLAGS=["-sENVIRONMENT=web,worker"])
  230. # Wrap the JavaScript support code around a closure named Godot.
  231. env.Append(LINKFLAGS=["-sMODULARIZE=1", "-sEXPORT_NAME='Godot'"])
  232. # Force long jump mode to 'wasm'
  233. env.Append(CCFLAGS=["-sSUPPORT_LONGJMP='wasm'"])
  234. env.Append(LINKFLAGS=["-sSUPPORT_LONGJMP='wasm'"])
  235. # Allow increasing memory buffer size during runtime. This is efficient
  236. # when using WebAssembly (in comparison to asm.js) and works well for
  237. # us since we don't know requirements at compile-time.
  238. env.Append(LINKFLAGS=["-sALLOW_MEMORY_GROWTH=1"])
  239. # Do not call main immediately when the support code is ready.
  240. env.Append(LINKFLAGS=["-sINVOKE_RUN=0"])
  241. # callMain for manual start, cwrap for the mono version.
  242. env.Append(LINKFLAGS=["-sEXPORTED_RUNTIME_METHODS=['callMain','cwrap']"])
  243. # Add code that allow exiting runtime.
  244. env.Append(LINKFLAGS=["-sEXIT_RUNTIME=1"])
  245. # This workaround creates a closure that prevents the garbage collector from freeing the WebGL context.
  246. # We also only use WebGL2, and changing context version is not widely supported anyway.
  247. env.Append(LINKFLAGS=["-sGL_WORKAROUND_SAFARI_GETCONTEXT_BUG=0"])