methods.py 42 KB

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