methods.py 61 KB

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