detect.py 28 KB

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