methods.py 62 KB

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