methods.py 42 KB

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