methods.py 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668
  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", "--no-show-signature", 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, "r", encoding="utf-8") 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. zip_archive_message = "{}Archiving {}$TARGET{} ...{}".format(*colors)
  443. generated_file_message = "{}Generating {}$TARGET{} ...{}".format(*colors)
  444. env["CXXCOMSTR"] = compile_source_message
  445. env["CCCOMSTR"] = compile_source_message
  446. env["SHCCCOMSTR"] = compile_shared_source_message
  447. env["SHCXXCOMSTR"] = compile_shared_source_message
  448. env["ARCOMSTR"] = link_library_message
  449. env["RANLIBCOMSTR"] = ranlib_library_message
  450. env["SHLINKCOMSTR"] = link_shared_library_message
  451. env["LINKCOMSTR"] = link_program_message
  452. env["JARCOMSTR"] = java_library_message
  453. env["JAVACCOMSTR"] = java_compile_source_message
  454. env["RCCOMSTR"] = compiled_resource_message
  455. env["ZIPCOMSTR"] = zip_archive_message
  456. env["GENCOMSTR"] = generated_file_message
  457. def detect_visual_c_compiler_version(tools_env):
  458. # tools_env is the variable scons uses to call tools that execute tasks, SCons's env['ENV'] that executes tasks...
  459. # (see the SCons documentation for more information on what it does)...
  460. # in order for this function to be well encapsulated i choose to force it to receive SCons's TOOLS env (env['ENV']
  461. # and not scons setup environment (env)... so make sure you call the right environment on it or it will fail to detect
  462. # the proper vc version that will be called
  463. # 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.).
  464. # There are many different cl.exe files that are run, and each one compiles & links to a different architecture
  465. # As far as I know, the only way to figure out what compiler will be run when Scons calls cl.exe via Program()
  466. # is to check the PATH variable and figure out which one will be called first. Code below does that and returns:
  467. # the following string values:
  468. # "" Compiler not detected
  469. # "amd64" Native 64 bit compiler
  470. # "amd64_x86" 64 bit Cross Compiler for 32 bit
  471. # "x86" Native 32 bit compiler
  472. # "x86_amd64" 32 bit Cross Compiler for 64 bit
  473. # There are other architectures, but Godot does not support them currently, so this function does not detect arm/amd64_arm
  474. # and similar architectures/compilers
  475. # Set chosen compiler to "not detected"
  476. vc_chosen_compiler_index = -1
  477. vc_chosen_compiler_str = ""
  478. # Start with Pre VS 2017 checks which uses VCINSTALLDIR:
  479. if "VCINSTALLDIR" in tools_env:
  480. # print("Checking VCINSTALLDIR")
  481. # find() works with -1 so big ifs below are needed... the simplest solution, in fact
  482. # First test if amd64 and amd64_x86 compilers are present in the path
  483. vc_amd64_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\amd64;")
  484. if vc_amd64_compiler_detection_index > -1:
  485. vc_chosen_compiler_index = vc_amd64_compiler_detection_index
  486. vc_chosen_compiler_str = "amd64"
  487. vc_amd64_x86_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\amd64_x86;")
  488. if vc_amd64_x86_compiler_detection_index > -1 and (
  489. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index
  490. ):
  491. vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index
  492. vc_chosen_compiler_str = "amd64_x86"
  493. # Now check the 32 bit compilers
  494. vc_x86_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN;")
  495. if vc_x86_compiler_detection_index > -1 and (
  496. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_compiler_detection_index
  497. ):
  498. vc_chosen_compiler_index = vc_x86_compiler_detection_index
  499. vc_chosen_compiler_str = "x86"
  500. vc_x86_amd64_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\x86_amd64;")
  501. if vc_x86_amd64_compiler_detection_index > -1 and (
  502. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index
  503. ):
  504. vc_chosen_compiler_index = vc_x86_amd64_compiler_detection_index
  505. vc_chosen_compiler_str = "x86_amd64"
  506. # and for VS 2017 and newer we check VCTOOLSINSTALLDIR:
  507. if "VCTOOLSINSTALLDIR" in tools_env:
  508. # Newer versions have a different path available
  509. vc_amd64_compiler_detection_index = (
  510. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX64\\X64;")
  511. )
  512. if vc_amd64_compiler_detection_index > -1:
  513. vc_chosen_compiler_index = vc_amd64_compiler_detection_index
  514. vc_chosen_compiler_str = "amd64"
  515. vc_amd64_x86_compiler_detection_index = (
  516. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX64\\X86;")
  517. )
  518. if vc_amd64_x86_compiler_detection_index > -1 and (
  519. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index
  520. ):
  521. vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index
  522. vc_chosen_compiler_str = "amd64_x86"
  523. vc_x86_compiler_detection_index = (
  524. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX86\\X86;")
  525. )
  526. if vc_x86_compiler_detection_index > -1 and (
  527. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_compiler_detection_index
  528. ):
  529. vc_chosen_compiler_index = vc_x86_compiler_detection_index
  530. vc_chosen_compiler_str = "x86"
  531. vc_x86_amd64_compiler_detection_index = (
  532. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX86\\X64;")
  533. )
  534. if vc_x86_amd64_compiler_detection_index > -1 and (
  535. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index
  536. ):
  537. vc_chosen_compiler_str = "x86_amd64"
  538. return vc_chosen_compiler_str
  539. def find_visual_c_batch_file(env):
  540. # TODO: We should investigate if we can avoid relying on SCons internals here.
  541. from SCons.Tool.MSCommon.vc import find_batch_file, find_vc_pdir, get_default_version, get_host_target
  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. # Param names need to be explicit, as they were shuffled around in SCons 4.8.0.
  553. product_dir = find_vc_pdir(msvc_version=msvc_version, env=env)
  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. for name in ["GDVIRTUAL", "EXBIND", "MODBIND"]:
  564. for count in range(13):
  565. for suffix in ["", "R", "C", "RC"]:
  566. fd.write(f"#define {name}{count}{suffix}(")
  567. if "R" in suffix:
  568. fd.write("m_ret, ")
  569. fd.write("m_name")
  570. for idx in range(1, count + 1):
  571. fd.write(f", type{idx}")
  572. fd.write(")\n")
  573. except OSError:
  574. print_warning("Could not write cpp.hint file.")
  575. def glob_recursive(pattern, node="."):
  576. from SCons import Node
  577. from SCons.Script import Glob
  578. results = []
  579. for f in Glob(str(node) + "/*", source=True):
  580. if type(f) is Node.FS.Dir:
  581. results += glob_recursive(pattern, f)
  582. results += Glob(str(node) + "/" + pattern, source=True)
  583. return results
  584. def add_to_vs_project(env, sources):
  585. for x in sources:
  586. fname = env.File(x).path if isinstance(x, str) else env.File(x)[0].path
  587. pieces = fname.split(".")
  588. if len(pieces) > 0:
  589. basename = pieces[0]
  590. basename = basename.replace("\\\\", "/")
  591. if os.path.isfile(basename + ".h"):
  592. env.vs_incs += [basename + ".h"]
  593. elif os.path.isfile(basename + ".hpp"):
  594. env.vs_incs += [basename + ".hpp"]
  595. if os.path.isfile(basename + ".c"):
  596. env.vs_srcs += [basename + ".c"]
  597. elif os.path.isfile(basename + ".cpp"):
  598. env.vs_srcs += [basename + ".cpp"]
  599. def precious_program(env, program, sources, **args):
  600. program = env.ProgramOriginal(program, sources, **args)
  601. env.Precious(program)
  602. return program
  603. def add_shared_library(env, name, sources, **args):
  604. library = env.SharedLibrary(name, sources, **args)
  605. env.NoCache(library)
  606. return library
  607. def add_library(env, name, sources, **args):
  608. library = env.Library(name, sources, **args)
  609. env.NoCache(library)
  610. return library
  611. def add_program(env, name, sources, **args):
  612. program = env.Program(name, sources, **args)
  613. env.NoCache(program)
  614. return program
  615. def CommandNoCache(env, target, sources, command, **args):
  616. result = env.Command(target, sources, command, **args)
  617. env.NoCache(result)
  618. return result
  619. def Run(env, function):
  620. from SCons.Script import Action
  621. return Action(function, "$GENCOMSTR")
  622. def detect_darwin_sdk_path(platform, env):
  623. sdk_name = ""
  624. if platform == "macos":
  625. sdk_name = "macosx"
  626. var_name = "MACOS_SDK_PATH"
  627. elif platform == "ios":
  628. sdk_name = "iphoneos"
  629. var_name = "IOS_SDK_PATH"
  630. elif platform == "iossimulator":
  631. sdk_name = "iphonesimulator"
  632. var_name = "IOS_SDK_PATH"
  633. else:
  634. raise Exception("Invalid platform argument passed to detect_darwin_sdk_path")
  635. if not env[var_name]:
  636. try:
  637. sdk_path = subprocess.check_output(["xcrun", "--sdk", sdk_name, "--show-sdk-path"]).strip().decode("utf-8")
  638. if sdk_path:
  639. env[var_name] = sdk_path
  640. except (subprocess.CalledProcessError, OSError):
  641. print_error("Failed to find SDK path while running xcrun --sdk {} --show-sdk-path.".format(sdk_name))
  642. raise
  643. def is_vanilla_clang(env):
  644. if not using_clang(env):
  645. return False
  646. try:
  647. version = subprocess.check_output([env.subst(env["CXX"]), "--version"]).strip().decode("utf-8")
  648. except (subprocess.CalledProcessError, OSError):
  649. print_warning("Couldn't parse CXX environment variable to infer compiler version.")
  650. return False
  651. return not version.startswith("Apple")
  652. def get_compiler_version(env):
  653. """
  654. Returns a dictionary with various version information:
  655. - major, minor, patch: Version following semantic versioning system
  656. - metadata1, metadata2: Extra information
  657. - date: Date of the build
  658. """
  659. ret = {
  660. "major": -1,
  661. "minor": -1,
  662. "patch": -1,
  663. "metadata1": None,
  664. "metadata2": None,
  665. "date": None,
  666. "apple_major": -1,
  667. "apple_minor": -1,
  668. "apple_patch1": -1,
  669. "apple_patch2": -1,
  670. "apple_patch3": -1,
  671. }
  672. if not env.msvc:
  673. # Not using -dumpversion as some GCC distros only return major, and
  674. # Clang used to return hardcoded 4.2.1: # https://reviews.llvm.org/D56803
  675. try:
  676. version = (
  677. subprocess.check_output([env.subst(env["CXX"]), "--version"], shell=(os.name == "nt"))
  678. .strip()
  679. .decode("utf-8")
  680. )
  681. except (subprocess.CalledProcessError, OSError):
  682. print_warning("Couldn't parse CXX environment variable to infer compiler version.")
  683. return ret
  684. else:
  685. # TODO: Implement for MSVC
  686. return ret
  687. match = re.search(
  688. r"(?:(?<=version )|(?<=\) )|(?<=^))"
  689. r"(?P<major>\d+)"
  690. r"(?:\.(?P<minor>\d*))?"
  691. r"(?:\.(?P<patch>\d*))?"
  692. r"(?:-(?P<metadata1>[0-9a-zA-Z-]*))?"
  693. r"(?:\+(?P<metadata2>[0-9a-zA-Z-]*))?"
  694. r"(?: (?P<date>[0-9]{8}|[0-9]{6})(?![0-9a-zA-Z]))?",
  695. version,
  696. )
  697. if match is not None:
  698. for key, value in match.groupdict().items():
  699. if value is not None:
  700. ret[key] = value
  701. match_apple = re.search(
  702. r"(?:(?<=clang-)|(?<=\) )|(?<=^))"
  703. r"(?P<apple_major>\d+)"
  704. r"(?:\.(?P<apple_minor>\d*))?"
  705. r"(?:\.(?P<apple_patch1>\d*))?"
  706. r"(?:\.(?P<apple_patch2>\d*))?"
  707. r"(?:\.(?P<apple_patch3>\d*))?",
  708. version,
  709. )
  710. if match_apple is not None:
  711. for key, value in match_apple.groupdict().items():
  712. if value is not None:
  713. ret[key] = value
  714. # Transform semantic versioning to integers
  715. for key in [
  716. "major",
  717. "minor",
  718. "patch",
  719. "apple_major",
  720. "apple_minor",
  721. "apple_patch1",
  722. "apple_patch2",
  723. "apple_patch3",
  724. ]:
  725. ret[key] = int(ret[key] or -1)
  726. return ret
  727. def using_gcc(env):
  728. return "gcc" in os.path.basename(env["CC"])
  729. def using_clang(env):
  730. return "clang" in os.path.basename(env["CC"])
  731. def using_emcc(env):
  732. return "emcc" in os.path.basename(env["CC"])
  733. def show_progress(env):
  734. if env["ninja"]:
  735. # Has its own progress/tracking tool that clashes with ours
  736. return
  737. import sys
  738. from SCons.Script import AlwaysBuild, Command, Progress
  739. screen = sys.stdout
  740. # Progress reporting is not available in non-TTY environments since it
  741. # messes with the output (for example, when writing to a file)
  742. show_progress = env["progress"] and sys.stdout.isatty()
  743. node_count = 0
  744. node_count_max = 0
  745. node_count_interval = 1
  746. node_count_fname = str(env.Dir("#")) + "/.scons_node_count"
  747. import math
  748. class cache_progress:
  749. # The default is 1 GB cache
  750. def __init__(self, path=None, limit=pow(1024, 3)):
  751. self.path = path
  752. self.limit = limit
  753. if env["verbose"] and path is not None:
  754. screen.write(
  755. "Current cache limit is {} (used: {})\n".format(
  756. self.convert_size(limit), self.convert_size(self.get_size(path))
  757. )
  758. )
  759. def __call__(self, node, *args, **kw):
  760. nonlocal node_count, node_count_max, node_count_interval, node_count_fname, show_progress
  761. if show_progress:
  762. # Print the progress percentage
  763. node_count += node_count_interval
  764. if node_count_max > 0 and node_count <= node_count_max:
  765. screen.write("\r[%3d%%] " % (node_count * 100 / node_count_max))
  766. screen.flush()
  767. elif node_count_max > 0 and node_count > node_count_max:
  768. screen.write("\r[100%] ")
  769. screen.flush()
  770. else:
  771. screen.write("\r[Initial build] ")
  772. screen.flush()
  773. def convert_size(self, size_bytes):
  774. if size_bytes == 0:
  775. return "0 bytes"
  776. size_name = ("bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
  777. i = int(math.floor(math.log(size_bytes, 1024)))
  778. p = math.pow(1024, i)
  779. s = round(size_bytes / p, 2)
  780. return "%s %s" % (int(s) if i == 0 else s, size_name[i])
  781. def get_size(self, start_path="."):
  782. total_size = 0
  783. for dirpath, dirnames, filenames in os.walk(start_path):
  784. for f in filenames:
  785. fp = os.path.join(dirpath, f)
  786. total_size += os.path.getsize(fp)
  787. return total_size
  788. def progress_finish(target, source, env):
  789. nonlocal node_count, progressor
  790. try:
  791. with open(node_count_fname, "w", encoding="utf-8", newline="\n") as f:
  792. f.write("%d\n" % node_count)
  793. except Exception:
  794. pass
  795. try:
  796. with open(node_count_fname, "r", encoding="utf-8") as f:
  797. node_count_max = int(f.readline())
  798. except Exception:
  799. pass
  800. cache_directory = os.environ.get("SCONS_CACHE")
  801. # Simple cache pruning, attached to SCons' progress callback. Trim the
  802. # cache directory to a size not larger than cache_limit.
  803. cache_limit = float(os.getenv("SCONS_CACHE_LIMIT", 1024)) * 1024 * 1024
  804. progressor = cache_progress(cache_directory, cache_limit)
  805. Progress(progressor, interval=node_count_interval)
  806. progress_finish_command = Command("progress_finish", [], progress_finish)
  807. AlwaysBuild(progress_finish_command)
  808. def clean_cache(env):
  809. import atexit
  810. import time
  811. class cache_clean:
  812. def __init__(self, path=None, limit=pow(1024, 3)):
  813. self.path = path
  814. self.limit = limit
  815. def clean(self):
  816. self.delete(self.file_list())
  817. def delete(self, files):
  818. if len(files) == 0:
  819. return
  820. if env["verbose"]:
  821. # Utter something
  822. print("Purging %d %s from cache..." % (len(files), "files" if len(files) > 1 else "file"))
  823. [os.remove(f) for f in files]
  824. def file_list(self):
  825. if self.path is None:
  826. # Nothing to do
  827. return []
  828. # Gather a list of (filename, (size, atime)) within the
  829. # cache directory
  830. file_stat = [(x, os.stat(x)[6:8]) for x in glob.glob(os.path.join(self.path, "*", "*"))]
  831. if file_stat == []:
  832. # Nothing to do
  833. return []
  834. # Weight the cache files by size (assumed to be roughly
  835. # proportional to the recompilation time) times an exponential
  836. # decay since the ctime, and return a list with the entries
  837. # (filename, size, weight).
  838. current_time = time.time()
  839. file_stat = [(x[0], x[1][0], (current_time - x[1][1])) for x in file_stat]
  840. # Sort by the most recently accessed files (most sensible to keep) first
  841. file_stat.sort(key=lambda x: x[2])
  842. # Search for the first entry where the storage limit is
  843. # reached
  844. sum, mark = 0, None
  845. for i, x in enumerate(file_stat):
  846. sum += x[1]
  847. if sum > self.limit:
  848. mark = i
  849. break
  850. if mark is None:
  851. return []
  852. else:
  853. return [x[0] for x in file_stat[mark:]]
  854. def cache_finally():
  855. nonlocal cleaner
  856. try:
  857. cleaner.clean()
  858. except Exception:
  859. pass
  860. cache_directory = os.environ.get("SCONS_CACHE")
  861. # Simple cache pruning, attached to SCons' progress callback. Trim the
  862. # cache directory to a size not larger than cache_limit.
  863. cache_limit = float(os.getenv("SCONS_CACHE_LIMIT", 1024)) * 1024 * 1024
  864. cleaner = cache_clean(cache_directory, cache_limit)
  865. atexit.register(cache_finally)
  866. def dump(env):
  867. # Dumps latest build information for debugging purposes and external tools.
  868. from json import dump
  869. def non_serializable(obj):
  870. return "<<non-serializable: %s>>" % (type(obj).__qualname__)
  871. with open(".scons_env.json", "w", encoding="utf-8", newline="\n") as f:
  872. dump(env.Dictionary(), f, indent=4, default=non_serializable)
  873. # Custom Visual Studio project generation logic that supports any platform that has a msvs.py
  874. # script, so Visual Studio can be used to run scons for any platform, with the right defines per target.
  875. # Invoked with scons vsproj=yes
  876. #
  877. # Only platforms that opt in to vs proj generation by having a msvs.py file in the platform folder are included.
  878. # Platforms with a msvs.py file will be added to the solution, but only the current active platform+target+arch
  879. # will have a build configuration generated, because we only know what the right defines/includes/flags/etc are
  880. # on the active build target.
  881. #
  882. # Platforms that don't support an editor target will have a dummy editor target that won't do anything on build,
  883. # but will have the files and configuration for the windows editor target.
  884. #
  885. # To generate build configuration files for all platforms+targets+arch combinations, users can call
  886. # scons vsproj=yes
  887. # for each combination of platform+target+arch. This will generate the relevant vs project files but
  888. # skip the build process. This lets project files be quickly generated even if there are build errors.
  889. #
  890. # To generate AND build from the command line:
  891. # scons vsproj=yes vsproj_gen_only=no
  892. def generate_vs_project(env, original_args, project_name="godot"):
  893. # Augmented glob_recursive that also fills the dirs argument with traversed directories that have content.
  894. def glob_recursive_2(pattern, dirs, node="."):
  895. from SCons import Node
  896. from SCons.Script import Glob
  897. results = []
  898. for f in Glob(str(node) + "/*", source=True):
  899. if type(f) is Node.FS.Dir:
  900. results += glob_recursive_2(pattern, dirs, f)
  901. r = Glob(str(node) + "/" + pattern, source=True)
  902. if len(r) > 0 and str(node) not in dirs:
  903. d = ""
  904. for part in str(node).split("\\"):
  905. d += part
  906. if d not in dirs:
  907. dirs.append(d)
  908. d += "\\"
  909. results += r
  910. return results
  911. def get_bool(args, option, default):
  912. from SCons.Variables.BoolVariable import _text2bool
  913. val = args.get(option, default)
  914. if val is not None:
  915. try:
  916. return _text2bool(val)
  917. except (ValueError, AttributeError):
  918. return default
  919. else:
  920. return default
  921. def format_key_value(v):
  922. if type(v) in [tuple, list]:
  923. return v[0] if len(v) == 1 else f"{v[0]}={v[1]}"
  924. return v
  925. filtered_args = original_args.copy()
  926. # Ignore the "vsproj" option to not regenerate the VS project on every build
  927. filtered_args.pop("vsproj", None)
  928. # This flag allows users to regenerate the proj files but skip the building process.
  929. # This lets projects be regenerated even if there are build errors.
  930. filtered_args.pop("vsproj_gen_only", None)
  931. # This flag allows users to regenerate only the props file without touching the sln or vcxproj files.
  932. # This preserves any customizations users have done to the solution, while still updating the file list
  933. # and build commands.
  934. filtered_args.pop("vsproj_props_only", None)
  935. # The "progress" option is ignored as the current compilation progress indication doesn't work in VS
  936. filtered_args.pop("progress", None)
  937. # We add these three manually because they might not be explicitly passed in, and it's important to always set them.
  938. filtered_args.pop("platform", None)
  939. filtered_args.pop("target", None)
  940. filtered_args.pop("arch", None)
  941. platform = env["platform"]
  942. target = env["target"]
  943. arch = env["arch"]
  944. vs_configuration = {}
  945. common_build_prefix = []
  946. confs = []
  947. for x in sorted(glob.glob("platform/*")):
  948. # Only platforms that opt in to vs proj generation are included.
  949. if not os.path.isdir(x) or not os.path.exists(x + "/msvs.py"):
  950. continue
  951. tmppath = "./" + x
  952. sys.path.insert(0, tmppath)
  953. import msvs
  954. vs_plats = []
  955. vs_confs = []
  956. try:
  957. platform_name = x[9:]
  958. vs_plats = msvs.get_platforms()
  959. vs_confs = msvs.get_configurations()
  960. val = []
  961. for plat in vs_plats:
  962. val += [{"platform": plat[0], "architecture": plat[1]}]
  963. vsconf = {"platform": platform_name, "targets": vs_confs, "arches": val}
  964. confs += [vsconf]
  965. # Save additional information about the configuration for the actively selected platform,
  966. # so we can generate the platform-specific props file with all the build commands/defines/etc
  967. if platform == platform_name:
  968. common_build_prefix = msvs.get_build_prefix(env)
  969. vs_configuration = vsconf
  970. except Exception:
  971. pass
  972. sys.path.remove(tmppath)
  973. sys.modules.pop("msvs")
  974. headers = []
  975. headers_dirs = []
  976. for file in glob_recursive_2("*.h", headers_dirs):
  977. headers.append(str(file).replace("/", "\\"))
  978. for file in glob_recursive_2("*.hpp", headers_dirs):
  979. headers.append(str(file).replace("/", "\\"))
  980. sources = []
  981. sources_dirs = []
  982. for file in glob_recursive_2("*.cpp", sources_dirs):
  983. sources.append(str(file).replace("/", "\\"))
  984. for file in glob_recursive_2("*.c", sources_dirs):
  985. sources.append(str(file).replace("/", "\\"))
  986. others = []
  987. others_dirs = []
  988. for file in glob_recursive_2("*.natvis", others_dirs):
  989. others.append(str(file).replace("/", "\\"))
  990. for file in glob_recursive_2("*.glsl", others_dirs):
  991. others.append(str(file).replace("/", "\\"))
  992. skip_filters = False
  993. import hashlib
  994. import json
  995. md5 = hashlib.md5(
  996. json.dumps(headers + headers_dirs + sources + sources_dirs + others + others_dirs, sort_keys=True).encode(
  997. "utf-8"
  998. )
  999. ).hexdigest()
  1000. if os.path.exists(f"{project_name}.vcxproj.filters"):
  1001. with open(f"{project_name}.vcxproj.filters", "r", encoding="utf-8") as file:
  1002. existing_filters = file.read()
  1003. match = re.search(r"(?ms)^<!-- CHECKSUM$.([0-9a-f]{32})", existing_filters)
  1004. if match is not None and md5 == match.group(1):
  1005. skip_filters = True
  1006. import uuid
  1007. # Don't regenerate the filters file if nothing has changed, so we keep the existing UUIDs.
  1008. if not skip_filters:
  1009. print(f"Regenerating {project_name}.vcxproj.filters")
  1010. with open("misc/msvs/vcxproj.filters.template", "r", encoding="utf-8") as file:
  1011. filters_template = file.read()
  1012. for i in range(1, 10):
  1013. filters_template = filters_template.replace(f"%%UUID{i}%%", str(uuid.uuid4()))
  1014. filters = ""
  1015. for d in headers_dirs:
  1016. filters += f'<Filter Include="Header Files\\{d}"><UniqueIdentifier>{{{str(uuid.uuid4())}}}</UniqueIdentifier></Filter>\n'
  1017. for d in sources_dirs:
  1018. filters += f'<Filter Include="Source Files\\{d}"><UniqueIdentifier>{{{str(uuid.uuid4())}}}</UniqueIdentifier></Filter>\n'
  1019. for d in others_dirs:
  1020. filters += f'<Filter Include="Other Files\\{d}"><UniqueIdentifier>{{{str(uuid.uuid4())}}}</UniqueIdentifier></Filter>\n'
  1021. filters_template = filters_template.replace("%%FILTERS%%", filters)
  1022. filters = ""
  1023. for file in headers:
  1024. filters += (
  1025. f'<ClInclude Include="{file}"><Filter>Header Files\\{os.path.dirname(file)}</Filter></ClInclude>\n'
  1026. )
  1027. filters_template = filters_template.replace("%%INCLUDES%%", filters)
  1028. filters = ""
  1029. for file in sources:
  1030. filters += (
  1031. f'<ClCompile Include="{file}"><Filter>Source Files\\{os.path.dirname(file)}</Filter></ClCompile>\n'
  1032. )
  1033. filters_template = filters_template.replace("%%COMPILES%%", filters)
  1034. filters = ""
  1035. for file in others:
  1036. filters += f'<None Include="{file}"><Filter>Other Files\\{os.path.dirname(file)}</Filter></None>\n'
  1037. filters_template = filters_template.replace("%%OTHERS%%", filters)
  1038. filters_template = filters_template.replace("%%HASH%%", md5)
  1039. with open(f"{project_name}.vcxproj.filters", "w", encoding="utf-8", newline="\r\n") as f:
  1040. f.write(filters_template)
  1041. envsources = []
  1042. envsources += env.core_sources
  1043. envsources += env.drivers_sources
  1044. envsources += env.main_sources
  1045. envsources += env.modules_sources
  1046. envsources += env.scene_sources
  1047. envsources += env.servers_sources
  1048. if env.editor_build:
  1049. envsources += env.editor_sources
  1050. envsources += env.platform_sources
  1051. headers_active = []
  1052. sources_active = []
  1053. others_active = []
  1054. for x in envsources:
  1055. fname = ""
  1056. if isinstance(x, str):
  1057. fname = env.File(x).path
  1058. else:
  1059. # Some object files might get added directly as a File object and not a list.
  1060. try:
  1061. fname = env.File(x)[0].path
  1062. except Exception:
  1063. fname = x.path
  1064. pass
  1065. if fname:
  1066. fname = fname.replace("\\\\", "/")
  1067. parts = os.path.splitext(fname)
  1068. basename = parts[0]
  1069. ext = parts[1]
  1070. idx = fname.find(env["OBJSUFFIX"])
  1071. if ext in [".h", ".hpp"]:
  1072. headers_active += [fname]
  1073. elif ext in [".c", ".cpp"]:
  1074. sources_active += [fname]
  1075. elif idx > 0:
  1076. basename = fname[:idx]
  1077. if os.path.isfile(basename + ".h"):
  1078. headers_active += [basename + ".h"]
  1079. elif os.path.isfile(basename + ".hpp"):
  1080. headers_active += [basename + ".hpp"]
  1081. elif basename.endswith(".gen") and os.path.isfile(basename[:-4] + ".h"):
  1082. headers_active += [basename[:-4] + ".h"]
  1083. if os.path.isfile(basename + ".c"):
  1084. sources_active += [basename + ".c"]
  1085. elif os.path.isfile(basename + ".cpp"):
  1086. sources_active += [basename + ".cpp"]
  1087. else:
  1088. fname = os.path.relpath(os.path.abspath(fname), env.Dir("").abspath)
  1089. others_active += [fname]
  1090. all_items = []
  1091. properties = []
  1092. activeItems = []
  1093. extraItems = []
  1094. set_headers = set(headers_active)
  1095. set_sources = set(sources_active)
  1096. set_others = set(others_active)
  1097. for file in headers:
  1098. base_path = os.path.dirname(file).replace("\\", "_")
  1099. all_items.append(f'<ClInclude Include="{file}">')
  1100. all_items.append(
  1101. f" <ExcludedFromBuild Condition=\"!$(ActiveProjectItemList_{base_path}.Contains(';{file};'))\">true</ExcludedFromBuild>"
  1102. )
  1103. all_items.append("</ClInclude>")
  1104. if file in set_headers:
  1105. activeItems.append(file)
  1106. for file in sources:
  1107. base_path = os.path.dirname(file).replace("\\", "_")
  1108. all_items.append(f'<ClCompile Include="{file}">')
  1109. all_items.append(
  1110. f" <ExcludedFromBuild Condition=\"!$(ActiveProjectItemList_{base_path}.Contains(';{file};'))\">true</ExcludedFromBuild>"
  1111. )
  1112. all_items.append("</ClCompile>")
  1113. if file in set_sources:
  1114. activeItems.append(file)
  1115. for file in others:
  1116. base_path = os.path.dirname(file).replace("\\", "_")
  1117. all_items.append(f'<None Include="{file}">')
  1118. all_items.append(
  1119. f" <ExcludedFromBuild Condition=\"!$(ActiveProjectItemList_{base_path}.Contains(';{file};'))\">true</ExcludedFromBuild>"
  1120. )
  1121. all_items.append("</None>")
  1122. if file in set_others:
  1123. activeItems.append(file)
  1124. if vs_configuration:
  1125. vsconf = ""
  1126. for a in vs_configuration["arches"]:
  1127. if arch == a["architecture"]:
  1128. vsconf = f'{target}|{a["platform"]}'
  1129. break
  1130. condition = "'$(GodotConfiguration)|$(GodotPlatform)'=='" + vsconf + "'"
  1131. itemlist = {}
  1132. for item in activeItems:
  1133. key = os.path.dirname(item).replace("\\", "_")
  1134. if key not in itemlist:
  1135. itemlist[key] = [item]
  1136. else:
  1137. itemlist[key] += [item]
  1138. for x in itemlist.keys():
  1139. properties.append(
  1140. "<ActiveProjectItemList_%s>;%s;</ActiveProjectItemList_%s>" % (x, ";".join(itemlist[x]), x)
  1141. )
  1142. output = f'bin\\godot{env["PROGSUFFIX"]}'
  1143. with open("misc/msvs/props.template", "r", encoding="utf-8") as file:
  1144. props_template = file.read()
  1145. props_template = props_template.replace("%%VSCONF%%", vsconf)
  1146. props_template = props_template.replace("%%CONDITION%%", condition)
  1147. props_template = props_template.replace("%%PROPERTIES%%", "\n ".join(properties))
  1148. props_template = props_template.replace("%%EXTRA_ITEMS%%", "\n ".join(extraItems))
  1149. props_template = props_template.replace("%%OUTPUT%%", output)
  1150. proplist = [format_key_value(v) for v in list(env["CPPDEFINES"])]
  1151. proplist += [format_key_value(j) for j in env.get("VSHINT_DEFINES", [])]
  1152. props_template = props_template.replace("%%DEFINES%%", ";".join(proplist))
  1153. proplist = [str(j) for j in env["CPPPATH"]]
  1154. proplist += [str(j) for j in env.get("VSHINT_INCLUDES", [])]
  1155. props_template = props_template.replace("%%INCLUDES%%", ";".join(proplist))
  1156. proplist = env["CCFLAGS"]
  1157. proplist += [x for x in env["CXXFLAGS"] if not x.startswith("$")]
  1158. proplist += [str(j) for j in env.get("VSHINT_OPTIONS", [])]
  1159. props_template = props_template.replace("%%OPTIONS%%", " ".join(proplist))
  1160. # Windows allows us to have spaces in paths, so we need
  1161. # to double quote off the directory. However, the path ends
  1162. # in a backslash, so we need to remove this, lest it escape the
  1163. # last double quote off, confusing MSBuild
  1164. common_build_postfix = [
  1165. "--directory=&quot;$(ProjectDir.TrimEnd(&apos;\\&apos;))&quot;",
  1166. "progress=no",
  1167. f"platform={platform}",
  1168. f"target={target}",
  1169. f"arch={arch}",
  1170. ]
  1171. for arg, value in filtered_args.items():
  1172. common_build_postfix.append(f"{arg}={value}")
  1173. cmd_rebuild = [
  1174. "vsproj=yes",
  1175. "vsproj_props_only=yes",
  1176. "vsproj_gen_only=no",
  1177. f"vsproj_name={project_name}",
  1178. ] + common_build_postfix
  1179. cmd_clean = [
  1180. "--clean",
  1181. ] + common_build_postfix
  1182. commands = "scons"
  1183. if len(common_build_prefix) == 0:
  1184. commands = "echo Starting SCons &amp;&amp; cmd /V /C " + commands
  1185. else:
  1186. common_build_prefix[0] = "echo Starting SCons &amp;&amp; cmd /V /C " + common_build_prefix[0]
  1187. cmd = " ^&amp; ".join(common_build_prefix + [" ".join([commands] + common_build_postfix)])
  1188. props_template = props_template.replace("%%BUILD%%", cmd)
  1189. cmd = " ^&amp; ".join(common_build_prefix + [" ".join([commands] + cmd_rebuild)])
  1190. props_template = props_template.replace("%%REBUILD%%", cmd)
  1191. cmd = " ^&amp; ".join(common_build_prefix + [" ".join([commands] + cmd_clean)])
  1192. props_template = props_template.replace("%%CLEAN%%", cmd)
  1193. with open(
  1194. f"{project_name}.{platform}.{target}.{arch}.generated.props", "w", encoding="utf-8", newline="\r\n"
  1195. ) as f:
  1196. f.write(props_template)
  1197. proj_uuid = str(uuid.uuid4())
  1198. sln_uuid = str(uuid.uuid4())
  1199. if os.path.exists(f"{project_name}.sln"):
  1200. for line in open(f"{project_name}.sln", "r", encoding="utf-8").read().splitlines():
  1201. if line.startswith('Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}")'):
  1202. proj_uuid = re.search(
  1203. 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)}\"$",
  1204. line,
  1205. ).group(1)
  1206. elif line.strip().startswith("SolutionGuid ="):
  1207. sln_uuid = re.search(
  1208. 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
  1209. ).group(1)
  1210. break
  1211. configurations = []
  1212. imports = []
  1213. properties = []
  1214. section1 = []
  1215. section2 = []
  1216. for conf in confs:
  1217. godot_platform = conf["platform"]
  1218. for p in conf["arches"]:
  1219. sln_plat = p["platform"]
  1220. proj_plat = sln_plat
  1221. godot_arch = p["architecture"]
  1222. # Redirect editor configurations for non-Windows platforms to the Windows one, so the solution has all the permutations
  1223. # and VS doesn't complain about missing project configurations.
  1224. # These configurations are disabled, so they show up but won't build.
  1225. if godot_platform != "windows":
  1226. section1 += [f"editor|{sln_plat} = editor|{proj_plat}"]
  1227. section2 += [
  1228. f"{{{proj_uuid}}}.editor|{proj_plat}.ActiveCfg = editor|{proj_plat}",
  1229. ]
  1230. for t in conf["targets"]:
  1231. godot_target = t
  1232. # Windows x86 is a special little flower that requires a project platform == Win32 but a solution platform == x86.
  1233. if godot_platform == "windows" and godot_target == "editor" and godot_arch == "x86_32":
  1234. sln_plat = "x86"
  1235. configurations += [
  1236. f'<ProjectConfiguration Include="{godot_target}|{proj_plat}">',
  1237. f" <Configuration>{godot_target}</Configuration>",
  1238. f" <Platform>{proj_plat}</Platform>",
  1239. "</ProjectConfiguration>",
  1240. ]
  1241. properties += [
  1242. f"<PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='{godot_target}|{proj_plat}'\">",
  1243. f" <GodotConfiguration>{godot_target}</GodotConfiguration>",
  1244. f" <GodotPlatform>{proj_plat}</GodotPlatform>",
  1245. "</PropertyGroup>",
  1246. ]
  1247. if godot_platform != "windows":
  1248. configurations += [
  1249. f'<ProjectConfiguration Include="editor|{proj_plat}">',
  1250. " <Configuration>editor</Configuration>",
  1251. f" <Platform>{proj_plat}</Platform>",
  1252. "</ProjectConfiguration>",
  1253. ]
  1254. properties += [
  1255. f"<PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='editor|{proj_plat}'\">",
  1256. " <GodotConfiguration>editor</GodotConfiguration>",
  1257. f" <GodotPlatform>{proj_plat}</GodotPlatform>",
  1258. "</PropertyGroup>",
  1259. ]
  1260. p = f"{project_name}.{godot_platform}.{godot_target}.{godot_arch}.generated.props"
  1261. imports += [
  1262. f'<Import Project="$(MSBuildProjectDirectory)\\{p}" Condition="Exists(\'$(MSBuildProjectDirectory)\\{p}\')"/>'
  1263. ]
  1264. section1 += [f"{godot_target}|{sln_plat} = {godot_target}|{sln_plat}"]
  1265. section2 += [
  1266. f"{{{proj_uuid}}}.{godot_target}|{sln_plat}.ActiveCfg = {godot_target}|{proj_plat}",
  1267. f"{{{proj_uuid}}}.{godot_target}|{sln_plat}.Build.0 = {godot_target}|{proj_plat}",
  1268. ]
  1269. # Add an extra import for a local user props file at the end, so users can add more overrides.
  1270. imports += [
  1271. f'<Import Project="$(MSBuildProjectDirectory)\\{project_name}.vs.user.props" Condition="Exists(\'$(MSBuildProjectDirectory)\\{project_name}.vs.user.props\')"/>'
  1272. ]
  1273. section1 = sorted(section1)
  1274. section2 = sorted(section2)
  1275. if not get_bool(original_args, "vsproj_props_only", False):
  1276. with open("misc/msvs/vcxproj.template", "r", encoding="utf-8") as file:
  1277. proj_template = file.read()
  1278. proj_template = proj_template.replace("%%UUID%%", proj_uuid)
  1279. proj_template = proj_template.replace("%%CONFS%%", "\n ".join(configurations))
  1280. proj_template = proj_template.replace("%%IMPORTS%%", "\n ".join(imports))
  1281. proj_template = proj_template.replace("%%DEFAULT_ITEMS%%", "\n ".join(all_items))
  1282. proj_template = proj_template.replace("%%PROPERTIES%%", "\n ".join(properties))
  1283. with open(f"{project_name}.vcxproj", "w", encoding="utf-8", newline="\r\n") as f:
  1284. f.write(proj_template)
  1285. if not get_bool(original_args, "vsproj_props_only", False):
  1286. with open("misc/msvs/sln.template", "r", encoding="utf-8") as file:
  1287. sln_template = file.read()
  1288. sln_template = sln_template.replace("%%NAME%%", project_name)
  1289. sln_template = sln_template.replace("%%UUID%%", proj_uuid)
  1290. sln_template = sln_template.replace("%%SLNUUID%%", sln_uuid)
  1291. sln_template = sln_template.replace("%%SECTION1%%", "\n\t\t".join(section1))
  1292. sln_template = sln_template.replace("%%SECTION2%%", "\n\t\t".join(section2))
  1293. with open(f"{project_name}.sln", "w", encoding="utf-8", newline="\r\n") as f:
  1294. f.write(sln_template)
  1295. if get_bool(original_args, "vsproj_gen_only", True):
  1296. sys.exit()
  1297. def generate_copyright_header(filename: str) -> str:
  1298. MARGIN = 70
  1299. TEMPLATE = """\
  1300. /**************************************************************************/
  1301. /* %s*/
  1302. /**************************************************************************/
  1303. /* This file is part of: */
  1304. /* GODOT ENGINE */
  1305. /* https://godotengine.org */
  1306. /**************************************************************************/
  1307. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  1308. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  1309. /* */
  1310. /* Permission is hereby granted, free of charge, to any person obtaining */
  1311. /* a copy of this software and associated documentation files (the */
  1312. /* "Software"), to deal in the Software without restriction, including */
  1313. /* without limitation the rights to use, copy, modify, merge, publish, */
  1314. /* distribute, sublicense, and/or sell copies of the Software, and to */
  1315. /* permit persons to whom the Software is furnished to do so, subject to */
  1316. /* the following conditions: */
  1317. /* */
  1318. /* The above copyright notice and this permission notice shall be */
  1319. /* included in all copies or substantial portions of the Software. */
  1320. /* */
  1321. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  1322. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  1323. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  1324. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  1325. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  1326. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  1327. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  1328. /**************************************************************************/
  1329. """
  1330. filename = filename.split("/")[-1].ljust(MARGIN)
  1331. if len(filename) > MARGIN:
  1332. print(f'WARNING: Filename "{filename}" too large for copyright header.')
  1333. return TEMPLATE % filename
  1334. @contextlib.contextmanager
  1335. def generated_wrapper(
  1336. path, # FIXME: type with `Union[str, Node, List[Node]]` when pytest conflicts are resolved
  1337. guard: Optional[bool] = None,
  1338. prefix: str = "",
  1339. suffix: str = "",
  1340. ) -> Generator[TextIOWrapper, None, None]:
  1341. """
  1342. Wrapper class to automatically handle copyright headers and header guards
  1343. for generated scripts. Meant to be invoked via `with` statement similar to
  1344. creating a file.
  1345. - `path`: The path of the file to be created. Can be passed a raw string, an
  1346. isolated SCons target, or a full SCons target list. If a target list contains
  1347. multiple entries, produces a warning & only creates the first entry.
  1348. - `guard`: Optional bool to determine if a header guard should be added. If
  1349. unassigned, header guards are determined by the file extension.
  1350. - `prefix`: Custom prefix to prepend to a header guard. Produces a warning if
  1351. provided a value when `guard` evaluates to `False`.
  1352. - `suffix`: Custom suffix to append to a header guard. Produces a warning if
  1353. provided a value when `guard` evaluates to `False`.
  1354. """
  1355. # Handle unfiltered SCons target[s] passed as path.
  1356. if not isinstance(path, str):
  1357. if isinstance(path, list):
  1358. if len(path) > 1:
  1359. print_warning(
  1360. "Attempting to use generated wrapper with multiple targets; "
  1361. f"will only use first entry: {path[0]}"
  1362. )
  1363. path = path[0]
  1364. if not hasattr(path, "get_abspath"):
  1365. raise TypeError(f'Expected type "str", "Node" or "List[Node]"; was passed {type(path)}.')
  1366. path = path.get_abspath()
  1367. path = str(path).replace("\\", "/")
  1368. if guard is None:
  1369. guard = path.endswith((".h", ".hh", ".hpp", ".inc"))
  1370. if not guard and (prefix or suffix):
  1371. print_warning(f'Trying to assign header guard prefix/suffix while `guard` is disabled: "{path}".')
  1372. header_guard = ""
  1373. if guard:
  1374. if prefix:
  1375. prefix += "_"
  1376. if suffix:
  1377. suffix = f"_{suffix}"
  1378. split = path.split("/")[-1].split(".")
  1379. header_guard = (f"{prefix}{split[0]}{suffix}.{'.'.join(split[1:])}".upper()
  1380. .replace(".", "_").replace("-", "_").replace(" ", "_").replace("__", "_")) # fmt: skip
  1381. with open(path, "wt", encoding="utf-8", newline="\n") as file:
  1382. file.write(generate_copyright_header(path))
  1383. file.write("\n/* THIS FILE IS GENERATED. EDITS WILL BE LOST. */\n\n")
  1384. if guard:
  1385. file.write(f"#ifndef {header_guard}\n")
  1386. file.write(f"#define {header_guard}\n\n")
  1387. with StringIO(newline="\n") as str_io:
  1388. yield str_io
  1389. file.write(str_io.getvalue().strip() or "/* NO CONTENT */")
  1390. if guard:
  1391. file.write(f"\n\n#endif // {header_guard}")
  1392. file.write("\n")