methods.py 35 KB

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