methods.py 40 KB

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