methods.py 37 KB

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