methods.py 40 KB

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