SConstruct 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118
  1. #!/usr/bin/env python
  2. from misc.utility.scons_hints import *
  3. EnsureSConsVersion(4, 0)
  4. EnsurePythonVersion(3, 8)
  5. # System
  6. import atexit
  7. import glob
  8. import os
  9. import pickle
  10. import sys
  11. import time
  12. from collections import OrderedDict
  13. from importlib.util import module_from_spec, spec_from_file_location
  14. from types import ModuleType
  15. from SCons import __version__ as scons_raw_version
  16. # Explicitly resolve the helper modules, this is done to avoid clash with
  17. # modules of the same name that might be randomly added (e.g. someone adding
  18. # an `editor.py` file at the root of the module creates a clash with the editor
  19. # folder when doing `import editor.template_builder`)
  20. def _helper_module(name, path):
  21. spec = spec_from_file_location(name, path)
  22. module = module_from_spec(spec)
  23. spec.loader.exec_module(module)
  24. sys.modules[name] = module
  25. # Ensure the module's parents are in loaded to avoid loading the wrong parent
  26. # when doing "import foo.bar" while only "foo.bar" as declared as helper module
  27. child_module = module
  28. parent_name = name
  29. while True:
  30. try:
  31. parent_name, child_name = parent_name.rsplit(".", 1)
  32. except ValueError:
  33. break
  34. try:
  35. parent_module = sys.modules[parent_name]
  36. except KeyError:
  37. parent_module = ModuleType(parent_name)
  38. sys.modules[parent_name] = parent_module
  39. setattr(parent_module, child_name, child_module)
  40. _helper_module("gles3_builders", "gles3_builders.py")
  41. _helper_module("glsl_builders", "glsl_builders.py")
  42. _helper_module("methods", "methods.py")
  43. _helper_module("platform_methods", "platform_methods.py")
  44. _helper_module("version", "version.py")
  45. _helper_module("core.core_builders", "core/core_builders.py")
  46. _helper_module("main.main_builders", "main/main_builders.py")
  47. # Local
  48. import gles3_builders
  49. import glsl_builders
  50. import methods
  51. import scu_builders
  52. from methods import print_error, print_warning
  53. from platform_methods import architecture_aliases, architectures, compatibility_platform_aliases
  54. if ARGUMENTS.get("target", "editor") == "editor":
  55. _helper_module("editor.editor_builders", "editor/editor_builders.py")
  56. _helper_module("editor.template_builders", "editor/template_builders.py")
  57. # Enable ANSI escape code support on Windows 10 and later (for colored console output).
  58. # <https://github.com/python/cpython/issues/73245>
  59. if sys.stdout.isatty() and sys.platform == "win32":
  60. try:
  61. from ctypes import WinError, byref, windll # type: ignore
  62. from ctypes.wintypes import DWORD # type: ignore
  63. stdout_handle = windll.kernel32.GetStdHandle(DWORD(-11))
  64. mode = DWORD(0)
  65. if not windll.kernel32.GetConsoleMode(stdout_handle, byref(mode)):
  66. raise WinError()
  67. mode = DWORD(mode.value | 4)
  68. if not windll.kernel32.SetConsoleMode(stdout_handle, mode):
  69. raise WinError()
  70. except Exception as e:
  71. methods._colorize = False
  72. print_error(f"Failed to enable ANSI escape code support, disabling color output.\n{e}")
  73. # Scan possible build platforms
  74. platform_list = [] # list of platforms
  75. platform_opts = {} # options for each platform
  76. platform_flags = {} # flags for each platform
  77. platform_doc_class_path = {}
  78. platform_exporters = []
  79. platform_apis = []
  80. time_at_start = time.time()
  81. for x in sorted(glob.glob("platform/*")):
  82. if not os.path.isdir(x) or not os.path.exists(x + "/detect.py"):
  83. continue
  84. tmppath = "./" + x
  85. sys.path.insert(0, tmppath)
  86. import detect
  87. # Get doc classes paths (if present)
  88. try:
  89. doc_classes = detect.get_doc_classes()
  90. doc_path = detect.get_doc_path()
  91. for c in doc_classes:
  92. platform_doc_class_path[c] = x.replace("\\", "/") + "/" + doc_path
  93. except Exception:
  94. pass
  95. platform_name = x[9:]
  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. custom_tools = ["default"]
  111. platform_arg = ARGUMENTS.get("platform", ARGUMENTS.get("p", False))
  112. if platform_arg == "android":
  113. custom_tools = ["clang", "clang++", "as", "ar", "link"]
  114. elif platform_arg == "web":
  115. # Use generic POSIX build toolchain for Emscripten.
  116. custom_tools = ["cc", "c++", "ar", "link", "textfile", "zip"]
  117. elif os.name == "nt" and methods.get_cmdline_bool("use_mingw", False):
  118. custom_tools = ["mingw"]
  119. # We let SCons build its default ENV as it includes OS-specific things which we don't
  120. # want to have to pull in manually.
  121. # Then we prepend PATH to make it take precedence, while preserving SCons' own entries.
  122. env = Environment(tools=custom_tools)
  123. env.PrependENVPath("PATH", os.getenv("PATH"))
  124. env.PrependENVPath("PKG_CONFIG_PATH", os.getenv("PKG_CONFIG_PATH"))
  125. if "TERM" in os.environ: # Used for colored output.
  126. env["ENV"]["TERM"] = os.environ["TERM"]
  127. env.disabled_modules = set()
  128. env.module_version_string = ""
  129. env.msvc = False
  130. env.scons_version = env._get_major_minor_revision(scons_raw_version)
  131. env.__class__.add_module_version_string = methods.add_module_version_string
  132. env.__class__.add_source_files = methods.add_source_files
  133. env.__class__.use_windows_spawn_fix = methods.use_windows_spawn_fix
  134. env.__class__.add_shared_library = methods.add_shared_library
  135. env.__class__.add_library = methods.add_library
  136. env.__class__.add_program = methods.add_program
  137. env.__class__.CommandNoCache = methods.CommandNoCache
  138. env.__class__.Run = methods.Run
  139. env.__class__.disable_warnings = methods.disable_warnings
  140. env.__class__.force_optimization_on_debug = methods.force_optimization_on_debug
  141. env.__class__.module_add_dependencies = methods.module_add_dependencies
  142. env.__class__.module_check_dependencies = methods.module_check_dependencies
  143. env["x86_libtheora_opt_gcc"] = False
  144. env["x86_libtheora_opt_vc"] = False
  145. # avoid issues when building with different versions of python out of the same directory
  146. env.SConsignFile(File("#.sconsign{0}.dblite".format(pickle.HIGHEST_PROTOCOL)).abspath)
  147. # Build options
  148. customs = ["custom.py"]
  149. profile = ARGUMENTS.get("profile", "")
  150. if profile:
  151. if os.path.isfile(profile):
  152. customs.append(profile)
  153. elif os.path.isfile(profile + ".py"):
  154. customs.append(profile + ".py")
  155. opts = Variables(customs, ARGUMENTS)
  156. # Target build options
  157. if env.scons_version >= (4, 3):
  158. opts.Add(["platform", "p"], "Target platform (%s)" % "|".join(platform_list), "")
  159. else:
  160. opts.Add("platform", "Target platform (%s)" % "|".join(platform_list), "")
  161. opts.Add("p", "Alias for 'platform'", "")
  162. opts.Add(EnumVariable("target", "Compilation target", "editor", ("editor", "template_release", "template_debug")))
  163. opts.Add(EnumVariable("arch", "CPU architecture", "auto", ["auto"] + architectures, architecture_aliases))
  164. opts.Add(BoolVariable("dev_build", "Developer build with dev-only debugging code (DEV_ENABLED)", False))
  165. opts.Add(
  166. EnumVariable(
  167. "optimize",
  168. "Optimization level (by default inferred from 'target' and 'dev_build')",
  169. "auto",
  170. ("auto", "none", "custom", "debug", "speed", "speed_trace", "size"),
  171. )
  172. )
  173. opts.Add(BoolVariable("debug_symbols", "Build with debugging symbols", False))
  174. opts.Add(BoolVariable("separate_debug_symbols", "Extract debugging symbols to a separate file", False))
  175. opts.Add(BoolVariable("debug_paths_relative", "Make file paths in debug symbols relative (if supported)", False))
  176. opts.Add(EnumVariable("lto", "Link-time optimization (production builds)", "none", ("none", "auto", "thin", "full")))
  177. opts.Add(BoolVariable("production", "Set defaults to build Godot for use in production", False))
  178. opts.Add(BoolVariable("threads", "Enable threading support", True))
  179. # Components
  180. opts.Add(BoolVariable("deprecated", "Enable compatibility code for deprecated and removed features", True))
  181. opts.Add(EnumVariable("precision", "Set the floating-point precision level", "single", ("single", "double")))
  182. opts.Add(BoolVariable("minizip", "Enable ZIP archive support using minizip", True))
  183. opts.Add(BoolVariable("brotli", "Enable Brotli for decompresson and WOFF2 fonts support", True))
  184. opts.Add(BoolVariable("xaudio2", "Enable the XAudio2 audio driver on supported platforms", False))
  185. opts.Add(BoolVariable("vulkan", "Enable the vulkan rendering driver", True))
  186. opts.Add(BoolVariable("opengl3", "Enable the OpenGL/GLES3 rendering driver", True))
  187. opts.Add(BoolVariable("d3d12", "Enable the Direct3D 12 rendering driver on supported platforms", False))
  188. opts.Add(BoolVariable("metal", "Enable the Metal rendering driver on supported platforms (Apple arm64 only)", False))
  189. opts.Add(BoolVariable("openxr", "Enable the OpenXR driver", True))
  190. opts.Add(BoolVariable("use_volk", "Use the volk library to load the Vulkan loader dynamically", True))
  191. opts.Add(BoolVariable("disable_exceptions", "Force disabling exception handling code", True))
  192. opts.Add("custom_modules", "A list of comma-separated directory paths containing custom modules to build.", "")
  193. opts.Add(BoolVariable("custom_modules_recursive", "Detect custom modules recursively for each specified path.", True))
  194. # Advanced options
  195. opts.Add(
  196. BoolVariable(
  197. "dev_mode", "Alias for dev options: verbose=yes warnings=extra werror=yes tests=yes strict_checks=yes", False
  198. )
  199. )
  200. opts.Add(BoolVariable("tests", "Build the unit tests", False))
  201. opts.Add(BoolVariable("fast_unsafe", "Enable unsafe options for faster rebuilds", False))
  202. opts.Add(BoolVariable("ninja", "Use the ninja backend for faster rebuilds", False))
  203. opts.Add(BoolVariable("ninja_auto_run", "Run ninja automatically after generating the ninja file", True))
  204. opts.Add("ninja_file", "Path to the generated ninja file", "build.ninja")
  205. opts.Add(BoolVariable("compiledb", "Generate compilation DB (`compile_commands.json`) for external tools", False))
  206. opts.Add(
  207. "num_jobs",
  208. "Use up to N jobs when compiling (equivalent to `-j N`). Defaults to max jobs - 1. Ignored if -j is used.",
  209. "",
  210. )
  211. opts.Add(BoolVariable("verbose", "Enable verbose output for the compilation", False))
  212. opts.Add(BoolVariable("progress", "Show a progress indicator during compilation", True))
  213. opts.Add(EnumVariable("warnings", "Level of compilation warnings", "all", ("extra", "all", "moderate", "no")))
  214. opts.Add(BoolVariable("werror", "Treat compiler warnings as errors", False))
  215. opts.Add("extra_suffix", "Custom extra suffix added to the base filename of all generated binary files", "")
  216. opts.Add("object_prefix", "Custom prefix added to the base filename of all generated object files", "")
  217. opts.Add(BoolVariable("vsproj", "Generate a Visual Studio solution", False))
  218. opts.Add("vsproj_name", "Name of the Visual Studio solution", "godot")
  219. opts.Add("import_env_vars", "A comma-separated list of environment variables to copy from the outer environment.", "")
  220. opts.Add(BoolVariable("disable_3d", "Disable 3D nodes for a smaller executable", False))
  221. opts.Add(BoolVariable("disable_advanced_gui", "Disable advanced GUI nodes and behaviors", False))
  222. opts.Add("build_profile", "Path to a file containing a feature build profile", "")
  223. opts.Add(BoolVariable("modules_enabled_by_default", "If no, disable all modules except ones explicitly enabled", True))
  224. opts.Add(BoolVariable("no_editor_splash", "Don't use the custom splash screen for the editor", True))
  225. opts.Add(
  226. "system_certs_path",
  227. "Use this path as TLS certificates default for editor and Linux/BSD export templates (for package maintainers)",
  228. "",
  229. )
  230. opts.Add(BoolVariable("use_precise_math_checks", "Math checks use very precise epsilon (debug option)", False))
  231. opts.Add(BoolVariable("strict_checks", "Enforce stricter checks (debug option)", False))
  232. opts.Add(BoolVariable("scu_build", "Use single compilation unit build", False))
  233. opts.Add("scu_limit", "Max includes per SCU file when using scu_build (determines RAM use)", "0")
  234. opts.Add(BoolVariable("engine_update_check", "Enable engine update checks in the Project Manager", True))
  235. opts.Add(BoolVariable("steamapi", "Enable minimal SteamAPI integration for usage time tracking (editor only)", False))
  236. opts.Add("cache_path", "Path to a directory where SCons cache files will be stored. No value disables the cache.", "")
  237. opts.Add("cache_limit", "Max size (in GiB) for the SCons cache. 0 means no limit.", "0")
  238. # Thirdparty libraries
  239. opts.Add(BoolVariable("builtin_brotli", "Use the built-in Brotli library", True))
  240. opts.Add(BoolVariable("builtin_certs", "Use the built-in SSL certificates bundles", True))
  241. opts.Add(BoolVariable("builtin_clipper2", "Use the built-in Clipper2 library", True))
  242. opts.Add(BoolVariable("builtin_embree", "Use the built-in Embree library", True))
  243. opts.Add(BoolVariable("builtin_enet", "Use the built-in ENet library", True))
  244. opts.Add(BoolVariable("builtin_freetype", "Use the built-in FreeType library", True))
  245. opts.Add(BoolVariable("builtin_msdfgen", "Use the built-in MSDFgen library", True))
  246. opts.Add(BoolVariable("builtin_glslang", "Use the built-in glslang library", True))
  247. opts.Add(BoolVariable("builtin_graphite", "Use the built-in Graphite library", True))
  248. opts.Add(BoolVariable("builtin_harfbuzz", "Use the built-in HarfBuzz library", True))
  249. opts.Add(BoolVariable("builtin_icu4c", "Use the built-in ICU library", True))
  250. opts.Add(BoolVariable("builtin_libogg", "Use the built-in libogg library", True))
  251. opts.Add(BoolVariable("builtin_libpng", "Use the built-in libpng library", True))
  252. opts.Add(BoolVariable("builtin_libtheora", "Use the built-in libtheora library", True))
  253. opts.Add(BoolVariable("builtin_libvorbis", "Use the built-in libvorbis library", True))
  254. opts.Add(BoolVariable("builtin_libwebp", "Use the built-in libwebp library", True))
  255. opts.Add(BoolVariable("builtin_wslay", "Use the built-in wslay library", True))
  256. opts.Add(BoolVariable("builtin_mbedtls", "Use the built-in mbedTLS library", True))
  257. opts.Add(BoolVariable("builtin_miniupnpc", "Use the built-in miniupnpc library", True))
  258. opts.Add(BoolVariable("builtin_openxr", "Use the built-in OpenXR library", True))
  259. opts.Add(BoolVariable("builtin_pcre2", "Use the built-in PCRE2 library", True))
  260. opts.Add(BoolVariable("builtin_pcre2_with_jit", "Use JIT compiler for the built-in PCRE2 library", True))
  261. opts.Add(BoolVariable("builtin_recastnavigation", "Use the built-in Recast navigation library", True))
  262. opts.Add(BoolVariable("builtin_rvo2_2d", "Use the built-in RVO2 2D library", True))
  263. opts.Add(BoolVariable("builtin_rvo2_3d", "Use the built-in RVO2 3D library", True))
  264. opts.Add(BoolVariable("builtin_xatlas", "Use the built-in xatlas library", True))
  265. opts.Add(BoolVariable("builtin_zlib", "Use the built-in zlib library", True))
  266. opts.Add(BoolVariable("builtin_zstd", "Use the built-in Zstd library", True))
  267. # Compilation environment setup
  268. # CXX, CC, and LINK directly set the equivalent `env` values (which may still
  269. # be overridden for a specific platform), the lowercase ones are appended.
  270. opts.Add("CXX", "C++ compiler binary")
  271. opts.Add("CC", "C compiler binary")
  272. opts.Add("LINK", "Linker binary")
  273. opts.Add("cppdefines", "Custom defines for the pre-processor")
  274. opts.Add("ccflags", "Custom flags for both the C and C++ compilers")
  275. opts.Add("cxxflags", "Custom flags for the C++ compiler")
  276. opts.Add("cflags", "Custom flags for the C compiler")
  277. opts.Add("linkflags", "Custom flags for the linker")
  278. opts.Add("asflags", "Custom flags for the assembler")
  279. opts.Add("arflags", "Custom flags for the archive tool")
  280. opts.Add("rcflags", "Custom flags for Windows resource compiler")
  281. # Update the environment to have all above options defined
  282. # in following code (especially platform and custom_modules).
  283. opts.Update(env)
  284. # Setup caching logic early to catch everything.
  285. methods.prepare_cache(env)
  286. # Copy custom environment variables if set.
  287. if env["import_env_vars"]:
  288. for env_var in str(env["import_env_vars"]).split(","):
  289. if env_var in os.environ:
  290. env["ENV"][env_var] = os.environ[env_var]
  291. # Platform selection: validate input, and add options.
  292. if env.scons_version < (4, 3) and not env["platform"]:
  293. env["platform"] = env["p"]
  294. if env["platform"] == "":
  295. # Missing `platform` argument, try to detect platform automatically
  296. if (
  297. sys.platform.startswith("linux")
  298. or sys.platform.startswith("dragonfly")
  299. or sys.platform.startswith("freebsd")
  300. or sys.platform.startswith("netbsd")
  301. or sys.platform.startswith("openbsd")
  302. ):
  303. env["platform"] = "linuxbsd"
  304. elif sys.platform == "darwin":
  305. env["platform"] = "macos"
  306. elif sys.platform == "win32":
  307. env["platform"] = "windows"
  308. if env["platform"] != "":
  309. print(f'Automatically detected platform: {env["platform"]}')
  310. # Deprecated aliases kept for compatibility.
  311. if env["platform"] in compatibility_platform_aliases:
  312. alias = env["platform"]
  313. platform = compatibility_platform_aliases[alias]
  314. print_warning(
  315. f'Platform "{alias}" has been renamed to "{platform}" in Godot 4. Building for platform "{platform}".'
  316. )
  317. env["platform"] = platform
  318. # Alias for convenience.
  319. if env["platform"] in ["linux", "bsd"]:
  320. env["platform"] = "linuxbsd"
  321. if env["platform"] not in platform_list:
  322. text = "The following platforms are available:\n\t{}\n".format("\n\t".join(platform_list))
  323. text += "Please run SCons again and select a valid platform: platform=<string>."
  324. if env["platform"] == "list":
  325. print(text)
  326. elif env["platform"] == "":
  327. print_error("Could not detect platform automatically.\n" + text)
  328. else:
  329. print_error(f'Invalid target platform "{env["platform"]}".\n' + text)
  330. Exit(0 if env["platform"] == "list" else 255)
  331. # Add platform-specific options.
  332. if env["platform"] in platform_opts:
  333. opts.AddVariables(*platform_opts[env["platform"]])
  334. # Platform-specific flags.
  335. # These can sometimes override default options, so they need to be processed
  336. # as early as possible to ensure that we're using the correct values.
  337. flag_list = platform_flags[env["platform"]]
  338. for key, value in flag_list.items():
  339. if key not in ARGUMENTS or ARGUMENTS[key] == "auto": # Allow command line to override platform flags
  340. env[key] = value
  341. # Update the environment to take platform-specific options into account.
  342. opts.Update(env, {**ARGUMENTS, **env.Dictionary()})
  343. # Detect modules.
  344. modules_detected = OrderedDict()
  345. module_search_paths = ["modules"] # Built-in path.
  346. if env["custom_modules"]:
  347. paths = env["custom_modules"].split(",")
  348. for p in paths:
  349. try:
  350. module_search_paths.append(methods.convert_custom_modules_path(p))
  351. except ValueError as e:
  352. print_error(e)
  353. Exit(255)
  354. for path in module_search_paths:
  355. if path == "modules":
  356. # Built-in modules don't have nested modules,
  357. # so save the time it takes to parse directories.
  358. modules = methods.detect_modules(path, recursive=False)
  359. else: # Custom.
  360. modules = methods.detect_modules(path, env["custom_modules_recursive"])
  361. # Provide default include path for both the custom module search `path`
  362. # and the base directory containing custom modules, as it may be different
  363. # from the built-in "modules" name (e.g. "custom_modules/summator/summator.h"),
  364. # so it can be referenced simply as `#include "summator/summator.h"`
  365. # independently of where a module is located on user's filesystem.
  366. env.Prepend(CPPPATH=[path, os.path.dirname(path)])
  367. # Note: custom modules can override built-in ones.
  368. modules_detected.update(modules)
  369. # Add module options.
  370. for name, path in modules_detected.items():
  371. sys.path.insert(0, path)
  372. import config
  373. if env["modules_enabled_by_default"]:
  374. enabled = True
  375. try:
  376. enabled = config.is_enabled()
  377. except AttributeError:
  378. pass
  379. else:
  380. enabled = False
  381. opts.Add(BoolVariable(f"module_{name}_enabled", f"Enable module '{name}'", enabled))
  382. # Add module-specific options.
  383. try:
  384. opts.AddVariables(*config.get_opts(env["platform"]))
  385. except AttributeError:
  386. pass
  387. sys.path.remove(path)
  388. sys.modules.pop("config")
  389. env.modules_detected = modules_detected
  390. # Update the environment again after all the module options are added.
  391. opts.Update(env, {**ARGUMENTS, **env.Dictionary()})
  392. Help(opts.GenerateHelpText(env))
  393. # add default include paths
  394. env.Prepend(CPPPATH=["#"])
  395. # configure ENV for platform
  396. env.platform_exporters = platform_exporters
  397. env.platform_apis = platform_apis
  398. # Configuration of build targets:
  399. # - Editor or template
  400. # - Debug features (DEBUG_ENABLED code)
  401. # - Dev only code (DEV_ENABLED code)
  402. # - Optimization level
  403. # - Debug symbols for crash traces / debuggers
  404. env.editor_build = env["target"] == "editor"
  405. env.dev_build = env["dev_build"]
  406. env.debug_features = env["target"] in ["editor", "template_debug"]
  407. if env["optimize"] == "auto":
  408. if env.dev_build:
  409. opt_level = "none"
  410. elif env.debug_features:
  411. opt_level = "speed_trace"
  412. else: # Release
  413. opt_level = "speed"
  414. env["optimize"] = ARGUMENTS.get("optimize", opt_level)
  415. env["debug_symbols"] = methods.get_cmdline_bool("debug_symbols", env.dev_build)
  416. if env.editor_build:
  417. env.Append(CPPDEFINES=["TOOLS_ENABLED"])
  418. if env.debug_features:
  419. # DEBUG_ENABLED enables debugging *features* and debug-only code, which is intended
  420. # to give *users* extra debugging information for their game development.
  421. env.Append(CPPDEFINES=["DEBUG_ENABLED"])
  422. if env.dev_build:
  423. # DEV_ENABLED enables *engine developer* code which should only be compiled for those
  424. # working on the engine itself.
  425. env.Append(CPPDEFINES=["DEV_ENABLED"])
  426. else:
  427. # Disable assert() for production targets (only used in thirdparty code).
  428. env.Append(CPPDEFINES=["NDEBUG"])
  429. # SCons speed optimization controlled by the `fast_unsafe` option, which provide
  430. # more than 10 s speed up for incremental rebuilds.
  431. # Unsafe as they reduce the certainty of rebuilding all changed files, so it's
  432. # enabled by default for `debug` builds, and can be overridden from command line.
  433. # Ref: https://github.com/SCons/scons/wiki/GoFastButton
  434. if methods.get_cmdline_bool("fast_unsafe", env.dev_build):
  435. # Renamed to `content-timestamp` in SCons >= 4.2, keeping MD5 for compat.
  436. env.Decider("MD5-timestamp")
  437. env.SetOption("implicit_cache", 1)
  438. env.SetOption("max_drift", 60)
  439. if env["use_precise_math_checks"]:
  440. env.Append(CPPDEFINES=["PRECISE_MATH_CHECKS"])
  441. if env.editor_build:
  442. if env["engine_update_check"]:
  443. env.Append(CPPDEFINES=["ENGINE_UPDATE_CHECK_ENABLED"])
  444. if not env.File("#main/splash_editor.png").exists():
  445. # Force disabling editor splash if missing.
  446. env["no_editor_splash"] = True
  447. if env["no_editor_splash"]:
  448. env.Append(CPPDEFINES=["NO_EDITOR_SPLASH"])
  449. if not env["deprecated"]:
  450. env.Append(CPPDEFINES=["DISABLE_DEPRECATED"])
  451. if env["precision"] == "double":
  452. env.Append(CPPDEFINES=["REAL_T_IS_DOUBLE"])
  453. tmppath = "./platform/" + env["platform"]
  454. sys.path.insert(0, tmppath)
  455. import detect
  456. # Default num_jobs to local cpu count if not user specified.
  457. # SCons has a peculiarity where user-specified options won't be overridden
  458. # by SetOption, so we can rely on this to know if we should use our default.
  459. initial_num_jobs = env.GetOption("num_jobs")
  460. altered_num_jobs = initial_num_jobs + 1
  461. env.SetOption("num_jobs", altered_num_jobs)
  462. if env.GetOption("num_jobs") == altered_num_jobs:
  463. num_jobs = env.get("num_jobs", "")
  464. if str(num_jobs).isdigit() and int(num_jobs) > 0:
  465. env.SetOption("num_jobs", num_jobs)
  466. else:
  467. cpu_count = os.cpu_count()
  468. if cpu_count is None:
  469. print_warning(
  470. "Couldn't auto-detect CPU count to configure build parallelism. Specify it with the `-j` or `num_jobs` arguments."
  471. )
  472. else:
  473. safer_cpu_count = cpu_count if cpu_count <= 4 else cpu_count - 1
  474. print(
  475. "Auto-detected %d CPU cores available for build parallelism. Using %d cores by default. You can override it with the `-j` or `num_jobs` arguments."
  476. % (cpu_count, safer_cpu_count)
  477. )
  478. env.SetOption("num_jobs", safer_cpu_count)
  479. env.extra_suffix = ""
  480. if env["extra_suffix"] != "":
  481. env.extra_suffix += "." + env["extra_suffix"]
  482. # Environment flags
  483. env.Append(CPPDEFINES=env.get("cppdefines", "").split())
  484. env.Append(CCFLAGS=env.get("ccflags", "").split())
  485. env.Append(CXXFLAGS=env.get("cxxflags", "").split())
  486. env.Append(CFLAGS=env.get("cflags", "").split())
  487. env.Append(LINKFLAGS=env.get("linkflags", "").split())
  488. env.Append(ASFLAGS=env.get("asflags", "").split())
  489. env.Append(ARFLAGS=env.get("arflags", "").split())
  490. env.Append(RCFLAGS=env.get("rcflags", "").split())
  491. # Feature build profile
  492. env.disabled_classes = []
  493. if env["build_profile"] != "":
  494. print(f'Using feature build profile: "{env["build_profile"]}"')
  495. import json
  496. try:
  497. ft = json.load(open(env["build_profile"], "r", encoding="utf-8"))
  498. if "disabled_classes" in ft:
  499. env.disabled_classes = ft["disabled_classes"]
  500. if "disabled_build_options" in ft:
  501. dbo = ft["disabled_build_options"]
  502. for c in dbo:
  503. env[c] = dbo[c]
  504. except json.JSONDecodeError:
  505. print_error(f'Failed to open feature build profile: "{env["build_profile"]}"')
  506. Exit(255)
  507. # 'dev_mode' and 'production' are aliases to set default options if they haven't been
  508. # set manually by the user.
  509. if env["dev_mode"]:
  510. env["verbose"] = methods.get_cmdline_bool("verbose", True)
  511. env["warnings"] = ARGUMENTS.get("warnings", "extra")
  512. env["werror"] = methods.get_cmdline_bool("werror", True)
  513. env["tests"] = methods.get_cmdline_bool("tests", True)
  514. env["strict_checks"] = methods.get_cmdline_bool("strict_checks", True)
  515. if env["production"]:
  516. env["use_static_cpp"] = methods.get_cmdline_bool("use_static_cpp", True)
  517. env["debug_symbols"] = methods.get_cmdline_bool("debug_symbols", False)
  518. if platform_arg == "android":
  519. env["swappy"] = methods.get_cmdline_bool("swappy", True)
  520. # LTO "auto" means we handle the preferred option in each platform detect.py.
  521. env["lto"] = ARGUMENTS.get("lto", "auto")
  522. if env["strict_checks"]:
  523. env.Append(CPPDEFINES=["STRICT_CHECKS"])
  524. # Run SCU file generation script if in a SCU build.
  525. if env["scu_build"]:
  526. max_includes_per_scu = 8
  527. if env.dev_build:
  528. max_includes_per_scu = 1024
  529. read_scu_limit = int(env["scu_limit"])
  530. read_scu_limit = max(0, min(read_scu_limit, 1024))
  531. if read_scu_limit != 0:
  532. max_includes_per_scu = read_scu_limit
  533. methods.set_scu_folders(scu_builders.generate_scu_files(max_includes_per_scu))
  534. # Must happen after the flags' definition, as configure is when most flags
  535. # are actually handled to change compile options, etc.
  536. detect.configure(env)
  537. print(f'Building for platform "{env["platform"]}", architecture "{env["arch"]}", target "{env["target"]}".')
  538. if env.dev_build:
  539. print("NOTE: Developer build, with debug optimization level and debug symbols (unless overridden).")
  540. # Enforce our minimal compiler version requirements
  541. cc_version = methods.get_compiler_version(env)
  542. cc_version_major = cc_version["major"]
  543. cc_version_minor = cc_version["minor"]
  544. cc_version_metadata1 = cc_version["metadata1"]
  545. if cc_version_major == -1:
  546. print_warning(
  547. "Couldn't detect compiler version, skipping version checks. "
  548. "Build may fail if the compiler doesn't support C++17 fully."
  549. )
  550. elif methods.using_gcc(env):
  551. if cc_version_major < 9:
  552. print_error(
  553. "Detected GCC version older than 9, which does not fully support "
  554. "C++17, or has bugs when compiling Godot. Supported versions are 9 "
  555. "and later. Use a newer GCC version, or Clang 6 or later by passing "
  556. '"use_llvm=yes" to the SCons command line.'
  557. )
  558. Exit(255)
  559. elif cc_version_metadata1 == "win32":
  560. print_error(
  561. "Detected mingw version is not using posix threads. Only posix "
  562. "version of mingw is supported. "
  563. 'Use "update-alternatives --config x86_64-w64-mingw32-g++" '
  564. "to switch to posix threads."
  565. )
  566. Exit(255)
  567. elif methods.using_clang(env):
  568. # Apple LLVM versions differ from upstream LLVM version \o/, compare
  569. # in https://en.wikipedia.org/wiki/Xcode#Toolchain_versions
  570. if methods.is_apple_clang(env):
  571. if cc_version_major < 10:
  572. print_error(
  573. "Detected Apple Clang version older than 10, which does not fully "
  574. "support C++17. Supported versions are Apple Clang 10 and later."
  575. )
  576. Exit(255)
  577. elif env["debug_paths_relative"] and cc_version_major < 12:
  578. print_warning(
  579. "Apple Clang < 12 doesn't support -ffile-prefix-map, disabling `debug_paths_relative` option."
  580. )
  581. env["debug_paths_relative"] = False
  582. else:
  583. if cc_version_major < 6:
  584. print_error(
  585. "Detected Clang version older than 6, which does not fully support "
  586. "C++17. Supported versions are Clang 6 and later."
  587. )
  588. Exit(255)
  589. elif env["debug_paths_relative"] and cc_version_major < 10:
  590. print_warning("Clang < 10 doesn't support -ffile-prefix-map, disabling `debug_paths_relative` option.")
  591. env["debug_paths_relative"] = False
  592. elif env.msvc:
  593. # Ensure latest minor builds of Visual Studio 2017/2019.
  594. # https://github.com/godotengine/godot/pull/94995#issuecomment-2336464574
  595. if cc_version_major == 16 and cc_version_minor < 11:
  596. print_error(
  597. "Detected Visual Studio 2019 version older than 16.11, which has bugs "
  598. "when compiling Godot. Use a newer VS2019 version, or VS2022."
  599. )
  600. Exit(255)
  601. if cc_version_major == 15 and cc_version_minor < 9:
  602. print_error(
  603. "Detected Visual Studio 2017 version older than 15.9, which has bugs "
  604. "when compiling Godot. Use a newer VS2017 version, or VS2019/VS2022."
  605. )
  606. Exit(255)
  607. if cc_version_major < 15:
  608. print_error(
  609. "Detected Visual Studio 2015 or earlier, which is unsupported in Godot. "
  610. "Supported versions are Visual Studio 2017 and later."
  611. )
  612. Exit(255)
  613. # Set optimize and debug_symbols flags.
  614. # "custom" means do nothing and let users set their own optimization flags.
  615. # Needs to happen after configure to have `env.msvc` defined.
  616. if env.msvc:
  617. if env["debug_symbols"]:
  618. env.Append(CCFLAGS=["/Zi", "/FS"])
  619. env.Append(LINKFLAGS=["/DEBUG:FULL"])
  620. else:
  621. env.Append(LINKFLAGS=["/DEBUG:NONE"])
  622. if env["optimize"].startswith("speed"):
  623. env.Append(CCFLAGS=["/O2"])
  624. env.Append(LINKFLAGS=["/OPT:REF"])
  625. if env["optimize"] == "speed_trace":
  626. env.Append(LINKFLAGS=["/OPT:NOICF"])
  627. elif env["optimize"] == "size":
  628. env.Append(CCFLAGS=["/O1"])
  629. env.Append(LINKFLAGS=["/OPT:REF"])
  630. elif env["optimize"] == "debug" or env["optimize"] == "none":
  631. env.Append(CCFLAGS=["/Od"])
  632. else:
  633. if env["debug_symbols"]:
  634. # Adding dwarf-4 explicitly makes stacktraces work with clang builds,
  635. # otherwise addr2line doesn't understand them
  636. env.Append(CCFLAGS=["-gdwarf-4"])
  637. if methods.using_emcc(env):
  638. # Emscripten only produces dwarf symbols when using "-g3".
  639. env.Append(CCFLAGS=["-g3"])
  640. # Emscripten linker needs debug symbols options too.
  641. env.Append(LINKFLAGS=["-gdwarf-4"])
  642. env.Append(LINKFLAGS=["-g3"])
  643. elif env.dev_build:
  644. env.Append(CCFLAGS=["-g3"])
  645. else:
  646. env.Append(CCFLAGS=["-g2"])
  647. if env["debug_paths_relative"]:
  648. # Remap absolute paths to relative paths for debug symbols.
  649. project_path = Dir("#").abspath
  650. env.Append(CCFLAGS=[f"-ffile-prefix-map={project_path}=."])
  651. else:
  652. if methods.is_apple_clang(env):
  653. # Apple Clang, its linker doesn't like -s.
  654. env.Append(LINKFLAGS=["-Wl,-S", "-Wl,-x", "-Wl,-dead_strip"])
  655. else:
  656. env.Append(LINKFLAGS=["-s"])
  657. # Linker needs optimization flags too, at least for Emscripten.
  658. # For other toolchains, this _may_ be useful for LTO too to disambiguate.
  659. if env["optimize"] == "speed":
  660. env.Append(CCFLAGS=["-O3"])
  661. env.Append(LINKFLAGS=["-O3"])
  662. # `-O2` is friendlier to debuggers than `-O3`, leading to better crash backtraces.
  663. elif env["optimize"] == "speed_trace":
  664. env.Append(CCFLAGS=["-O2"])
  665. env.Append(LINKFLAGS=["-O2"])
  666. elif env["optimize"] == "size":
  667. env.Append(CCFLAGS=["-Os"])
  668. env.Append(LINKFLAGS=["-Os"])
  669. elif env["optimize"] == "debug":
  670. env.Append(CCFLAGS=["-Og"])
  671. env.Append(LINKFLAGS=["-Og"])
  672. elif env["optimize"] == "none":
  673. env.Append(CCFLAGS=["-O0"])
  674. env.Append(LINKFLAGS=["-O0"])
  675. # Needs to happen after configure to handle "auto".
  676. if env["lto"] != "none":
  677. print("Using LTO: " + env["lto"])
  678. # Set our C and C++ standard requirements.
  679. # C++17 is required as we need guaranteed copy elision as per GH-36436.
  680. # Prepending to make it possible to override.
  681. # This needs to come after `configure`, otherwise we don't have env.msvc.
  682. if not env.msvc:
  683. # Specifying GNU extensions support explicitly, which are supported by
  684. # both GCC and Clang. Both currently default to gnu17 and gnu++17.
  685. env.Prepend(CFLAGS=["-std=gnu17"])
  686. env.Prepend(CXXFLAGS=["-std=gnu++17"])
  687. else:
  688. # MSVC started offering C standard support with Visual Studio 2019 16.8, which covers all
  689. # of our supported VS2019 & VS2022 versions; VS2017 will only pass the C++ standard.
  690. env.Prepend(CXXFLAGS=["/std:c++17"])
  691. if cc_version_major < 16:
  692. print_warning("Visual Studio 2017 cannot specify a C-Standard.")
  693. else:
  694. env.Prepend(CFLAGS=["/std:c17"])
  695. # MSVC is non-conforming with the C++ standard by default, so we enable more conformance.
  696. # Note that this is still not complete conformance, as certain Windows-related headers
  697. # don't compile under complete conformance.
  698. env.Prepend(CCFLAGS=["/permissive-"])
  699. # Allow use of `__cplusplus` macro to determine C++ standard universally.
  700. env.Prepend(CXXFLAGS=["/Zc:__cplusplus"])
  701. # Disable exception handling. Godot doesn't use exceptions anywhere, and this
  702. # saves around 20% of binary size and very significant build time (GH-80513).
  703. if env["disable_exceptions"]:
  704. if env.msvc:
  705. env.Append(CPPDEFINES=[("_HAS_EXCEPTIONS", 0)])
  706. else:
  707. env.Append(CXXFLAGS=["-fno-exceptions"])
  708. elif env.msvc:
  709. env.Append(CXXFLAGS=["/EHsc"])
  710. # Configure compiler warnings
  711. if env.msvc and not methods.using_clang(env): # MSVC
  712. if env["warnings"] == "no":
  713. env.Append(CCFLAGS=["/w"])
  714. else:
  715. if env["warnings"] == "extra":
  716. env.Append(CCFLAGS=["/W4"])
  717. elif env["warnings"] == "all":
  718. # C4458 is like -Wshadow. Part of /W4 but let's apply it for the default /W3 too.
  719. env.Append(CCFLAGS=["/W3", "/w34458"])
  720. elif env["warnings"] == "moderate":
  721. env.Append(CCFLAGS=["/W2"])
  722. # Disable warnings which we don't plan to fix.
  723. env.Append(
  724. CCFLAGS=[
  725. "/wd4100", # C4100 (unreferenced formal parameter): Doesn't play nice with polymorphism.
  726. "/wd4127", # C4127 (conditional expression is constant)
  727. "/wd4201", # C4201 (non-standard nameless struct/union): Only relevant for C89.
  728. "/wd4244", # C4244 C4245 C4267 (narrowing conversions): Unavoidable at this scale.
  729. "/wd4245",
  730. "/wd4267",
  731. "/wd4305", # C4305 (truncation): double to float or real_t, too hard to avoid.
  732. "/wd4324", # C4820 (structure was padded due to alignment specifier)
  733. "/wd4514", # C4514 (unreferenced inline function has been removed)
  734. "/wd4714", # C4714 (function marked as __forceinline not inlined)
  735. "/wd4820", # C4820 (padding added after construct)
  736. ]
  737. )
  738. if env["werror"]:
  739. env.Append(CCFLAGS=["/WX"])
  740. env.Append(LINKFLAGS=["/WX"])
  741. else: # GCC, Clang
  742. common_warnings = []
  743. if methods.using_gcc(env):
  744. common_warnings += ["-Wshadow", "-Wno-misleading-indentation"]
  745. if cc_version_major < 11:
  746. # Regression in GCC 9/10, spams so much in our variadic templates
  747. # that we need to outright disable it.
  748. common_warnings += ["-Wno-type-limits"]
  749. if cc_version_major >= 12: # False positives in our error macros, see GH-58747.
  750. common_warnings += ["-Wno-return-type"]
  751. elif methods.using_clang(env) or methods.using_emcc(env):
  752. common_warnings += ["-Wshadow-field-in-constructor", "-Wshadow-uncaptured-local"]
  753. # We often implement `operator<` for structs of pointers as a requirement
  754. # for putting them in `Set` or `Map`. We don't mind about unreliable ordering.
  755. common_warnings += ["-Wno-ordered-compare-function-pointers"]
  756. # clang-cl will interpret `-Wall` as `-Weverything`, workaround with compatibility cast
  757. W_ALL = "-Wall" if not env.msvc else "-W3"
  758. if env["warnings"] == "extra":
  759. env.Append(CCFLAGS=[W_ALL, "-Wextra", "-Wwrite-strings", "-Wno-unused-parameter"] + common_warnings)
  760. env.Append(CXXFLAGS=["-Wctor-dtor-privacy", "-Wnon-virtual-dtor"])
  761. if methods.using_gcc(env):
  762. env.Append(
  763. CCFLAGS=[
  764. "-Walloc-zero",
  765. "-Wduplicated-branches",
  766. "-Wduplicated-cond",
  767. "-Wstringop-overflow=4",
  768. ]
  769. )
  770. env.Append(CXXFLAGS=["-Wplacement-new=1"])
  771. # Need to fix a warning with AudioServer lambdas before enabling.
  772. # if cc_version_major != 9: # GCC 9 had a regression (GH-36325).
  773. # env.Append(CXXFLAGS=["-Wnoexcept"])
  774. if cc_version_major >= 9:
  775. env.Append(CCFLAGS=["-Wattribute-alias=2"])
  776. if cc_version_major >= 11: # Broke on MethodBind templates before GCC 11.
  777. env.Append(CCFLAGS=["-Wlogical-op"])
  778. elif methods.using_clang(env) or methods.using_emcc(env):
  779. env.Append(CCFLAGS=["-Wimplicit-fallthrough"])
  780. elif env["warnings"] == "all":
  781. env.Append(CCFLAGS=[W_ALL] + common_warnings)
  782. elif env["warnings"] == "moderate":
  783. env.Append(CCFLAGS=[W_ALL, "-Wno-unused"] + common_warnings)
  784. else: # 'no'
  785. env.Append(CCFLAGS=["-w"])
  786. if env["werror"]:
  787. env.Append(CCFLAGS=["-Werror"])
  788. if hasattr(detect, "get_program_suffix"):
  789. suffix = "." + detect.get_program_suffix()
  790. else:
  791. suffix = "." + env["platform"]
  792. suffix += "." + env["target"]
  793. if env.dev_build:
  794. suffix += ".dev"
  795. if env["precision"] == "double":
  796. suffix += ".double"
  797. suffix += "." + env["arch"]
  798. if not env["threads"]:
  799. suffix += ".nothreads"
  800. suffix += env.extra_suffix
  801. sys.path.remove(tmppath)
  802. sys.modules.pop("detect")
  803. modules_enabled = OrderedDict()
  804. env.module_dependencies = {}
  805. env.module_icons_paths = []
  806. env.doc_class_path = platform_doc_class_path
  807. for name, path in modules_detected.items():
  808. if not env[f"module_{name}_enabled"]:
  809. continue
  810. sys.path.insert(0, path)
  811. env.current_module = name
  812. import config
  813. if config.can_build(env, env["platform"]):
  814. # Disable it if a required dependency is missing.
  815. if not env.module_check_dependencies(name):
  816. continue
  817. config.configure(env)
  818. # Get doc classes paths (if present)
  819. try:
  820. doc_classes = config.get_doc_classes()
  821. doc_path = config.get_doc_path()
  822. for c in doc_classes:
  823. env.doc_class_path[c] = path + "/" + doc_path
  824. except Exception:
  825. pass
  826. # Get icon paths (if present)
  827. try:
  828. icons_path = config.get_icons_path()
  829. env.module_icons_paths.append(path + "/" + icons_path)
  830. except Exception:
  831. # Default path for module icons
  832. env.module_icons_paths.append(path + "/" + "icons")
  833. modules_enabled[name] = path
  834. sys.path.remove(path)
  835. sys.modules.pop("config")
  836. env.module_list = modules_enabled
  837. methods.sort_module_list(env)
  838. if env.editor_build:
  839. # Add editor-specific dependencies to the dependency graph.
  840. env.module_add_dependencies("editor", ["freetype", "svg"])
  841. # And check if they are met.
  842. if not env.module_check_dependencies("editor"):
  843. print_error("Not all modules required by editor builds are enabled.")
  844. Exit(255)
  845. env.version_info = methods.get_version_info(env.module_version_string)
  846. env["PROGSUFFIX_WRAP"] = suffix + env.module_version_string + ".console" + env["PROGSUFFIX"]
  847. env["PROGSUFFIX"] = suffix + env.module_version_string + env["PROGSUFFIX"]
  848. env["OBJSUFFIX"] = suffix + env["OBJSUFFIX"]
  849. # (SH)LIBSUFFIX will be used for our own built libraries
  850. # LIBSUFFIXES contains LIBSUFFIX and SHLIBSUFFIX by default,
  851. # so we need to append the default suffixes to keep the ability
  852. # to link against thirdparty libraries (.a, .so, .lib, etc.).
  853. if os.name == "nt":
  854. # On Windows, only static libraries and import libraries can be
  855. # statically linked - both using .lib extension
  856. env["LIBSUFFIXES"] += [env["LIBSUFFIX"]]
  857. else:
  858. env["LIBSUFFIXES"] += [env["LIBSUFFIX"], env["SHLIBSUFFIX"]]
  859. env["LIBSUFFIX"] = suffix + env["LIBSUFFIX"]
  860. env["SHLIBSUFFIX"] = suffix + env["SHLIBSUFFIX"]
  861. env["OBJPREFIX"] = env["object_prefix"]
  862. env["SHOBJPREFIX"] = env["object_prefix"]
  863. if env["disable_3d"]:
  864. if env.editor_build:
  865. print_error("Build option `disable_3d=yes` cannot be used for editor builds, only for export template builds.")
  866. Exit(255)
  867. else:
  868. env.Append(CPPDEFINES=["_3D_DISABLED"])
  869. if env["disable_advanced_gui"]:
  870. if env.editor_build:
  871. print_error(
  872. "Build option `disable_advanced_gui=yes` cannot be used for editor builds, "
  873. "only for export template builds."
  874. )
  875. Exit(255)
  876. else:
  877. env.Append(CPPDEFINES=["ADVANCED_GUI_DISABLED"])
  878. if env["minizip"]:
  879. env.Append(CPPDEFINES=["MINIZIP_ENABLED"])
  880. if env["brotli"]:
  881. env.Append(CPPDEFINES=["BROTLI_ENABLED"])
  882. if not env["verbose"]:
  883. methods.no_verbose(env)
  884. GLSL_BUILDERS = {
  885. "RD_GLSL": env.Builder(
  886. action=env.Run(glsl_builders.build_rd_headers),
  887. suffix="glsl.gen.h",
  888. src_suffix=".glsl",
  889. ),
  890. "GLSL_HEADER": env.Builder(
  891. action=env.Run(glsl_builders.build_raw_headers),
  892. suffix="glsl.gen.h",
  893. src_suffix=".glsl",
  894. ),
  895. "GLES3_GLSL": env.Builder(
  896. action=env.Run(gles3_builders.build_gles3_headers),
  897. suffix="glsl.gen.h",
  898. src_suffix=".glsl",
  899. ),
  900. }
  901. env.Append(BUILDERS=GLSL_BUILDERS)
  902. if env["compiledb"]:
  903. env.Tool("compilation_db")
  904. env.Alias("compiledb", env.CompilationDatabase())
  905. if env["ninja"]:
  906. if env.scons_version < (4, 2, 0):
  907. print_error(f"The `ninja=yes` option requires SCons 4.2 or later, but your version is {scons_raw_version}.")
  908. Exit(255)
  909. SetOption("experimental", "ninja")
  910. env["NINJA_FILE_NAME"] = env["ninja_file"]
  911. env["NINJA_DISABLE_AUTO_RUN"] = not env["ninja_auto_run"]
  912. env.Tool("ninja", env["ninja_file"])
  913. # Threads
  914. if env["threads"]:
  915. env.Append(CPPDEFINES=["THREADS_ENABLED"])
  916. # Build subdirs, the build order is dependent on link order.
  917. Export("env")
  918. SConscript("core/SCsub")
  919. SConscript("servers/SCsub")
  920. SConscript("scene/SCsub")
  921. if env.editor_build:
  922. SConscript("editor/SCsub")
  923. SConscript("drivers/SCsub")
  924. SConscript("platform/SCsub")
  925. SConscript("modules/SCsub")
  926. if env["tests"]:
  927. SConscript("tests/SCsub")
  928. SConscript("main/SCsub")
  929. SConscript("platform/" + env["platform"] + "/SCsub") # Build selected platform.
  930. # Microsoft Visual Studio Project Generation
  931. if env["vsproj"]:
  932. methods.generate_cpp_hint_file("cpp.hint")
  933. env["CPPPATH"] = [Dir(path) for path in env["CPPPATH"]]
  934. methods.generate_vs_project(env, ARGUMENTS, env["vsproj_name"])
  935. # Check for the existence of headers
  936. conf = Configure(env)
  937. if "check_c_headers" in env:
  938. headers = env["check_c_headers"]
  939. for header in headers:
  940. if conf.CheckCHeader(header):
  941. env.AppendUnique(CPPDEFINES=[headers[header]])
  942. methods.show_progress(env)
  943. # TODO: replace this with `env.Dump(format="json")`
  944. # once we start requiring SCons 4.0 as min version.
  945. methods.dump(env)
  946. def print_elapsed_time():
  947. elapsed_time_sec = round(time.time() - time_at_start, 2)
  948. time_centiseconds = round((elapsed_time_sec % 1) * 100)
  949. print(
  950. "{}[Time elapsed: {}.{:02}]{}".format(
  951. methods.ANSI.GRAY,
  952. time.strftime("%H:%M:%S", time.gmtime(elapsed_time_sec)),
  953. time_centiseconds,
  954. methods.ANSI.RESET,
  955. )
  956. )
  957. atexit.register(print_elapsed_time)
  958. def purge_flaky_files():
  959. paths_to_keep = [env["ninja_file"]]
  960. for build_failure in GetBuildFailures():
  961. path = build_failure.node.path
  962. if os.path.isfile(path) and path not in paths_to_keep:
  963. os.remove(path)
  964. atexit.register(purge_flaky_files)