detect.py 11 KB

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