SConstruct 31 KB

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