methods.py 64 KB

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