methods.py 62 KB

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