methods.py 64 KB

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