methods.py 37 KB

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