methods.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140
  1. import os
  2. import sys
  3. import re
  4. import glob
  5. import subprocess
  6. from collections import OrderedDict
  7. from collections.abc import Mapping
  8. from typing import Iterator
  9. def add_source_files(self, sources, files):
  10. # Convert string to list of absolute paths (including expanding wildcard)
  11. if isinstance(files, (str, bytes)):
  12. # Keep SCons project-absolute path as they are (no wildcard support)
  13. if files.startswith("#"):
  14. if "*" in files:
  15. print("ERROR: Wildcards can't be expanded in SCons project-absolute path: '{}'".format(files))
  16. return
  17. files = [files]
  18. else:
  19. # Exclude .gen.cpp files from globbing, to avoid including obsolete ones.
  20. # They should instead be added manually.
  21. skip_gen_cpp = "*" in files
  22. dir_path = self.Dir(".").abspath
  23. files = sorted(glob.glob(dir_path + "/" + files))
  24. if skip_gen_cpp:
  25. files = [f for f in files if not f.endswith(".gen.cpp")]
  26. # Add each path as compiled Object following environment (self) configuration
  27. for path in files:
  28. obj = self.Object(path)
  29. if obj in sources:
  30. print('WARNING: Object "{}" already included in environment sources.'.format(obj))
  31. continue
  32. sources.append(obj)
  33. def disable_warnings(self):
  34. # 'self' is the environment
  35. if self.msvc:
  36. # We have to remove existing warning level defines before appending /w,
  37. # otherwise we get: "warning D9025 : overriding '/W3' with '/w'"
  38. self["CCFLAGS"] = [x for x in self["CCFLAGS"] if not (x.startswith("/W") or x.startswith("/w"))]
  39. self["CFLAGS"] = [x for x in self["CFLAGS"] if not (x.startswith("/W") or x.startswith("/w"))]
  40. self["CXXFLAGS"] = [x for x in self["CXXFLAGS"] if not (x.startswith("/W") or x.startswith("/w"))]
  41. self.AppendUnique(CCFLAGS=["/w"])
  42. else:
  43. self.AppendUnique(CCFLAGS=["-w"])
  44. def force_optimization_on_debug(self):
  45. # 'self' is the environment
  46. if self["target"] == "template_release":
  47. return
  48. if self.msvc:
  49. # We have to remove existing optimization level defines before appending /O2,
  50. # otherwise we get: "warning D9025 : overriding '/0d' with '/02'"
  51. self["CCFLAGS"] = [x for x in self["CCFLAGS"] if not x.startswith("/O")]
  52. self["CFLAGS"] = [x for x in self["CFLAGS"] if not x.startswith("/O")]
  53. self["CXXFLAGS"] = [x for x in self["CXXFLAGS"] if not x.startswith("/O")]
  54. self.AppendUnique(CCFLAGS=["/O2"])
  55. else:
  56. self.AppendUnique(CCFLAGS=["-O3"])
  57. def add_module_version_string(self, s):
  58. self.module_version_string += "." + s
  59. def get_version_info(module_version_string="", silent=False):
  60. build_name = "custom_build"
  61. if os.getenv("BUILD_NAME") != None:
  62. build_name = str(os.getenv("BUILD_NAME"))
  63. if not silent:
  64. print(f"Using custom build name: '{build_name}'.")
  65. import version
  66. version_info = {
  67. "short_name": str(version.short_name),
  68. "name": str(version.name),
  69. "major": int(version.major),
  70. "minor": int(version.minor),
  71. "patch": int(version.patch),
  72. "status": str(version.status),
  73. "build": str(build_name),
  74. "module_config": str(version.module_config) + module_version_string,
  75. "year": int(version.year),
  76. "website": str(version.website),
  77. "docs_branch": str(version.docs),
  78. }
  79. # For dev snapshots (alpha, beta, RC, etc.) we do not commit status change to Git,
  80. # so this define provides a way to override it without having to modify the source.
  81. if os.getenv("GODOT_VERSION_STATUS") != None:
  82. version_info["status"] = str(os.getenv("GODOT_VERSION_STATUS"))
  83. if not silent:
  84. print(f"Using version status '{version_info['status']}', overriding the original '{version.status}'.")
  85. # Parse Git hash if we're in a Git repo.
  86. githash = ""
  87. gitfolder = ".git"
  88. if os.path.isfile(".git"):
  89. module_folder = open(".git", "r").readline().strip()
  90. if module_folder.startswith("gitdir: "):
  91. gitfolder = module_folder[8:]
  92. if os.path.isfile(os.path.join(gitfolder, "HEAD")):
  93. head = open(os.path.join(gitfolder, "HEAD"), "r", encoding="utf8").readline().strip()
  94. if head.startswith("ref: "):
  95. ref = head[5:]
  96. # If this directory is a Git worktree instead of a root clone.
  97. parts = gitfolder.split("/")
  98. if len(parts) > 2 and parts[-2] == "worktrees":
  99. gitfolder = "/".join(parts[0:-2])
  100. head = os.path.join(gitfolder, ref)
  101. packedrefs = os.path.join(gitfolder, "packed-refs")
  102. if os.path.isfile(head):
  103. githash = open(head, "r").readline().strip()
  104. elif os.path.isfile(packedrefs):
  105. # Git may pack refs into a single file. This code searches .git/packed-refs file for the current ref's hash.
  106. # https://mirrors.edge.kernel.org/pub/software/scm/git/docs/git-pack-refs.html
  107. for line in open(packedrefs, "r").read().splitlines():
  108. if line.startswith("#"):
  109. continue
  110. (line_hash, line_ref) = line.split(" ")
  111. if ref == line_ref:
  112. githash = line_hash
  113. break
  114. else:
  115. githash = head
  116. version_info["git_hash"] = githash
  117. return version_info
  118. def generate_version_header(module_version_string=""):
  119. version_info = get_version_info(module_version_string)
  120. # NOTE: It is safe to generate these files here, since this is still executed serially.
  121. f = open("core/version_generated.gen.h", "w")
  122. f.write(
  123. """/* THIS FILE IS GENERATED DO NOT EDIT */
  124. #ifndef VERSION_GENERATED_GEN_H
  125. #define VERSION_GENERATED_GEN_H
  126. #define VERSION_SHORT_NAME "{short_name}"
  127. #define VERSION_NAME "{name}"
  128. #define VERSION_MAJOR {major}
  129. #define VERSION_MINOR {minor}
  130. #define VERSION_PATCH {patch}
  131. #define VERSION_STATUS "{status}"
  132. #define VERSION_BUILD "{build}"
  133. #define VERSION_MODULE_CONFIG "{module_config}"
  134. #define VERSION_YEAR {year}
  135. #define VERSION_WEBSITE "{website}"
  136. #define VERSION_DOCS_BRANCH "{docs_branch}"
  137. #define VERSION_DOCS_URL "https://docs.godotengine.org/en/" VERSION_DOCS_BRANCH
  138. #endif // VERSION_GENERATED_GEN_H
  139. """.format(
  140. **version_info
  141. )
  142. )
  143. f.close()
  144. fhash = open("core/version_hash.gen.cpp", "w")
  145. fhash.write(
  146. """/* THIS FILE IS GENERATED DO NOT EDIT */
  147. #include "core/version.h"
  148. const char *const VERSION_HASH = "{git_hash}";
  149. """.format(
  150. **version_info
  151. )
  152. )
  153. fhash.close()
  154. def parse_cg_file(fname, uniforms, sizes, conditionals):
  155. fs = open(fname, "r")
  156. line = fs.readline()
  157. while line:
  158. if re.match(r"^\s*uniform", line):
  159. res = re.match(r"uniform ([\d\w]*) ([\d\w]*)")
  160. type = res.groups(1)
  161. name = res.groups(2)
  162. uniforms.append(name)
  163. if type.find("texobj") != -1:
  164. sizes.append(1)
  165. else:
  166. t = re.match(r"float(\d)x(\d)", type)
  167. if t:
  168. sizes.append(int(t.groups(1)) * int(t.groups(2)))
  169. else:
  170. t = re.match(r"float(\d)", type)
  171. sizes.append(int(t.groups(1)))
  172. if line.find("[branch]") != -1:
  173. conditionals.append(name)
  174. line = fs.readline()
  175. fs.close()
  176. def get_cmdline_bool(option, default):
  177. """We use `ARGUMENTS.get()` to check if options were manually overridden on the command line,
  178. and SCons' _text2bool helper to convert them to booleans, otherwise they're handled as strings.
  179. """
  180. from SCons.Script import ARGUMENTS
  181. from SCons.Variables.BoolVariable import _text2bool
  182. cmdline_val = ARGUMENTS.get(option)
  183. if cmdline_val is not None:
  184. return _text2bool(cmdline_val)
  185. else:
  186. return default
  187. def detect_modules(search_path, recursive=False):
  188. """Detects and collects a list of C++ modules at specified path
  189. `search_path` - a directory path containing modules. The path may point to
  190. a single module, which may have other nested modules. A module must have
  191. "register_types.h", "SCsub", "config.py" files created to be detected.
  192. `recursive` - if `True`, then all subdirectories are searched for modules as
  193. specified by the `search_path`, otherwise collects all modules under the
  194. `search_path` directory. If the `search_path` is a module, it is collected
  195. in all cases.
  196. Returns an `OrderedDict` with module names as keys, and directory paths as
  197. values. If a path is relative, then it is a built-in module. If a path is
  198. absolute, then it is a custom module collected outside of the engine source.
  199. """
  200. modules = OrderedDict()
  201. def add_module(path):
  202. module_name = os.path.basename(path)
  203. module_path = path.replace("\\", "/") # win32
  204. modules[module_name] = module_path
  205. def is_engine(path):
  206. # Prevent recursively detecting modules in self and other
  207. # Godot sources when using `custom_modules` build option.
  208. version_path = os.path.join(path, "version.py")
  209. if os.path.exists(version_path):
  210. with open(version_path) as f:
  211. if 'short_name = "godot"' in f.read():
  212. return True
  213. return False
  214. def get_files(path):
  215. files = glob.glob(os.path.join(path, "*"))
  216. # Sort so that `register_module_types` does not change that often,
  217. # and plugins are registered in alphabetic order as well.
  218. files.sort()
  219. return files
  220. if not recursive:
  221. if is_module(search_path):
  222. add_module(search_path)
  223. for path in get_files(search_path):
  224. if is_engine(path):
  225. continue
  226. if is_module(path):
  227. add_module(path)
  228. else:
  229. to_search = [search_path]
  230. while to_search:
  231. path = to_search.pop()
  232. if is_module(path):
  233. add_module(path)
  234. for child in get_files(path):
  235. if not os.path.isdir(child):
  236. continue
  237. if is_engine(child):
  238. continue
  239. to_search.insert(0, child)
  240. return modules
  241. def is_module(path):
  242. if not os.path.isdir(path):
  243. return False
  244. must_exist = ["register_types.h", "SCsub", "config.py"]
  245. for f in must_exist:
  246. if not os.path.exists(os.path.join(path, f)):
  247. return False
  248. return True
  249. def write_disabled_classes(class_list):
  250. f = open("core/disabled_classes.gen.h", "w")
  251. f.write("/* THIS FILE IS GENERATED DO NOT EDIT */\n")
  252. f.write("#ifndef DISABLED_CLASSES_GEN_H\n")
  253. f.write("#define DISABLED_CLASSES_GEN_H\n\n")
  254. for c in class_list:
  255. cs = c.strip()
  256. if cs != "":
  257. f.write("#define ClassDB_Disable_" + cs + " 1\n")
  258. f.write("\n#endif\n")
  259. def write_modules(modules):
  260. includes_cpp = ""
  261. initialize_cpp = ""
  262. uninitialize_cpp = ""
  263. for name, path in modules.items():
  264. try:
  265. with open(os.path.join(path, "register_types.h")):
  266. includes_cpp += '#include "' + path + '/register_types.h"\n'
  267. initialize_cpp += "#ifdef MODULE_" + name.upper() + "_ENABLED\n"
  268. initialize_cpp += "\tinitialize_" + name + "_module(p_level);\n"
  269. initialize_cpp += "#endif\n"
  270. uninitialize_cpp += "#ifdef MODULE_" + name.upper() + "_ENABLED\n"
  271. uninitialize_cpp += "\tuninitialize_" + name + "_module(p_level);\n"
  272. uninitialize_cpp += "#endif\n"
  273. except OSError:
  274. pass
  275. modules_cpp = """// register_module_types.gen.cpp
  276. /* THIS FILE IS GENERATED DO NOT EDIT */
  277. #include "register_module_types.h"
  278. #include "modules/modules_enabled.gen.h"
  279. %s
  280. void initialize_modules(ModuleInitializationLevel p_level) {
  281. %s
  282. }
  283. void uninitialize_modules(ModuleInitializationLevel p_level) {
  284. %s
  285. }
  286. """ % (
  287. includes_cpp,
  288. initialize_cpp,
  289. uninitialize_cpp,
  290. )
  291. # NOTE: It is safe to generate this file here, since this is still executed serially
  292. with open("modules/register_module_types.gen.cpp", "w") as f:
  293. f.write(modules_cpp)
  294. def convert_custom_modules_path(path):
  295. if not path:
  296. return path
  297. path = os.path.realpath(os.path.expanduser(os.path.expandvars(path)))
  298. err_msg = "Build option 'custom_modules' must %s"
  299. if not os.path.isdir(path):
  300. raise ValueError(err_msg % "point to an existing directory.")
  301. if path == os.path.realpath("modules"):
  302. raise ValueError(err_msg % "be a directory other than built-in `modules` directory.")
  303. return path
  304. def disable_module(self):
  305. self.disabled_modules.append(self.current_module)
  306. def module_add_dependencies(self, module, dependencies, optional=False):
  307. """
  308. Adds dependencies for a given module.
  309. Meant to be used in module `can_build` methods.
  310. """
  311. if module not in self.module_dependencies:
  312. self.module_dependencies[module] = [[], []]
  313. if optional:
  314. self.module_dependencies[module][1].extend(dependencies)
  315. else:
  316. self.module_dependencies[module][0].extend(dependencies)
  317. def module_check_dependencies(self, module):
  318. """
  319. Checks if module dependencies are enabled for a given module,
  320. and prints a warning if they aren't.
  321. Meant to be used in module `can_build` methods.
  322. Returns a boolean (True if dependencies are satisfied).
  323. """
  324. missing_deps = []
  325. required_deps = self.module_dependencies[module][0] if module in self.module_dependencies else []
  326. for dep in required_deps:
  327. opt = "module_{}_enabled".format(dep)
  328. if not opt in self or not self[opt]:
  329. missing_deps.append(dep)
  330. if missing_deps != []:
  331. print(
  332. "Disabling '{}' module as the following dependencies are not satisfied: {}".format(
  333. module, ", ".join(missing_deps)
  334. )
  335. )
  336. return False
  337. else:
  338. return True
  339. def sort_module_list(env):
  340. out = OrderedDict()
  341. deps = {k: v[0] + list(filter(lambda x: x in env.module_list, v[1])) for k, v in env.module_dependencies.items()}
  342. frontier = list(env.module_list.keys())
  343. explored = []
  344. while len(frontier):
  345. cur = frontier.pop()
  346. deps_list = deps[cur] if cur in deps else []
  347. if len(deps_list) and any([d not in explored for d in deps_list]):
  348. # Will explore later, after its dependencies
  349. frontier.insert(0, cur)
  350. continue
  351. explored.append(cur)
  352. for k in explored:
  353. env.module_list.move_to_end(k)
  354. def use_windows_spawn_fix(self, platform=None):
  355. if os.name != "nt":
  356. return # not needed, only for windows
  357. # On Windows, due to the limited command line length, when creating a static library
  358. # from a very high number of objects SCons will invoke "ar" once per object file;
  359. # that makes object files with same names to be overwritten so the last wins and
  360. # the library loses symbols defined by overwritten objects.
  361. # By enabling quick append instead of the default mode (replacing), libraries will
  362. # got built correctly regardless the invocation strategy.
  363. # Furthermore, since SCons will rebuild the library from scratch when an object file
  364. # changes, no multiple versions of the same object file will be present.
  365. self.Replace(ARFLAGS="q")
  366. def mySubProcess(cmdline, env):
  367. startupinfo = subprocess.STARTUPINFO()
  368. startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  369. popen_args = {
  370. "stdin": subprocess.PIPE,
  371. "stdout": subprocess.PIPE,
  372. "stderr": subprocess.PIPE,
  373. "startupinfo": startupinfo,
  374. "shell": False,
  375. "env": env,
  376. }
  377. if sys.version_info >= (3, 7, 0):
  378. popen_args["text"] = True
  379. proc = subprocess.Popen(cmdline, **popen_args)
  380. _, err = proc.communicate()
  381. rv = proc.wait()
  382. if rv:
  383. print("=====")
  384. print(err)
  385. print("=====")
  386. return rv
  387. def mySpawn(sh, escape, cmd, args, env):
  388. newargs = " ".join(args[1:])
  389. cmdline = cmd + " " + newargs
  390. rv = 0
  391. env = {str(key): str(value) for key, value in iter(env.items())}
  392. if len(cmdline) > 32000 and cmd.endswith("ar"):
  393. cmdline = cmd + " " + args[1] + " " + args[2] + " "
  394. for i in range(3, len(args)):
  395. rv = mySubProcess(cmdline + args[i], env)
  396. if rv:
  397. break
  398. else:
  399. rv = mySubProcess(cmdline, env)
  400. return rv
  401. self["SPAWN"] = mySpawn
  402. def save_active_platforms(apnames, ap):
  403. for x in ap:
  404. svg_names = []
  405. if os.path.isfile(x + "/logo.svg"):
  406. svg_names.append("logo")
  407. if os.path.isfile(x + "/run_icon.svg"):
  408. svg_names.append("run_icon")
  409. for name in svg_names:
  410. svgf = open(x + "/" + name + ".svg", "rb")
  411. b = svgf.read(1)
  412. svg_str = " /* AUTOGENERATED FILE, DO NOT EDIT */ \n"
  413. svg_str += " static const char *_" + x[9:] + "_" + name + '_svg = "'
  414. while len(b) == 1:
  415. svg_str += "\\" + hex(ord(b))[1:]
  416. b = svgf.read(1)
  417. svg_str += '";\n'
  418. svgf.close()
  419. # NOTE: It is safe to generate this file here, since this is still executed serially
  420. wf = x + "/" + name + "_svg.gen.h"
  421. with open(wf, "w") as svgw:
  422. svgw.write(svg_str)
  423. def no_verbose(sys, env):
  424. colors = {}
  425. # Colors are disabled in non-TTY environments such as pipes. This means
  426. # that if output is redirected to a file, it will not contain color codes
  427. if sys.stdout.isatty():
  428. colors["blue"] = "\033[0;94m"
  429. colors["bold_blue"] = "\033[1;94m"
  430. colors["reset"] = "\033[0m"
  431. else:
  432. colors["blue"] = ""
  433. colors["bold_blue"] = ""
  434. colors["reset"] = ""
  435. # There is a space before "..." to ensure that source file names can be
  436. # Ctrl + clicked in the VS Code terminal.
  437. compile_source_message = "{}Compiling {}$SOURCE{} ...{}".format(
  438. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  439. )
  440. java_compile_source_message = "{}Compiling {}$SOURCE{} ...{}".format(
  441. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  442. )
  443. compile_shared_source_message = "{}Compiling shared {}$SOURCE{} ...{}".format(
  444. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  445. )
  446. link_program_message = "{}Linking Program {}$TARGET{} ...{}".format(
  447. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  448. )
  449. link_library_message = "{}Linking Static Library {}$TARGET{} ...{}".format(
  450. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  451. )
  452. ranlib_library_message = "{}Ranlib Library {}$TARGET{} ...{}".format(
  453. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  454. )
  455. link_shared_library_message = "{}Linking Shared Library {}$TARGET{} ...{}".format(
  456. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  457. )
  458. java_library_message = "{}Creating Java Archive {}$TARGET{} ...{}".format(
  459. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  460. )
  461. env.Append(CXXCOMSTR=[compile_source_message])
  462. env.Append(CCCOMSTR=[compile_source_message])
  463. env.Append(SHCCCOMSTR=[compile_shared_source_message])
  464. env.Append(SHCXXCOMSTR=[compile_shared_source_message])
  465. env.Append(ARCOMSTR=[link_library_message])
  466. env.Append(RANLIBCOMSTR=[ranlib_library_message])
  467. env.Append(SHLINKCOMSTR=[link_shared_library_message])
  468. env.Append(LINKCOMSTR=[link_program_message])
  469. env.Append(JARCOMSTR=[java_library_message])
  470. env.Append(JAVACCOMSTR=[java_compile_source_message])
  471. def detect_visual_c_compiler_version(tools_env):
  472. # tools_env is the variable scons uses to call tools that execute tasks, SCons's env['ENV'] that executes tasks...
  473. # (see the SCons documentation for more information on what it does)...
  474. # in order for this function to be well encapsulated i choose to force it to receive SCons's TOOLS env (env['ENV']
  475. # and not scons setup environment (env)... so make sure you call the right environment on it or it will fail to detect
  476. # the proper vc version that will be called
  477. # 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.).
  478. # There are many different cl.exe files that are run, and each one compiles & links to a different architecture
  479. # As far as I know, the only way to figure out what compiler will be run when Scons calls cl.exe via Program()
  480. # is to check the PATH variable and figure out which one will be called first. Code below does that and returns:
  481. # the following string values:
  482. # "" Compiler not detected
  483. # "amd64" Native 64 bit compiler
  484. # "amd64_x86" 64 bit Cross Compiler for 32 bit
  485. # "x86" Native 32 bit compiler
  486. # "x86_amd64" 32 bit Cross Compiler for 64 bit
  487. # There are other architectures, but Godot does not support them currently, so this function does not detect arm/amd64_arm
  488. # and similar architectures/compilers
  489. # Set chosen compiler to "not detected"
  490. vc_chosen_compiler_index = -1
  491. vc_chosen_compiler_str = ""
  492. # Start with Pre VS 2017 checks which uses VCINSTALLDIR:
  493. if "VCINSTALLDIR" in tools_env:
  494. # print("Checking VCINSTALLDIR")
  495. # find() works with -1 so big ifs below are needed... the simplest solution, in fact
  496. # First test if amd64 and amd64_x86 compilers are present in the path
  497. vc_amd64_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\amd64;")
  498. if vc_amd64_compiler_detection_index > -1:
  499. vc_chosen_compiler_index = vc_amd64_compiler_detection_index
  500. vc_chosen_compiler_str = "amd64"
  501. vc_amd64_x86_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\amd64_x86;")
  502. if vc_amd64_x86_compiler_detection_index > -1 and (
  503. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index
  504. ):
  505. vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index
  506. vc_chosen_compiler_str = "amd64_x86"
  507. # Now check the 32 bit compilers
  508. vc_x86_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN;")
  509. if vc_x86_compiler_detection_index > -1 and (
  510. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_compiler_detection_index
  511. ):
  512. vc_chosen_compiler_index = vc_x86_compiler_detection_index
  513. vc_chosen_compiler_str = "x86"
  514. vc_x86_amd64_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\x86_amd64;")
  515. if vc_x86_amd64_compiler_detection_index > -1 and (
  516. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index
  517. ):
  518. vc_chosen_compiler_index = vc_x86_amd64_compiler_detection_index
  519. vc_chosen_compiler_str = "x86_amd64"
  520. # and for VS 2017 and newer we check VCTOOLSINSTALLDIR:
  521. if "VCTOOLSINSTALLDIR" in tools_env:
  522. # Newer versions have a different path available
  523. vc_amd64_compiler_detection_index = (
  524. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX64\\X64;")
  525. )
  526. if vc_amd64_compiler_detection_index > -1:
  527. vc_chosen_compiler_index = vc_amd64_compiler_detection_index
  528. vc_chosen_compiler_str = "amd64"
  529. vc_amd64_x86_compiler_detection_index = (
  530. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX64\\X86;")
  531. )
  532. if vc_amd64_x86_compiler_detection_index > -1 and (
  533. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index
  534. ):
  535. vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index
  536. vc_chosen_compiler_str = "amd64_x86"
  537. vc_x86_compiler_detection_index = (
  538. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX86\\X86;")
  539. )
  540. if vc_x86_compiler_detection_index > -1 and (
  541. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_compiler_detection_index
  542. ):
  543. vc_chosen_compiler_index = vc_x86_compiler_detection_index
  544. vc_chosen_compiler_str = "x86"
  545. vc_x86_amd64_compiler_detection_index = (
  546. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX86\\X64;")
  547. )
  548. if vc_x86_amd64_compiler_detection_index > -1 and (
  549. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index
  550. ):
  551. vc_chosen_compiler_str = "x86_amd64"
  552. return vc_chosen_compiler_str
  553. def find_visual_c_batch_file(env):
  554. from SCons.Tool.MSCommon.vc import (
  555. get_default_version,
  556. get_host_target,
  557. find_batch_file,
  558. )
  559. # Syntax changed in SCons 4.4.0.
  560. from SCons import __version__ as scons_raw_version
  561. scons_ver = env._get_major_minor_revision(scons_raw_version)
  562. version = get_default_version(env)
  563. if scons_ver >= (4, 4, 0):
  564. (host_platform, target_platform, _) = get_host_target(env, version)
  565. else:
  566. (host_platform, target_platform, _) = get_host_target(env)
  567. return find_batch_file(env, version, host_platform, target_platform)[0]
  568. def generate_cpp_hint_file(filename):
  569. if os.path.isfile(filename):
  570. # Don't overwrite an existing hint file since the user may have customized it.
  571. pass
  572. else:
  573. try:
  574. with open(filename, "w") as fd:
  575. fd.write("#define GDCLASS(m_class, m_inherits)\n")
  576. except OSError:
  577. print("Could not write cpp.hint file.")
  578. def glob_recursive(pattern, node="."):
  579. from SCons import Node
  580. from SCons.Script import Glob
  581. results = []
  582. for f in Glob(str(node) + "/*", source=True):
  583. if type(f) is Node.FS.Dir:
  584. results += glob_recursive(pattern, f)
  585. results += Glob(str(node) + "/" + pattern, source=True)
  586. return results
  587. def add_to_vs_project(env, sources):
  588. for x in sources:
  589. if type(x) == type(""):
  590. fname = env.File(x).path
  591. else:
  592. fname = env.File(x)[0].path
  593. pieces = fname.split(".")
  594. if len(pieces) > 0:
  595. basename = pieces[0]
  596. basename = basename.replace("\\\\", "/")
  597. if os.path.isfile(basename + ".h"):
  598. env.vs_incs += [basename + ".h"]
  599. elif os.path.isfile(basename + ".hpp"):
  600. env.vs_incs += [basename + ".hpp"]
  601. if os.path.isfile(basename + ".c"):
  602. env.vs_srcs += [basename + ".c"]
  603. elif os.path.isfile(basename + ".cpp"):
  604. env.vs_srcs += [basename + ".cpp"]
  605. def generate_vs_project(env, num_jobs, project_name="godot"):
  606. batch_file = find_visual_c_batch_file(env)
  607. if batch_file:
  608. class ModuleConfigs(Mapping):
  609. # This version information (Win32, x64, Debug, Release) seems to be
  610. # required for Visual Studio to understand that it needs to generate an NMAKE
  611. # project. Do not modify without knowing what you are doing.
  612. PLATFORMS = ["Win32", "x64"]
  613. PLATFORM_IDS = ["x86_32", "x86_64"]
  614. CONFIGURATIONS = ["editor", "template_release", "template_debug"]
  615. DEV_SUFFIX = ".dev" if env["dev_build"] else ""
  616. @staticmethod
  617. def for_every_variant(value):
  618. return [value for _ in range(len(ModuleConfigs.CONFIGURATIONS) * len(ModuleConfigs.PLATFORMS))]
  619. def __init__(self):
  620. shared_targets_array = []
  621. self.names = []
  622. self.arg_dict = {
  623. "variant": [],
  624. "runfile": shared_targets_array,
  625. "buildtarget": shared_targets_array,
  626. "cpppaths": [],
  627. "cppdefines": [],
  628. "cmdargs": [],
  629. }
  630. self.add_mode() # default
  631. def add_mode(
  632. self,
  633. name: str = "",
  634. includes: str = "",
  635. cli_args: str = "",
  636. defines=None,
  637. ):
  638. if defines is None:
  639. defines = []
  640. self.names.append(name)
  641. self.arg_dict["variant"] += [
  642. f'{config}{f"_[{name}]" if name else ""}|{platform}'
  643. for config in ModuleConfigs.CONFIGURATIONS
  644. for platform in ModuleConfigs.PLATFORMS
  645. ]
  646. self.arg_dict["runfile"] += [
  647. f'bin\\godot.windows.{config}{ModuleConfigs.DEV_SUFFIX}{".double" if env["precision"] == "double" else ""}.{plat_id}{f".{name}" if name else ""}.exe'
  648. for config in ModuleConfigs.CONFIGURATIONS
  649. for plat_id in ModuleConfigs.PLATFORM_IDS
  650. ]
  651. self.arg_dict["cpppaths"] += ModuleConfigs.for_every_variant(env["CPPPATH"] + [includes])
  652. self.arg_dict["cppdefines"] += ModuleConfigs.for_every_variant(list(env["CPPDEFINES"]) + defines)
  653. self.arg_dict["cmdargs"] += ModuleConfigs.for_every_variant(cli_args)
  654. def build_commandline(self, commands):
  655. configuration_getter = (
  656. "$(Configuration"
  657. + "".join([f'.Replace("{name}", "")' for name in self.names[1:]])
  658. + '.Replace("_[]", "")'
  659. + ")"
  660. )
  661. common_build_prefix = [
  662. 'cmd /V /C set "plat=$(PlatformTarget)"',
  663. '(if "$(PlatformTarget)"=="x64" (set "plat=x86_amd64"))',
  664. 'call "' + batch_file + '" !plat!',
  665. ]
  666. # Windows allows us to have spaces in paths, so we need
  667. # to double quote off the directory. However, the path ends
  668. # in a backslash, so we need to remove this, lest it escape the
  669. # last double quote off, confusing MSBuild
  670. common_build_postfix = [
  671. "--directory=\"$(ProjectDir.TrimEnd('\\'))\"",
  672. "platform=windows",
  673. f"target={configuration_getter}",
  674. "progress=no",
  675. "-j%s" % num_jobs,
  676. ]
  677. if env["dev_build"]:
  678. common_build_postfix.append("dev_build=yes")
  679. if env["dev_mode"]:
  680. common_build_postfix.append("dev_mode=yes")
  681. elif env["tests"]:
  682. common_build_postfix.append("tests=yes")
  683. if env["custom_modules"]:
  684. common_build_postfix.append("custom_modules=%s" % env["custom_modules"])
  685. if env["precision"] == "double":
  686. common_build_postfix.append("precision=double")
  687. result = " ^& ".join(common_build_prefix + [" ".join([commands] + common_build_postfix)])
  688. return result
  689. # Mappings interface definitions
  690. def __iter__(self) -> Iterator[str]:
  691. for x in self.arg_dict:
  692. yield x
  693. def __len__(self) -> int:
  694. return len(self.names)
  695. def __getitem__(self, k: str):
  696. return self.arg_dict[k]
  697. add_to_vs_project(env, env.core_sources)
  698. add_to_vs_project(env, env.drivers_sources)
  699. add_to_vs_project(env, env.main_sources)
  700. add_to_vs_project(env, env.modules_sources)
  701. add_to_vs_project(env, env.scene_sources)
  702. add_to_vs_project(env, env.servers_sources)
  703. if env["tests"]:
  704. add_to_vs_project(env, env.tests_sources)
  705. if env.editor_build:
  706. add_to_vs_project(env, env.editor_sources)
  707. for header in glob_recursive("**/*.h"):
  708. env.vs_incs.append(str(header))
  709. module_configs = ModuleConfigs()
  710. if env.get("module_mono_enabled"):
  711. mono_defines = [("GD_MONO_HOT_RELOAD",)] if env.editor_build else []
  712. module_configs.add_mode(
  713. "mono",
  714. cli_args="module_mono_enabled=yes",
  715. defines=mono_defines,
  716. )
  717. env["MSVSBUILDCOM"] = module_configs.build_commandline("scons")
  718. env["MSVSREBUILDCOM"] = module_configs.build_commandline("scons vsproj=yes")
  719. env["MSVSCLEANCOM"] = module_configs.build_commandline("scons --clean")
  720. if not env.get("MSVS"):
  721. env["MSVS"]["PROJECTSUFFIX"] = ".vcxproj"
  722. env["MSVS"]["SOLUTIONSUFFIX"] = ".sln"
  723. env.MSVSProject(
  724. target=["#" + project_name + env["MSVSPROJECTSUFFIX"]],
  725. incs=env.vs_incs,
  726. srcs=env.vs_srcs,
  727. auto_build_solution=1,
  728. **module_configs,
  729. )
  730. else:
  731. print("Could not locate Visual Studio batch file to set up the build environment. Not generating VS project.")
  732. def precious_program(env, program, sources, **args):
  733. program = env.ProgramOriginal(program, sources, **args)
  734. env.Precious(program)
  735. return program
  736. def add_shared_library(env, name, sources, **args):
  737. library = env.SharedLibrary(name, sources, **args)
  738. env.NoCache(library)
  739. return library
  740. def add_library(env, name, sources, **args):
  741. library = env.Library(name, sources, **args)
  742. env.NoCache(library)
  743. return library
  744. def add_program(env, name, sources, **args):
  745. program = env.Program(name, sources, **args)
  746. env.NoCache(program)
  747. return program
  748. def CommandNoCache(env, target, sources, command, **args):
  749. result = env.Command(target, sources, command, **args)
  750. env.NoCache(result)
  751. return result
  752. def Run(env, function, short_message, subprocess=True):
  753. from SCons.Script import Action
  754. from platform_methods import run_in_subprocess
  755. output_print = short_message if not env["verbose"] else ""
  756. if not subprocess:
  757. return Action(function, output_print)
  758. else:
  759. return Action(run_in_subprocess(function), output_print)
  760. def detect_darwin_sdk_path(platform, env):
  761. sdk_name = ""
  762. if platform == "macos":
  763. sdk_name = "macosx"
  764. var_name = "MACOS_SDK_PATH"
  765. elif platform == "ios":
  766. sdk_name = "iphoneos"
  767. var_name = "IOS_SDK_PATH"
  768. elif platform == "iossimulator":
  769. sdk_name = "iphonesimulator"
  770. var_name = "IOS_SDK_PATH"
  771. else:
  772. raise Exception("Invalid platform argument passed to detect_darwin_sdk_path")
  773. if not env[var_name]:
  774. try:
  775. sdk_path = subprocess.check_output(["xcrun", "--sdk", sdk_name, "--show-sdk-path"]).strip().decode("utf-8")
  776. if sdk_path:
  777. env[var_name] = sdk_path
  778. except (subprocess.CalledProcessError, OSError):
  779. print("Failed to find SDK path while running xcrun --sdk {} --show-sdk-path.".format(sdk_name))
  780. raise
  781. def is_vanilla_clang(env):
  782. if not using_clang(env):
  783. return False
  784. try:
  785. version = subprocess.check_output([env.subst(env["CXX"]), "--version"]).strip().decode("utf-8")
  786. except (subprocess.CalledProcessError, OSError):
  787. print("Couldn't parse CXX environment variable to infer compiler version.")
  788. return False
  789. return not version.startswith("Apple")
  790. def get_compiler_version(env):
  791. """
  792. Returns an array of version numbers as ints: [major, minor, patch].
  793. The return array should have at least two values (major, minor).
  794. """
  795. if not env.msvc:
  796. # Not using -dumpversion as some GCC distros only return major, and
  797. # Clang used to return hardcoded 4.2.1: # https://reviews.llvm.org/D56803
  798. try:
  799. version = subprocess.check_output([env.subst(env["CXX"]), "--version"]).strip().decode("utf-8")
  800. except (subprocess.CalledProcessError, OSError):
  801. print("Couldn't parse CXX environment variable to infer compiler version.")
  802. return None
  803. else: # TODO: Implement for MSVC
  804. return None
  805. match = re.search(
  806. r"(?:(?<=version )|(?<=\) )|(?<=^))"
  807. r"(?P<major>\d+)"
  808. r"(?:\.(?P<minor>\d*))?"
  809. r"(?:\.(?P<patch>\d*))?"
  810. r"(?:-(?P<metadata1>[0-9a-zA-Z-]*))?"
  811. r"(?:\+(?P<metadata2>[0-9a-zA-Z-]*))?"
  812. r"(?: (?P<date>[0-9]{8}|[0-9]{6})(?![0-9a-zA-Z]))?",
  813. version,
  814. )
  815. if match is not None:
  816. return match.groupdict()
  817. else:
  818. return None
  819. def using_gcc(env):
  820. return "gcc" in os.path.basename(env["CC"])
  821. def using_clang(env):
  822. return "clang" in os.path.basename(env["CC"])
  823. def using_emcc(env):
  824. return "emcc" in os.path.basename(env["CC"])
  825. def show_progress(env):
  826. import sys
  827. from SCons.Script import Progress, Command, AlwaysBuild
  828. screen = sys.stdout
  829. # Progress reporting is not available in non-TTY environments since it
  830. # messes with the output (for example, when writing to a file)
  831. show_progress = env["progress"] and sys.stdout.isatty()
  832. node_count = 0
  833. node_count_max = 0
  834. node_count_interval = 1
  835. node_count_fname = str(env.Dir("#")) + "/.scons_node_count"
  836. import time, math
  837. class cache_progress:
  838. # The default is 1 GB cache and 12 hours half life
  839. def __init__(self, path=None, limit=1073741824, half_life=43200):
  840. self.path = path
  841. self.limit = limit
  842. self.exponent_scale = math.log(2) / half_life
  843. if env["verbose"] and path != None:
  844. screen.write(
  845. "Current cache limit is {} (used: {})\n".format(
  846. self.convert_size(limit), self.convert_size(self.get_size(path))
  847. )
  848. )
  849. self.delete(self.file_list())
  850. def __call__(self, node, *args, **kw):
  851. nonlocal node_count, node_count_max, node_count_interval, node_count_fname, show_progress
  852. if show_progress:
  853. # Print the progress percentage
  854. node_count += node_count_interval
  855. if node_count_max > 0 and node_count <= node_count_max:
  856. screen.write("\r[%3d%%] " % (node_count * 100 / node_count_max))
  857. screen.flush()
  858. elif node_count_max > 0 and node_count > node_count_max:
  859. screen.write("\r[100%] ")
  860. screen.flush()
  861. else:
  862. screen.write("\r[Initial build] ")
  863. screen.flush()
  864. def delete(self, files):
  865. if len(files) == 0:
  866. return
  867. if env["verbose"]:
  868. # Utter something
  869. screen.write("\rPurging %d %s from cache...\n" % (len(files), len(files) > 1 and "files" or "file"))
  870. [os.remove(f) for f in files]
  871. def file_list(self):
  872. if self.path is None:
  873. # Nothing to do
  874. return []
  875. # Gather a list of (filename, (size, atime)) within the
  876. # cache directory
  877. file_stat = [(x, os.stat(x)[6:8]) for x in glob.glob(os.path.join(self.path, "*", "*"))]
  878. if file_stat == []:
  879. # Nothing to do
  880. return []
  881. # Weight the cache files by size (assumed to be roughly
  882. # proportional to the recompilation time) times an exponential
  883. # decay since the ctime, and return a list with the entries
  884. # (filename, size, weight).
  885. current_time = time.time()
  886. file_stat = [(x[0], x[1][0], (current_time - x[1][1])) for x in file_stat]
  887. # Sort by the most recently accessed files (most sensible to keep) first
  888. file_stat.sort(key=lambda x: x[2])
  889. # Search for the first entry where the storage limit is
  890. # reached
  891. sum, mark = 0, None
  892. for i, x in enumerate(file_stat):
  893. sum += x[1]
  894. if sum > self.limit:
  895. mark = i
  896. break
  897. if mark is None:
  898. return []
  899. else:
  900. return [x[0] for x in file_stat[mark:]]
  901. def convert_size(self, size_bytes):
  902. if size_bytes == 0:
  903. return "0 bytes"
  904. size_name = ("bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
  905. i = int(math.floor(math.log(size_bytes, 1024)))
  906. p = math.pow(1024, i)
  907. s = round(size_bytes / p, 2)
  908. return "%s %s" % (int(s) if i == 0 else s, size_name[i])
  909. def get_size(self, start_path="."):
  910. total_size = 0
  911. for dirpath, dirnames, filenames in os.walk(start_path):
  912. for f in filenames:
  913. fp = os.path.join(dirpath, f)
  914. total_size += os.path.getsize(fp)
  915. return total_size
  916. def progress_finish(target, source, env):
  917. nonlocal node_count, progressor
  918. try:
  919. with open(node_count_fname, "w") as f:
  920. f.write("%d\n" % node_count)
  921. progressor.delete(progressor.file_list())
  922. except Exception:
  923. pass
  924. try:
  925. with open(node_count_fname) as f:
  926. node_count_max = int(f.readline())
  927. except Exception:
  928. pass
  929. cache_directory = os.environ.get("SCONS_CACHE")
  930. # Simple cache pruning, attached to SCons' progress callback. Trim the
  931. # cache directory to a size not larger than cache_limit.
  932. cache_limit = float(os.getenv("SCONS_CACHE_LIMIT", 1024)) * 1024 * 1024
  933. progressor = cache_progress(cache_directory, cache_limit)
  934. Progress(progressor, interval=node_count_interval)
  935. progress_finish_command = Command("progress_finish", [], progress_finish)
  936. AlwaysBuild(progress_finish_command)
  937. def dump(env):
  938. # Dumps latest build information for debugging purposes and external tools.
  939. from json import dump
  940. def non_serializable(obj):
  941. return "<<non-serializable: %s>>" % (type(obj).__qualname__)
  942. with open(".scons_env.json", "w") as f:
  943. dump(env.Dictionary(), f, indent=4, default=non_serializable)