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