detect.py 9.8 KB

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