methods.py 60 KB

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