methods.py 64 KB

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