methods.py 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687
  1. from __future__ import annotations
  2. import atexit
  3. import contextlib
  4. import glob
  5. import math
  6. import os
  7. import re
  8. import subprocess
  9. import sys
  10. import textwrap
  11. import zlib
  12. from collections import OrderedDict
  13. from io import StringIO
  14. from pathlib import Path
  15. from typing import Generator, TextIO, cast
  16. from misc.utility.color import print_error, print_info, print_warning
  17. from platform_methods import detect_arch
  18. # Get the "Godot" folder name ahead of time
  19. base_folder = Path(__file__).resolve().parent
  20. compiler_version_cache = None
  21. # Listing all the folders we have converted
  22. # for SCU in scu_builders.py
  23. _scu_folders = set()
  24. def set_scu_folders(scu_folders):
  25. global _scu_folders
  26. _scu_folders = scu_folders
  27. def add_source_files_orig(self, sources, files, allow_gen=False):
  28. # Convert string to list of absolute paths (including expanding wildcard)
  29. if isinstance(files, str):
  30. # Exclude .gen.cpp files from globbing, to avoid including obsolete ones.
  31. # They should instead be added manually.
  32. skip_gen_cpp = "*" in files
  33. files = self.Glob(files)
  34. if skip_gen_cpp and not allow_gen:
  35. files = [f for f in files if not str(f).endswith(".gen.cpp")]
  36. # Add each path as compiled Object following environment (self) configuration
  37. for file in files:
  38. obj = self.Object(file)
  39. if obj in sources:
  40. print_warning('Object "{}" already included in environment sources.'.format(obj))
  41. continue
  42. sources.append(obj)
  43. def add_source_files_scu(self, sources, files, allow_gen=False):
  44. if self["scu_build"] and isinstance(files, str):
  45. if "*." not in files:
  46. return False
  47. # If the files are in a subdirectory, we want to create the scu gen
  48. # files inside this subdirectory.
  49. subdir = os.path.dirname(files)
  50. subdir = subdir if subdir == "" else subdir + "/"
  51. section_name = self.Dir(subdir).tpath
  52. section_name = section_name.replace("\\", "/") # win32
  53. # if the section name is in the hash table?
  54. # i.e. is it part of the SCU build?
  55. global _scu_folders
  56. if section_name not in (_scu_folders):
  57. return False
  58. # Add all the gen.cpp files in the SCU directory
  59. add_source_files_orig(self, sources, subdir + ".scu/scu_*.gen.cpp", True)
  60. return True
  61. return False
  62. # Either builds the folder using the SCU system,
  63. # or reverts to regular build.
  64. def add_source_files(self, sources, files, allow_gen=False):
  65. if not add_source_files_scu(self, sources, files, allow_gen):
  66. # Wraps the original function when scu build is not active.
  67. add_source_files_orig(self, sources, files, allow_gen)
  68. return False
  69. return True
  70. def redirect_emitter(target, source, env):
  71. """
  72. Emitter to automatically redirect object/library build files to the `bin/obj` directory,
  73. retaining subfolder structure. External build files will attempt to retain subfolder
  74. structure relative to their environment's parent directory, sorted under `bin/obj/external`.
  75. If `redirect_build_objects` is `False`, an external build file isn't relative to the passed
  76. environment, or a file is being written directly into `bin`, this emitter does nothing.
  77. """
  78. if not env["redirect_build_objects"]:
  79. return target, source
  80. redirected_targets = []
  81. for item in target:
  82. path = Path(item.get_abspath()).resolve()
  83. if path.parent == base_folder / "bin":
  84. pass
  85. elif base_folder in path.parents:
  86. item = env.File(f"#bin/obj/{path.relative_to(base_folder)}")
  87. elif (alt_base := Path(env.Dir(".").get_abspath()).resolve().parent) in path.parents:
  88. item = env.File(f"#bin/obj/external/{path.relative_to(alt_base)}")
  89. else:
  90. print_warning(f'Failed to redirect "{path}"')
  91. redirected_targets.append(item)
  92. return redirected_targets, source
  93. def disable_warnings(self):
  94. # 'self' is the environment
  95. if self.msvc and not using_clang(self):
  96. self["WARNLEVEL"] = "/w"
  97. else:
  98. self["WARNLEVEL"] = "-w"
  99. def force_optimization_on_debug(self):
  100. # 'self' is the environment
  101. if self["target"] == "template_release":
  102. return
  103. elif self.msvc:
  104. self["OPTIMIZELEVEL"] = "/O2"
  105. else:
  106. self["OPTIMIZELEVEL"] = "-O3"
  107. def add_module_version_string(self, s):
  108. self.module_version_string += "." + s
  109. def get_version_info(module_version_string="", silent=False):
  110. build_name = "custom_build"
  111. if os.getenv("BUILD_NAME") is not None:
  112. build_name = str(os.getenv("BUILD_NAME"))
  113. if not silent:
  114. print_info(f"Using custom build name: '{build_name}'.")
  115. import version
  116. version_info = {
  117. "short_name": str(version.short_name),
  118. "name": str(version.name),
  119. "major": int(version.major),
  120. "minor": int(version.minor),
  121. "patch": int(version.patch),
  122. "status": str(version.status),
  123. "build": str(build_name),
  124. "module_config": str(version.module_config) + module_version_string,
  125. "website": str(version.website),
  126. "docs_branch": str(version.docs),
  127. }
  128. # For dev snapshots (alpha, beta, RC, etc.) we do not commit status change to Git,
  129. # so this define provides a way to override it without having to modify the source.
  130. if os.getenv("GODOT_VERSION_STATUS") is not None:
  131. version_info["status"] = str(os.getenv("GODOT_VERSION_STATUS"))
  132. if not silent:
  133. print_info(f"Using version status '{version_info['status']}', overriding the original '{version.status}'.")
  134. return version_info
  135. def get_git_info():
  136. os.chdir(base_folder)
  137. # Parse Git hash if we're in a Git repo.
  138. git_hash = ""
  139. git_folder = ".git"
  140. if os.path.isfile(".git"):
  141. with open(".git", "r", encoding="utf-8") as file:
  142. module_folder = file.readline().strip()
  143. if module_folder.startswith("gitdir: "):
  144. git_folder = module_folder[8:]
  145. if os.path.isfile(os.path.join(git_folder, "HEAD")):
  146. with open(os.path.join(git_folder, "HEAD"), "r", encoding="utf8") as file:
  147. head = file.readline().strip()
  148. if head.startswith("ref: "):
  149. ref = head[5:]
  150. # If this directory is a Git worktree instead of a root clone.
  151. parts = git_folder.split("/")
  152. if len(parts) > 2 and parts[-2] == "worktrees":
  153. git_folder = "/".join(parts[0:-2])
  154. head = os.path.join(git_folder, ref)
  155. packedrefs = os.path.join(git_folder, "packed-refs")
  156. if os.path.isfile(head):
  157. with open(head, "r", encoding="utf-8") as file:
  158. git_hash = file.readline().strip()
  159. elif os.path.isfile(packedrefs):
  160. # Git may pack refs into a single file. This code searches .git/packed-refs file for the current ref's hash.
  161. # https://mirrors.edge.kernel.org/pub/software/scm/git/docs/git-pack-refs.html
  162. for line in open(packedrefs, "r", encoding="utf-8").read().splitlines():
  163. if line.startswith("#"):
  164. continue
  165. (line_hash, line_ref) = line.split(" ")
  166. if ref == line_ref:
  167. git_hash = line_hash
  168. break
  169. else:
  170. git_hash = head
  171. # Get the UNIX timestamp of the build commit.
  172. git_timestamp = 0
  173. if os.path.exists(".git"):
  174. try:
  175. git_timestamp = subprocess.check_output(
  176. ["git", "log", "-1", "--pretty=format:%ct", "--no-show-signature", git_hash], encoding="utf-8"
  177. )
  178. except (subprocess.CalledProcessError, OSError):
  179. # `git` not found in PATH.
  180. pass
  181. return {
  182. "git_hash": git_hash,
  183. "git_timestamp": git_timestamp,
  184. }
  185. def get_cmdline_bool(option, default):
  186. """We use `ARGUMENTS.get()` to check if options were manually overridden on the command line,
  187. and SCons' _text2bool helper to convert them to booleans, otherwise they're handled as strings.
  188. """
  189. from SCons.Script import ARGUMENTS
  190. from SCons.Variables.BoolVariable import _text2bool
  191. cmdline_val = ARGUMENTS.get(option)
  192. if cmdline_val is not None:
  193. return _text2bool(cmdline_val)
  194. else:
  195. return default
  196. def detect_modules(search_path, recursive=False):
  197. """Detects and collects a list of C++ modules at specified path
  198. `search_path` - a directory path containing modules. The path may point to
  199. a single module, which may have other nested modules. A module must have
  200. "register_types.h", "SCsub", "config.py" files created to be detected.
  201. `recursive` - if `True`, then all subdirectories are searched for modules as
  202. specified by the `search_path`, otherwise collects all modules under the
  203. `search_path` directory. If the `search_path` is a module, it is collected
  204. in all cases.
  205. Returns an `OrderedDict` with module names as keys, and directory paths as
  206. values. If a path is relative, then it is a built-in module. If a path is
  207. absolute, then it is a custom module collected outside of the engine source.
  208. """
  209. modules = OrderedDict()
  210. def add_module(path):
  211. module_name = os.path.basename(path)
  212. module_path = path.replace("\\", "/") # win32
  213. modules[module_name] = module_path
  214. def is_engine(path):
  215. # Prevent recursively detecting modules in self and other
  216. # Godot sources when using `custom_modules` build option.
  217. version_path = os.path.join(path, "version.py")
  218. if os.path.exists(version_path):
  219. with open(version_path, "r", encoding="utf-8") as f:
  220. if 'short_name = "godot"' in f.read():
  221. return True
  222. return False
  223. def get_files(path):
  224. files = glob.glob(os.path.join(path, "*"))
  225. # Sort so that `register_module_types` does not change that often,
  226. # and plugins are registered in alphabetic order as well.
  227. files.sort()
  228. return files
  229. if not recursive:
  230. if is_module(search_path):
  231. add_module(search_path)
  232. for path in get_files(search_path):
  233. if is_engine(path):
  234. continue
  235. if is_module(path):
  236. add_module(path)
  237. else:
  238. to_search = [search_path]
  239. while to_search:
  240. path = to_search.pop()
  241. if is_module(path):
  242. add_module(path)
  243. for child in get_files(path):
  244. if not os.path.isdir(child):
  245. continue
  246. if is_engine(child):
  247. continue
  248. to_search.insert(0, child)
  249. return modules
  250. def is_module(path):
  251. if not os.path.isdir(path):
  252. return False
  253. must_exist = ["register_types.h", "SCsub", "config.py"]
  254. for f in must_exist:
  255. if not os.path.exists(os.path.join(path, f)):
  256. return False
  257. return True
  258. def convert_custom_modules_path(path):
  259. if not path:
  260. return path
  261. path = os.path.realpath(os.path.expanduser(os.path.expandvars(path)))
  262. err_msg = "Build option 'custom_modules' must %s"
  263. if not os.path.isdir(path):
  264. raise ValueError(err_msg % "point to an existing directory.")
  265. if path == os.path.realpath("modules"):
  266. raise ValueError(err_msg % "be a directory other than built-in `modules` directory.")
  267. return path
  268. def module_add_dependencies(self, module, dependencies, optional=False):
  269. """
  270. Adds dependencies for a given module.
  271. Meant to be used in module `can_build` methods.
  272. """
  273. if module not in self.module_dependencies:
  274. self.module_dependencies[module] = [[], []]
  275. if optional:
  276. self.module_dependencies[module][1].extend(dependencies)
  277. else:
  278. self.module_dependencies[module][0].extend(dependencies)
  279. def module_check_dependencies(self, module):
  280. """
  281. Checks if module dependencies are enabled for a given module,
  282. and prints a warning if they aren't.
  283. Meant to be used in module `can_build` methods.
  284. Returns a boolean (True if dependencies are satisfied).
  285. """
  286. missing_deps = set()
  287. required_deps = self.module_dependencies[module][0] if module in self.module_dependencies else []
  288. for dep in required_deps:
  289. opt = "module_{}_enabled".format(dep)
  290. if opt not in self or not self[opt] or not module_check_dependencies(self, dep):
  291. missing_deps.add(dep)
  292. if missing_deps:
  293. if module not in self.disabled_modules:
  294. print_warning(
  295. "Disabling '{}' module as the following dependencies are not satisfied: {}".format(
  296. module, ", ".join(missing_deps)
  297. )
  298. )
  299. self.disabled_modules.add(module)
  300. return False
  301. else:
  302. return True
  303. def sort_module_list(env):
  304. deps = {k: v[0] + list(filter(lambda x: x in env.module_list, v[1])) for k, v in env.module_dependencies.items()}
  305. frontier = list(env.module_list.keys())
  306. explored = []
  307. while len(frontier):
  308. cur = frontier.pop()
  309. deps_list = deps[cur] if cur in deps else []
  310. if len(deps_list) and any([d not in explored for d in deps_list]):
  311. # Will explore later, after its dependencies
  312. frontier.insert(0, cur)
  313. continue
  314. explored.append(cur)
  315. for k in explored:
  316. env.module_list.move_to_end(k)
  317. def use_windows_spawn_fix(self, platform=None):
  318. if os.name != "nt":
  319. return # not needed, only for windows
  320. def mySubProcess(cmdline, env):
  321. startupinfo = subprocess.STARTUPINFO()
  322. startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  323. popen_args = {
  324. "stdin": subprocess.PIPE,
  325. "stdout": subprocess.PIPE,
  326. "stderr": subprocess.PIPE,
  327. "startupinfo": startupinfo,
  328. "shell": False,
  329. "env": env,
  330. }
  331. popen_args["text"] = True
  332. proc = subprocess.Popen(cmdline, **popen_args)
  333. _, err = proc.communicate()
  334. rv = proc.wait()
  335. if rv:
  336. print_error(err)
  337. elif len(err) > 0 and not err.isspace():
  338. print(err)
  339. return rv
  340. def mySpawn(sh, escape, cmd, args, env):
  341. # Used by TEMPFILE.
  342. if cmd == "del":
  343. os.remove(args[1])
  344. return 0
  345. newargs = " ".join(args[1:])
  346. cmdline = cmd + " " + newargs
  347. rv = 0
  348. env = {str(key): str(value) for key, value in iter(env.items())}
  349. rv = mySubProcess(cmdline, env)
  350. return rv
  351. self["SPAWN"] = mySpawn
  352. def no_verbose(env):
  353. from misc.utility.color import Ansi, is_stdout_color
  354. colors = [Ansi.BLUE, Ansi.BOLD, Ansi.REGULAR, Ansi.RESET] if is_stdout_color() else ["", "", "", ""]
  355. # There is a space before "..." to ensure that source file names can be
  356. # Ctrl + clicked in the VS Code terminal.
  357. compile_source_message = "{}Compiling {}$SOURCE{} ...{}".format(*colors)
  358. java_compile_source_message = "{}Compiling {}$SOURCE{} ...{}".format(*colors)
  359. compile_shared_source_message = "{}Compiling shared {}$SOURCE{} ...{}".format(*colors)
  360. link_program_message = "{}Linking Program {}$TARGET{} ...{}".format(*colors)
  361. link_library_message = "{}Linking Static Library {}$TARGET{} ...{}".format(*colors)
  362. ranlib_library_message = "{}Ranlib Library {}$TARGET{} ...{}".format(*colors)
  363. link_shared_library_message = "{}Linking Shared Library {}$TARGET{} ...{}".format(*colors)
  364. java_library_message = "{}Creating Java Archive {}$TARGET{} ...{}".format(*colors)
  365. compiled_resource_message = "{}Creating Compiled Resource {}$TARGET{} ...{}".format(*colors)
  366. zip_archive_message = "{}Archiving {}$TARGET{} ...{}".format(*colors)
  367. generated_file_message = "{}Generating {}$TARGET{} ...{}".format(*colors)
  368. env["CXXCOMSTR"] = compile_source_message
  369. env["CCCOMSTR"] = compile_source_message
  370. env["SWIFTCOMSTR"] = compile_source_message
  371. env["SHCCCOMSTR"] = compile_shared_source_message
  372. env["SHCXXCOMSTR"] = compile_shared_source_message
  373. env["ARCOMSTR"] = link_library_message
  374. env["RANLIBCOMSTR"] = ranlib_library_message
  375. env["SHLINKCOMSTR"] = link_shared_library_message
  376. env["LINKCOMSTR"] = link_program_message
  377. env["JARCOMSTR"] = java_library_message
  378. env["JAVACCOMSTR"] = java_compile_source_message
  379. env["RCCOMSTR"] = compiled_resource_message
  380. env["ZIPCOMSTR"] = zip_archive_message
  381. env["GENCOMSTR"] = generated_file_message
  382. def detect_visual_c_compiler_version(tools_env):
  383. # tools_env is the variable scons uses to call tools that execute tasks, SCons's env['ENV'] that executes tasks...
  384. # (see the SCons documentation for more information on what it does)...
  385. # in order for this function to be well encapsulated i choose to force it to receive SCons's TOOLS env (env['ENV']
  386. # and not scons setup environment (env)... so make sure you call the right environment on it or it will fail to detect
  387. # the proper vc version that will be called
  388. # There is no flag to give to visual c compilers to set the architecture, i.e. scons arch argument (x86_32, x86_64, arm64, etc.).
  389. # There are many different cl.exe files that are run, and each one compiles & links to a different architecture
  390. # As far as I know, the only way to figure out what compiler will be run when Scons calls cl.exe via Program()
  391. # is to check the PATH variable and figure out which one will be called first. Code below does that and returns:
  392. # the following string values:
  393. # "" Compiler not detected
  394. # "amd64" Native 64 bit compiler
  395. # "amd64_x86" 64 bit Cross Compiler for 32 bit
  396. # "x86" Native 32 bit compiler
  397. # "x86_amd64" 32 bit Cross Compiler for 64 bit
  398. # There are other architectures, but Godot does not support them currently, so this function does not detect arm/amd64_arm
  399. # and similar architectures/compilers
  400. # Set chosen compiler to "not detected"
  401. vc_chosen_compiler_index = -1
  402. vc_chosen_compiler_str = ""
  403. # VS 2017 and newer should set VCTOOLSINSTALLDIR
  404. if "VCTOOLSINSTALLDIR" in tools_env:
  405. # Newer versions have a different path available
  406. vc_amd64_compiler_detection_index = (
  407. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX64\\X64;")
  408. )
  409. if vc_amd64_compiler_detection_index > -1:
  410. vc_chosen_compiler_index = vc_amd64_compiler_detection_index
  411. vc_chosen_compiler_str = "amd64"
  412. vc_amd64_x86_compiler_detection_index = (
  413. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX64\\X86;")
  414. )
  415. if vc_amd64_x86_compiler_detection_index > -1 and (
  416. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index
  417. ):
  418. vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index
  419. vc_chosen_compiler_str = "amd64_x86"
  420. vc_x86_compiler_detection_index = (
  421. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX86\\X86;")
  422. )
  423. if vc_x86_compiler_detection_index > -1 and (
  424. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_compiler_detection_index
  425. ):
  426. vc_chosen_compiler_index = vc_x86_compiler_detection_index
  427. vc_chosen_compiler_str = "x86"
  428. vc_x86_amd64_compiler_detection_index = (
  429. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX86\\X64;")
  430. )
  431. if vc_x86_amd64_compiler_detection_index > -1 and (
  432. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index
  433. ):
  434. vc_chosen_compiler_str = "x86_amd64"
  435. return vc_chosen_compiler_str
  436. def find_visual_c_batch_file(env):
  437. # TODO: We should investigate if we can avoid relying on SCons internals here.
  438. from SCons.Tool.MSCommon.vc import find_batch_file, find_vc_pdir, get_default_version, get_host_target
  439. msvc_version = get_default_version(env)
  440. # Syntax changed in SCons 4.4.0.
  441. if env.scons_version >= (4, 4, 0):
  442. (host_platform, target_platform, _) = get_host_target(env, msvc_version)
  443. else:
  444. (host_platform, target_platform, _) = get_host_target(env)
  445. if env.scons_version < (4, 6, 0):
  446. return find_batch_file(env, msvc_version, host_platform, target_platform)[0]
  447. # SCons 4.6.0+ removed passing env, so we need to get the product_dir ourselves first,
  448. # then pass that as the last param instead of env as the first param as before.
  449. # Param names need to be explicit, as they were shuffled around in SCons 4.8.0.
  450. product_dir = find_vc_pdir(msvc_version=msvc_version, env=env)
  451. return find_batch_file(msvc_version, host_platform, target_platform, product_dir)[0]
  452. def generate_cpp_hint_file(filename):
  453. if os.path.isfile(filename):
  454. # Don't overwrite an existing hint file since the user may have customized it.
  455. pass
  456. else:
  457. try:
  458. with open(filename, "w", encoding="utf-8", newline="\n") as fd:
  459. fd.write("#define GDCLASS(m_class, m_inherits)\n")
  460. for name in ["GDVIRTUAL", "EXBIND", "MODBIND"]:
  461. for count in range(13):
  462. for suffix in ["", "R", "C", "RC"]:
  463. fd.write(f"#define {name}{count}{suffix}(")
  464. if "R" in suffix:
  465. fd.write("m_ret, ")
  466. fd.write("m_name")
  467. for idx in range(1, count + 1):
  468. fd.write(f", type{idx}")
  469. fd.write(")\n")
  470. except OSError:
  471. print_warning("Could not write cpp.hint file.")
  472. def glob_recursive(pattern, node="."):
  473. from SCons import Node
  474. from SCons.Script import Glob
  475. results = []
  476. for f in Glob(str(node) + "/*", source=True):
  477. if type(f) is Node.FS.Dir:
  478. results += glob_recursive(pattern, f)
  479. results += Glob(str(node) + "/" + pattern, source=True)
  480. return results
  481. def precious_program(env, program, sources, **args):
  482. program = env.Program(program, sources, **args)
  483. env.Precious(program)
  484. return program
  485. def add_shared_library(env, name, sources, **args):
  486. library = env.SharedLibrary(name, sources, **args)
  487. env.NoCache(library)
  488. return library
  489. def add_library(env, name, sources, **args):
  490. library = env.Library(name, sources, **args)
  491. env.NoCache(library)
  492. return library
  493. def add_program(env, name, sources, **args):
  494. program = env.Program(name, sources, **args)
  495. env.NoCache(program)
  496. return program
  497. def CommandNoCache(env, target, sources, command, **args):
  498. result = env.Command(target, sources, command, **args)
  499. env.NoCache(result)
  500. return result
  501. def Run(env, function, comstr="$GENCOMSTR"):
  502. from SCons.Script import Action
  503. return Action(function, comstr)
  504. def detect_darwin_toolchain_path(env):
  505. var_name = "APPLE_TOOLCHAIN_PATH"
  506. if not env[var_name]:
  507. try:
  508. xcode_path = subprocess.check_output(["xcode-select", "-p"]).strip().decode("utf-8")
  509. if xcode_path:
  510. env[var_name] = xcode_path + "/Toolchains/XcodeDefault.xctoolchain"
  511. except (subprocess.CalledProcessError, OSError):
  512. print_error("Failed to find SDK path while running 'xcode-select -p'.")
  513. raise
  514. def detect_darwin_sdk_path(platform, env):
  515. sdk_name = ""
  516. if platform == "macos":
  517. sdk_name = "macosx"
  518. var_name = "MACOS_SDK_PATH"
  519. elif platform == "ios":
  520. sdk_name = "iphoneos"
  521. var_name = "APPLE_SDK_PATH"
  522. elif platform == "iossimulator":
  523. sdk_name = "iphonesimulator"
  524. var_name = "APPLE_SDK_PATH"
  525. elif platform == "visionos":
  526. sdk_name = "xros"
  527. var_name = "APPLE_SDK_PATH"
  528. elif platform == "visionossimulator":
  529. sdk_name = "xrsimulator"
  530. var_name = "APPLE_SDK_PATH"
  531. else:
  532. raise Exception("Invalid platform argument passed to detect_darwin_sdk_path")
  533. if not env[var_name]:
  534. try:
  535. sdk_path = subprocess.check_output(["xcrun", "--sdk", sdk_name, "--show-sdk-path"]).strip().decode("utf-8")
  536. if sdk_path:
  537. env[var_name] = sdk_path
  538. except (subprocess.CalledProcessError, OSError):
  539. print_error("Failed to find SDK path while running 'xcrun --sdk {} --show-sdk-path'.".format(sdk_name))
  540. raise
  541. def is_apple_clang(env):
  542. import shlex
  543. if env["platform"] not in ["macos", "ios"]:
  544. return False
  545. if not using_clang(env):
  546. return False
  547. try:
  548. version = (
  549. subprocess.check_output(shlex.split(env.subst(env["CXX"]), posix=False) + ["--version"])
  550. .strip()
  551. .decode("utf-8")
  552. )
  553. except (subprocess.CalledProcessError, OSError):
  554. print_warning("Couldn't parse CXX environment variable to infer compiler version.")
  555. return False
  556. return version.startswith("Apple")
  557. def get_compiler_version(env):
  558. """
  559. Returns a dictionary with various version information:
  560. - major, minor, patch: Version following semantic versioning system
  561. - metadata1, metadata2: Extra information
  562. - date: Date of the build
  563. """
  564. global compiler_version_cache
  565. if compiler_version_cache is not None:
  566. return compiler_version_cache
  567. import shlex
  568. ret = {
  569. "major": -1,
  570. "minor": -1,
  571. "patch": -1,
  572. "metadata1": "",
  573. "metadata2": "",
  574. "date": "",
  575. "apple_major": -1,
  576. "apple_minor": -1,
  577. "apple_patch1": -1,
  578. "apple_patch2": -1,
  579. "apple_patch3": -1,
  580. }
  581. if env.msvc and not using_clang(env):
  582. try:
  583. # FIXME: `-latest` works for most cases, but there are edge-cases where this would
  584. # benefit from a more nuanced search.
  585. # https://github.com/godotengine/godot/pull/91069#issuecomment-2358956731
  586. # https://github.com/godotengine/godot/pull/91069#issuecomment-2380836341
  587. args = [
  588. env["VSWHERE"],
  589. "-latest",
  590. "-prerelease",
  591. "-products",
  592. "*",
  593. "-requires",
  594. "Microsoft.Component.MSBuild",
  595. "-utf8",
  596. ]
  597. version = subprocess.check_output(args, encoding="utf-8").strip()
  598. for line in version.splitlines():
  599. split = line.split(":", 1)
  600. if split[0] == "catalog_productSemanticVersion":
  601. match = re.match(r" ([0-9]*).([0-9]*).([0-9]*)-?([a-z0-9.+]*)", split[1])
  602. if match is not None:
  603. ret["major"] = int(match.group(1))
  604. ret["minor"] = int(match.group(2))
  605. ret["patch"] = int(match.group(3))
  606. # Semantic suffix (i.e. insiders+11116.177)
  607. ret["metadata2"] = match.group(4)
  608. # Could potentially add section for determining preview version, but
  609. # that can wait until metadata is actually used for something.
  610. if split[0] == "catalog_buildVersion":
  611. ret["metadata1"] = split[1]
  612. except (subprocess.CalledProcessError, OSError):
  613. print_warning("Couldn't find vswhere to determine compiler version.")
  614. return update_compiler_version_cache(ret)
  615. # Not using -dumpversion as some GCC distros only return major, and
  616. # Clang used to return hardcoded 4.2.1: # https://reviews.llvm.org/D56803
  617. try:
  618. version = subprocess.check_output(
  619. shlex.split(env.subst(env["CXX"]), posix=False) + ["--version"], shell=(os.name == "nt"), encoding="utf-8"
  620. ).strip()
  621. except (subprocess.CalledProcessError, OSError):
  622. print_warning("Couldn't parse CXX environment variable to infer compiler version.")
  623. return update_compiler_version_cache(ret)
  624. match = re.search(
  625. r"(?:(?<=version )|(?<=\) )|(?<=^))"
  626. r"(?P<major>\d+)"
  627. r"(?:\.(?P<minor>\d*))?"
  628. r"(?:\.(?P<patch>\d*))?"
  629. r"(?:-(?P<metadata1>[0-9a-zA-Z-]*))?"
  630. r"(?:\+(?P<metadata2>[0-9a-zA-Z-]*))?"
  631. r"(?: (?P<date>[0-9]{8}|[0-9]{6})(?![0-9a-zA-Z]))?",
  632. version,
  633. )
  634. if match is not None:
  635. for key, value in match.groupdict().items():
  636. if value is not None:
  637. ret[key] = value
  638. match_apple = re.search(
  639. r"(?:(?<=clang-)|(?<=\) )|(?<=^))"
  640. r"(?P<apple_major>\d+)"
  641. r"(?:\.(?P<apple_minor>\d*))?"
  642. r"(?:\.(?P<apple_patch1>\d*))?"
  643. r"(?:\.(?P<apple_patch2>\d*))?"
  644. r"(?:\.(?P<apple_patch3>\d*))?",
  645. version,
  646. )
  647. if match_apple is not None:
  648. for key, value in match_apple.groupdict().items():
  649. if value is not None:
  650. ret[key] = value
  651. # Transform semantic versioning to integers
  652. for key in [
  653. "major",
  654. "minor",
  655. "patch",
  656. "apple_major",
  657. "apple_minor",
  658. "apple_patch1",
  659. "apple_patch2",
  660. "apple_patch3",
  661. ]:
  662. ret[key] = int(ret[key] or -1)
  663. return update_compiler_version_cache(ret)
  664. def update_compiler_version_cache(value):
  665. global compiler_version_cache
  666. compiler_version_cache = value
  667. return value
  668. def using_gcc(env):
  669. return "gcc" in os.path.basename(env["CC"])
  670. def using_clang(env):
  671. return "clang" in os.path.basename(env["CC"])
  672. def using_emcc(env):
  673. return "emcc" in os.path.basename(env["CC"])
  674. def show_progress(env):
  675. # Ninja has its own progress/tracking tool that clashes with ours.
  676. if env["ninja"]:
  677. return
  678. NODE_COUNT_FILENAME = base_folder / ".scons_node_count"
  679. class ShowProgress:
  680. def __init__(self):
  681. self.count = 0
  682. self.max = 0
  683. try:
  684. with open(NODE_COUNT_FILENAME, "r", encoding="utf-8") as f:
  685. self.max = int(f.readline())
  686. except OSError:
  687. pass
  688. # Progress reporting is not available in non-TTY environments since it
  689. # messes with the output (for example, when writing to a file).
  690. self.display = cast(bool, env["progress"] and sys.stdout.isatty())
  691. if self.display and not self.max:
  692. print_info("Performing initial build, progress percentage unavailable!")
  693. self.display = False
  694. def __call__(self, node, *args, **kw):
  695. self.count += 1
  696. if self.display:
  697. percent = int(min(self.count * 100 / self.max, 100))
  698. sys.stdout.write(f"\r[{percent:3d}%] ")
  699. sys.stdout.flush()
  700. from SCons.Script import Progress
  701. from SCons.Script.Main import GetBuildFailures
  702. progressor = ShowProgress()
  703. Progress(progressor)
  704. def progress_finish():
  705. if GetBuildFailures() or not progressor.count:
  706. return
  707. try:
  708. with open(NODE_COUNT_FILENAME, "w", encoding="utf-8", newline="\n") as f:
  709. f.write(f"{progressor.count}\n")
  710. except OSError:
  711. pass
  712. atexit.register(progress_finish)
  713. def convert_size(size_bytes: int) -> str:
  714. if size_bytes == 0:
  715. return "0 bytes"
  716. SIZE_NAMES = ["bytes", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"]
  717. index = math.floor(math.log(size_bytes, 1024))
  718. power = math.pow(1024, index)
  719. size = round(size_bytes / power, 2)
  720. return f"{size} {SIZE_NAMES[index]}"
  721. def get_size(start_path: str = ".") -> int:
  722. total_size = 0
  723. for dirpath, _, filenames in os.walk(start_path):
  724. for file in filenames:
  725. path = os.path.join(dirpath, file)
  726. total_size += os.path.getsize(path)
  727. return total_size
  728. def clean_cache(cache_path: str, cache_limit: int, verbose: bool) -> None:
  729. if not cache_limit:
  730. return
  731. files = glob.glob(os.path.join(cache_path, "*", "*"))
  732. if not files:
  733. return
  734. # Store files in list of (filename, size, atime).
  735. stats = []
  736. for file in files:
  737. try:
  738. stats.append((file, *os.stat(file)[6:8]))
  739. except OSError:
  740. print_error(f'Failed to access cache file "{file}"; skipping.')
  741. # Sort by most recent access (most sensible to keep) first. Search for the first entry where
  742. # the cache limit is reached.
  743. stats.sort(key=lambda x: x[2], reverse=True)
  744. sum = 0
  745. for index, stat in enumerate(stats):
  746. sum += stat[1]
  747. if sum > cache_limit:
  748. purge = [x[0] for x in stats[index:]]
  749. count = len(purge)
  750. for file in purge:
  751. try:
  752. os.remove(file)
  753. except OSError:
  754. print_error(f'Failed to remove cache file "{file}"; skipping.')
  755. count -= 1
  756. if verbose and count:
  757. print_info(f"Purged {count} file{'s' if count else ''} from cache.")
  758. break
  759. def prepare_cache(env) -> None:
  760. cache_path = ""
  761. if env["cache_path"]:
  762. cache_path = cast(str, env["cache_path"])
  763. elif os.environ.get("SCONS_CACHE"):
  764. print_warning("Environment variable `SCONS_CACHE` is deprecated; use `cache_path` argument instead.")
  765. cache_path = cast(str, os.environ.get("SCONS_CACHE"))
  766. if not cache_path:
  767. return
  768. env.CacheDir(cache_path)
  769. print(f'SCons cache enabled... (path: "{cache_path}")')
  770. if env["cache_limit"]:
  771. cache_limit = float(env["cache_limit"])
  772. elif os.environ.get("SCONS_CACHE_LIMIT"):
  773. print_warning("Environment variable `SCONS_CACHE_LIMIT` is deprecated; use `cache_limit` argument instead.")
  774. cache_limit = float(os.getenv("SCONS_CACHE_LIMIT", "0")) / 1024 # Old method used MiB, convert to GiB
  775. # Convert GiB to bytes; treat negative numbers as 0 (unlimited).
  776. cache_limit = max(0, int(cache_limit * 1024 * 1024 * 1024))
  777. if env["verbose"]:
  778. print_info(
  779. f"Current cache size is {convert_size(get_size(cache_path))}"
  780. + (f" (limit: {convert_size(cache_limit)})" if cache_limit else "")
  781. )
  782. atexit.register(clean_cache, cache_path, cache_limit, env["verbose"])
  783. def prepare_purge(env):
  784. from SCons.Script.Main import GetBuildFailures
  785. def purge_flaky_files():
  786. paths_to_keep = [env["ninja_file"]]
  787. for build_failure in GetBuildFailures():
  788. path = build_failure.node.path
  789. if os.path.isfile(path) and path not in paths_to_keep:
  790. os.remove(path)
  791. atexit.register(purge_flaky_files)
  792. def prepare_timer():
  793. import time
  794. def print_elapsed_time(time_at_start: float):
  795. time_elapsed = time.time() - time_at_start
  796. time_formatted = time.strftime("%H:%M:%S", time.gmtime(time_elapsed))
  797. time_centiseconds = (time_elapsed % 1) * 100
  798. print_info(f"Time elapsed: {time_formatted}.{time_centiseconds:02.0f}")
  799. atexit.register(print_elapsed_time, time.time())
  800. def dump(env):
  801. """
  802. Dumps latest build information for debugging purposes and external tools.
  803. """
  804. with open(".scons_env.json", "w", encoding="utf-8", newline="\n") as file:
  805. file.write(env.Dump(format="json"))
  806. # Custom Visual Studio project generation logic that supports any platform that has a msvs.py
  807. # script, so Visual Studio can be used to run scons for any platform, with the right defines per target.
  808. # Invoked with scons vsproj=yes
  809. #
  810. # Only platforms that opt in to vs proj generation by having a msvs.py file in the platform folder are included.
  811. # Platforms with a msvs.py file will be added to the solution, but only the current active platform+target+arch
  812. # will have a build configuration generated, because we only know what the right defines/includes/flags/etc are
  813. # on the active build target.
  814. #
  815. # Platforms that don't support an editor target will have a dummy editor target that won't do anything on build,
  816. # but will have the files and configuration for the windows editor target.
  817. #
  818. # To generate build configuration files for all platforms+targets+arch combinations, users can call
  819. # scons vsproj=yes
  820. # for each combination of platform+target+arch. This will generate the relevant vs project files but
  821. # skip the build process. This lets project files be quickly generated even if there are build errors.
  822. #
  823. # To generate AND build from the command line:
  824. # scons vsproj=yes vsproj_gen_only=no
  825. def generate_vs_project(env, original_args, project_name="godot"):
  826. # Augmented glob_recursive that also fills the dirs argument with traversed directories that have content.
  827. def glob_recursive_2(pattern, dirs, node="."):
  828. from SCons import Node
  829. from SCons.Script import Glob
  830. results = []
  831. for f in Glob(str(node) + "/*", source=True):
  832. if type(f) is Node.FS.Dir:
  833. results += glob_recursive_2(pattern, dirs, f)
  834. r = Glob(str(node) + "/" + pattern, source=True)
  835. if len(r) > 0 and str(node) not in dirs:
  836. d = ""
  837. for part in str(node).split("\\"):
  838. d += part
  839. if d not in dirs:
  840. dirs.append(d)
  841. d += "\\"
  842. results += r
  843. return results
  844. def get_bool(args, option, default):
  845. from SCons.Variables.BoolVariable import _text2bool
  846. val = args.get(option, default)
  847. if val is not None:
  848. try:
  849. return _text2bool(val)
  850. except (ValueError, AttributeError):
  851. return default
  852. else:
  853. return default
  854. def format_key_value(v):
  855. if type(v) in [tuple, list]:
  856. return v[0] if len(v) == 1 else f"{v[0]}={v[1]}"
  857. return v
  858. def get_dependencies(file, env, exts, headers, sources, others):
  859. for child in file.children():
  860. if isinstance(child, str):
  861. child = env.File(x)
  862. fname = ""
  863. try:
  864. fname = child.path
  865. except AttributeError:
  866. # It's not a file.
  867. pass
  868. if fname:
  869. parts = os.path.splitext(fname)
  870. if len(parts) > 1:
  871. ext = parts[1].lower()
  872. if ext in exts["sources"]:
  873. sources += [fname]
  874. elif ext in exts["headers"]:
  875. headers += [fname]
  876. elif ext in exts["others"]:
  877. others += [fname]
  878. get_dependencies(child, env, exts, headers, sources, others)
  879. filtered_args = original_args.copy()
  880. # Ignore the "vsproj" option to not regenerate the VS project on every build
  881. filtered_args.pop("vsproj", None)
  882. # This flag allows users to regenerate the proj files but skip the building process.
  883. # This lets projects be regenerated even if there are build errors.
  884. filtered_args.pop("vsproj_gen_only", None)
  885. # This flag allows users to regenerate only the props file without touching the sln or vcxproj files.
  886. # This preserves any customizations users have done to the solution, while still updating the file list
  887. # and build commands.
  888. filtered_args.pop("vsproj_props_only", None)
  889. # The "progress" option is ignored as the current compilation progress indication doesn't work in VS
  890. filtered_args.pop("progress", None)
  891. # We add these three manually because they might not be explicitly passed in, and it's important to always set them.
  892. filtered_args.pop("platform", None)
  893. filtered_args.pop("target", None)
  894. filtered_args.pop("arch", None)
  895. platform = env["platform"]
  896. target = env["target"]
  897. arch = env["arch"]
  898. host_arch = detect_arch()
  899. host_platform = "windows"
  900. if (
  901. sys.platform.startswith("linux")
  902. or sys.platform.startswith("dragonfly")
  903. or sys.platform.startswith("freebsd")
  904. or sys.platform.startswith("netbsd")
  905. or sys.platform.startswith("openbsd")
  906. ):
  907. host_platform = "linuxbsd"
  908. elif sys.platform == "darwin":
  909. host_platform = "macos"
  910. vs_configuration = {}
  911. host_vs_configuration = {}
  912. common_build_prefix = []
  913. confs = []
  914. for x in sorted(glob.glob("platform/*")):
  915. # Only platforms that opt in to vs proj generation are included.
  916. if not os.path.isdir(x) or not os.path.exists(x + "/msvs.py"):
  917. continue
  918. tmppath = "./" + x
  919. sys.path.insert(0, tmppath)
  920. import msvs
  921. vs_plats = []
  922. vs_confs = []
  923. try:
  924. platform_name = x[9:]
  925. vs_plats = msvs.get_platforms()
  926. vs_confs = msvs.get_configurations()
  927. val = []
  928. for plat in vs_plats:
  929. val += [{"platform": plat[0], "architecture": plat[1]}]
  930. vsconf = {"platform": platform_name, "targets": vs_confs, "arches": val}
  931. confs += [vsconf]
  932. # Save additional information about the configuration for the actively selected platform,
  933. # so we can generate the platform-specific props file with all the build commands/defines/etc
  934. if platform == platform_name:
  935. common_build_prefix = msvs.get_build_prefix(env)
  936. vs_configuration = vsconf
  937. if platform_name == host_platform:
  938. host_vs_configuration = vsconf
  939. for a in vsconf["arches"]:
  940. if host_arch == a["architecture"]:
  941. host_arch = a["platform"]
  942. break
  943. except Exception:
  944. pass
  945. sys.path.remove(tmppath)
  946. sys.modules.pop("msvs")
  947. extensions = {}
  948. extensions["headers"] = [".h", ".hh", ".hpp", ".hxx", ".inc"]
  949. extensions["sources"] = [".c", ".cc", ".cpp", ".cxx", ".m", ".mm", ".java"]
  950. extensions["others"] = [".natvis", ".glsl", ".rc"]
  951. headers = []
  952. headers_dirs = []
  953. for ext in extensions["headers"]:
  954. for file in glob_recursive_2("*" + ext, headers_dirs):
  955. headers.append(str(file).replace("/", "\\"))
  956. sources = []
  957. sources_dirs = []
  958. for ext in extensions["sources"]:
  959. for file in glob_recursive_2("*" + ext, sources_dirs):
  960. sources.append(str(file).replace("/", "\\"))
  961. others = []
  962. others_dirs = []
  963. for ext in extensions["others"]:
  964. for file in glob_recursive_2("*" + ext, others_dirs):
  965. others.append(str(file).replace("/", "\\"))
  966. skip_filters = False
  967. import hashlib
  968. import json
  969. md5 = hashlib.md5(
  970. json.dumps(sorted(headers + headers_dirs + sources + sources_dirs + others + others_dirs)).encode("utf-8")
  971. ).hexdigest()
  972. if os.path.exists(f"{project_name}.vcxproj.filters"):
  973. with open(f"{project_name}.vcxproj.filters", "r", encoding="utf-8") as file:
  974. existing_filters = file.read()
  975. match = re.search(r"(?ms)^<!-- CHECKSUM$.([0-9a-f]{32})", existing_filters)
  976. if match is not None and md5 == match.group(1):
  977. skip_filters = True
  978. import uuid
  979. # Don't regenerate the filters file if nothing has changed, so we keep the existing UUIDs.
  980. if not skip_filters:
  981. print(f"Regenerating {project_name}.vcxproj.filters")
  982. with open("misc/msvs/vcxproj.filters.template", "r", encoding="utf-8") as file:
  983. filters_template = file.read()
  984. for i in range(1, 10):
  985. filters_template = filters_template.replace(f"%%UUID{i}%%", str(uuid.uuid4()))
  986. filters = ""
  987. for d in headers_dirs:
  988. filters += f'<Filter Include="Header Files\\{d}"><UniqueIdentifier>{{{str(uuid.uuid4())}}}</UniqueIdentifier></Filter>\n'
  989. for d in sources_dirs:
  990. filters += f'<Filter Include="Source Files\\{d}"><UniqueIdentifier>{{{str(uuid.uuid4())}}}</UniqueIdentifier></Filter>\n'
  991. for d in others_dirs:
  992. filters += f'<Filter Include="Other Files\\{d}"><UniqueIdentifier>{{{str(uuid.uuid4())}}}</UniqueIdentifier></Filter>\n'
  993. filters_template = filters_template.replace("%%FILTERS%%", filters)
  994. filters = ""
  995. for file in headers:
  996. filters += (
  997. f'<ClInclude Include="{file}"><Filter>Header Files\\{os.path.dirname(file)}</Filter></ClInclude>\n'
  998. )
  999. filters_template = filters_template.replace("%%INCLUDES%%", filters)
  1000. filters = ""
  1001. for file in sources:
  1002. filters += (
  1003. f'<ClCompile Include="{file}"><Filter>Source Files\\{os.path.dirname(file)}</Filter></ClCompile>\n'
  1004. )
  1005. filters_template = filters_template.replace("%%COMPILES%%", filters)
  1006. filters = ""
  1007. for file in others:
  1008. filters += f'<None Include="{file}"><Filter>Other Files\\{os.path.dirname(file)}</Filter></None>\n'
  1009. filters_template = filters_template.replace("%%OTHERS%%", filters)
  1010. filters_template = filters_template.replace("%%HASH%%", md5)
  1011. with open(f"{project_name}.vcxproj.filters", "w", encoding="utf-8", newline="\r\n") as f:
  1012. f.write(filters_template)
  1013. headers_active = []
  1014. sources_active = []
  1015. others_active = []
  1016. get_dependencies(
  1017. env.File(f"#bin/godot{env['PROGSUFFIX']}"), env, extensions, headers_active, sources_active, others_active
  1018. )
  1019. all_items = []
  1020. properties = []
  1021. activeItems = []
  1022. extraItems = []
  1023. set_headers = set(headers_active)
  1024. set_sources = set(sources_active)
  1025. set_others = set(others_active)
  1026. for file in headers:
  1027. base_path = os.path.dirname(file).replace("\\", "_")
  1028. all_items.append(f'<ClInclude Include="{file}">')
  1029. all_items.append(
  1030. f" <ExcludedFromBuild Condition=\"!$(ActiveProjectItemList_{base_path}.Contains(';{file};'))\">true</ExcludedFromBuild>"
  1031. )
  1032. all_items.append("</ClInclude>")
  1033. if file in set_headers:
  1034. activeItems.append(file)
  1035. for file in sources:
  1036. base_path = os.path.dirname(file).replace("\\", "_")
  1037. all_items.append(f'<ClCompile Include="{file}">')
  1038. all_items.append(
  1039. f" <ExcludedFromBuild Condition=\"!$(ActiveProjectItemList_{base_path}.Contains(';{file};'))\">true</ExcludedFromBuild>"
  1040. )
  1041. all_items.append("</ClCompile>")
  1042. if file in set_sources:
  1043. activeItems.append(file)
  1044. for file in others:
  1045. base_path = os.path.dirname(file).replace("\\", "_")
  1046. all_items.append(f'<None Include="{file}">')
  1047. all_items.append(
  1048. f" <ExcludedFromBuild Condition=\"!$(ActiveProjectItemList_{base_path}.Contains(';{file};'))\">true</ExcludedFromBuild>"
  1049. )
  1050. all_items.append("</None>")
  1051. if file in set_others:
  1052. activeItems.append(file)
  1053. if vs_configuration:
  1054. vsconf = ""
  1055. for a in vs_configuration["arches"]:
  1056. if arch == a["architecture"]:
  1057. vsconf = f"{target}|{a['platform']}"
  1058. break
  1059. condition = "'$(GodotConfiguration)|$(GodotPlatform)'=='" + vsconf + "'"
  1060. itemlist = {}
  1061. for item in activeItems:
  1062. key = os.path.dirname(item).replace("\\", "_")
  1063. if key not in itemlist:
  1064. itemlist[key] = [item]
  1065. else:
  1066. itemlist[key] += [item]
  1067. for x in itemlist.keys():
  1068. properties.append(
  1069. "<ActiveProjectItemList_%s>;%s;</ActiveProjectItemList_%s>" % (x, ";".join(itemlist[x]), x)
  1070. )
  1071. output = os.path.join("bin", f"godot{env['PROGSUFFIX']}")
  1072. # The modules_enabled.gen.h header containing the defines is only generated on build, and only for the most recently built
  1073. # platform, which means VS can't properly render code that's inside module-specific ifdefs. This adds those defines to the
  1074. # platform-specific VS props file, so that VS knows which defines are enabled for the selected platform.
  1075. env.Append(VSHINT_DEFINES=[f"MODULE_{module.upper()}_ENABLED" for module in env.module_list])
  1076. with open("misc/msvs/props.template", "r", encoding="utf-8") as file:
  1077. props_template = file.read()
  1078. props_template = props_template.replace("%%CONDITION%%", condition)
  1079. props_template = props_template.replace("%%PROPERTIES%%", "\n ".join(properties))
  1080. props_template = props_template.replace("%%EXTRA_ITEMS%%", "\n ".join(extraItems))
  1081. props_template = props_template.replace("%%OUTPUT%%", output)
  1082. proplist = [format_key_value(j) for j in list(env["CPPDEFINES"])]
  1083. proplist += [format_key_value(j) for j in env.get("VSHINT_DEFINES", [])]
  1084. props_template = props_template.replace("%%DEFINES%%", ";".join(proplist))
  1085. proplist = [str(j) for j in env["CPPPATH"]]
  1086. proplist += [str(j) for j in env.get("VSHINT_INCLUDES", [])]
  1087. proplist += [str(j) for j in get_default_include_paths(env)]
  1088. props_template = props_template.replace("%%INCLUDES%%", ";".join(proplist))
  1089. proplist = [env.subst("$CCFLAGS")]
  1090. proplist += [env.subst("$CXXFLAGS")]
  1091. proplist += [env.subst("$VSHINT_OPTIONS")]
  1092. props_template = props_template.replace("%%OPTIONS%%", " ".join(proplist))
  1093. # Windows allows us to have spaces in paths, so we need
  1094. # to double quote off the directory. However, the path ends
  1095. # in a backslash, so we need to remove this, lest it escape the
  1096. # last double quote off, confusing MSBuild
  1097. common_build_postfix = [
  1098. "--directory=&quot;$(ProjectDir.TrimEnd(&apos;\\&apos;))&quot;",
  1099. "progress=no",
  1100. f"platform={platform}",
  1101. f"target={target}",
  1102. f"arch={arch}",
  1103. ]
  1104. for arg, value in filtered_args.items():
  1105. common_build_postfix.append(f"{arg}={value}")
  1106. cmd_rebuild = [
  1107. "vsproj=yes",
  1108. "vsproj_props_only=yes",
  1109. "vsproj_gen_only=no",
  1110. f"vsproj_name={project_name}",
  1111. ] + common_build_postfix
  1112. cmd_clean = [
  1113. "--clean",
  1114. ] + common_build_postfix
  1115. commands = "scons"
  1116. if len(common_build_prefix) == 0:
  1117. commands = "echo Starting SCons &amp; " + commands
  1118. else:
  1119. common_build_prefix[0] = "echo Starting SCons &amp; " + common_build_prefix[0]
  1120. cmd = " ".join(common_build_prefix + [" ".join([commands] + common_build_postfix)])
  1121. props_template = props_template.replace("%%BUILD%%", cmd)
  1122. cmd = " ".join(common_build_prefix + [" ".join([commands] + cmd_rebuild)])
  1123. props_template = props_template.replace("%%REBUILD%%", cmd)
  1124. cmd = " ".join(common_build_prefix + [" ".join([commands] + cmd_clean)])
  1125. props_template = props_template.replace("%%CLEAN%%", cmd)
  1126. with open(
  1127. f"{project_name}.{platform}.{target}.{arch}.generated.props", "w", encoding="utf-8", newline="\r\n"
  1128. ) as f:
  1129. f.write(props_template)
  1130. proj_uuid = str(uuid.uuid4())
  1131. sln_uuid = str(uuid.uuid4())
  1132. if os.path.exists(f"{project_name}.sln"):
  1133. for line in open(f"{project_name}.sln", "r", encoding="utf-8").read().splitlines():
  1134. if line.startswith('Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}")'):
  1135. proj_uuid = re.search(
  1136. r"\"{(\b[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-\b[0-9a-fA-F]{12}\b)}\"$",
  1137. line,
  1138. ).group(1)
  1139. elif line.strip().startswith("SolutionGuid ="):
  1140. sln_uuid = re.search(
  1141. r"{(\b[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-\b[0-9a-fA-F]{12}\b)}", line
  1142. ).group(1)
  1143. break
  1144. configurations = []
  1145. imports = []
  1146. properties = []
  1147. section1 = []
  1148. section2 = []
  1149. for conf in confs:
  1150. godot_platform = conf["platform"]
  1151. has_editor = "editor" in conf["targets"]
  1152. # Skip any platforms that can build the editor and don't match the host platform.
  1153. #
  1154. # When both Windows and Mac define an editor target, it's defined as platform+target+arch (windows+editor+x64 for example).
  1155. # VS only supports two attributes, a "Configuration" and a "Platform", and we currently map our target to the Configuration
  1156. # (i.e. editor/template_debug/template_release), and our architecture to the "Platform" (i.e. x64, arm64, etc).
  1157. # Those two are not enough to disambiguate multiple godot targets for different godot platforms with the same architecture,
  1158. # i.e. editor|x64 would currently match both windows editor intel 64 and linux editor intel 64.
  1159. #
  1160. # TODO: More work is needed in order to support generating VS projects that unambiguously support all platform+target+arch variations.
  1161. # The VS "Platform" has to be a known architecture that VS recognizes, so we can only play around with the "Configuration" part of the combo.
  1162. if has_editor and godot_platform != host_vs_configuration["platform"]:
  1163. continue
  1164. for p in conf["arches"]:
  1165. sln_plat = p["platform"]
  1166. proj_plat = sln_plat
  1167. godot_arch = p["architecture"]
  1168. # Redirect editor configurations for platforms that don't support the editor target to the default editor target on the
  1169. # active host platform, so the solution has all the permutations and VS doesn't complain about missing project configurations.
  1170. # These configurations are disabled, so they show up but won't build.
  1171. if not has_editor:
  1172. section1 += [f"editor|{sln_plat} = editor|{proj_plat}"]
  1173. section2 += [f"{{{proj_uuid}}}.editor|{proj_plat}.ActiveCfg = editor|{host_arch}"]
  1174. configurations += [
  1175. f'<ProjectConfiguration Include="editor|{proj_plat}">',
  1176. " <Configuration>editor</Configuration>",
  1177. f" <Platform>{proj_plat}</Platform>",
  1178. "</ProjectConfiguration>",
  1179. ]
  1180. properties += [
  1181. f"<PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='editor|{proj_plat}'\">",
  1182. " <GodotConfiguration>editor</GodotConfiguration>",
  1183. f" <GodotPlatform>{proj_plat}</GodotPlatform>",
  1184. "</PropertyGroup>",
  1185. ]
  1186. for t in conf["targets"]:
  1187. godot_target = t
  1188. # Windows x86 is a special little flower that requires a project platform == Win32 but a solution platform == x86.
  1189. if godot_platform == "windows" and godot_target == "editor" and godot_arch == "x86_32":
  1190. sln_plat = "x86"
  1191. configurations += [
  1192. f'<ProjectConfiguration Include="{godot_target}|{proj_plat}">',
  1193. f" <Configuration>{godot_target}</Configuration>",
  1194. f" <Platform>{proj_plat}</Platform>",
  1195. "</ProjectConfiguration>",
  1196. ]
  1197. properties += [
  1198. f"<PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='{godot_target}|{proj_plat}'\">",
  1199. f" <GodotConfiguration>{godot_target}</GodotConfiguration>",
  1200. f" <GodotPlatform>{proj_plat}</GodotPlatform>",
  1201. "</PropertyGroup>",
  1202. ]
  1203. p = f"{project_name}.{godot_platform}.{godot_target}.{godot_arch}.generated.props"
  1204. imports += [
  1205. f'<Import Project="$(MSBuildProjectDirectory)\\{p}" Condition="Exists(\'$(MSBuildProjectDirectory)\\{p}\')"/>'
  1206. ]
  1207. section1 += [f"{godot_target}|{sln_plat} = {godot_target}|{sln_plat}"]
  1208. section2 += [
  1209. f"{{{proj_uuid}}}.{godot_target}|{sln_plat}.ActiveCfg = {godot_target}|{proj_plat}",
  1210. f"{{{proj_uuid}}}.{godot_target}|{sln_plat}.Build.0 = {godot_target}|{proj_plat}",
  1211. ]
  1212. # Add an extra import for a local user props file at the end, so users can add more overrides.
  1213. imports += [
  1214. f'<Import Project="$(MSBuildProjectDirectory)\\{project_name}.vs.user.props" Condition="Exists(\'$(MSBuildProjectDirectory)\\{project_name}.vs.user.props\')"/>'
  1215. ]
  1216. section1 = sorted(section1)
  1217. section2 = sorted(section2)
  1218. if not get_bool(original_args, "vsproj_props_only", False):
  1219. with open("misc/msvs/vcxproj.template", "r", encoding="utf-8") as file:
  1220. proj_template = file.read()
  1221. proj_template = proj_template.replace("%%UUID%%", proj_uuid)
  1222. proj_template = proj_template.replace("%%CONFS%%", "\n ".join(configurations))
  1223. proj_template = proj_template.replace("%%IMPORTS%%", "\n ".join(imports))
  1224. proj_template = proj_template.replace("%%DEFAULT_ITEMS%%", "\n ".join(all_items))
  1225. proj_template = proj_template.replace("%%PROPERTIES%%", "\n ".join(properties))
  1226. with open(f"{project_name}.vcxproj", "w", encoding="utf-8", newline="\r\n") as f:
  1227. f.write(proj_template)
  1228. if not get_bool(original_args, "vsproj_props_only", False):
  1229. with open("misc/msvs/sln.template", "r", encoding="utf-8") as file:
  1230. sln_template = file.read()
  1231. sln_template = sln_template.replace("%%NAME%%", project_name)
  1232. sln_template = sln_template.replace("%%UUID%%", proj_uuid)
  1233. sln_template = sln_template.replace("%%SLNUUID%%", sln_uuid)
  1234. sln_template = sln_template.replace("%%SECTION1%%", "\n\t\t".join(section1))
  1235. sln_template = sln_template.replace("%%SECTION2%%", "\n\t\t".join(section2))
  1236. with open(f"{project_name}.sln", "w", encoding="utf-8", newline="\r\n") as f:
  1237. f.write(sln_template)
  1238. if get_bool(original_args, "vsproj_gen_only", True):
  1239. sys.exit()
  1240. ############################################################
  1241. # FILE GENERATION & FORMATTING
  1242. ############################################################
  1243. def generate_copyright_header(filename: str) -> str:
  1244. MARGIN = 70
  1245. TEMPLATE = """\
  1246. /**************************************************************************/
  1247. /* %s*/
  1248. /**************************************************************************/
  1249. /* This file is part of: */
  1250. /* GODOT ENGINE */
  1251. /* https://godotengine.org */
  1252. /**************************************************************************/
  1253. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  1254. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  1255. /* */
  1256. /* Permission is hereby granted, free of charge, to any person obtaining */
  1257. /* a copy of this software and associated documentation files (the */
  1258. /* "Software"), to deal in the Software without restriction, including */
  1259. /* without limitation the rights to use, copy, modify, merge, publish, */
  1260. /* distribute, sublicense, and/or sell copies of the Software, and to */
  1261. /* permit persons to whom the Software is furnished to do so, subject to */
  1262. /* the following conditions: */
  1263. /* */
  1264. /* The above copyright notice and this permission notice shall be */
  1265. /* included in all copies or substantial portions of the Software. */
  1266. /* */
  1267. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  1268. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  1269. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  1270. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  1271. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  1272. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  1273. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  1274. /**************************************************************************/
  1275. """
  1276. if len(filename := os.path.basename(filename).ljust(MARGIN)) > MARGIN:
  1277. print_warning(f'Filename "{filename}" too large for copyright header.')
  1278. return TEMPLATE % filename
  1279. @contextlib.contextmanager
  1280. def generated_wrapper(
  1281. path: str,
  1282. guard: bool | None = None,
  1283. ) -> Generator[TextIO, None, None]:
  1284. """
  1285. Wrapper class to automatically handle copyright headers and header guards
  1286. for generated scripts. Meant to be invoked via `with` statement similar to
  1287. creating a file.
  1288. - `path`: The path of the file to be created.
  1289. - `guard`: Optional bool to determine if `#pragma once` should be added. If
  1290. unassigned, the value is determined by file extension.
  1291. """
  1292. with open(path, "wt", encoding="utf-8", newline="\n") as file:
  1293. if not path.endswith(".out"): # For test output, we only care about the content.
  1294. file.write(generate_copyright_header(path))
  1295. file.write("\n/* THIS FILE IS GENERATED. EDITS WILL BE LOST. */\n\n")
  1296. if guard is None:
  1297. guard = path.endswith((".h", ".hh", ".hpp", ".hxx", ".inc"))
  1298. if guard:
  1299. file.write("#pragma once\n\n")
  1300. with StringIO(newline="\n") as str_io:
  1301. yield str_io
  1302. file.write(str_io.getvalue().strip() or "/* NO CONTENT */")
  1303. file.write("\n")
  1304. def get_buffer(path: str) -> bytes:
  1305. with open(path, "rb") as file:
  1306. return file.read()
  1307. def compress_buffer(buffer: bytes) -> bytes:
  1308. # Use maximum zlib compression level to further reduce file size
  1309. # (at the cost of initial build times).
  1310. return zlib.compress(buffer, zlib.Z_BEST_COMPRESSION)
  1311. def format_buffer(buffer: bytes, indent: int = 0, width: int = 120, initial_indent: bool = False) -> str:
  1312. return textwrap.fill(
  1313. ", ".join(str(byte) for byte in buffer),
  1314. width=width,
  1315. initial_indent="\t" * indent if initial_indent else "",
  1316. subsequent_indent="\t" * indent,
  1317. tabsize=4,
  1318. )
  1319. ############################################################
  1320. # CSTRING PARSING
  1321. ############################################################
  1322. C_ESCAPABLES = [
  1323. ("\\", "\\\\"),
  1324. ("\a", "\\a"),
  1325. ("\b", "\\b"),
  1326. ("\f", "\\f"),
  1327. ("\n", "\\n"),
  1328. ("\r", "\\r"),
  1329. ("\t", "\\t"),
  1330. ("\v", "\\v"),
  1331. # ("'", "\\'"), # Skip, as we're only dealing with full strings.
  1332. ('"', '\\"'),
  1333. ]
  1334. C_ESCAPE_TABLE = str.maketrans(dict((x, y) for x, y in C_ESCAPABLES))
  1335. def to_escaped_cstring(value: str) -> str:
  1336. return value.translate(C_ESCAPE_TABLE)
  1337. def to_raw_cstring(value: str | list[str]) -> str:
  1338. MAX_LITERAL = 16 * 1024
  1339. if isinstance(value, list):
  1340. value = "\n".join(value) + "\n"
  1341. split: list[bytes] = []
  1342. offset = 0
  1343. encoded = value.encode()
  1344. while offset <= len(encoded):
  1345. segment = encoded[offset : offset + MAX_LITERAL]
  1346. offset += MAX_LITERAL
  1347. if len(segment) == MAX_LITERAL:
  1348. # Try to segment raw strings at double newlines to keep readable.
  1349. pretty_break = segment.rfind(b"\n\n")
  1350. if pretty_break != -1:
  1351. segment = segment[: pretty_break + 1]
  1352. offset -= MAX_LITERAL - pretty_break - 1
  1353. # If none found, ensure we end with valid utf8.
  1354. # https://github.com/halloleo/unicut/blob/master/truncate.py
  1355. elif segment[-1] & 0b10000000:
  1356. last_11xxxxxx_index = [i for i in range(-1, -5, -1) if segment[i] & 0b11000000 == 0b11000000][0]
  1357. last_11xxxxxx = segment[last_11xxxxxx_index]
  1358. if not last_11xxxxxx & 0b00100000:
  1359. last_char_length = 2
  1360. elif not last_11xxxxxx & 0b0010000:
  1361. last_char_length = 3
  1362. elif not last_11xxxxxx & 0b0001000:
  1363. last_char_length = 4
  1364. if last_char_length > -last_11xxxxxx_index:
  1365. segment = segment[:last_11xxxxxx_index]
  1366. offset += last_11xxxxxx_index
  1367. split += [segment]
  1368. if len(split) == 1:
  1369. return f'R"<!>({split[0].decode()})<!>"'
  1370. else:
  1371. # Wrap multiple segments in parenthesis to suppress `string-concatenation` warnings on clang.
  1372. return "({})".format(" ".join(f'R"<!>({segment.decode()})<!>"' for segment in split))
  1373. def get_default_include_paths(env):
  1374. if env.msvc:
  1375. return []
  1376. compiler = env.subst("$CXX")
  1377. target = os.path.join(env.Dir("#main").abspath, "main.cpp")
  1378. args = [compiler, target, "-x", "c++", "-v"]
  1379. ret = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
  1380. output = ret.stdout
  1381. match = re.search(r"#include <\.\.\.> search starts here:([\S\s]*)End of search list.", output)
  1382. if not match:
  1383. print_warning("Failed to find the include paths in the compiler output.")
  1384. return []
  1385. return [x.strip() for x in match[1].strip().splitlines()]