methods.py 40 KB

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