detect.py 10 KB

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