detect.py 11 KB

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