Skip to content
0.2.0-dev Download ZIP
1279 lines ·52.7 KB Raw
1#!/usr/bin/env python
2from misc.utility.scons_hints import *
3
4EnsureSConsVersion(4, 4)
5EnsurePythonVersion(3, 10)
6
7# System
8import glob
9import os
10import pickle
11import sys
12from collections import OrderedDict
13from importlib.util import module_from_spec, spec_from_file_location
14from types import ModuleType
15
16from SCons import __version__ as scons_raw_version
17from SCons.Builder import ListEmitter
18
19# Explicitly resolve the helper modules, this is done to avoid clash with
20# modules of the same name that might be randomly added (e.g. someone adding
21# an `editor.py` file at the root of the module creates a clash with the editor
22# folder when doing `import editor.template_builder`)
23
24
25def _helper_module(name, path):
26 spec = spec_from_file_location(name, path)
27 module = module_from_spec(spec)
28 spec.loader.exec_module(module)
29 sys.modules[name] = module
30 # Ensure the module's parents are in loaded to avoid loading the wrong parent
31 # when doing "import foo.bar" while only "foo.bar" as declared as helper module
32 child_module = module
33 parent_name = name
34 while True:
35 try:
36 parent_name, child_name = parent_name.rsplit(".", 1)
37 except ValueError:
38 break
39 try:
40 parent_module = sys.modules[parent_name]
41 except KeyError:
42 parent_module = ModuleType(parent_name)
43 sys.modules[parent_name] = parent_module
44 setattr(parent_module, child_name, child_module)
45
46
47_helper_module("gles3_builders", "gles3_builders.py")
48_helper_module("glsl_builders", "glsl_builders.py")
49_helper_module("methods", "methods.py")
50_helper_module("platform_methods", "platform_methods.py")
51_helper_module("version", "version.py")
52_helper_module("core.core_builders", "core/core_builders.py")
53_helper_module("main.main_builders", "main/main_builders.py")
54_helper_module("misc.utility.color", "misc/utility/color.py")
55
56# Local
57import gles3_builders
58import glsl_builders
59import methods
60import scu_builders
61from misc.utility.color import is_stderr_color, print_error, print_info, print_warning
62from platform_methods import architecture_aliases, architectures, compatibility_platform_aliases
63
64if ARGUMENTS.get("target", "editor") == "editor":
65 _helper_module("editor.editor_builders", "editor/editor_builders.py")
66 _helper_module("editor.template_builders", "editor/template_builders.py")
67
68# Scan possible build platforms
69
70platform_list = [] # list of platforms
71platform_opts = {} # options for each platform
72platform_flags = {} # flags for each platform
73platform_doc_class_path = {}
74platform_exporters = []
75platform_apis = []
76
77for x in sorted(glob.glob("platform/*")):
78 if not os.path.isdir(x) or not os.path.exists(x + "/detect.py"):
79 continue
80 tmppath = "./" + x
81
82 sys.path.insert(0, tmppath)
83 import detect
84
85 # Get doc classes paths (if present)
86 try:
87 doc_classes = detect.get_doc_classes()
88 doc_path = detect.get_doc_path()
89 for c in doc_classes:
90 platform_doc_class_path[c] = x.replace("\\", "/") + "/" + doc_path
91 except Exception:
92 pass
93
94 platform_name = x[9:]
95
96 if os.path.exists(x + "/export/export.cpp"):
97 platform_exporters.append(platform_name)
98 if os.path.exists(x + "/api/api.cpp"):
99 platform_apis.append(platform_name)
100 if detect.can_build():
101 x = x.replace("platform/", "") # rest of world
102 x = x.replace("platform\\", "") # win32
103 platform_list += [x]
104 platform_opts[x] = detect.get_opts()
105 platform_flags[x] = detect.get_flags()
106 if isinstance(platform_flags[x], list): # backwards compatibility
107 platform_flags[x] = {flag[0]: flag[1] for flag in platform_flags[x]}
108 sys.path.remove(tmppath)
109 sys.modules.pop("detect")
110
111# We let SCons build its default ENV as it includes OS-specific things which we don't
112# want to have to pull in manually. However we enforce no "tools", which we register
113# further down after parsing our platform-specific configuration.
114# Then we prepend PATH to make it take precedence, while preserving SCons' own entries.
115env = Environment(tools=[])
116env.PrependENVPath("PATH", os.getenv("PATH"))
117env.PrependENVPath("PKG_CONFIG_PATH", os.getenv("PKG_CONFIG_PATH"))
118if "TERM" in os.environ: # Used for colored output.
119 env["ENV"]["TERM"] = os.environ["TERM"]
120
121env.disabled_modules = set()
122env.module_version_string = ""
123env.msvc = False
124env.scons_version = env._get_major_minor_revision(scons_raw_version)
125
126env.__class__.add_module_version_string = methods.add_module_version_string
127
128env.__class__.add_source_files = methods.add_source_files
129env.__class__.use_windows_spawn_fix = methods.use_windows_spawn_fix
130
131env.__class__.add_shared_library = methods.add_shared_library
132env.__class__.add_library = methods.add_library
133env.__class__.add_program = methods.add_program
134env.__class__.CommandNoCache = methods.CommandNoCache
135env.__class__.Run = methods.Run
136env.__class__.disable_warnings = methods.disable_warnings
137env.__class__.force_optimization_on_debug = methods.force_optimization_on_debug
138env.__class__.module_add_dependencies = methods.module_add_dependencies
139env.__class__.module_check_dependencies = methods.module_check_dependencies
140
141env["x86_libtheora_opt_gcc"] = False
142env["x86_libtheora_opt_vc"] = False
143
144# avoid issues when building with different versions of python out of the same directory
145env.SConsignFile(File(f"#.sconsign{pickle.HIGHEST_PROTOCOL}.dblite").abspath)
146
147# Build options
148
149customs = ["custom.py"]
150
151profile = ARGUMENTS.get("profile", "")
152if profile:
153 if os.path.isfile(profile):
154 customs.append(profile)
155 elif os.path.isfile(profile + ".py"):
156 customs.append(profile + ".py")
157
158opts = Variables(customs, ARGUMENTS)
159
160# Target build options
161opts.Add((["platform", "p"], f"Target platform ({'|'.join(platform_list)})", ""))
162opts.Add(
163 EnumVariable(
164 "target", "Compilation target", "editor", ["editor", "template_release", "template_debug"], ignorecase=2
165 )
166)
167opts.Add(EnumVariable("arch", "CPU architecture", "auto", ["auto"] + architectures, architecture_aliases, ignorecase=2))
168opts.Add(BoolVariable("dev_build", "Developer build with dev-only debugging code (DEV_ENABLED)", False))
169opts.Add(
170 EnumVariable(
171 "optimize",
172 "Optimization level (by default inferred from 'target' and 'dev_build')",
173 "auto",
174 ["auto", "none", "custom", "debug", "speed", "speed_trace", "size", "size_extra"],
175 ignorecase=2,
176 )
177)
178opts.Add(BoolVariable("debug_symbols", "Build with debugging symbols", False))
179opts.Add(BoolVariable("separate_debug_symbols", "Extract debugging symbols to a separate file", False))
180opts.Add(BoolVariable("debug_paths_relative", "Make file paths in debug symbols relative (if supported)", False))
181opts.Add(
182 EnumVariable(
183 "lto", "Link-time optimization (production builds)", "none", ["none", "auto", "thin", "full"], ignorecase=2
184 )
185)
186opts.Add(BoolVariable("production", "Set defaults to build Godot for use in production", False))
187opts.Add(BoolVariable("threads", "Enable threading support", True))
188
189# Components
190opts.Add(BoolVariable("deprecated", "Enable compatibility code for deprecated and removed features", True))
191opts.Add(
192 EnumVariable("precision", "Set the floating-point precision level", "single", ["single", "double"], ignorecase=2)
193)
194opts.Add(BoolVariable("minizip", "Enable ZIP archive support using minizip", True))
195opts.Add(BoolVariable("brotli", "Enable Brotli for decompression and WOFF2 fonts support", True))
196opts.Add(BoolVariable("xaudio2", "Enable the XAudio2 audio driver on supported platforms", False))
197opts.Add(
198 BoolVariable(
199 "rendering_device",
200 "Enable RenderingDevice abstraction for modern graphics APIs (use the `vulkan`, `d3d12`, and `metal` options to toggle individual drivers)",
201 True,
202 )
203)
204opts.Add(BoolVariable("forward_plus_renderer", "Enable the Forward+ renderer (requires RenderingDevice)", True))
205opts.Add(BoolVariable("forward_mobile_renderer", "Enable the Mobile renderer (requires RenderingDevice)", True))
206opts.Add(BoolVariable("vulkan", "Enable the Vulkan rendering driver", True))
207opts.Add(BoolVariable("opengl3", "Enable the OpenGL/GLES3 rendering driver", True))
208opts.Add(BoolVariable("d3d12", "Enable the Direct3D 12 rendering driver on supported platforms", False))
209opts.Add(BoolVariable("metal", "Enable the Metal rendering driver on supported platforms (Apple arm64 only)", False))
210opts.Add(BoolVariable("use_volk", "Use the volk library to load the Vulkan loader dynamically", True))
211opts.Add(BoolVariable("accesskit", "Enable the AccessKit driver for screen reader support", True))
212opts.Add(BoolVariable("angle", "Enable the ANGLE rendering driver for OpenGL ES 3.0 on supported platforms", True))
213opts.Add(BoolVariable("sdl", "Enable the SDL3 input driver", True))
214opts.Add(
215 EnumVariable(
216 "profiler", "Specify the profiler to use", "none", ["none", "tracy", "perfetto", "instruments"], ignorecase=2
217 )
218)
219opts.Add(("profiler_path", "Path to the Profiler framework.", ""))
220opts.Add(
221 BoolVariable(
222 "profiler_sample_callstack",
223 "Profile random samples application-wide using a callstack based sampler.",
224 False,
225 )
226)
227opts.Add(
228 BoolVariable(
229 "profiler_track_memory",
230 "Profile memory allocations, if the profiler supports it.",
231 False,
232 )
233)
234opts.Add(
235 BoolVariable(
236 "profiler_record_on_demand",
237 "Record only when the profiler is connected, if the profiler supports it. In Tracy, this configures TRACY_ON_DEMAND, which has a performance impact if enabled.",
238 True,
239 )
240)
241opts.Add((
242 "profiler_broadcast_address",
243 "The broadcast IP address used for announcing the profiler application. In Tracy this configures TRACY_CLIENT_ADDRESS.",
244 "",
245))
246
247
248# Advanced options
249opts.Add(
250 BoolVariable(
251 "dev_mode", "Alias for dev options: verbose=yes warnings=extra werror=yes tests=yes strict_checks=yes", False
252 )
253)
254opts.Add(BoolVariable("tests", "Build the unit tests", False))
255opts.Add(BoolVariable("fast_unsafe", "Enable unsafe options for faster incremental builds", False))
256opts.Add(BoolVariable("ninja", "Use the ninja backend for faster rebuilds", False))
257opts.Add(BoolVariable("ninja_auto_run", "Run ninja automatically after generating the ninja file", True))
258opts.Add("ninja_file", "Path to the generated ninja file", "build.ninja")
259opts.Add(BoolVariable("compiledb", "Generate compilation DB (`compile_commands.json`) for external tools", False))
260opts.Add(BoolVariable("compiledb_gen_only", "Exit after building the compilation database", False))
261opts.Add(
262 "num_jobs",
263 "Use up to N jobs when compiling (equivalent to `-j N`). Defaults to max jobs - 1. Ignored if -j is used.",
264 "",
265)
266opts.Add(BoolVariable("verbose", "Enable verbose output for the compilation", False))
267opts.Add(BoolVariable("progress", "Show a progress indicator during compilation", True))
268opts.Add(
269 EnumVariable("warnings", "Level of compilation warnings", "all", ["extra", "all", "moderate", "no"], ignorecase=2)
270)
271opts.Add(BoolVariable("werror", "Treat compiler warnings as errors", False))
272opts.Add("extra_suffix", "Custom extra suffix added to the base filename of all generated binary files", "")
273opts.Add("object_prefix", "Custom prefix added to the base filename of all generated object files", "")
274opts.Add(BoolVariable("vsproj", "Generate a Visual Studio solution", False))
275opts.Add("vsproj_name", "Name of the Visual Studio solution", "godot")
276opts.Add("import_env_vars", "A comma-separated list of environment variables to copy from the outer environment.", "")
277opts.Add(BoolVariable("disable_exceptions", "Force disabling exception handling code", True))
278opts.Add(BoolVariable("disable_2d", "Disable 2D nodes for a smaller executable", False))
279opts.Add(BoolVariable("disable_3d", "Disable 3D nodes for a smaller executable", False))
280opts.Add(BoolVariable("disable_advanced_gui", "Disable advanced GUI nodes and behaviors", False))
281opts.Add(BoolVariable("disable_physics_2d", "Disable 2D physics nodes and server", False))
282opts.Add(BoolVariable("disable_physics_3d", "Disable 3D physics nodes and server", False))
283opts.Add(BoolVariable("disable_navigation_2d", "Disable 2D navigation features", False))
284opts.Add(BoolVariable("disable_navigation_3d", "Disable 3D navigation features", False))
285opts.Add(BoolVariable("disable_xr", "Disable XR nodes and server", False))
286opts.Add(BoolVariable("disable_overrides", "Disable project settings overrides (override.cfg)", False))
287opts.Add(
288 BoolVariable(
289 "disable_path_overrides",
290 "Disable CLI arguments to override project path/main pack/scene and run scripts (export template only)",
291 True,
292 )
293)
294opts.Add("build_profile", "Path to a file containing a feature build profile", "")
295opts.Add("custom_modules", "A list of comma-separated directory paths containing custom modules to build.", "")
296opts.Add(BoolVariable("custom_modules_recursive", "Detect custom modules recursively for each specified path.", True))
297opts.Add(BoolVariable("modules_enabled_by_default", "If no, disable all modules except ones explicitly enabled", True))
298opts.Add(BoolVariable("no_editor_splash", "Don't use the custom splash screen for the editor", True))
299opts.Add(
300 "system_certs_path",
301 "Use this path as TLS certificates default for editor and Linux/BSD export templates (for package maintainers)",
302 "",
303)
304opts.Add(BoolVariable("use_precise_math_checks", "Math checks use very precise epsilon (debug option)", False))
305opts.Add(BoolVariable("strict_checks", "Enforce stricter checks (debug option)", False))
306opts.Add(
307 BoolVariable(
308 "limit_transitive_includes", "Attempt to limit the amount of transitive includes in system headers", True
309 )
310)
311opts.Add(BoolVariable("scu_build", "Use single compilation unit build", False))
312opts.Add("scu_limit", "Max includes per SCU file when using scu_build (determines RAM use)", "0")
313opts.Add(BoolVariable("engine_update_check", "Enable engine update checks in the Project Manager", True))
314opts.Add(BoolVariable("steamapi", "Enable minimal SteamAPI integration for usage time tracking (editor only)", False))
315opts.Add("cache_path", "Path to a directory where SCons cache files will be stored. No value disables the cache.", "")
316opts.Add("cache_limit", "Max size (in GiB) for the SCons cache. 0 means no limit.", "0")
317opts.Add(
318 BoolVariable(
319 "redirect_build_objects",
320 "Enable redirecting built objects/libraries to `bin/obj/` to declutter the repository.",
321 True,
322 )
323)
324opts.Add(
325 EnumVariable(
326 "library_type",
327 "Build library type",
328 "executable",
329 ("executable", "static_library", "shared_library"),
330 )
331)
332
333# Thirdparty libraries
334opts.Add(BoolVariable("builtin_brotli", "Use the built-in Brotli library", True))
335opts.Add(BoolVariable("builtin_certs", "Use the built-in SSL certificates bundles", True))
336opts.Add(BoolVariable("builtin_clipper2", "Use the built-in Clipper2 library", True))
337opts.Add(BoolVariable("builtin_embree", "Use the built-in Embree library", True))
338opts.Add(BoolVariable("builtin_enet", "Use the built-in ENet library", True))
339opts.Add(BoolVariable("builtin_freetype", "Use the built-in FreeType library", True))
340opts.Add(BoolVariable("builtin_msdfgen", "Use the built-in MSDFgen library", True))
341opts.Add(BoolVariable("builtin_glslang", "Use the built-in glslang library", True))
342opts.Add(BoolVariable("builtin_graphite", "Use the built-in Graphite library", True))
343opts.Add(BoolVariable("builtin_harfbuzz", "Use the built-in HarfBuzz library", True))
344opts.Add(BoolVariable("builtin_sdl", "Use the built-in SDL library", True))
345opts.Add(BoolVariable("builtin_icu4c", "Use the built-in ICU library", True))
346opts.Add(BoolVariable("builtin_libjpeg_turbo", "Use the built-in libjpeg-turbo library", True))
347opts.Add(BoolVariable("builtin_libogg", "Use the built-in libogg library", True))
348opts.Add(BoolVariable("builtin_libpng", "Use the built-in libpng library", True))
349opts.Add(BoolVariable("builtin_libtheora", "Use the built-in libtheora library", True))
350opts.Add(BoolVariable("builtin_libvorbis", "Use the built-in libvorbis library", True))
351opts.Add(BoolVariable("builtin_libwebp", "Use the built-in libwebp library", True))
352opts.Add(BoolVariable("builtin_wslay", "Use the built-in wslay library", True))
353opts.Add(BoolVariable("builtin_mbedtls", "Use the built-in mbedTLS library", True))
354opts.Add(BoolVariable("builtin_miniupnpc", "Use the built-in miniupnpc library", True))
355opts.Add(BoolVariable("builtin_openxr", "Use the built-in OpenXR library", True))
356opts.Add(BoolVariable("builtin_pcre2", "Use the built-in PCRE2 library", True))
357opts.Add(BoolVariable("builtin_pcre2_with_jit", "Use JIT compiler for the built-in PCRE2 library", True))
358opts.Add(BoolVariable("builtin_recastnavigation", "Use the built-in Recast navigation library", True))
359opts.Add(BoolVariable("builtin_rvo2_2d", "Use the built-in RVO2 2D library", True))
360opts.Add(BoolVariable("builtin_rvo2_3d", "Use the built-in RVO2 3D library", True))
361opts.Add(BoolVariable("builtin_xatlas", "Use the built-in xatlas library", True))
362opts.Add(BoolVariable("builtin_zlib", "Use the built-in zlib library", True))
363opts.Add(BoolVariable("builtin_zstd", "Use the built-in Zstd library", True))
364
365# Compilation environment setup
366# CXX, CC, and LINK directly set the equivalent `env` values (which may still
367# be overridden for a specific platform), the lowercase ones are appended.
368opts.Add("CXX", "C++ compiler binary")
369opts.Add("CC", "C compiler binary")
370opts.Add("LINK", "Linker binary")
371opts.Add("cppdefines", "Custom defines for the pre-processor")
372opts.Add("ccflags", "Custom flags for both the C and C++ compilers")
373opts.Add("cxxflags", "Custom flags for the C++ compiler")
374opts.Add("cflags", "Custom flags for the C compiler")
375opts.Add("linkflags", "Custom flags for the linker")
376opts.Add("asflags", "Custom flags for the assembler")
377opts.Add("arflags", "Custom flags for the archive tool")
378opts.Add("rcflags", "Custom flags for Windows resource compiler")
379
380opts.Add("c_compiler_launcher", "C compiler launcher (e.g. `ccache`)")
381opts.Add("cpp_compiler_launcher", "C++ compiler launcher (e.g. `ccache`)")
382
383# Update the environment to have all above options defined
384# in following code (especially platform and custom_modules).
385opts.Update(env)
386
387# Setup caching logic early to catch everything.
388methods.prepare_cache(env)
389
390# Copy custom environment variables if set.
391if env["import_env_vars"]:
392 for env_var in str(env["import_env_vars"]).split(","):
393 if env_var in os.environ:
394 env["ENV"][env_var] = os.environ[env_var]
395
396# Platform selection: validate input, and add options.
397
398if not env["platform"]:
399 # Missing `platform` argument, try to detect platform automatically
400 if (
401 sys.platform.startswith("linux")
402 or sys.platform.startswith("dragonfly")
403 or sys.platform.startswith("freebsd")
404 or sys.platform.startswith("netbsd")
405 or sys.platform.startswith("openbsd")
406 ):
407 env["platform"] = "linuxbsd"
408 elif sys.platform == "darwin":
409 env["platform"] = "macos"
410 elif sys.platform == "win32":
411 env["platform"] = "windows"
412
413 if env["platform"]:
414 print(f"Automatically detected platform: {env['platform']}")
415
416# Deprecated aliases kept for compatibility.
417if env["platform"] in compatibility_platform_aliases:
418 alias = env["platform"]
419 platform = compatibility_platform_aliases[alias]
420 print_warning(
421 f'Platform "{alias}" has been renamed to "{platform}" in Godot 4. Building for platform "{platform}".'
422 )
423 env["platform"] = platform
424
425# Alias for convenience.
426if env["platform"] in ["linux", "bsd"]:
427 env["platform"] = "linuxbsd"
428
429if env["platform"] not in platform_list:
430 text = "The following platforms are available:\n\t{}\n".format("\n\t".join(platform_list))
431 text += "Please run SCons again and select a valid platform: platform=<string>."
432
433 if env["platform"] == "list":
434 print(text)
435 elif not env["platform"]:
436 print_error("Could not detect platform automatically.\n" + text)
437 else:
438 print_error(f'Invalid target platform "{env["platform"]}".\n' + text)
439
440 Exit(0 if env["platform"] == "list" else 255)
441
442# Add platform-specific options.
443if env["platform"] in platform_opts:
444 opts.AddVariables(*platform_opts[env["platform"]])
445
446# Platform-specific flags.
447# These can sometimes override default options, so they need to be processed
448# as early as possible to ensure that we're using the correct values.
449flag_list = platform_flags[env["platform"]]
450for key, value in flag_list.items():
451 if key not in ARGUMENTS or ARGUMENTS[key] == "auto": # Allow command line to override platform flags
452 env[key] = value
453
454# Update the environment to take platform-specific options into account.
455opts.Update(env, {**ARGUMENTS, **env.Dictionary()})
456
457# Detect modules.
458modules_detected = OrderedDict()
459module_search_paths = ["modules"] # Built-in path.
460
461if env["custom_modules"]:
462 paths = env["custom_modules"].split(",")
463 for p in paths:
464 try:
465 module_search_paths.append(methods.convert_custom_modules_path(p))
466 except ValueError as e:
467 print_error(e)
468 Exit(255)
469
470for path in module_search_paths:
471 if path == "modules":
472 # Built-in modules don't have nested modules,
473 # so save the time it takes to parse directories.
474 modules = methods.detect_modules(path, recursive=False)
475 else: # Custom.
476 modules = methods.detect_modules(path, env["custom_modules_recursive"])
477 # Provide default include path for both the custom module search `path`
478 # and the base directory containing custom modules, as it may be different
479 # from the built-in "modules" name (e.g. "custom_modules/summator/summator.h"),
480 # so it can be referenced simply as `#include "summator/summator.h"`
481 # independently of where a module is located on user's filesystem.
482 env.Prepend(CPPPATH=[path, os.path.dirname(path)])
483 # Note: custom modules can override built-in ones.
484 modules_detected.update(modules)
485
486# Add module options.
487for name, path in modules_detected.items():
488 sys.path.insert(0, path)
489 import config
490
491 if env["modules_enabled_by_default"]:
492 enabled = True
493 try:
494 enabled = config.is_enabled()
495 except AttributeError:
496 pass
497 else:
498 enabled = False
499
500 opts.Add(BoolVariable(f"module_{name}_enabled", f"Enable module '{name}'", enabled))
501
502 # Add module-specific options.
503 try:
504 opts.AddVariables(*config.get_opts(env["platform"]))
505 except AttributeError:
506 pass
507
508 sys.path.remove(path)
509 sys.modules.pop("config")
510
511env.modules_detected = modules_detected
512
513# Update the environment again after all the module options are added.
514opts.Update(env, {**ARGUMENTS, **env.Dictionary()})
515Help(opts.GenerateHelpText(env))
516
517
518# FIXME: Tool assignment happening at this stage is a direct consequence of getting the platform logic AFTER the SCons
519# environment was already been constructed. Fixing this would require a broader refactor where all options are setup
520# ahead of time with native validator/converter functions.
521tmppath = "./platform/" + env["platform"]
522sys.path.insert(0, tmppath)
523import detect
524
525custom_tools = ["default"]
526try: # Platform custom tools are optional
527 custom_tools = detect.get_tools(env)
528except AttributeError:
529 pass
530for tool in custom_tools:
531 env.Tool(tool)
532
533
534# Add default include paths.
535env.Prepend(CPPPATH=["#"])
536
537# configure ENV for platform
538env.platform_exporters = platform_exporters
539env.platform_apis = platform_apis
540
541# Configuration of build targets:
542# - Editor or template
543# - Debug features (DEBUG_ENABLED code)
544# - Dev only code (DEV_ENABLED code)
545# - Optimization level
546# - Debug symbols for crash traces / debuggers
547
548env.editor_build = env["target"] == "editor"
549env.dev_build = env["dev_build"]
550env.debug_features = env["target"] in ["editor", "template_debug"]
551
552if env["optimize"] == "auto":
553 if env.dev_build:
554 opt_level = "none"
555 elif env.debug_features:
556 opt_level = "speed_trace"
557 else: # Release
558 opt_level = "speed"
559 env["optimize"] = opt_level
560
561env["debug_symbols"] = methods.get_cmdline_bool("debug_symbols", env.dev_build)
562
563if env.editor_build:
564 env.Append(CPPDEFINES=["TOOLS_ENABLED"])
565
566if env.debug_features:
567 # DEBUG_ENABLED enables debugging *features* and debug-only code, which is intended
568 # to give *users* extra debugging information for their game development.
569 env.Append(CPPDEFINES=["DEBUG_ENABLED"])
570
571if env.dev_build:
572 # DEV_ENABLED enables *engine developer* code which should only be compiled for those
573 # working on the engine itself.
574 env.Append(CPPDEFINES=["DEV_ENABLED"])
575else:
576 # Disable assert() for production targets (only used in thirdparty code).
577 env.Append(CPPDEFINES=["NDEBUG"])
578
579# This is not part of fast_unsafe because the only downside it has compared to
580# the default is that SCons won't mark files that were changed in the last second
581# as different. This is unlikely to be a problem in any real situation as just booting
582# up scons takes more than that time.
583# Renamed to `content-timestamp` in SCons >= 4.2, keeping MD5 for compat.
584env.Decider("MD5-timestamp")
585
586# SCons speed optimization controlled by the `fast_unsafe` option, which provide
587# more than 10 s speed up for incremental rebuilds.
588# Unsafe as they reduce the certainty of rebuilding all changed files.
589# If you use it and run into corrupted incremental builds, try to turn it off.
590# Ref: https://github.com/SCons/scons/wiki/GoFastButton
591if env["fast_unsafe"]:
592 env.SetOption("implicit_cache", 1)
593 env.SetOption("max_drift", 60)
594
595if env["use_precise_math_checks"]:
596 env.Append(CPPDEFINES=["PRECISE_MATH_CHECKS"])
597
598if env.editor_build:
599 if env["engine_update_check"]:
600 env.Append(CPPDEFINES=["ENGINE_UPDATE_CHECK_ENABLED"])
601
602 if not env.File("#main/splash_editor.png").exists():
603 # Force disabling editor splash if missing.
604 env["no_editor_splash"] = True
605 if env["no_editor_splash"]:
606 env.Append(CPPDEFINES=["NO_EDITOR_SPLASH"])
607
608if not env["deprecated"]:
609 env.Append(CPPDEFINES=["DISABLE_DEPRECATED"])
610
611if env["precision"] == "double":
612 env.Append(CPPDEFINES=["REAL_T_IS_DOUBLE"])
613
614# Library Support
615if env["library_type"] != "executable":
616 if "library" not in env.get("supported", []):
617 print_error(f"Library builds unsupported for {env['platform']}")
618 Exit(255)
619 env.Append(CPPDEFINES=["LIBGODOT_ENABLED"])
620
621# Default num_jobs to local cpu count if not user specified.
622# SCons has a peculiarity where user-specified options won't be overridden
623# by SetOption, so we can rely on this to know if we should use our default.
624initial_num_jobs = env.GetOption("num_jobs")
625altered_num_jobs = initial_num_jobs + 1
626env.SetOption("num_jobs", altered_num_jobs)
627if env.GetOption("num_jobs") == altered_num_jobs:
628 num_jobs = env.get("num_jobs", "")
629 if str(num_jobs).isdigit() and int(num_jobs) > 0:
630 env.SetOption("num_jobs", num_jobs)
631 else:
632 cpu_count = os.cpu_count()
633 if cpu_count is None:
634 print_warning(
635 "Couldn't auto-detect CPU count to configure build parallelism. Specify it with the `-j` or `num_jobs` arguments."
636 )
637 else:
638 safer_cpu_count = cpu_count if cpu_count <= 4 else cpu_count - 1
639 print(
640 f"Auto-detected {cpu_count} CPU cores available for build parallelism. Using {safer_cpu_count} cores by default. "
641 "You can override it with the `-j` or `num_jobs` arguments."
642 )
643 env.SetOption("num_jobs", safer_cpu_count)
644
645env.extra_suffix = ""
646
647if env["extra_suffix"] != "":
648 env.extra_suffix += "." + env["extra_suffix"]
649
650# Environment flags
651env.Append(CPPDEFINES=env.get("cppdefines", "").split())
652env.Append(CCFLAGS=env.get("ccflags", "").split())
653env.Append(CXXFLAGS=env.get("cxxflags", "").split())
654env.Append(CFLAGS=env.get("cflags", "").split())
655env.Append(LINKFLAGS=env.get("linkflags", "").split())
656env.Append(ASFLAGS=env.get("asflags", "").split())
657env.Append(ARFLAGS=env.get("arflags", "").split())
658env.Append(RCFLAGS=env.get("rcflags", "").split())
659
660# Feature build profile
661env.disabled_classes = []
662if env["build_profile"] != "":
663 print(f'Using feature build profile: "{env["build_profile"]}"')
664 import json
665
666 try:
667 ft = json.load(open(env["build_profile"], "r", encoding="utf-8"))
668 if "disabled_classes" in ft:
669 env.disabled_classes = ft["disabled_classes"]
670 if "disabled_build_options" in ft:
671 dbo = ft["disabled_build_options"]
672 for c in dbo:
673 env[c] = dbo[c]
674 except json.JSONDecodeError as err:
675 print_error(f'Failed to open feature build profile due to JSON decoding error: "{env["build_profile"]}"\n{err}')
676 Exit(255)
677 except FileNotFoundError:
678 print_error(f'Feature build profile not found at: "{env["build_profile"]}"')
679 Exit(255)
680
681# 'dev_mode' and 'production' are aliases to set default options if they haven't been
682# set manually by the user.
683if env["dev_mode"]:
684 env["verbose"] = methods.get_cmdline_bool("verbose", True)
685 env["warnings"] = ARGUMENTS.get("warnings", "extra")
686 env["werror"] = methods.get_cmdline_bool("werror", True)
687 env["tests"] = methods.get_cmdline_bool("tests", True)
688 env["strict_checks"] = methods.get_cmdline_bool("strict_checks", True)
689if env["production"]:
690 env["use_static_cpp"] = methods.get_cmdline_bool("use_static_cpp", True)
691 env["debug_symbols"] = methods.get_cmdline_bool("debug_symbols", False)
692 if env["platform"] == "android":
693 env["swappy"] = methods.get_cmdline_bool("swappy", True)
694 # LTO "auto" means we handle the preferred option in each platform detect.py.
695 env["lto"] = ARGUMENTS.get("lto", "auto")
696
697if env["strict_checks"]:
698 env.Append(CPPDEFINES=["STRICT_CHECKS"])
699
700# Run SCU file generation script if in a SCU build.
701if env["scu_build"]:
702 env.Append(CPPDEFINES=["SCU_BUILD_ENABLED"])
703 max_includes_per_scu = 8
704 if env.dev_build:
705 max_includes_per_scu = 1024
706
707 read_scu_limit = int(env["scu_limit"])
708 read_scu_limit = max(0, min(read_scu_limit, 1024))
709 if read_scu_limit != 0:
710 max_includes_per_scu = read_scu_limit
711
712 methods.set_scu_folders(scu_builders.generate_scu_files(max_includes_per_scu))
713
714if env["rendering_device"]:
715 if env["platform"] == "web":
716 # Not available in the web platform.
717 env["rendering_device"] = False
718 else:
719 env.Append(CPPDEFINES=["RD_ENABLED"])
720 if env["forward_mobile_renderer"]:
721 env.Append(CPPDEFINES=["MOBILE_RD_ENABLED"])
722 if env["forward_plus_renderer"]:
723 env.Append(CPPDEFINES=["FORWARD_RD_ENABLED"])
724# These need to be set before platform detection.
725if not env["rendering_device"] or not (env["forward_mobile_renderer"] or env["forward_plus_renderer"]):
726 env["d3d12"] = False
727 env["metal"] = False
728 env["vulkan"] = False
729
730# Must happen after the flags' definition, as configure is when most flags
731# are actually handled to change compile options, etc.
732detect.configure(env)
733
734platform_string = env["platform"]
735if env.get("simulator"):
736 platform_string += " (simulator)"
737print(f'Building for platform "{platform_string}", architecture "{env["arch"]}", target "{env["target"]}".')
738
739if env.dev_build:
740 print_info("Developer build, with debug optimization level and debug symbols (unless overridden).")
741
742# Enforce our minimal compiler version requirements
743cc_version = methods.get_compiler_version(env)
744cc_version_major = cc_version["major"]
745cc_version_minor = cc_version["minor"]
746cc_version_metadata1 = cc_version["metadata1"]
747
748if cc_version_major == -1:
749 print_warning(
750 "Couldn't detect compiler version, skipping version checks. Build may fail if the compiler doesn't support C++17 fully."
751 )
752elif methods.using_gcc(env):
753 if cc_version_major < 11:
754 print_error(
755 f'Detected GCC version {cc_version_major} while Godot requires GCC 11 or newer. Use a newer GCC version, or Clang 9 or newer by passing "use_llvm=yes" to the SCons command line.'
756 )
757 Exit(255)
758 if cc_version_metadata1 == "win32":
759 print_error(
760 'Detected mingw version is not using posix threads. Only posix version of mingw is supported. Use "update-alternatives --config x86_64-w64-mingw32-g++" to switch to posix threads.'
761 )
762 Exit(255)
763elif methods.using_clang(env):
764 # Apple LLVM versions differ from upstream LLVM version \o/, compare
765 # in https://en.wikipedia.org/wiki/Xcode#Toolchain_versions
766 if methods.is_apple_clang(env):
767 if cc_version_major < 16:
768 print_error(
769 f"Detected Apple Clang version {cc_version_major} while Godot requires Apple Clang 16 (Xcode 16) or newer."
770 )
771 Exit(255)
772 else:
773 if cc_version_major < 9:
774 print_error(
775 f"Detected Clang version {cc_version_major} while Godot requires Clang 9 or newer. Use a newer Clang version, or GCC 11 or newer."
776 )
777 Exit(255)
778 elif env["debug_paths_relative"] and cc_version_major < 10:
779 print_warning("Clang < 10 doesn't support -ffile-prefix-map, disabling `debug_paths_relative` option.")
780 env["debug_paths_relative"] = False
781
782elif env.msvc:
783 if cc_version_major == 16 and cc_version_minor < 11:
784 # Ensure latest minor build of Visual Studio 2019.
785 # https://github.com/godotengine/godot/pull/94995#issuecomment-2336464574
786 print_error(
787 "Detected Visual Studio 2019 version older than 16.11, which has bugs "
788 "when compiling Godot. Use a newer VS2019 version, or VS2022+."
789 )
790 Exit(255)
791 elif cc_version_major < 16:
792 print_error(
793 "Detected Visual Studio 2017 or earlier, which is unsupported in Godot. "
794 "Supported versions are Visual Studio 2019 and later."
795 )
796 Exit(255)
797
798# Set x86 CPU instruction sets to use by the compiler's autovectorization.
799if env["arch"] == "x86_64":
800 # On 64-bit x86, enable SSE 4.2 and prior instruction sets (SSE3/SSSE3/SSE4/SSE4.1) to improve performance.
801 # This is supported on most CPUs released after 2009-2011 (Intel Nehalem, AMD Bulldozer).
802 # AVX and AVX2 aren't enabled because they aren't available on more recent low-end Intel CPUs.
803 if env.msvc and not methods.using_clang(env):
804 # https://stackoverflow.com/questions/64053597/how-do-i-enable-sse4-1-and-sse3-but-not-avx-in-msvc/69328426
805 env.Append(CCFLAGS=["/d2archSSE42"])
806 else:
807 # `-msse2` is implied when compiling for x86_64.
808 env.Append(CCFLAGS=["-msse4.2", "-mpopcnt"])
809elif env["arch"] == "x86_32":
810 # Be more conservative with instruction sets on 32-bit x86 to improve compatibility.
811 # SSE and SSE2 are present on all CPUs that support 64-bit, even if running a 32-bit OS.
812 if env.msvc and not methods.using_clang(env):
813 env.Append(CCFLAGS=["/arch:SSE2"])
814 else:
815 # Use `-mfpmath=sse` to use SSE for floating-point math, which is more stable than x87.
816 # `-mstackrealign` is needed for it to work.
817 env.Append(CCFLAGS=["-msse2", "-mfpmath=sse", "-mstackrealign"])
818
819# Explicitly specify colored output.
820if methods.using_gcc(env):
821 env.AppendUnique(CCFLAGS=["-fdiagnostics-color" if is_stderr_color() else "-fno-diagnostics-color"])
822elif methods.using_clang(env) or methods.using_emcc(env):
823 env.AppendUnique(CCFLAGS=["-fcolor-diagnostics" if is_stderr_color() else "-fno-color-diagnostics"])
824 if sys.platform == "win32":
825 env.AppendUnique(CCFLAGS=["-fansi-escape-codes"])
826
827# Attempt to reduce transitive includes.
828if env["limit_transitive_includes"]:
829 if not env.msvc:
830 # FIXME: This define only affects `libcpp`, but lack of guaranteed, granular detection means
831 # we're better off applying it universally.
832 env.AppendUnique(CPPDEFINES=["_LIBCPP_REMOVE_TRANSITIVE_INCLUDES"])
833
834# Set optimize and debug_symbols flags.
835# "custom" means do nothing and let users set their own optimization flags.
836# Needs to happen after configure to have `env.msvc` defined.
837env.AppendUnique(CCFLAGS=["$OPTIMIZELEVEL"])
838if env.msvc:
839 if env["debug_symbols"]:
840 env.AppendUnique(CCFLAGS=["/Zi", "/FS"])
841 env.AppendUnique(LINKFLAGS=["/DEBUG:FULL"])
842 else:
843 env.AppendUnique(LINKFLAGS=["/DEBUG:NONE"])
844
845 if env["optimize"].startswith("speed"):
846 env["OPTIMIZELEVEL"] = "/O2"
847 env.AppendUnique(LINKFLAGS=["/OPT:REF"])
848 if env["optimize"] == "speed_trace":
849 env.AppendUnique(LINKFLAGS=["/OPT:NOICF"])
850 elif env["optimize"].startswith("size"):
851 env["OPTIMIZELEVEL"] = "/O1"
852 env.AppendUnique(LINKFLAGS=["/OPT:REF"])
853 if env["optimize"] == "size_extra":
854 env.AppendUnique(CPPDEFINES=["SIZE_EXTRA"])
855 elif env["optimize"] == "debug" or env["optimize"] == "none":
856 env["OPTIMIZELEVEL"] = "/Od"
857else:
858 if env["debug_symbols"]:
859 if env["platform"] == "windows":
860 if methods.using_clang(env):
861 env.AppendUnique(CCFLAGS=["-gdwarf-4"]) # clang dwarf-5 symbols are broken on Windows.
862 else:
863 env.AppendUnique(CCFLAGS=["-gdwarf-5"]) # For gcc, only dwarf-5 symbols seem usable by libbacktrace.
864 else:
865 # Adding dwarf-4 explicitly makes stacktraces work with clang builds,
866 # otherwise addr2line doesn't understand them
867 env.AppendUnique(CCFLAGS=["-gdwarf-4"])
868 if methods.using_emcc(env):
869 # Emscripten only produces dwarf symbols when using "-g3".
870 env.AppendUnique(CCFLAGS=["-g3"])
871 # Emscripten linker needs debug symbols options too.
872 env.AppendUnique(LINKFLAGS=["-gdwarf-4"])
873 env.AppendUnique(LINKFLAGS=["-g3"])
874 elif env.dev_build:
875 env.AppendUnique(CCFLAGS=["-g3"])
876 else:
877 env.AppendUnique(CCFLAGS=["-g2"])
878 if env["debug_paths_relative"]:
879 # Remap absolute paths to relative paths for debug symbols.
880 project_path = Dir("#").abspath
881 env.AppendUnique(CCFLAGS=[f"-ffile-prefix-map={project_path}=."])
882 env.AppendUnique(LINKFLAGS=[f"-ffile-prefix-map={project_path}=."])
883 else:
884 if methods.is_apple_clang(env):
885 # Apple Clang, its linker doesn't like -s.
886 env.AppendUnique(LINKFLAGS=["-Wl,-S", "-Wl,-x", "-Wl,-dead_strip"])
887 elif methods.using_emcc(env):
888 # Emscripten can use separate -s for build options, so pass the alias directly to the linker.
889 env.AppendUnique(LINKFLAGS=["-Wl,-s"])
890 else:
891 env.AppendUnique(LINKFLAGS=["-s"])
892
893 # Linker needs optimization flags too, at least for Emscripten.
894 # For other toolchains, this _may_ be useful for LTO too to disambiguate.
895 env.AppendUnique(LINKFLAGS=["$OPTIMIZELEVEL"])
896
897 if env["optimize"] == "speed":
898 env["OPTIMIZELEVEL"] = "-O3"
899 # `-O2` is friendlier to debuggers than `-O3`, leading to better crash backtraces.
900 elif env["optimize"] == "speed_trace":
901 env["OPTIMIZELEVEL"] = "-O2"
902 elif env["optimize"].startswith("size"):
903 env["OPTIMIZELEVEL"] = "-Os"
904 if env["optimize"] == "size_extra":
905 env.AppendUnique(CPPDEFINES=["SIZE_EXTRA"])
906 elif env["optimize"] == "debug":
907 env["OPTIMIZELEVEL"] = "-Og"
908 elif env["optimize"] == "none":
909 env["OPTIMIZELEVEL"] = "-O0"
910
911# Needs to happen after configure to handle "auto".
912if env["lto"] != "none":
913 print("Using LTO: " + env["lto"])
914
915# Set our C and C++ standard requirements.
916# C++17 is required as we need guaranteed copy elision as per GH-36436.
917# Prepending to make it possible to override.
918# This needs to come after `configure`, otherwise we don't have env.msvc.
919if not env.msvc:
920 # Specifying GNU extensions support explicitly, which are supported by
921 # both GCC and Clang. Both currently default to gnu17 and gnu++17.
922 env.Prepend(CFLAGS=["-std=gnu17"])
923 env.Prepend(CXXFLAGS=["-std=gnu++17"])
924else:
925 # MSVC started offering C standard support with Visual Studio 2019 16.8, which covers all
926 # of our supported Visual Studio versions.
927 env.Prepend(CFLAGS=["/std:c17"])
928 env.Prepend(CXXFLAGS=["/std:c++17"])
929 # MSVC is non-conforming with the C++ standard by default, so we enable more conformance.
930 # Note that this is still not complete conformance, as certain Windows-related headers
931 # don't compile under complete conformance.
932 env.Prepend(CCFLAGS=["/permissive-"])
933 # Allow use of `__cplusplus` macro to determine C++ standard universally.
934 env.Prepend(CXXFLAGS=["/Zc:__cplusplus"])
935
936# Disable exception handling. Godot doesn't use exceptions anywhere, and this
937# saves around 20% of binary size and very significant build time (GH-80513).
938if env["disable_exceptions"]:
939 if env.msvc:
940 env.Append(CPPDEFINES=[("_HAS_EXCEPTIONS", 0)])
941 else:
942 env.Append(CXXFLAGS=["-fno-exceptions"])
943elif env.msvc:
944 env.Append(CXXFLAGS=["/EHsc"])
945
946# Configure compiler warnings
947env.AppendUnique(CCFLAGS=["$WARNLEVEL"])
948if env.msvc and not methods.using_clang(env): # MSVC
949 # Disable warnings which we don't plan to fix.
950 disabled_warnings = [
951 "/wd4100", # C4100 (unreferenced formal parameter): Doesn't play nice with polymorphism.
952 "/wd4127", # C4127 (conditional expression is constant)
953 "/wd4201", # C4201 (non-standard nameless struct/union): Only relevant for C89.
954 "/wd4244", # C4244 C4245 C4267 (narrowing conversions): Unavoidable at this scale.
955 "/wd4245",
956 "/wd4267",
957 "/wd4305", # C4305 (truncation): double to float or real_t, too hard to avoid.
958 "/wd4324", # C4820 (structure was padded due to alignment specifier)
959 "/wd4514", # C4514 (unreferenced inline function has been removed)
960 "/wd4714", # C4714 (function marked as __forceinline not inlined)
961 "/wd4820", # C4820 (padding added after construct)
962 ]
963
964 if env["warnings"] == "extra":
965 env["WARNLEVEL"] = "/W4"
966 env.AppendUnique(CCFLAGS=disabled_warnings)
967 elif env["warnings"] == "all":
968 env["WARNLEVEL"] = "/W3"
969 # C4458 is like -Wshadow. Part of /W4 but let's apply it for the default /W3 too.
970 env.AppendUnique(CCFLAGS=["/w34458"] + disabled_warnings)
971 elif env["warnings"] == "moderate":
972 env["WARNLEVEL"] = "/W2"
973 env.AppendUnique(CCFLAGS=disabled_warnings)
974 else: # 'no'
975 env["WARNLEVEL"] = "/w"
976 # C4267 is particularly finicky & needs to be explicitly disabled.
977 env.AppendUnique(CCFLAGS=["/wd4267"])
978
979 if env["werror"]:
980 env.AppendUnique(CCFLAGS=["/WX"])
981 env.AppendUnique(LINKFLAGS=["/WX"])
982
983else: # GCC, Clang
984 common_warnings = []
985 if methods.using_gcc(env):
986 common_warnings += ["-Wshadow", "-Wno-misleading-indentation"]
987 if cc_version_major < 11:
988 # Regression in GCC 9/10, spams so much in our variadic templates
989 # that we need to outright disable it.
990 common_warnings += ["-Wno-type-limits"]
991 if cc_version_major == 12:
992 # Regression in GCC 12, false positives in our error macros, see GH-58747.
993 common_warnings += ["-Wno-return-type"]
994 if cc_version_major >= 11:
995 common_warnings += ["-Wenum-conversion"]
996 if cc_version_major >= 16:
997 # GCC 16 flags type-incompleteness assertions on their intended behavior, see GH-119269.
998 env.AppendUnique(CXXFLAGS=["-Wno-sfinae-incomplete"])
999 elif methods.using_clang(env) or methods.using_emcc(env):
1000 common_warnings += ["-Wshadow-field-in-constructor", "-Wshadow-uncaptured-local"]
1001 # We often implement `operator<` for structs of pointers as a requirement
1002 # for putting them in `Set` or `Map`. We don't mind about unreliable ordering.
1003 common_warnings += ["-Wno-ordered-compare-function-pointers"]
1004 common_warnings += ["-Wenum-conversion"]
1005
1006 # clang-cl will interpret `-Wall` as `-Weverything`, workaround with compatibility cast.
1007 env["WARNLEVEL"] = "-Wall" if not env.msvc else "-W3"
1008
1009 if env["warnings"] == "extra":
1010 env.AppendUnique(CCFLAGS=["-Wextra", "-Wwrite-strings", "-Wno-unused-parameter"] + common_warnings)
1011 env.AppendUnique(CXXFLAGS=["-Wctor-dtor-privacy", "-Wnon-virtual-dtor"])
1012 if methods.using_gcc(env):
1013 env.AppendUnique(
1014 CCFLAGS=[
1015 "-Walloc-zero",
1016 "-Wduplicated-branches",
1017 "-Wduplicated-cond",
1018 "-Wstringop-overflow=4",
1019 ]
1020 )
1021 env.AppendUnique(CXXFLAGS=["-Wplacement-new=1", "-Wvirtual-inheritance"])
1022 # Need to fix a warning with AudioServer lambdas before enabling.
1023 # if cc_version_major != 9: # GCC 9 had a regression (GH-36325).
1024 # env.Append(CXXFLAGS=["-Wnoexcept"])
1025 if cc_version_major >= 9:
1026 env.AppendUnique(CCFLAGS=["-Wattribute-alias=2"])
1027 if cc_version_major >= 11: # Broke on MethodBind templates before GCC 11.
1028 env.AppendUnique(CCFLAGS=["-Wlogical-op"])
1029 elif methods.using_clang(env) or methods.using_emcc(env):
1030 env.AppendUnique(CCFLAGS=["-Wimplicit-fallthrough"])
1031 elif env["warnings"] == "all":
1032 env.AppendUnique(CCFLAGS=common_warnings)
1033 elif env["warnings"] == "moderate":
1034 env.AppendUnique(CCFLAGS=["-Wno-unused"] + common_warnings)
1035 else: # 'no'
1036 env["WARNLEVEL"] = "-w"
1037
1038 if env["werror"]:
1039 env.AppendUnique(CCFLAGS=["-Werror"])
1040 if env["platform"] != "macos":
1041 env.AppendUnique(LINKFLAGS=["-Wl,--fatal-warnings"])
1042 elif env["arch"] != "x86_64":
1043 # Disabled for x86-64 macOS build due to MoltenVK min. target version mismatch.
1044 env.AppendUnique(LINKFLAGS=["-Wl,-fatal_warnings"])
1045
1046if hasattr(detect, "get_program_suffix"):
1047 suffix = "." + detect.get_program_suffix()
1048else:
1049 suffix = "." + env["platform"]
1050
1051suffix += "." + env["target"]
1052if env.dev_build:
1053 suffix += ".dev"
1054
1055if env["precision"] == "double":
1056 suffix += ".double"
1057
1058suffix += "." + env["arch"]
1059
1060if not env["threads"]:
1061 suffix += ".nothreads"
1062
1063suffix += env.extra_suffix
1064
1065sys.path.remove(tmppath)
1066sys.modules.pop("detect")
1067
1068if env.editor_build:
1069 unsupported_opts = []
1070 for disable_opt in [
1071 "disable_2d",
1072 "disable_3d",
1073 "disable_advanced_gui",
1074 "disable_physics_2d",
1075 "disable_physics_3d",
1076 "disable_navigation_2d",
1077 "disable_navigation_3d",
1078 ]:
1079 if env[disable_opt]:
1080 unsupported_opts.append(disable_opt)
1081 if unsupported_opts != []:
1082 print_error(
1083 "The following build option(s) cannot be used for editor builds, but only for export template builds: {}.".format(
1084 ", ".join(unsupported_opts)
1085 )
1086 )
1087 Exit(255)
1088
1089if env["disable_2d"]:
1090 env.Append(CPPDEFINES=["_2D_DISABLED"])
1091 env["disable_navigation_2d"] = True
1092 env["disable_physics_2d"] = True
1093 env["tests"] = False
1094if env["disable_3d"]:
1095 env.Append(CPPDEFINES=["_3D_DISABLED"])
1096 env["disable_navigation_3d"] = True
1097 env["disable_physics_3d"] = True
1098 env["disable_xr"] = True
1099if env["disable_advanced_gui"]:
1100 env.Append(CPPDEFINES=["ADVANCED_GUI_DISABLED"])
1101if env["disable_physics_2d"]:
1102 env.Append(CPPDEFINES=["PHYSICS_2D_DISABLED"])
1103if env["disable_physics_3d"]:
1104 env.Append(CPPDEFINES=["PHYSICS_3D_DISABLED"])
1105if env["disable_navigation_2d"]:
1106 env.Append(CPPDEFINES=["NAVIGATION_2D_DISABLED"])
1107if env["disable_navigation_3d"]:
1108 env.Append(CPPDEFINES=["NAVIGATION_3D_DISABLED"])
1109if env["disable_xr"]:
1110 env.Append(CPPDEFINES=["XR_DISABLED"])
1111if env["minizip"]:
1112 env.Append(CPPDEFINES=["MINIZIP_ENABLED"])
1113if env["brotli"]:
1114 env.Append(CPPDEFINES=["BROTLI_ENABLED"])
1115
1116if not env["disable_overrides"]:
1117 env.Append(CPPDEFINES=["OVERRIDE_ENABLED"])
1118
1119if env.editor_build or not env["disable_path_overrides"]:
1120 env.Append(CPPDEFINES=["OVERRIDE_PATH_ENABLED"])
1121
1122if not env["verbose"]:
1123 methods.no_verbose(env)
1124
1125modules_enabled = OrderedDict()
1126env.module_dependencies = {}
1127env.module_icons_paths = []
1128env.doc_class_path = platform_doc_class_path
1129
1130for name, path in modules_detected.items():
1131 if not env[f"module_{name}_enabled"]:
1132 continue
1133 sys.path.insert(0, path)
1134 env.current_module = name
1135 import config
1136
1137 if config.can_build(env, env["platform"]):
1138 # Disable it if a required dependency is missing.
1139 if not env.module_check_dependencies(name):
1140 continue
1141
1142 config.configure(env)
1143 # Get doc classes paths (if present)
1144 try:
1145 doc_classes = config.get_doc_classes()
1146 doc_path = config.get_doc_path()
1147 for c in doc_classes:
1148 env.doc_class_path[c] = path + "/" + doc_path
1149 except Exception:
1150 pass
1151 # Get icon paths (if present)
1152 try:
1153 icons_path = config.get_icons_path()
1154 env.module_icons_paths.append(path + "/" + icons_path)
1155 except Exception:
1156 # Default path for module icons
1157 env.module_icons_paths.append(path + "/" + "icons")
1158 modules_enabled[name] = path
1159
1160 sys.path.remove(path)
1161 sys.modules.pop("config")
1162
1163env.module_list = modules_enabled
1164methods.sort_module_list(env)
1165
1166if env.editor_build:
1167 # Add editor-specific dependencies to the dependency graph.
1168 env.module_add_dependencies("editor", ["freetype", "svg"])
1169
1170 # And check if they are met.
1171 if not env.module_check_dependencies("editor"):
1172 print_error("Not all modules required by editor builds are enabled.")
1173 Exit(255)
1174
1175env["PROGSUFFIX_WRAP"] = suffix + env.module_version_string + ".console" + env["PROGSUFFIX"]
1176env["PROGSUFFIX"] = suffix + env.module_version_string + env["PROGSUFFIX"]
1177env["OBJSUFFIX"] = suffix + env["OBJSUFFIX"]
1178# (SH)LIBSUFFIX will be used for our own built libraries
1179# LIBSUFFIXES contains LIBSUFFIX and SHLIBSUFFIX by default,
1180# so we need to append the default suffixes to keep the ability
1181# to link against thirdparty libraries (.a, .so, .lib, etc.).
1182if os.name == "nt":
1183 # On Windows, only static libraries and import libraries can be
1184 # statically linked - both using .lib extension
1185 env["LIBSUFFIXES"] += [env["LIBSUFFIX"]]
1186else:
1187 env["LIBSUFFIXES"] += [env["LIBSUFFIX"], env["SHLIBSUFFIX"]]
1188env["LIBSUFFIX"] = suffix + env["LIBSUFFIX"]
1189env["SHLIBSUFFIX"] = suffix + env["SHLIBSUFFIX"]
1190
1191env["OBJPREFIX"] = env["object_prefix"]
1192env["SHOBJPREFIX"] = env["object_prefix"]
1193
1194GLSL_BUILDERS = {
1195 "RD_GLSL": env.Builder(
1196 action=env.Run(glsl_builders.build_rd_headers),
1197 suffix="glsl.gen.h",
1198 src_suffix=".glsl",
1199 ),
1200 "GLSL_HEADER": env.Builder(
1201 action=env.Run(glsl_builders.build_raw_headers),
1202 suffix="glsl.gen.h",
1203 src_suffix=".glsl",
1204 ),
1205 "GLES3_GLSL": env.Builder(
1206 action=env.Run(gles3_builders.build_gles3_headers),
1207 suffix="glsl.gen.h",
1208 src_suffix=".glsl",
1209 ),
1210}
1211env.Append(BUILDERS=GLSL_BUILDERS)
1212
1213if env["compiledb"]:
1214 env.Tool("compilation_db")
1215 env.NoCache(env.CompilationDatabase())
1216 if not env["verbose"]:
1217 env["COMPILATIONDB_COMSTR"] = "$GENCOMSTR"
1218
1219if env["ninja"]:
1220 SetOption("experimental", "ninja")
1221 env["NINJA_FILE_NAME"] = env["ninja_file"]
1222 env["NINJA_DISABLE_AUTO_RUN"] = not env["ninja_auto_run"]
1223 env.Tool("ninja", env["ninja_file"])
1224
1225# Threads
1226if env["threads"]:
1227 env.Append(CPPDEFINES=["THREADS_ENABLED"])
1228
1229# Ensure build objects are put in their own folder if `redirect_build_objects` is enabled.
1230env.Prepend(LIBEMITTER=[methods.redirect_emitter])
1231env.Prepend(SHLIBEMITTER=[methods.redirect_emitter])
1232for key in (emitters := env.StaticObject.builder.emitter):
1233 emitters[key] = ListEmitter([methods.redirect_emitter] + env.Flatten(emitters[key]))
1234for key in (emitters := env.SharedObject.builder.emitter):
1235 emitters[key] = ListEmitter([methods.redirect_emitter] + env.Flatten(emitters[key]))
1236
1237# Prepend compiler launchers
1238if "c_compiler_launcher" in env:
1239 env["CC"] = " ".join([env["c_compiler_launcher"], env["CC"]])
1240
1241if "cpp_compiler_launcher" in env:
1242 env["CXX"] = " ".join([env["cpp_compiler_launcher"], env["CXX"]])
1243
1244# Build subdirs, the build order is dependent on link order.
1245Export("env")
1246
1247SConscript("core/SCsub")
1248SConscript("servers/SCsub")
1249SConscript("scene/SCsub")
1250if env.editor_build:
1251 SConscript("editor/SCsub")
1252SConscript("drivers/SCsub")
1253
1254SConscript("platform/SCsub")
1255SConscript("modules/SCsub")
1256if env["tests"]:
1257 SConscript("tests/SCsub")
1258SConscript("main/SCsub")
1259
1260SConscript("platform/" + env["platform"] + "/SCsub") # Build selected platform.
1261
1262# Microsoft Visual Studio Project Generation
1263if env["vsproj"]:
1264 methods.generate_cpp_hint_file("cpp.hint")
1265 env["CPPPATH"] = [Dir(path) for path in env["CPPPATH"]]
1266 methods.generate_vs_project(env, ARGUMENTS, env["vsproj_name"])
1267
1268# Miscellaneous & post-build methods.
1269if not env.GetOption("clean") and not env.GetOption("help"):
1270 if env["compiledb"] and env["compiledb_gen_only"]:
1271 from SCons.Tool.compilation_db import write_compilation_db
1272
1273 write_compilation_db([env.File("compile_commands.json")], [], env)
1274 env.Exit()
1275
1276 methods.dump(env)
1277 methods.show_progress(env)
1278 methods.prepare_purge(env)
1279 methods.prepare_timer()