methods.py 40 KB

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