methods.py 60 KB

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