SConstruct 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  1. #!/usr/bin/env python
  2. EnsureSConsVersion(0, 98, 1)
  3. # System
  4. import atexit
  5. import glob
  6. import os
  7. import pickle
  8. import sys
  9. import time
  10. from collections import OrderedDict
  11. # Local
  12. import methods
  13. import gles_builders
  14. import scu_builders
  15. from platform_methods import run_in_subprocess
  16. # scan possible build platforms
  17. platform_list = [] # list of platforms
  18. platform_opts = {} # options for each platform
  19. platform_flags = {} # flags for each platform
  20. active_platforms = []
  21. active_platform_ids = []
  22. platform_exporters = []
  23. platform_apis = []
  24. time_at_start = time.time()
  25. for x in sorted(glob.glob("platform/*")):
  26. if not os.path.isdir(x) or not os.path.exists(x + "/detect.py"):
  27. continue
  28. tmppath = "./" + x
  29. sys.path.insert(0, tmppath)
  30. import detect
  31. if os.path.exists(x + "/export/export.cpp"):
  32. platform_exporters.append(x[9:])
  33. if os.path.exists(x + "/api/api.cpp"):
  34. platform_apis.append(x[9:])
  35. if detect.is_active():
  36. active_platforms.append(detect.get_name())
  37. active_platform_ids.append(x)
  38. if detect.can_build():
  39. x = x.replace("platform/", "") # rest of world
  40. x = x.replace("platform\\", "") # win32
  41. platform_list += [x]
  42. platform_opts[x] = detect.get_opts()
  43. platform_flags[x] = detect.get_flags()
  44. sys.path.remove(tmppath)
  45. sys.modules.pop("detect")
  46. methods.save_active_platforms(active_platforms, active_platform_ids)
  47. custom_tools = ["default"]
  48. platform_arg = ARGUMENTS.get("platform", ARGUMENTS.get("p", False))
  49. if platform_arg == "android":
  50. custom_tools = ["clang", "clang++", "as", "ar", "link"]
  51. elif platform_arg == "javascript":
  52. # Use generic POSIX build toolchain for Emscripten.
  53. custom_tools = ["cc", "c++", "ar", "link", "textfile", "zip"]
  54. elif os.name == "nt" and methods.get_cmdline_bool("use_mingw", False):
  55. custom_tools = ["mingw"]
  56. # We let SCons build its default ENV as it includes OS-specific things which we don't
  57. # want to have to pull in manually.
  58. # Then we prepend PATH to make it take precedence, while preserving SCons' own entries.
  59. env_base = Environment(tools=custom_tools)
  60. env_base.PrependENVPath("PATH", os.getenv("PATH"))
  61. env_base.PrependENVPath("PKG_CONFIG_PATH", os.getenv("PKG_CONFIG_PATH"))
  62. if "TERM" in os.environ: # Used for colored output.
  63. env_base["ENV"]["TERM"] = os.environ["TERM"]
  64. env_base.disabled_modules = []
  65. env_base.use_ptrcall = False
  66. env_base.module_version_string = ""
  67. env_base.msvc = False
  68. env_base.__class__.disable_module = methods.disable_module
  69. env_base.__class__.add_module_version_string = methods.add_module_version_string
  70. env_base.__class__.add_source_files = methods.add_source_files
  71. env_base.__class__.use_windows_spawn_fix = methods.use_windows_spawn_fix
  72. env_base.__class__.split_lib = methods.split_lib
  73. env_base.__class__.add_shared_library = methods.add_shared_library
  74. env_base.__class__.add_library = methods.add_library
  75. env_base.__class__.add_program = methods.add_program
  76. env_base.__class__.CommandNoCache = methods.CommandNoCache
  77. env_base.__class__.disable_warnings = methods.disable_warnings
  78. env_base.__class__.force_optimization_on_debug = methods.force_optimization_on_debug
  79. env_base["x86_libtheora_opt_gcc"] = False
  80. env_base["x86_libtheora_opt_vc"] = False
  81. # avoid issues when building with different versions of python out of the same directory
  82. env_base.SConsignFile(".sconsign{0}.dblite".format(pickle.HIGHEST_PROTOCOL))
  83. # Build options
  84. customs = ["custom.py"]
  85. profile = ARGUMENTS.get("profile", "")
  86. if profile:
  87. if os.path.isfile(profile):
  88. customs.append(profile)
  89. elif os.path.isfile(profile + ".py"):
  90. customs.append(profile + ".py")
  91. opts = Variables(customs, ARGUMENTS)
  92. # Target build options
  93. opts.Add("p", "Platform (alias for 'platform')", "")
  94. opts.Add("platform", "Target platform (%s)" % ("|".join(platform_list),), "")
  95. opts.Add(BoolVariable("tools", "Build the tools (a.k.a. the Godot editor)", True))
  96. opts.Add(EnumVariable("target", "Compilation target", "debug", ("debug", "release_debug", "release")))
  97. opts.Add("arch", "Platform-dependent architecture (arm/arm64/x86/x64/mips/...)", "")
  98. opts.Add(EnumVariable("bits", "Target platform bits", "default", ("default", "32", "64")))
  99. opts.Add(EnumVariable("optimize", "Optimization type", "speed", ("speed", "size", "none")))
  100. opts.Add(BoolVariable("production", "Set defaults to build Godot for use in production", False))
  101. opts.Add(EnumVariable("lto", "Link-time optimization (production builds)", "none", ("none", "auto", "thin", "full")))
  102. # Components
  103. opts.Add(BoolVariable("deprecated", "Enable deprecated features", True))
  104. opts.Add(BoolVariable("minizip", "Enable ZIP archive support using minizip", True))
  105. opts.Add(BoolVariable("xaudio2", "Enable the XAudio2 audio driver", False))
  106. opts.Add(BoolVariable("disable_exceptions", "Force disabling exception handling code", True))
  107. opts.Add("custom_modules", "A list of comma-separated directory paths containing custom modules to build.", "")
  108. opts.Add(BoolVariable("custom_modules_recursive", "Detect custom modules recursively for each specified path.", True))
  109. # Advanced options
  110. opts.Add(BoolVariable("dev", "If yes, alias for verbose=yes warnings=extra werror=yes", False))
  111. opts.Add(BoolVariable("fast_unsafe", "Enable unsafe options for faster rebuilds", False))
  112. opts.Add(BoolVariable("compiledb", "Generate compilation DB (`compile_commands.json`) for external tools", False))
  113. opts.Add(BoolVariable("verbose", "Enable verbose output for the compilation", False))
  114. opts.Add(BoolVariable("progress", "Show a progress indicator during compilation", True))
  115. opts.Add(EnumVariable("warnings", "Level of compilation warnings", "all", ("extra", "all", "moderate", "no")))
  116. opts.Add(BoolVariable("werror", "Treat compiler warnings as errors", False))
  117. opts.Add("extra_suffix", "Custom extra suffix added to the base filename of all generated binary files", "")
  118. opts.Add(BoolVariable("vsproj", "Generate a Visual Studio solution", False))
  119. opts.Add(
  120. BoolVariable(
  121. "split_libmodules",
  122. "Split intermediate libmodules.a in smaller chunks to prevent exceeding linker command line size (forced to True when using MinGW)",
  123. False,
  124. )
  125. )
  126. opts.Add(BoolVariable("disable_3d", "Disable 3D nodes for a smaller executable", False))
  127. opts.Add(BoolVariable("disable_advanced_gui", "Disable advanced GUI nodes and behaviors", False))
  128. opts.Add(BoolVariable("modules_enabled_by_default", "If no, disable all modules except ones explicitly enabled", True))
  129. opts.Add(BoolVariable("no_editor_splash", "Don't use the custom splash screen for the editor", True))
  130. opts.Add("system_certs_path", "Use this path as SSL certificates default for editor (for package maintainers)", "")
  131. opts.Add(BoolVariable("use_precise_math_checks", "Math checks use very precise epsilon (debug option)", False))
  132. opts.Add(BoolVariable("scu_build", "Use single compilation unit build", False))
  133. opts.Add(
  134. EnumVariable(
  135. "rids",
  136. "Server object management technique (debug option)",
  137. "pointers",
  138. ("pointers", "handles", "tracked_handles"),
  139. )
  140. )
  141. # Thirdparty libraries
  142. opts.Add(BoolVariable("builtin_bullet", "Use the built-in Bullet library", True))
  143. opts.Add(BoolVariable("builtin_certs", "Use the built-in SSL certificates bundles", True))
  144. opts.Add(BoolVariable("builtin_embree", "Use the built-in Embree library", True))
  145. opts.Add(BoolVariable("builtin_enet", "Use the built-in ENet library", True))
  146. opts.Add(BoolVariable("builtin_freetype", "Use the built-in FreeType library", True))
  147. opts.Add(BoolVariable("builtin_libogg", "Use the built-in libogg library", True))
  148. opts.Add(BoolVariable("builtin_libpng", "Use the built-in libpng library", True))
  149. opts.Add(BoolVariable("builtin_libtheora", "Use the built-in libtheora library", True))
  150. opts.Add(BoolVariable("builtin_libvorbis", "Use the built-in libvorbis library", True))
  151. opts.Add(BoolVariable("builtin_libvpx", "Use the built-in libvpx library", True))
  152. opts.Add(BoolVariable("builtin_libwebp", "Use the built-in libwebp library", True))
  153. opts.Add(BoolVariable("builtin_wslay", "Use the built-in wslay library", True))
  154. opts.Add(BoolVariable("builtin_mbedtls", "Use the built-in mbedTLS library", True))
  155. opts.Add(BoolVariable("builtin_miniupnpc", "Use the built-in miniupnpc library", True))
  156. opts.Add(BoolVariable("builtin_opus", "Use the built-in Opus library", True))
  157. opts.Add(BoolVariable("builtin_pcre2", "Use the built-in PCRE2 library", True))
  158. opts.Add(BoolVariable("builtin_pcre2_with_jit", "Use JIT compiler for the built-in PCRE2 library", True))
  159. opts.Add(BoolVariable("builtin_recast", "Use the built-in Recast library", True))
  160. opts.Add(BoolVariable("builtin_rvo2", "Use the built-in RVO2 library", True))
  161. opts.Add(BoolVariable("builtin_squish", "Use the built-in squish library", True))
  162. opts.Add(BoolVariable("builtin_xatlas", "Use the built-in xatlas library", True))
  163. opts.Add(BoolVariable("builtin_zlib", "Use the built-in zlib library", True))
  164. opts.Add(BoolVariable("builtin_zstd", "Use the built-in Zstd library", True))
  165. # Compilation environment setup
  166. opts.Add("CXX", "C++ compiler")
  167. opts.Add("CC", "C compiler")
  168. opts.Add("LINK", "Linker")
  169. opts.Add("CCFLAGS", "Custom flags for both the C and C++ compilers")
  170. opts.Add("CFLAGS", "Custom flags for the C compiler")
  171. opts.Add("CXXFLAGS", "Custom flags for the C++ compiler")
  172. opts.Add("LINKFLAGS", "Custom flags for the linker")
  173. # Update the environment to have all above options defined
  174. # in following code (especially platform and custom_modules).
  175. opts.Update(env_base)
  176. # Platform selection: validate input, and add options.
  177. selected_platform = ""
  178. if env_base["platform"] != "":
  179. selected_platform = env_base["platform"]
  180. elif env_base["p"] != "":
  181. selected_platform = env_base["p"]
  182. else:
  183. # Missing `platform` argument, try to detect platform automatically
  184. if (
  185. sys.platform.startswith("linux")
  186. or sys.platform.startswith("dragonfly")
  187. or sys.platform.startswith("freebsd")
  188. or sys.platform.startswith("netbsd")
  189. or sys.platform.startswith("openbsd")
  190. ):
  191. selected_platform = "x11"
  192. elif sys.platform == "darwin":
  193. selected_platform = "osx"
  194. elif sys.platform == "win32":
  195. selected_platform = "windows"
  196. else:
  197. print("Could not detect platform automatically. Supported platforms:")
  198. for x in platform_list:
  199. print("\t" + x)
  200. print("\nPlease run SCons again and select a valid platform: platform=<string>")
  201. if selected_platform != "":
  202. print("Automatically detected platform: " + selected_platform)
  203. if selected_platform == "macos":
  204. # Alias for forward compatibility.
  205. print('Platform "macos" is still called "osx" in Godot 3.x. Building for platform "osx".')
  206. selected_platform = "osx"
  207. if selected_platform == "ios":
  208. # Alias for forward compatibility.
  209. print('Platform "ios" is still called "iphone" in Godot 3.x. Building for platform "iphone".')
  210. selected_platform = "iphone"
  211. if selected_platform in ["linux", "bsd", "linuxbsd"]:
  212. if selected_platform == "linuxbsd":
  213. # Alias for forward compatibility.
  214. print('Platform "linuxbsd" is still called "x11" in Godot 3.x. Building for platform "x11".')
  215. # Alias for convenience.
  216. selected_platform = "x11"
  217. if selected_platform == "web":
  218. # Alias for forward compatibility.
  219. print('Platform "web" is still called "javascript" in Godot 3.x. Building for platform "javascript".')
  220. selected_platform = "javascript"
  221. # Make sure to update this to the found, valid platform as it's used through the buildsystem as the reference.
  222. # It should always be re-set after calling `opts.Update()` otherwise it uses the original input value.
  223. env_base["platform"] = selected_platform
  224. # Add platform-specific options.
  225. if selected_platform in platform_opts:
  226. for opt in platform_opts[selected_platform]:
  227. opts.Add(opt)
  228. # Update the environment to take platform-specific options into account.
  229. opts.Update(env_base)
  230. env_base["platform"] = selected_platform # Must always be re-set after calling opts.Update().
  231. # Detect modules.
  232. modules_detected = OrderedDict()
  233. module_search_paths = ["modules"] # Built-in path.
  234. if env_base["custom_modules"]:
  235. paths = env_base["custom_modules"].split(",")
  236. for p in paths:
  237. try:
  238. module_search_paths.append(methods.convert_custom_modules_path(p))
  239. except ValueError as e:
  240. print(e)
  241. sys.exit(255)
  242. for path in module_search_paths:
  243. if path == "modules":
  244. # Built-in modules don't have nested modules,
  245. # so save the time it takes to parse directories.
  246. modules = methods.detect_modules(path, recursive=False)
  247. else: # Custom.
  248. modules = methods.detect_modules(path, env_base["custom_modules_recursive"])
  249. # Provide default include path for both the custom module search `path`
  250. # and the base directory containing custom modules, as it may be different
  251. # from the built-in "modules" name (e.g. "custom_modules/summator/summator.h"),
  252. # so it can be referenced simply as `#include "summator/summator.h"`
  253. # independently of where a module is located on user's filesystem.
  254. env_base.Prepend(CPPPATH=[path, os.path.dirname(path)])
  255. # Note: custom modules can override built-in ones.
  256. modules_detected.update(modules)
  257. # Add module options
  258. for name, path in modules_detected.items():
  259. sys.path.insert(0, path)
  260. import config
  261. if env_base["modules_enabled_by_default"]:
  262. enabled = True
  263. try:
  264. enabled = config.is_enabled()
  265. except AttributeError:
  266. pass
  267. else:
  268. enabled = False
  269. sys.path.remove(path)
  270. sys.modules.pop("config")
  271. opts.Add(BoolVariable("module_" + name + "_enabled", "Enable module '%s'" % (name,), enabled))
  272. methods.write_modules(modules_detected)
  273. # Update the environment again after all the module options are added.
  274. opts.Update(env_base)
  275. env_base["platform"] = selected_platform # Must always be re-set after calling opts.Update().
  276. Help(opts.GenerateHelpText(env_base))
  277. # add default include paths
  278. env_base.Prepend(CPPPATH=["#"])
  279. # configure ENV for platform
  280. env_base.platform_exporters = platform_exporters
  281. env_base.platform_apis = platform_apis
  282. # Build type defines - more platform-specific ones can be in detect.py.
  283. if env_base["target"] == "release_debug" or env_base["target"] == "debug":
  284. # DEBUG_ENABLED enables debugging *features* and debug-only code, which is intended
  285. # to give *users* extra debugging information for their game development.
  286. env_base.Append(CPPDEFINES=["DEBUG_ENABLED"])
  287. if env_base["target"] == "debug":
  288. # DEV_ENABLED enables *engine developer* code which should only be compiled for those
  289. # working on the engine itself.
  290. env_base.Append(CPPDEFINES=["DEV_ENABLED"])
  291. else:
  292. # Disable assert() for production targets (only used in thirdparty code).
  293. env_base.Append(CPPDEFINES=["NDEBUG"])
  294. # SCons speed optimization controlled by the `fast_unsafe` option, which provide
  295. # more than 10 s speed up for incremental rebuilds.
  296. # Unsafe as they reduce the certainty of rebuilding all changed files, so it's
  297. # enabled by default for `debug` builds, and can be overridden from command line.
  298. # Ref: https://github.com/SCons/scons/wiki/GoFastButton
  299. if methods.get_cmdline_bool("fast_unsafe", env_base["target"] == "debug"):
  300. # Renamed to `content-timestamp` in SCons >= 4.2, keeping MD5 for compat.
  301. env_base.Decider("MD5-timestamp")
  302. env_base.SetOption("implicit_cache", 1)
  303. env_base.SetOption("max_drift", 60)
  304. if env_base["use_precise_math_checks"]:
  305. env_base.Append(CPPDEFINES=["PRECISE_MATH_CHECKS"])
  306. if env_base["tools"]:
  307. if not env_base.File("#main/splash_editor.png").exists():
  308. # Force disabling editor splash if missing.
  309. env_base["no_editor_splash"] = True
  310. if env_base["no_editor_splash"]:
  311. env_base.Append(CPPDEFINES=["NO_EDITOR_SPLASH"])
  312. if not env_base["deprecated"]:
  313. env_base.Append(CPPDEFINES=["DISABLE_DEPRECATED"])
  314. if env_base["rids"] == "handles":
  315. env_base.Append(CPPDEFINES=["RID_HANDLES_ENABLED"])
  316. print("WARNING: Building with RIDs as handles.")
  317. if env_base["rids"] == "tracked_handles":
  318. env_base.Append(CPPDEFINES=["RID_HANDLES_ENABLED"])
  319. env_base.Append(CPPDEFINES=["RID_HANDLE_ALLOCATION_TRACKING_ENABLED"])
  320. print("WARNING: Building with RIDs as tracked handles.")
  321. if selected_platform in platform_list:
  322. tmppath = "./platform/" + selected_platform
  323. sys.path.insert(0, tmppath)
  324. import detect
  325. env = env_base.Clone()
  326. # Default num_jobs to local cpu count if not user specified.
  327. # SCons has a peculiarity where user-specified options won't be overridden
  328. # by SetOption, so we can rely on this to know if we should use our default.
  329. initial_num_jobs = env.GetOption("num_jobs")
  330. altered_num_jobs = initial_num_jobs + 1
  331. env.SetOption("num_jobs", altered_num_jobs)
  332. # os.cpu_count() requires Python 3.4+.
  333. if hasattr(os, "cpu_count") and env.GetOption("num_jobs") == altered_num_jobs:
  334. cpu_count = os.cpu_count()
  335. if cpu_count is None:
  336. print("Couldn't auto-detect CPU count to configure build parallelism. Specify it with the -j argument.")
  337. else:
  338. safer_cpu_count = cpu_count if cpu_count <= 4 else cpu_count - 1
  339. print(
  340. "Auto-detected %d CPU cores available for build parallelism. Using %d cores by default. You can override it with the -j argument."
  341. % (cpu_count, safer_cpu_count)
  342. )
  343. env.SetOption("num_jobs", safer_cpu_count)
  344. env.extra_suffix = ""
  345. if env["extra_suffix"] != "":
  346. env.extra_suffix += "." + env["extra_suffix"]
  347. # Environment flags
  348. CCFLAGS = env.get("CCFLAGS", "")
  349. env["CCFLAGS"] = ""
  350. env.Append(CCFLAGS=str(CCFLAGS).split())
  351. CFLAGS = env.get("CFLAGS", "")
  352. env["CFLAGS"] = ""
  353. env.Append(CFLAGS=str(CFLAGS).split())
  354. CXXFLAGS = env.get("CXXFLAGS", "")
  355. env["CXXFLAGS"] = ""
  356. env.Append(CXXFLAGS=str(CXXFLAGS).split())
  357. LINKFLAGS = env.get("LINKFLAGS", "")
  358. env["LINKFLAGS"] = ""
  359. env.Append(LINKFLAGS=str(LINKFLAGS).split())
  360. # Platform specific flags.
  361. # These can sometimes override default options.
  362. flag_list = platform_flags[selected_platform]
  363. for f in flag_list:
  364. if not (f[0] in ARGUMENTS): # allow command line to override platform flags
  365. env[f[0]] = f[1]
  366. # 'dev' and 'production' are aliases to set default options if they haven't been
  367. # set manually by the user.
  368. # These need to be checked *after* platform specific flags so that different
  369. # default values can be set (e.g. to keep LTO off for `production` on some platforms).
  370. if env["dev"]:
  371. env["verbose"] = methods.get_cmdline_bool("verbose", True)
  372. env["warnings"] = ARGUMENTS.get("warnings", "extra")
  373. env["werror"] = methods.get_cmdline_bool("werror", True)
  374. if env["production"]:
  375. env["use_static_cpp"] = methods.get_cmdline_bool("use_static_cpp", True)
  376. env["debug_symbols"] = methods.get_cmdline_bool("debug_symbols", False)
  377. # LTO "auto" means we handle the preferred option in each platform detect.py.
  378. env["lto"] = ARGUMENTS.get("lto", "auto")
  379. if not env["tools"] and env["target"] == "debug":
  380. print(
  381. "WARNING: Requested `production` build with `tools=no target=debug`, "
  382. "this will give you a full debug template (use `target=release_debug` "
  383. "for an optimized template with debug features)."
  384. )
  385. # Run SCU file generation script if in a SCU build.
  386. if env["scu_build"]:
  387. methods.set_scu_folders(scu_builders.generate_scu_files(env["verbose"], env_base["target"] != "debug"))
  388. # Must happen after the flags' definition, as configure is when most flags
  389. # are actually handled to change compile options, etc.
  390. detect.configure(env)
  391. # Needs to happen after configure to handle "auto".
  392. if env["lto"] != "none":
  393. print("Using LTO: " + env["lto"])
  394. # Set our C and C++ standard requirements.
  395. # Prepending to make it possible to override
  396. # This needs to come after `configure`, otherwise we don't have env.msvc.
  397. if not env.msvc:
  398. # Specifying GNU extensions support explicitly, which are supported by
  399. # both GCC and Clang. This mirrors GCC and Clang's current default
  400. # compile flags if no -std is specified.
  401. env.Prepend(CFLAGS=["-std=gnu11"])
  402. env.Prepend(CXXFLAGS=["-std=gnu++14"])
  403. else:
  404. # MSVC doesn't have clear C standard support, /std only covers C++.
  405. # We apply it to CCFLAGS (both C and C++ code) in case it impacts C features.
  406. env.Prepend(CCFLAGS=["/std:c++14"])
  407. # Handle renamed options.
  408. if "use_lto" in ARGUMENTS or "use_thinlto" in ARGUMENTS:
  409. print("Error: The `use_lto` and `use_thinlto` boolean options have been unified to `lto=<none|thin|full>`.")
  410. print(" Please adjust your scripts accordingly.")
  411. Exit(255)
  412. if "use_lld" in ARGUMENTS:
  413. print("Error: The `use_lld` boolean option has been replaced by `linker=<default|bfd|gold|lld|mold>`.")
  414. print(" Please adjust your scripts accordingly.")
  415. Exit(255)
  416. # Disable exception handling. Godot doesn't use exceptions anywhere, and this
  417. # saves around 20% of binary size and very significant build time (GH-80513).
  418. if env["disable_exceptions"]:
  419. if env.msvc:
  420. env.Append(CPPDEFINES=[("_HAS_EXCEPTIONS", 0)])
  421. else:
  422. env.Append(CCFLAGS=["-fno-exceptions"])
  423. elif env.msvc:
  424. env.Append(CCFLAGS=["/EHsc"])
  425. # Configure compiler warnings
  426. if env.msvc: # MSVC
  427. # Truncations, narrowing conversions, signed/unsigned comparisons...
  428. disable_nonessential_warnings = ["/wd4267", "/wd4244", "/wd4305", "/wd4018", "/wd4800"]
  429. if env["warnings"] == "extra":
  430. env.Append(CCFLAGS=["/Wall"]) # Implies /W4
  431. elif env["warnings"] == "all":
  432. env.Append(CCFLAGS=["/W3"] + disable_nonessential_warnings)
  433. elif env["warnings"] == "moderate":
  434. env.Append(CCFLAGS=["/W2"] + disable_nonessential_warnings)
  435. else: # 'no'
  436. env.Append(CCFLAGS=["/w"])
  437. if env["werror"]:
  438. env.Append(CCFLAGS=["/WX"])
  439. env.Append(LINKFLAGS=["/WX"])
  440. else: # GCC, Clang
  441. version = methods.get_compiler_version(env) or [-1, -1]
  442. common_warnings = []
  443. if methods.using_gcc(env):
  444. common_warnings += ["-Wno-misleading-indentation"]
  445. if version[0] >= 7:
  446. common_warnings += ["-Wshadow-local"]
  447. elif methods.using_clang(env) or methods.using_emcc(env):
  448. # We often implement `operator<` for structs of pointers as a requirement
  449. # for putting them in `Set` or `Map`. We don't mind about unreliable ordering.
  450. common_warnings += ["-Wno-ordered-compare-function-pointers"]
  451. if env["warnings"] == "extra":
  452. # Note: enable -Wimplicit-fallthrough for Clang (already part of -Wextra for GCC)
  453. # once we switch to C++11 or later (necessary for our FALLTHROUGH macro).
  454. env.Append(CCFLAGS=["-Wall", "-Wextra", "-Wwrite-strings", "-Wno-unused-parameter"] + common_warnings)
  455. env.Append(CXXFLAGS=["-Wctor-dtor-privacy", "-Wnon-virtual-dtor"])
  456. if methods.using_gcc(env):
  457. env.Append(
  458. CCFLAGS=[
  459. "-Walloc-zero",
  460. "-Wduplicated-branches",
  461. "-Wduplicated-cond",
  462. "-Wstringop-overflow=4",
  463. "-Wlogical-op",
  464. ]
  465. )
  466. env.Append(CXXFLAGS=["-Wnoexcept", "-Wplacement-new=1"])
  467. if version[0] >= 9:
  468. env.Append(CCFLAGS=["-Wattribute-alias=2"])
  469. elif env["warnings"] == "all":
  470. env.Append(CCFLAGS=["-Wall"] + common_warnings)
  471. elif env["warnings"] == "moderate":
  472. env.Append(CCFLAGS=["-Wall", "-Wno-unused"] + common_warnings)
  473. else: # 'no'
  474. env.Append(CCFLAGS=["-w"])
  475. if env["werror"]:
  476. env.Append(CCFLAGS=["-Werror"])
  477. if methods.using_gcc(env) and version[0] >= 12: # False positives in our error macros, see GH-58747.
  478. env.Append(CCFLAGS=["-Wno-error=return-type"])
  479. if hasattr(detect, "get_program_suffix"):
  480. suffix = "." + detect.get_program_suffix()
  481. else:
  482. suffix = "." + selected_platform
  483. if env["target"] == "release":
  484. if env["tools"]:
  485. print("ERROR: The editor can only be built with `target=debug` or `target=release_debug`.")
  486. print(" Use `tools=no target=release` to build a release export template.")
  487. Exit(255)
  488. suffix += ".opt"
  489. elif env["target"] == "release_debug":
  490. if env["tools"]:
  491. suffix += ".opt.tools"
  492. else:
  493. suffix += ".opt.debug"
  494. else:
  495. if env["tools"]:
  496. print(
  497. "Note: Building a debug binary (which will run slowly). Use `target=release_debug` to build an optimized release binary."
  498. )
  499. suffix += ".tools"
  500. else:
  501. print(
  502. "Note: Building a debug binary (which will run slowly). Use `target=release` to build an optimized release binary."
  503. )
  504. suffix += ".debug"
  505. if env["arch"] != "":
  506. suffix += "." + env["arch"]
  507. elif env["bits"] == "32":
  508. suffix += ".32"
  509. elif env["bits"] == "64":
  510. suffix += ".64"
  511. suffix += env.extra_suffix
  512. sys.path.remove(tmppath)
  513. sys.modules.pop("detect")
  514. modules_enabled = OrderedDict()
  515. env.module_icons_paths = []
  516. env.doc_class_path = {}
  517. for name, path in modules_detected.items():
  518. if not env["module_" + name + "_enabled"]:
  519. continue
  520. sys.path.insert(0, path)
  521. env.current_module = name
  522. import config
  523. # can_build changed number of arguments between 3.0 (1) and 3.1 (2),
  524. # so try both to preserve compatibility for 3.0 modules
  525. can_build = False
  526. try:
  527. can_build = config.can_build(env, selected_platform)
  528. except TypeError:
  529. print(
  530. "Warning: module '%s' uses a deprecated `can_build` "
  531. "signature in its config.py file, it should be "
  532. "`can_build(env, platform)`." % x
  533. )
  534. can_build = config.can_build(selected_platform)
  535. if can_build:
  536. config.configure(env)
  537. # Get doc classes paths (if present)
  538. try:
  539. doc_classes = config.get_doc_classes()
  540. doc_path = config.get_doc_path()
  541. for c in doc_classes:
  542. env.doc_class_path[c] = path + "/" + doc_path
  543. except Exception:
  544. pass
  545. # Get icon paths (if present)
  546. try:
  547. icons_path = config.get_icons_path()
  548. env.module_icons_paths.append(path + "/" + icons_path)
  549. except Exception:
  550. # Default path for module icons
  551. env.module_icons_paths.append(path + "/" + "icons")
  552. modules_enabled[name] = path
  553. sys.path.remove(path)
  554. sys.modules.pop("config")
  555. env.module_list = modules_enabled
  556. methods.generate_version_header(env.module_version_string)
  557. env["PROGSUFFIX"] = suffix + env.module_version_string + env["PROGSUFFIX"]
  558. env["OBJSUFFIX"] = suffix + env["OBJSUFFIX"]
  559. # (SH)LIBSUFFIX will be used for our own built libraries
  560. # LIBSUFFIXES contains LIBSUFFIX and SHLIBSUFFIX by default,
  561. # so we need to append the default suffixes to keep the ability
  562. # to link against thirdparty libraries (.a, .so, .lib, etc.).
  563. if os.name == "nt":
  564. # On Windows, only static libraries and import libraries can be
  565. # statically linked - both using .lib extension
  566. env["LIBSUFFIXES"] += [env["LIBSUFFIX"]]
  567. else:
  568. env["LIBSUFFIXES"] += [env["LIBSUFFIX"], env["SHLIBSUFFIX"]]
  569. env["LIBSUFFIX"] = suffix + env["LIBSUFFIX"]
  570. env["SHLIBSUFFIX"] = suffix + env["SHLIBSUFFIX"]
  571. if env.use_ptrcall:
  572. env.Append(CPPDEFINES=["PTRCALL_ENABLED"])
  573. if env["tools"]:
  574. env.Append(CPPDEFINES=["TOOLS_ENABLED"])
  575. if env["disable_3d"]:
  576. if env["tools"]:
  577. print(
  578. "Build option 'disable_3d=yes' cannot be used with 'tools=yes' (editor), "
  579. "only with 'tools=no' (export template)."
  580. )
  581. sys.exit(255)
  582. else:
  583. env.Append(CPPDEFINES=["_3D_DISABLED"])
  584. if env["disable_advanced_gui"]:
  585. if env["tools"]:
  586. print(
  587. "Build option 'disable_advanced_gui=yes' cannot be used with 'tools=yes' (editor), "
  588. "only with 'tools=no' (export template)."
  589. )
  590. sys.exit(255)
  591. else:
  592. env.Append(CPPDEFINES=["ADVANCED_GUI_DISABLED"])
  593. if env["minizip"]:
  594. env.Append(CPPDEFINES=["MINIZIP_ENABLED"])
  595. editor_module_list = ["freetype"]
  596. for x in editor_module_list:
  597. if not env["module_" + x + "_enabled"]:
  598. if env["tools"]:
  599. print(
  600. "Build option 'module_" + x + "_enabled=no' cannot be used with 'tools=yes' (editor), "
  601. "only with 'tools=no' (export template)."
  602. )
  603. sys.exit(255)
  604. if not env["verbose"]:
  605. methods.no_verbose(sys, env)
  606. if not env["platform"] == "server": # FIXME: detect GLES3
  607. env.Append(
  608. BUILDERS={
  609. "GLES3_GLSL": env.Builder(
  610. action=run_in_subprocess(gles_builders.build_gles3_headers), suffix="glsl.gen.h", src_suffix=".glsl"
  611. )
  612. }
  613. )
  614. env.Append(
  615. BUILDERS={
  616. "GLES2_GLSL": env.Builder(
  617. action=run_in_subprocess(gles_builders.build_gles2_headers), suffix="glsl.gen.h", src_suffix=".glsl"
  618. )
  619. }
  620. )
  621. scons_cache_path = os.environ.get("SCONS_CACHE")
  622. if scons_cache_path != None:
  623. CacheDir(scons_cache_path)
  624. print("Scons cache enabled... (path: '" + scons_cache_path + "')")
  625. if env["vsproj"]:
  626. env.vs_incs = []
  627. env.vs_srcs = []
  628. if env["compiledb"]:
  629. # Generating the compilation DB (`compile_commands.json`) requires SCons 4.0.0 or later.
  630. from SCons import __version__ as scons_raw_version
  631. scons_ver = env._get_major_minor_revision(scons_raw_version)
  632. if scons_ver < (4, 0, 0):
  633. print("The `compiledb=yes` option requires SCons 4.0 or later, but your version is %s." % scons_raw_version)
  634. Exit(255)
  635. env.Tool("compilation_db")
  636. env.Alias("compiledb", env.CompilationDatabase())
  637. Export("env")
  638. # build subdirs, the build order is dependent on link order.
  639. SConscript("core/SCsub")
  640. SConscript("servers/SCsub")
  641. SConscript("scene/SCsub")
  642. if env["tools"]:
  643. SConscript("editor/SCsub")
  644. SConscript("drivers/SCsub")
  645. SConscript("platform/SCsub")
  646. SConscript("modules/SCsub")
  647. SConscript("main/SCsub")
  648. SConscript("platform/" + selected_platform + "/SCsub") # build selected platform
  649. # Microsoft Visual Studio Project Generation
  650. if env["vsproj"]:
  651. if os.name != "nt":
  652. print("Error: The `vsproj` option is only usable on Windows with Visual Studio.")
  653. Exit(255)
  654. env["CPPPATH"] = [Dir(path) for path in env["CPPPATH"]]
  655. methods.generate_vs_project(env, GetOption("num_jobs"))
  656. methods.generate_cpp_hint_file("cpp.hint")
  657. # Check for the existence of headers
  658. conf = Configure(env)
  659. if "check_c_headers" in env:
  660. for header in env["check_c_headers"]:
  661. if conf.CheckCHeader(header[0]):
  662. env.AppendUnique(CPPDEFINES=[header[1]])
  663. elif selected_platform != "":
  664. if selected_platform == "list":
  665. print("The following platforms are available:\n")
  666. else:
  667. print('Invalid target platform "' + selected_platform + '".')
  668. print("The following platforms were detected:\n")
  669. for x in platform_list:
  670. print("\t" + x)
  671. print("\nPlease run SCons again and select a valid platform: platform=<string>")
  672. if selected_platform == "list":
  673. # Exit early to suppress the rest of the built-in SCons messages
  674. sys.exit(0)
  675. else:
  676. sys.exit(255)
  677. # The following only makes sense when the 'env' is defined, and assumes it is.
  678. if "env" in locals():
  679. methods.show_progress(env)
  680. # TODO: replace this with `env.Dump(format="json")`
  681. # once we start requiring SCons 4.0 as min version.
  682. methods.dump(env)
  683. methods.clean_cache(env)
  684. def print_elapsed_time():
  685. elapsed_time_sec = round(time.time() - time_at_start, 3)
  686. time_ms = round((elapsed_time_sec % 1) * 1000)
  687. print("[Time elapsed: {}.{:03}]".format(time.strftime("%H:%M:%S", time.gmtime(elapsed_time_sec)), time_ms))
  688. atexit.register(print_elapsed_time)