detect.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  1. import os
  2. import re
  3. import subprocess
  4. import sys
  5. from typing import TYPE_CHECKING
  6. import methods
  7. from methods import print_error, print_warning
  8. from platform_methods import detect_arch
  9. if TYPE_CHECKING:
  10. from SCons.Script.SConscript import SConsEnvironment
  11. # To match other platforms
  12. STACK_SIZE = 8388608
  13. STACK_SIZE_SANITIZERS = 30 * 1024 * 1024
  14. def get_name():
  15. return "Windows"
  16. def try_cmd(test, prefix, arch, check_clang=False):
  17. archs = ["x86_64", "x86_32", "arm64", "arm32"]
  18. if arch:
  19. archs = [arch]
  20. for a in archs:
  21. try:
  22. out = subprocess.Popen(
  23. get_mingw_bin_prefix(prefix, a) + test,
  24. shell=True,
  25. stderr=subprocess.PIPE,
  26. stdout=subprocess.PIPE,
  27. )
  28. outs, errs = out.communicate()
  29. if out.returncode == 0:
  30. if check_clang and not outs.startswith(b"clang"):
  31. return False
  32. return True
  33. except Exception:
  34. pass
  35. return False
  36. def can_build():
  37. if os.name == "nt":
  38. # Building natively on Windows
  39. # If VCINSTALLDIR is set in the OS environ, use traditional Godot logic to set up MSVC
  40. if os.getenv("VCINSTALLDIR"): # MSVC, manual setup
  41. return True
  42. # Otherwise, let SCons find MSVC if installed, or else MinGW.
  43. # Since we're just returning True here, if there's no compiler
  44. # installed, we'll get errors when it tries to build with the
  45. # null compiler.
  46. return True
  47. if os.name == "posix":
  48. # Cross-compiling with MinGW-w64 (old MinGW32 is not supported)
  49. prefix = os.getenv("MINGW_PREFIX", "")
  50. if try_cmd("gcc --version", prefix, "") or try_cmd("clang --version", prefix, ""):
  51. return True
  52. return False
  53. def get_mingw_bin_prefix(prefix, arch):
  54. if not prefix:
  55. mingw_bin_prefix = ""
  56. elif prefix[-1] != "/":
  57. mingw_bin_prefix = prefix + "/bin/"
  58. else:
  59. mingw_bin_prefix = prefix + "bin/"
  60. if arch == "x86_64":
  61. mingw_bin_prefix += "x86_64-w64-mingw32-"
  62. elif arch == "x86_32":
  63. mingw_bin_prefix += "i686-w64-mingw32-"
  64. elif arch == "arm32":
  65. mingw_bin_prefix += "armv7-w64-mingw32-"
  66. elif arch == "arm64":
  67. mingw_bin_prefix += "aarch64-w64-mingw32-"
  68. return mingw_bin_prefix
  69. def detect_build_env_arch():
  70. msvc_target_aliases = {
  71. "amd64": "x86_64",
  72. "i386": "x86_32",
  73. "i486": "x86_32",
  74. "i586": "x86_32",
  75. "i686": "x86_32",
  76. "x86": "x86_32",
  77. "x64": "x86_64",
  78. "x86_64": "x86_64",
  79. "arm": "arm32",
  80. "arm64": "arm64",
  81. "aarch64": "arm64",
  82. }
  83. if os.getenv("VCINSTALLDIR") or os.getenv("VCTOOLSINSTALLDIR"):
  84. if os.getenv("Platform"):
  85. msvc_arch = os.getenv("Platform").lower()
  86. if msvc_arch in msvc_target_aliases.keys():
  87. return msvc_target_aliases[msvc_arch]
  88. if os.getenv("VSCMD_ARG_TGT_ARCH"):
  89. msvc_arch = os.getenv("VSCMD_ARG_TGT_ARCH").lower()
  90. if msvc_arch in msvc_target_aliases.keys():
  91. return msvc_target_aliases[msvc_arch]
  92. # Pre VS 2017 checks.
  93. if os.getenv("VCINSTALLDIR"):
  94. PATH = os.getenv("PATH").upper()
  95. VCINSTALLDIR = os.getenv("VCINSTALLDIR").upper()
  96. path_arch = {
  97. "BIN\\x86_ARM;": "arm32",
  98. "BIN\\amd64_ARM;": "arm32",
  99. "BIN\\x86_ARM64;": "arm64",
  100. "BIN\\amd64_ARM64;": "arm64",
  101. "BIN\\x86_amd64;": "a86_64",
  102. "BIN\\amd64;": "x86_64",
  103. "BIN\\amd64_x86;": "x86_32",
  104. "BIN;": "x86_32",
  105. }
  106. for path, arch in path_arch.items():
  107. final_path = VCINSTALLDIR + path
  108. if final_path in PATH:
  109. return arch
  110. # VS 2017 and newer.
  111. if os.getenv("VCTOOLSINSTALLDIR"):
  112. host_path_index = os.getenv("PATH").upper().find(os.getenv("VCTOOLSINSTALLDIR").upper() + "BIN\\HOST")
  113. if host_path_index > -1:
  114. first_path_arch = os.getenv("PATH")[host_path_index:].split(";")[0].rsplit("\\", 1)[-1].lower()
  115. if first_path_arch in msvc_target_aliases.keys():
  116. return msvc_target_aliases[first_path_arch]
  117. msys_target_aliases = {
  118. "mingw32": "x86_32",
  119. "mingw64": "x86_64",
  120. "ucrt64": "x86_64",
  121. "clang64": "x86_64",
  122. "clang32": "x86_32",
  123. "clangarm64": "arm64",
  124. }
  125. if os.getenv("MSYSTEM"):
  126. msys_arch = os.getenv("MSYSTEM").lower()
  127. if msys_arch in msys_target_aliases.keys():
  128. return msys_target_aliases[msys_arch]
  129. return ""
  130. def get_opts():
  131. from SCons.Variables import BoolVariable, EnumVariable
  132. mingw = os.getenv("MINGW_PREFIX", "")
  133. # Direct3D 12 SDK dependencies folder.
  134. d3d12_deps_folder = os.getenv("LOCALAPPDATA")
  135. if d3d12_deps_folder:
  136. d3d12_deps_folder = os.path.join(d3d12_deps_folder, "Godot", "build_deps")
  137. else:
  138. # Cross-compiling, the deps install script puts things in `bin`.
  139. # Getting an absolute path to it is a bit hacky in Python.
  140. try:
  141. import inspect
  142. caller_frame = inspect.stack()[1]
  143. caller_script_dir = os.path.dirname(os.path.abspath(caller_frame[1]))
  144. d3d12_deps_folder = os.path.join(caller_script_dir, "bin", "build_deps")
  145. except Exception: # Give up.
  146. d3d12_deps_folder = ""
  147. return [
  148. ("mingw_prefix", "MinGW prefix", mingw),
  149. # Targeted Windows version: 7 (and later), minimum supported version
  150. # XP support dropped after EOL due to missing API for IPv6 and other issues
  151. # Vista support dropped after EOL due to GH-10243
  152. (
  153. "target_win_version",
  154. "Targeted Windows version, >= 0x0601 (Windows 7)",
  155. "0x0601",
  156. ),
  157. EnumVariable("windows_subsystem", "Windows subsystem", "gui", ("gui", "console")),
  158. (
  159. "msvc_version",
  160. "MSVC version to use. Ignored if VCINSTALLDIR is set in shell env.",
  161. None,
  162. ),
  163. BoolVariable("use_mingw", "Use the Mingw compiler, even if MSVC is installed.", False),
  164. BoolVariable("use_llvm", "Use the LLVM compiler", False),
  165. BoolVariable("use_static_cpp", "Link MinGW/MSVC C++ runtime libraries statically", True),
  166. BoolVariable("use_asan", "Use address sanitizer (ASAN)", False),
  167. BoolVariable("use_ubsan", "Use LLVM compiler undefined behavior sanitizer (UBSAN)", False),
  168. BoolVariable("debug_crt", "Compile with MSVC's debug CRT (/MDd)", False),
  169. BoolVariable("incremental_link", "Use MSVC incremental linking. May increase or decrease build times.", False),
  170. BoolVariable("silence_msvc", "Silence MSVC's cl/link stdout bloat, redirecting any errors to stderr.", True),
  171. ("angle_libs", "Path to the ANGLE static libraries", ""),
  172. # Direct3D 12 support.
  173. (
  174. "mesa_libs",
  175. "Path to the MESA/NIR static libraries (required for D3D12)",
  176. os.path.join(d3d12_deps_folder, "mesa"),
  177. ),
  178. (
  179. "agility_sdk_path",
  180. "Path to the Agility SDK distribution (optional for D3D12)",
  181. os.path.join(d3d12_deps_folder, "agility_sdk"),
  182. ),
  183. BoolVariable(
  184. "agility_sdk_multiarch",
  185. "Whether the Agility SDK DLLs will be stored in arch-specific subdirectories",
  186. False,
  187. ),
  188. BoolVariable("use_pix", "Use PIX (Performance tuning and debugging for DirectX 12) runtime", False),
  189. (
  190. "pix_path",
  191. "Path to the PIX runtime distribution (optional for D3D12)",
  192. os.path.join(d3d12_deps_folder, "pix"),
  193. ),
  194. ]
  195. def get_doc_classes():
  196. return [
  197. "EditorExportPlatformWindows",
  198. ]
  199. def get_doc_path():
  200. return "doc_classes"
  201. def get_flags():
  202. arch = detect_build_env_arch() or detect_arch()
  203. return {
  204. "arch": arch,
  205. "supported": ["d3d12", "mono", "xaudio2"],
  206. }
  207. def build_res_file(target, source, env: "SConsEnvironment"):
  208. arch_aliases = {
  209. "x86_32": "pe-i386",
  210. "x86_64": "pe-x86-64",
  211. "arm32": "armv7-w64-mingw32",
  212. "arm64": "aarch64-w64-mingw32",
  213. }
  214. cmdbase = "windres --include-dir . --target=" + arch_aliases[env["arch"]]
  215. mingw_bin_prefix = get_mingw_bin_prefix(env["mingw_prefix"], env["arch"])
  216. for x in range(len(source)):
  217. ok = True
  218. # Try prefixed executable (MinGW on Linux).
  219. cmd = mingw_bin_prefix + cmdbase + " -i " + str(source[x]) + " -o " + str(target[x])
  220. try:
  221. out = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE).communicate()
  222. if len(out[1]):
  223. ok = False
  224. except Exception:
  225. ok = False
  226. # Try generic executable (MSYS2).
  227. if not ok:
  228. cmd = cmdbase + " -i " + str(source[x]) + " -o " + str(target[x])
  229. try:
  230. out = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE).communicate()
  231. if len(out[1]):
  232. return -1
  233. except Exception:
  234. return -1
  235. return 0
  236. def setup_msvc_manual(env: "SConsEnvironment"):
  237. """Running from VCVARS environment"""
  238. env_arch = detect_build_env_arch()
  239. if env["arch"] != env_arch:
  240. print_error(
  241. "Arch argument (%s) is not matching Native/Cross Compile Tools Prompt/Developer Console (or Visual Studio settings) that is being used to run SCons (%s).\n"
  242. "Run SCons again without arch argument (example: scons p=windows) and SCons will attempt to detect what MSVC compiler will be executed and inform you."
  243. % (env["arch"], env_arch)
  244. )
  245. sys.exit(255)
  246. print("Using VCVARS-determined MSVC, arch %s" % (env_arch))
  247. def setup_msvc_auto(env: "SConsEnvironment"):
  248. """Set up MSVC using SCons's auto-detection logic"""
  249. # If MSVC_VERSION is set by SCons, we know MSVC is installed.
  250. # But we may want a different version or target arch.
  251. # Valid architectures for MSVC's TARGET_ARCH:
  252. # ['amd64', 'emt64', 'i386', 'i486', 'i586', 'i686', 'ia64', 'itanium', 'x86', 'x86_64', 'arm', 'arm64', 'aarch64']
  253. # Our x86_64 and arm64 are the same, and we need to map the 32-bit
  254. # architectures to other names since MSVC isn't as explicit.
  255. # The rest we don't need to worry about because they are
  256. # aliases or aren't supported by Godot (itanium & ia64).
  257. msvc_arch_aliases = {"x86_32": "x86", "arm32": "arm"}
  258. if env["arch"] in msvc_arch_aliases.keys():
  259. env["TARGET_ARCH"] = msvc_arch_aliases[env["arch"]]
  260. else:
  261. env["TARGET_ARCH"] = env["arch"]
  262. # The env may have already been set up with default MSVC tools, so
  263. # reset a few things so we can set it up with the tools we want.
  264. # (Ideally we'd decide on the tool config before configuring any
  265. # environment, and just set the env up once, but this function runs
  266. # on an existing env so this is the simplest way.)
  267. env["MSVC_SETUP_RUN"] = False # Need to set this to re-run the tool
  268. env["MSVS_VERSION"] = None
  269. env["MSVC_VERSION"] = None
  270. if "msvc_version" in env:
  271. env["MSVC_VERSION"] = env["msvc_version"]
  272. env.Tool("msvc")
  273. env.Tool("mssdk") # we want the MS SDK
  274. # Re-add potentially overwritten flags.
  275. env.AppendUnique(CCFLAGS=env.get("ccflags", "").split())
  276. env.AppendUnique(CXXFLAGS=env.get("cxxflags", "").split())
  277. env.AppendUnique(CFLAGS=env.get("cflags", "").split())
  278. env.AppendUnique(RCFLAGS=env.get("rcflags", "").split())
  279. # Note: actual compiler version can be found in env['MSVC_VERSION'], e.g. "14.1" for VS2015
  280. print("Using SCons-detected MSVC version %s, arch %s" % (env["MSVC_VERSION"], env["arch"]))
  281. def setup_mingw(env: "SConsEnvironment"):
  282. """Set up env for use with mingw"""
  283. env_arch = detect_build_env_arch()
  284. if os.getenv("MSYSTEM") == "MSYS":
  285. print_error(
  286. "Running from base MSYS2 console/environment, use target specific environment instead (e.g., mingw32, mingw64, clang32, clang64)."
  287. )
  288. sys.exit(255)
  289. if env_arch != "" and env["arch"] != env_arch:
  290. print_error(
  291. "Arch argument (%s) is not matching MSYS2 console/environment that is being used to run SCons (%s).\n"
  292. "Run SCons again without arch argument (example: scons p=windows) and SCons will attempt to detect what MSYS2 compiler will be executed and inform you."
  293. % (env["arch"], env_arch)
  294. )
  295. sys.exit(255)
  296. if not try_cmd("gcc --version", env["mingw_prefix"], env["arch"]) and not try_cmd(
  297. "clang --version", env["mingw_prefix"], env["arch"]
  298. ):
  299. print_error("No valid compilers found, use MINGW_PREFIX environment variable to set MinGW path.")
  300. sys.exit(255)
  301. print("Using MinGW, arch %s" % (env["arch"]))
  302. def configure_msvc(env: "SConsEnvironment", vcvars_msvc_config):
  303. """Configure env to work with MSVC"""
  304. ## Build type
  305. # TODO: Re-evaluate the need for this / streamline with common config.
  306. if env["target"] == "template_release":
  307. env.Append(LINKFLAGS=["/ENTRY:mainCRTStartup"])
  308. if env["windows_subsystem"] == "gui":
  309. env.Append(LINKFLAGS=["/SUBSYSTEM:WINDOWS"])
  310. else:
  311. env.Append(LINKFLAGS=["/SUBSYSTEM:CONSOLE"])
  312. env.AppendUnique(CPPDEFINES=["WINDOWS_SUBSYSTEM_CONSOLE"])
  313. ## Compile/link flags
  314. env["MAXLINELENGTH"] = 8192 # Windows Vista and beyond, so always applicable.
  315. if env["silence_msvc"] and not env.GetOption("clean"):
  316. from tempfile import mkstemp
  317. # Ensure we have a location to write captured output to, in case of false positives.
  318. capture_path = methods.base_folder_path + "platform/windows/msvc_capture.log"
  319. with open(capture_path, "wt", encoding="utf-8"):
  320. pass
  321. old_spawn = env["SPAWN"]
  322. re_redirect_stream = re.compile(r"^[12]?>")
  323. re_cl_capture = re.compile(r"^.+\.(c|cc|cpp|cxx|c[+]{2})$", re.IGNORECASE)
  324. re_link_capture = re.compile(r'\s{3}\S.+\s(?:"[^"]+.lib"|\S+.lib)\s.+\s(?:"[^"]+.exp"|\S+.exp)')
  325. def spawn_capture(sh, escape, cmd, args, env):
  326. # We only care about cl/link, process everything else as normal.
  327. if args[0] not in ["cl", "link"]:
  328. return old_spawn(sh, escape, cmd, args, env)
  329. # Process as normal if the user is manually rerouting output.
  330. for arg in args:
  331. if re_redirect_stream.match(arg):
  332. return old_spawn(sh, escape, cmd, args, env)
  333. tmp_stdout, tmp_stdout_name = mkstemp()
  334. os.close(tmp_stdout)
  335. args.append(f">{tmp_stdout_name}")
  336. ret = old_spawn(sh, escape, cmd, args, env)
  337. try:
  338. with open(tmp_stdout_name, "r", encoding=sys.stdout.encoding, errors="replace") as tmp_stdout:
  339. lines = tmp_stdout.read().splitlines()
  340. os.remove(tmp_stdout_name)
  341. except OSError:
  342. pass
  343. # Early process no lines (OSError)
  344. if not lines:
  345. return ret
  346. is_cl = args[0] == "cl"
  347. content = ""
  348. caught = False
  349. for line in lines:
  350. # These conditions are far from all-encompassing, but are specialized
  351. # for what can be reasonably expected to show up in the repository.
  352. if not caught and (is_cl and re_cl_capture.match(line)) or (not is_cl and re_link_capture.match(line)):
  353. caught = True
  354. try:
  355. with open(capture_path, "a", encoding=sys.stdout.encoding) as log:
  356. log.write(line + "\n")
  357. except OSError:
  358. print_warning(f'Failed to log captured line: "{line}".')
  359. continue
  360. content += line + "\n"
  361. # Content remaining assumed to be an error/warning.
  362. if content:
  363. sys.stderr.write(content)
  364. return ret
  365. env["SPAWN"] = spawn_capture
  366. if env["debug_crt"]:
  367. # Always use dynamic runtime, static debug CRT breaks thread_local.
  368. env.AppendUnique(CCFLAGS=["/MDd"])
  369. else:
  370. if env["use_static_cpp"]:
  371. env.AppendUnique(CCFLAGS=["/MT"])
  372. else:
  373. env.AppendUnique(CCFLAGS=["/MD"])
  374. # MSVC incremental linking is broken and may _increase_ link time (GH-77968).
  375. if not env["incremental_link"]:
  376. env.Append(LINKFLAGS=["/INCREMENTAL:NO"])
  377. if env["arch"] == "x86_32":
  378. env["x86_libtheora_opt_vc"] = True
  379. env.Append(CCFLAGS=["/fp:strict"])
  380. env.AppendUnique(CCFLAGS=["/Gd", "/GR", "/nologo"])
  381. env.AppendUnique(CCFLAGS=["/utf-8"]) # Force to use Unicode encoding.
  382. env.AppendUnique(CXXFLAGS=["/TP"]) # assume all sources are C++
  383. # Once it was thought that only debug builds would be too large,
  384. # but this has recently stopped being true. See the mingw function
  385. # for notes on why this shouldn't be enabled for gcc
  386. env.AppendUnique(CCFLAGS=["/bigobj"])
  387. if vcvars_msvc_config: # should be automatic if SCons found it
  388. if os.getenv("WindowsSdkDir") is not None:
  389. env.Prepend(CPPPATH=[str(os.getenv("WindowsSdkDir")) + "/Include"])
  390. else:
  391. print_warning("Missing environment variable: WindowsSdkDir")
  392. if int(env["target_win_version"], 16) < 0x0601:
  393. print_error("`target_win_version` should be 0x0601 or higher (Windows 7).")
  394. sys.exit(255)
  395. env.AppendUnique(
  396. CPPDEFINES=[
  397. "WINDOWS_ENABLED",
  398. "WASAPI_ENABLED",
  399. "WINMIDI_ENABLED",
  400. "TYPED_METHOD_BIND",
  401. "WIN32",
  402. "WINVER=%s" % env["target_win_version"],
  403. "_WIN32_WINNT=%s" % env["target_win_version"],
  404. ]
  405. )
  406. env.AppendUnique(CPPDEFINES=["NOMINMAX"]) # disable bogus min/max WinDef.h macros
  407. if env["arch"] == "x86_64":
  408. env.AppendUnique(CPPDEFINES=["_WIN64"])
  409. # Sanitizers
  410. prebuilt_lib_extra_suffix = ""
  411. if env["use_asan"]:
  412. env.extra_suffix += ".san"
  413. prebuilt_lib_extra_suffix = ".san"
  414. env.AppendUnique(CPPDEFINES=["SANITIZERS_ENABLED"])
  415. env.Append(CCFLAGS=["/fsanitize=address"])
  416. env.Append(LINKFLAGS=["/INFERASANLIBS"])
  417. ## Libs
  418. LIBS = [
  419. "winmm",
  420. "dsound",
  421. "kernel32",
  422. "ole32",
  423. "oleaut32",
  424. "sapi",
  425. "user32",
  426. "gdi32",
  427. "IPHLPAPI",
  428. "Shlwapi",
  429. "wsock32",
  430. "Ws2_32",
  431. "shell32",
  432. "advapi32",
  433. "dinput8",
  434. "dxguid",
  435. "imm32",
  436. "bcrypt",
  437. "Crypt32",
  438. "Avrt",
  439. "dwmapi",
  440. "dwrite",
  441. "wbemuuid",
  442. "ntdll",
  443. ]
  444. if env.debug_features:
  445. LIBS += ["psapi", "dbghelp"]
  446. if env["vulkan"]:
  447. env.AppendUnique(CPPDEFINES=["VULKAN_ENABLED", "RD_ENABLED"])
  448. if not env["use_volk"]:
  449. LIBS += ["vulkan"]
  450. if env["d3d12"]:
  451. # Check whether we have d3d12 dependencies installed.
  452. if not os.path.exists(env["mesa_libs"]):
  453. print_error(
  454. "The Direct3D 12 rendering driver requires dependencies to be installed.\n"
  455. "You can install them by running `python misc\\scripts\\install_d3d12_sdk_windows.py`.\n"
  456. "See the documentation for more information:\n\t"
  457. "https://docs.godotengine.org/en/latest/contributing/development/compiling/compiling_for_windows.html"
  458. )
  459. sys.exit(255)
  460. env.AppendUnique(CPPDEFINES=["D3D12_ENABLED", "RD_ENABLED"])
  461. LIBS += ["dxgi", "dxguid"]
  462. LIBS += ["version"] # Mesa dependency.
  463. # Needed for avoiding C1128.
  464. if env["target"] == "release_debug":
  465. env.Append(CXXFLAGS=["/bigobj"])
  466. # PIX
  467. if env["arch"] not in ["x86_64", "arm64"] or env["pix_path"] == "" or not os.path.exists(env["pix_path"]):
  468. env["use_pix"] = False
  469. if env["use_pix"]:
  470. arch_subdir = "arm64" if env["arch"] == "arm64" else "x64"
  471. env.Append(LIBPATH=[env["pix_path"] + "/bin/" + arch_subdir])
  472. LIBS += ["WinPixEventRuntime"]
  473. env.Append(LIBPATH=[env["mesa_libs"] + "/bin"])
  474. LIBS += ["libNIR.windows." + env["arch"] + prebuilt_lib_extra_suffix]
  475. if env["opengl3"]:
  476. env.AppendUnique(CPPDEFINES=["GLES3_ENABLED"])
  477. if env["angle_libs"] != "":
  478. env.AppendUnique(CPPDEFINES=["EGL_STATIC"])
  479. env.Append(LIBPATH=[env["angle_libs"]])
  480. LIBS += [
  481. "libANGLE.windows." + env["arch"] + prebuilt_lib_extra_suffix,
  482. "libEGL.windows." + env["arch"] + prebuilt_lib_extra_suffix,
  483. "libGLES.windows." + env["arch"] + prebuilt_lib_extra_suffix,
  484. ]
  485. LIBS += ["dxgi", "d3d9", "d3d11"]
  486. env.Prepend(CPPPATH=["#thirdparty/angle/include"])
  487. if env["target"] in ["editor", "template_debug"]:
  488. LIBS += ["psapi", "dbghelp"]
  489. env.Append(LINKFLAGS=[p + env["LIBSUFFIX"] for p in LIBS])
  490. if vcvars_msvc_config:
  491. if os.getenv("WindowsSdkDir") is not None:
  492. env.Append(LIBPATH=[str(os.getenv("WindowsSdkDir")) + "/Lib"])
  493. else:
  494. print_warning("Missing environment variable: WindowsSdkDir")
  495. ## LTO
  496. if env["lto"] == "auto": # No LTO by default for MSVC, doesn't help.
  497. env["lto"] = "none"
  498. if env["lto"] != "none":
  499. if env["lto"] == "thin":
  500. print_error("ThinLTO is only compatible with LLVM, use `use_llvm=yes` or `lto=full`.")
  501. sys.exit(255)
  502. env.AppendUnique(CCFLAGS=["/GL"])
  503. env.AppendUnique(ARFLAGS=["/LTCG"])
  504. if env["progress"]:
  505. env.AppendUnique(LINKFLAGS=["/LTCG:STATUS"])
  506. else:
  507. env.AppendUnique(LINKFLAGS=["/LTCG"])
  508. if vcvars_msvc_config:
  509. env.Prepend(CPPPATH=[p for p in str(os.getenv("INCLUDE")).split(";")])
  510. env.Append(LIBPATH=[p for p in str(os.getenv("LIB")).split(";")])
  511. # Incremental linking fix
  512. env["BUILDERS"]["ProgramOriginal"] = env["BUILDERS"]["Program"]
  513. env["BUILDERS"]["Program"] = methods.precious_program
  514. env.Append(LINKFLAGS=["/NATVIS:platform\\windows\\godot.natvis"])
  515. if env["use_asan"]:
  516. env.AppendUnique(LINKFLAGS=["/STACK:" + str(STACK_SIZE_SANITIZERS)])
  517. else:
  518. env.AppendUnique(LINKFLAGS=["/STACK:" + str(STACK_SIZE)])
  519. def configure_mingw(env: "SConsEnvironment"):
  520. # Workaround for MinGW. See:
  521. # https://www.scons.org/wiki/LongCmdLinesOnWin32
  522. env.use_windows_spawn_fix()
  523. ## Build type
  524. if not env["use_llvm"] and not try_cmd("gcc --version", env["mingw_prefix"], env["arch"]):
  525. env["use_llvm"] = True
  526. if env["use_llvm"] and not try_cmd("clang --version", env["mingw_prefix"], env["arch"]):
  527. env["use_llvm"] = False
  528. if not env["use_llvm"] and try_cmd("gcc --version", env["mingw_prefix"], env["arch"], True):
  529. print("Detected GCC to be a wrapper for Clang.")
  530. env["use_llvm"] = True
  531. # TODO: Re-evaluate the need for this / streamline with common config.
  532. if env["target"] == "template_release":
  533. if env["arch"] != "arm64":
  534. env.Append(CCFLAGS=["-msse2"])
  535. elif env.dev_build:
  536. # Allow big objects. It's supposed not to have drawbacks but seems to break
  537. # GCC LTO, so enabling for debug builds only (which are not built with LTO
  538. # and are the only ones with too big objects).
  539. env.Append(CCFLAGS=["-Wa,-mbig-obj"])
  540. if env["windows_subsystem"] == "gui":
  541. env.Append(LINKFLAGS=["-Wl,--subsystem,windows"])
  542. else:
  543. env.Append(LINKFLAGS=["-Wl,--subsystem,console"])
  544. env.AppendUnique(CPPDEFINES=["WINDOWS_SUBSYSTEM_CONSOLE"])
  545. ## Compiler configuration
  546. if os.name != "nt":
  547. env["PROGSUFFIX"] = env["PROGSUFFIX"] + ".exe" # for linux cross-compilation
  548. if env["arch"] == "x86_32":
  549. if env["use_static_cpp"]:
  550. env.Append(LINKFLAGS=["-static"])
  551. env.Append(LINKFLAGS=["-static-libgcc"])
  552. env.Append(LINKFLAGS=["-static-libstdc++"])
  553. else:
  554. if env["use_static_cpp"]:
  555. env.Append(LINKFLAGS=["-static"])
  556. if env["arch"] in ["x86_32", "x86_64"]:
  557. env["x86_libtheora_opt_gcc"] = True
  558. env.Append(CCFLAGS=["-ffp-contract=off"])
  559. mingw_bin_prefix = get_mingw_bin_prefix(env["mingw_prefix"], env["arch"])
  560. if env["use_llvm"]:
  561. env["CC"] = mingw_bin_prefix + "clang"
  562. env["CXX"] = mingw_bin_prefix + "clang++"
  563. if try_cmd("as --version", env["mingw_prefix"], env["arch"]):
  564. env["AS"] = mingw_bin_prefix + "as"
  565. env.Append(ASFLAGS=["-c"])
  566. if try_cmd("ar --version", env["mingw_prefix"], env["arch"]):
  567. env["AR"] = mingw_bin_prefix + "ar"
  568. if try_cmd("ranlib --version", env["mingw_prefix"], env["arch"]):
  569. env["RANLIB"] = mingw_bin_prefix + "ranlib"
  570. env.extra_suffix = ".llvm" + env.extra_suffix
  571. else:
  572. env["CC"] = mingw_bin_prefix + "gcc"
  573. env["CXX"] = mingw_bin_prefix + "g++"
  574. if try_cmd("as --version", env["mingw_prefix"], env["arch"]):
  575. env["AS"] = mingw_bin_prefix + "as"
  576. if try_cmd("gcc-ar --version", env["mingw_prefix"], env["arch"]):
  577. env["AR"] = mingw_bin_prefix + "gcc-ar"
  578. if try_cmd("gcc-ranlib --version", env["mingw_prefix"], env["arch"]):
  579. env["RANLIB"] = mingw_bin_prefix + "gcc-ranlib"
  580. ## LTO
  581. if env["lto"] == "auto": # Full LTO for production with MinGW.
  582. env["lto"] = "full"
  583. if env["lto"] != "none":
  584. if env["lto"] == "thin":
  585. if not env["use_llvm"]:
  586. print("ThinLTO is only compatible with LLVM, use `use_llvm=yes` or `lto=full`.")
  587. sys.exit(255)
  588. env.Append(CCFLAGS=["-flto=thin"])
  589. env.Append(LINKFLAGS=["-flto=thin"])
  590. elif not env["use_llvm"] and env.GetOption("num_jobs") > 1:
  591. env.Append(CCFLAGS=["-flto"])
  592. env.Append(LINKFLAGS=["-flto=" + str(env.GetOption("num_jobs"))])
  593. else:
  594. env.Append(CCFLAGS=["-flto"])
  595. env.Append(LINKFLAGS=["-flto"])
  596. if env["use_asan"]:
  597. env.Append(LINKFLAGS=["-Wl,--stack," + str(STACK_SIZE_SANITIZERS)])
  598. else:
  599. env.Append(LINKFLAGS=["-Wl,--stack," + str(STACK_SIZE)])
  600. ## Compile flags
  601. if int(env["target_win_version"], 16) < 0x0601:
  602. print_error("`target_win_version` should be 0x0601 or higher (Windows 7).")
  603. sys.exit(255)
  604. if not env["use_llvm"]:
  605. env.Append(CCFLAGS=["-mwindows"])
  606. if env["use_asan"] or env["use_ubsan"]:
  607. if not env["use_llvm"]:
  608. print("GCC does not support sanitizers on Windows.")
  609. sys.exit(255)
  610. if env["arch"] not in ["x86_32", "x86_64"]:
  611. print("Sanitizers are only supported for x86_32 and x86_64.")
  612. sys.exit(255)
  613. env.extra_suffix += ".san"
  614. env.AppendUnique(CPPDEFINES=["SANITIZERS_ENABLED"])
  615. san_flags = []
  616. if env["use_asan"]:
  617. san_flags.append("-fsanitize=address")
  618. if env["use_ubsan"]:
  619. san_flags.append("-fsanitize=undefined")
  620. # Disable the vptr check since it gets triggered on any COM interface calls.
  621. san_flags.append("-fno-sanitize=vptr")
  622. env.Append(CFLAGS=san_flags)
  623. env.Append(CCFLAGS=san_flags)
  624. env.Append(LINKFLAGS=san_flags)
  625. if env["use_llvm"] and os.name == "nt" and methods._colorize:
  626. env.Append(CCFLAGS=["$(-fansi-escape-codes$)", "$(-fcolor-diagnostics$)"])
  627. env.Append(CPPDEFINES=["WINDOWS_ENABLED", "WASAPI_ENABLED", "WINMIDI_ENABLED"])
  628. env.Append(
  629. CPPDEFINES=[
  630. ("WINVER", env["target_win_version"]),
  631. ("_WIN32_WINNT", env["target_win_version"]),
  632. ]
  633. )
  634. env.Append(
  635. LIBS=[
  636. "mingw32",
  637. "dsound",
  638. "ole32",
  639. "d3d9",
  640. "winmm",
  641. "gdi32",
  642. "iphlpapi",
  643. "shlwapi",
  644. "wsock32",
  645. "ws2_32",
  646. "kernel32",
  647. "oleaut32",
  648. "sapi",
  649. "dinput8",
  650. "dxguid",
  651. "ksuser",
  652. "imm32",
  653. "bcrypt",
  654. "crypt32",
  655. "avrt",
  656. "uuid",
  657. "dwmapi",
  658. "dwrite",
  659. "wbemuuid",
  660. "ntdll",
  661. ]
  662. )
  663. if env.debug_features:
  664. env.Append(LIBS=["psapi", "dbghelp"])
  665. if env["vulkan"]:
  666. env.Append(CPPDEFINES=["VULKAN_ENABLED", "RD_ENABLED"])
  667. if not env["use_volk"]:
  668. env.Append(LIBS=["vulkan"])
  669. if env["d3d12"]:
  670. # Check whether we have d3d12 dependencies installed.
  671. if not os.path.exists(env["mesa_libs"]):
  672. print_error(
  673. "The Direct3D 12 rendering driver requires dependencies to be installed.\n"
  674. "You can install them by running `python misc\\scripts\\install_d3d12_sdk_windows.py`.\n"
  675. "See the documentation for more information:\n\t"
  676. "https://docs.godotengine.org/en/latest/contributing/development/compiling/compiling_for_windows.html"
  677. )
  678. sys.exit(255)
  679. env.AppendUnique(CPPDEFINES=["D3D12_ENABLED", "RD_ENABLED"])
  680. env.Append(LIBS=["dxgi", "dxguid"])
  681. # PIX
  682. if env["arch"] not in ["x86_64", "arm64"] or env["pix_path"] == "" or not os.path.exists(env["pix_path"]):
  683. env["use_pix"] = False
  684. if env["use_pix"]:
  685. arch_subdir = "arm64" if env["arch"] == "arm64" else "x64"
  686. env.Append(LIBPATH=[env["pix_path"] + "/bin/" + arch_subdir])
  687. env.Append(LIBS=["WinPixEventRuntime"])
  688. env.Append(LIBPATH=[env["mesa_libs"] + "/bin"])
  689. env.Append(LIBS=["libNIR.windows." + env["arch"]])
  690. env.Append(LIBS=["version"]) # Mesa dependency.
  691. if env["opengl3"]:
  692. env.Append(CPPDEFINES=["GLES3_ENABLED"])
  693. if env["angle_libs"] != "":
  694. env.AppendUnique(CPPDEFINES=["EGL_STATIC"])
  695. env.Append(LIBPATH=[env["angle_libs"]])
  696. env.Append(
  697. LIBS=[
  698. "EGL.windows." + env["arch"],
  699. "GLES.windows." + env["arch"],
  700. "ANGLE.windows." + env["arch"],
  701. ]
  702. )
  703. env.Append(LIBS=["dxgi", "d3d9", "d3d11"])
  704. env.Prepend(CPPPATH=["#thirdparty/angle/include"])
  705. env.Append(CPPDEFINES=["MINGW_ENABLED", ("MINGW_HAS_SECURE_API", 1)])
  706. # resrc
  707. env.Append(BUILDERS={"RES": env.Builder(action=build_res_file, suffix=".o", src_suffix=".rc")})
  708. def configure(env: "SConsEnvironment"):
  709. # Validate arch.
  710. supported_arches = ["x86_32", "x86_64", "arm32", "arm64"]
  711. if env["arch"] not in supported_arches:
  712. print_error(
  713. 'Unsupported CPU architecture "%s" for Windows. Supported architectures are: %s.'
  714. % (env["arch"], ", ".join(supported_arches))
  715. )
  716. sys.exit(255)
  717. # At this point the env has been set up with basic tools/compilers.
  718. env.Prepend(CPPPATH=["#platform/windows"])
  719. if os.name == "nt":
  720. env["ENV"] = os.environ # this makes build less repeatable, but simplifies some things
  721. env["ENV"]["TMP"] = os.environ["TMP"]
  722. # First figure out which compiler, version, and target arch we're using
  723. if os.getenv("VCINSTALLDIR") and detect_build_env_arch() and not env["use_mingw"]:
  724. setup_msvc_manual(env)
  725. env.msvc = True
  726. vcvars_msvc_config = True
  727. elif env.get("MSVC_VERSION", "") and not env["use_mingw"]:
  728. setup_msvc_auto(env)
  729. env.msvc = True
  730. vcvars_msvc_config = False
  731. else:
  732. setup_mingw(env)
  733. env.msvc = False
  734. # Now set compiler/linker flags
  735. if env.msvc:
  736. configure_msvc(env, vcvars_msvc_config)
  737. else: # MinGW
  738. configure_mingw(env)