methods.py 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090
  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. )
  278. _, err = proc.communicate()
  279. rv = proc.wait()
  280. if rv:
  281. print("=====")
  282. print(err)
  283. print("=====")
  284. return rv
  285. def mySpawn(sh, escape, cmd, args, env):
  286. newargs = " ".join(args[1:])
  287. cmdline = cmd + " " + newargs
  288. rv = 0
  289. env = {str(key): str(value) for key, value in iteritems(env)}
  290. if len(cmdline) > 32000 and cmd.endswith("ar"):
  291. cmdline = cmd + " " + args[1] + " " + args[2] + " "
  292. for i in range(3, len(args)):
  293. rv = mySubProcess(cmdline + args[i], env)
  294. if rv:
  295. break
  296. else:
  297. rv = mySubProcess(cmdline, env)
  298. return rv
  299. self["SPAWN"] = mySpawn
  300. def split_lib(self, libname, src_list=None, env_lib=None):
  301. env = self
  302. num = 0
  303. cur_base = ""
  304. max_src = 64
  305. list = []
  306. lib_list = []
  307. if src_list is None:
  308. src_list = getattr(env, libname + "_sources")
  309. if type(env_lib) == type(None):
  310. env_lib = env
  311. for f in src_list:
  312. fname = ""
  313. if type(f) == type(""):
  314. fname = env.File(f).path
  315. else:
  316. fname = env.File(f)[0].path
  317. fname = fname.replace("\\", "/")
  318. base = "/".join(fname.split("/")[:2])
  319. if base != cur_base and len(list) > max_src:
  320. if num > 0:
  321. lib = env_lib.add_library(libname + str(num), list)
  322. lib_list.append(lib)
  323. list = []
  324. num = num + 1
  325. cur_base = base
  326. list.append(f)
  327. lib = env_lib.add_library(libname + str(num), list)
  328. lib_list.append(lib)
  329. lib_base = []
  330. env_lib.add_source_files(lib_base, "*.cpp")
  331. lib = env_lib.add_library(libname, lib_base)
  332. lib_list.insert(0, lib)
  333. env.Prepend(LIBS=lib_list)
  334. # When we split modules into arbitrary chunks, we end up with linking issues
  335. # due to symbol dependencies split over several libs, which may not be linked
  336. # in the required order. We use --start-group and --end-group to tell the
  337. # linker that those archives should be searched repeatedly to resolve all
  338. # undefined references.
  339. # As SCons doesn't give us much control over how inserting libs in LIBS
  340. # impacts the linker call, we need to hack our way into the linking commands
  341. # LINKCOM and SHLINKCOM to set those flags.
  342. if "-Wl,--start-group" in env["LINKCOM"] and "-Wl,--start-group" in env["SHLINKCOM"]:
  343. # Already added by a previous call, skip.
  344. return
  345. env["LINKCOM"] = str(env["LINKCOM"]).replace("$_LIBFLAGS", "-Wl,--start-group $_LIBFLAGS -Wl,--end-group")
  346. env["SHLINKCOM"] = str(env["LINKCOM"]).replace("$_LIBFLAGS", "-Wl,--start-group $_LIBFLAGS -Wl,--end-group")
  347. def save_active_platforms(apnames, ap):
  348. for x in ap:
  349. names = ["logo"]
  350. if os.path.isfile(x + "/run_icon.png"):
  351. names.append("run_icon")
  352. for name in names:
  353. pngf = open(x + "/" + name + ".png", "rb")
  354. b = pngf.read(1)
  355. str = " /* AUTOGENERATED FILE, DO NOT EDIT */ \n"
  356. str += " static const unsigned char _" + x[9:] + "_" + name + "[]={"
  357. while len(b) == 1:
  358. str += hex(ord(b))
  359. b = pngf.read(1)
  360. if len(b) == 1:
  361. str += ","
  362. str += "};\n"
  363. pngf.close()
  364. # NOTE: It is safe to generate this file here, since this is still executed serially
  365. wf = x + "/" + name + ".gen.h"
  366. with open(wf, "w") as pngw:
  367. pngw.write(str)
  368. def no_verbose(sys, env):
  369. colors = {}
  370. # Colors are disabled in non-TTY environments such as pipes. This means
  371. # that if output is redirected to a file, it will not contain color codes
  372. if sys.stdout.isatty():
  373. colors["cyan"] = "\033[96m"
  374. colors["purple"] = "\033[95m"
  375. colors["blue"] = "\033[94m"
  376. colors["green"] = "\033[92m"
  377. colors["yellow"] = "\033[93m"
  378. colors["red"] = "\033[91m"
  379. colors["end"] = "\033[0m"
  380. else:
  381. colors["cyan"] = ""
  382. colors["purple"] = ""
  383. colors["blue"] = ""
  384. colors["green"] = ""
  385. colors["yellow"] = ""
  386. colors["red"] = ""
  387. colors["end"] = ""
  388. compile_source_message = "%sCompiling %s==> %s$SOURCE%s" % (
  389. colors["blue"],
  390. colors["purple"],
  391. colors["yellow"],
  392. colors["end"],
  393. )
  394. java_compile_source_message = "%sCompiling %s==> %s$SOURCE%s" % (
  395. colors["blue"],
  396. colors["purple"],
  397. colors["yellow"],
  398. colors["end"],
  399. )
  400. compile_shared_source_message = "%sCompiling shared %s==> %s$SOURCE%s" % (
  401. colors["blue"],
  402. colors["purple"],
  403. colors["yellow"],
  404. colors["end"],
  405. )
  406. link_program_message = "%sLinking Program %s==> %s$TARGET%s" % (
  407. colors["red"],
  408. colors["purple"],
  409. colors["yellow"],
  410. colors["end"],
  411. )
  412. link_library_message = "%sLinking Static Library %s==> %s$TARGET%s" % (
  413. colors["red"],
  414. colors["purple"],
  415. colors["yellow"],
  416. colors["end"],
  417. )
  418. ranlib_library_message = "%sRanlib Library %s==> %s$TARGET%s" % (
  419. colors["red"],
  420. colors["purple"],
  421. colors["yellow"],
  422. colors["end"],
  423. )
  424. link_shared_library_message = "%sLinking Shared Library %s==> %s$TARGET%s" % (
  425. colors["red"],
  426. colors["purple"],
  427. colors["yellow"],
  428. colors["end"],
  429. )
  430. java_library_message = "%sCreating Java Archive %s==> %s$TARGET%s" % (
  431. colors["red"],
  432. colors["purple"],
  433. colors["yellow"],
  434. colors["end"],
  435. )
  436. env.Append(CXXCOMSTR=[compile_source_message])
  437. env.Append(CCCOMSTR=[compile_source_message])
  438. env.Append(SHCCCOMSTR=[compile_shared_source_message])
  439. env.Append(SHCXXCOMSTR=[compile_shared_source_message])
  440. env.Append(ARCOMSTR=[link_library_message])
  441. env.Append(RANLIBCOMSTR=[ranlib_library_message])
  442. env.Append(SHLINKCOMSTR=[link_shared_library_message])
  443. env.Append(LINKCOMSTR=[link_program_message])
  444. env.Append(JARCOMSTR=[java_library_message])
  445. env.Append(JAVACCOMSTR=[java_compile_source_message])
  446. def detect_visual_c_compiler_version(tools_env):
  447. # tools_env is the variable scons uses to call tools that execute tasks, SCons's env['ENV'] that executes tasks...
  448. # (see the SCons documentation for more information on what it does)...
  449. # in order for this function to be well encapsulated i choose to force it to receive SCons's TOOLS env (env['ENV']
  450. # and not scons setup environment (env)... so make sure you call the right environment on it or it will fail to detect
  451. # the proper vc version that will be called
  452. # There is no flag to give to visual c compilers to set the architecture, ie scons bits argument (32,64,ARM etc)
  453. # There are many different cl.exe files that are run, and each one compiles & links to a different architecture
  454. # As far as I know, the only way to figure out what compiler will be run when Scons calls cl.exe via Program()
  455. # is to check the PATH variable and figure out which one will be called first. Code below does that and returns:
  456. # the following string values:
  457. # "" Compiler not detected
  458. # "amd64" Native 64 bit compiler
  459. # "amd64_x86" 64 bit Cross Compiler for 32 bit
  460. # "x86" Native 32 bit compiler
  461. # "x86_amd64" 32 bit Cross Compiler for 64 bit
  462. # There are other architectures, but Godot does not support them currently, so this function does not detect arm/amd64_arm
  463. # and similar architectures/compilers
  464. # Set chosen compiler to "not detected"
  465. vc_chosen_compiler_index = -1
  466. vc_chosen_compiler_str = ""
  467. # Start with Pre VS 2017 checks which uses VCINSTALLDIR:
  468. if "VCINSTALLDIR" in tools_env:
  469. # print("Checking VCINSTALLDIR")
  470. # find() works with -1 so big ifs below are needed... the simplest solution, in fact
  471. # First test if amd64 and amd64_x86 compilers are present in the path
  472. vc_amd64_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\amd64;")
  473. if vc_amd64_compiler_detection_index > -1:
  474. vc_chosen_compiler_index = vc_amd64_compiler_detection_index
  475. vc_chosen_compiler_str = "amd64"
  476. vc_amd64_x86_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\amd64_x86;")
  477. if vc_amd64_x86_compiler_detection_index > -1 and (
  478. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index
  479. ):
  480. vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index
  481. vc_chosen_compiler_str = "amd64_x86"
  482. # Now check the 32 bit compilers
  483. vc_x86_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN;")
  484. if vc_x86_compiler_detection_index > -1 and (
  485. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_compiler_detection_index
  486. ):
  487. vc_chosen_compiler_index = vc_x86_compiler_detection_index
  488. vc_chosen_compiler_str = "x86"
  489. vc_x86_amd64_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\x86_amd64;")
  490. if vc_x86_amd64_compiler_detection_index > -1 and (
  491. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index
  492. ):
  493. vc_chosen_compiler_index = vc_x86_amd64_compiler_detection_index
  494. vc_chosen_compiler_str = "x86_amd64"
  495. # and for VS 2017 and newer we check VCTOOLSINSTALLDIR:
  496. if "VCTOOLSINSTALLDIR" in tools_env:
  497. # Newer versions have a different path available
  498. vc_amd64_compiler_detection_index = (
  499. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX64\\X64;")
  500. )
  501. if vc_amd64_compiler_detection_index > -1:
  502. vc_chosen_compiler_index = vc_amd64_compiler_detection_index
  503. vc_chosen_compiler_str = "amd64"
  504. vc_amd64_x86_compiler_detection_index = (
  505. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX64\\X86;")
  506. )
  507. if vc_amd64_x86_compiler_detection_index > -1 and (
  508. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index
  509. ):
  510. vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index
  511. vc_chosen_compiler_str = "amd64_x86"
  512. vc_x86_compiler_detection_index = (
  513. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX86\\X86;")
  514. )
  515. if vc_x86_compiler_detection_index > -1 and (
  516. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_compiler_detection_index
  517. ):
  518. vc_chosen_compiler_index = vc_x86_compiler_detection_index
  519. vc_chosen_compiler_str = "x86"
  520. vc_x86_amd64_compiler_detection_index = (
  521. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX86\\X64;")
  522. )
  523. if vc_x86_amd64_compiler_detection_index > -1 and (
  524. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index
  525. ):
  526. vc_chosen_compiler_index = vc_x86_amd64_compiler_detection_index
  527. vc_chosen_compiler_str = "x86_amd64"
  528. return vc_chosen_compiler_str
  529. def find_visual_c_batch_file(env):
  530. from SCons.Tool.MSCommon.vc import (
  531. get_default_version,
  532. get_host_target,
  533. find_batch_file,
  534. )
  535. # Syntax changed in SCons 4.4.0.
  536. from SCons import __version__ as scons_raw_version
  537. scons_ver = env._get_major_minor_revision(scons_raw_version)
  538. version = get_default_version(env)
  539. if scons_ver >= (4, 4, 0):
  540. (host_platform, target_platform, _) = get_host_target(env, version)
  541. else:
  542. (host_platform, target_platform, _) = get_host_target(env)
  543. return find_batch_file(env, version, host_platform, target_platform)[0]
  544. def generate_cpp_hint_file(filename):
  545. if os.path.isfile(filename):
  546. # Don't overwrite an existing hint file since the user may have customized it.
  547. pass
  548. else:
  549. try:
  550. with open(filename, "w") as fd:
  551. fd.write("#define GDCLASS(m_class, m_inherits)\n")
  552. except IOError:
  553. print("Could not write cpp.hint file.")
  554. def glob_recursive(pattern, node="."):
  555. results = []
  556. for f in Glob(str(node) + "/*", source=True):
  557. if type(f) is Node.FS.Dir:
  558. results += glob_recursive(pattern, f)
  559. results += Glob(str(node) + "/" + pattern, source=True)
  560. return results
  561. def add_to_vs_project(env, sources):
  562. for x in sources:
  563. if type(x) == type(""):
  564. fname = env.File(x).path
  565. else:
  566. fname = env.File(x)[0].path
  567. pieces = fname.split(".")
  568. if len(pieces) > 0:
  569. basename = pieces[0]
  570. basename = basename.replace("\\\\", "/")
  571. if os.path.isfile(basename + ".h"):
  572. env.vs_incs += [basename + ".h"]
  573. elif os.path.isfile(basename + ".hpp"):
  574. env.vs_incs += [basename + ".hpp"]
  575. if os.path.isfile(basename + ".c"):
  576. env.vs_srcs += [basename + ".c"]
  577. elif os.path.isfile(basename + ".cpp"):
  578. env.vs_srcs += [basename + ".cpp"]
  579. def generate_vs_project(env, num_jobs):
  580. batch_file = find_visual_c_batch_file(env)
  581. if batch_file:
  582. class ModuleConfigs(Mapping):
  583. # This version information (Win32, x64, Debug, Release, Release_Debug seems to be
  584. # required for Visual Studio to understand that it needs to generate an NMAKE
  585. # project. Do not modify without knowing what you are doing.
  586. PLATFORMS = ["Win32", "x64"]
  587. PLATFORM_IDS = ["32", "64"]
  588. CONFIGURATIONS = ["debug", "release", "release_debug"]
  589. CONFIGURATION_IDS = ["tools", "opt", "opt.tools"]
  590. @staticmethod
  591. def for_every_variant(value):
  592. return [value for _ in range(len(ModuleConfigs.CONFIGURATIONS) * len(ModuleConfigs.PLATFORMS))]
  593. def __init__(self):
  594. shared_targets_array = []
  595. self.names = []
  596. self.arg_dict = {
  597. "variant": [],
  598. "runfile": shared_targets_array,
  599. "buildtarget": shared_targets_array,
  600. "cpppaths": [],
  601. "cppdefines": [],
  602. "cmdargs": [],
  603. }
  604. self.add_mode() # default
  605. def add_mode(
  606. self,
  607. name: str = "",
  608. includes: str = "",
  609. cli_args: str = "",
  610. defines=None,
  611. ):
  612. if defines is None:
  613. defines = []
  614. self.names.append(name)
  615. self.arg_dict["variant"] += [
  616. f'{config}{f"_[{name}]" if name else ""}|{platform}'
  617. for config in ModuleConfigs.CONFIGURATIONS
  618. for platform in ModuleConfigs.PLATFORMS
  619. ]
  620. self.arg_dict["runfile"] += [
  621. f'bin\\godot.windows.{config_id}.{plat_id}{f".{name}" if name else ""}.exe'
  622. for config_id in ModuleConfigs.CONFIGURATION_IDS
  623. for plat_id in ModuleConfigs.PLATFORM_IDS
  624. ]
  625. self.arg_dict["cpppaths"] += ModuleConfigs.for_every_variant(env["CPPPATH"] + [includes])
  626. self.arg_dict["cppdefines"] += ModuleConfigs.for_every_variant(env["CPPDEFINES"] + defines)
  627. self.arg_dict["cmdargs"] += ModuleConfigs.for_every_variant(cli_args)
  628. def build_commandline(self, commands):
  629. configuration_getter = (
  630. "$(Configuration"
  631. + "".join([f'.Replace("{name}", "")' for name in self.names[1:]])
  632. + '.Replace("_[]", "")'
  633. + ")"
  634. )
  635. common_build_prefix = [
  636. 'cmd /V /C set "plat=$(PlatformTarget)"',
  637. '(if "$(PlatformTarget)"=="x64" (set "plat=x86_amd64"))',
  638. 'set "tools=%s"' % env["tools"],
  639. f'(if "{configuration_getter}"=="release" (set "tools=no"))',
  640. 'call "' + batch_file + '" !plat!',
  641. ]
  642. # Windows allows us to have spaces in paths, so we need
  643. # to double quote off the directory. However, the path ends
  644. # in a backslash, so we need to remove this, lest it escape the
  645. # last double quote off, confusing MSBuild
  646. common_build_postfix = [
  647. "--directory=\"$(ProjectDir.TrimEnd('\\'))\"",
  648. "platform=windows",
  649. f"target={configuration_getter}",
  650. "progress=no",
  651. "tools=!tools!",
  652. "-j%s" % num_jobs,
  653. ]
  654. if env["custom_modules"]:
  655. common_build_postfix.append("custom_modules=%s" % env["custom_modules"])
  656. result = " ^& ".join(common_build_prefix + [" ".join([commands] + common_build_postfix)])
  657. return result
  658. # Mappings interface definitions
  659. def __iter__(self) -> Iterator[str]:
  660. for x in self.arg_dict:
  661. yield x
  662. def __len__(self) -> int:
  663. return len(self.names)
  664. def __getitem__(self, k: str):
  665. return self.arg_dict[k]
  666. add_to_vs_project(env, env.core_sources)
  667. add_to_vs_project(env, env.drivers_sources)
  668. add_to_vs_project(env, env.main_sources)
  669. add_to_vs_project(env, env.modules_sources)
  670. add_to_vs_project(env, env.scene_sources)
  671. add_to_vs_project(env, env.servers_sources)
  672. add_to_vs_project(env, env.editor_sources)
  673. for header in glob_recursive("**/*.h"):
  674. env.vs_incs.append(str(header))
  675. module_configs = ModuleConfigs()
  676. import modules.mono.build_scripts.mono_reg_utils as mono_reg
  677. if env.get("module_mono_enabled"):
  678. mono_root = env.get("mono_prefix") or mono_reg.find_mono_root_dir(env["bits"])
  679. if mono_root:
  680. module_configs.add_mode(
  681. "mono",
  682. includes=os.path.join(mono_root, "include", "mono-2.0"),
  683. cli_args="module_mono_enabled=yes mono_glue=yes",
  684. defines=[("MONO_GLUE_ENABLED",)],
  685. )
  686. else:
  687. print("Mono installation directory not found. Generated project will not have build variants for Mono.")
  688. env["MSVSBUILDCOM"] = module_configs.build_commandline("scons")
  689. env["MSVSREBUILDCOM"] = module_configs.build_commandline("scons vsproj=yes")
  690. env["MSVSCLEANCOM"] = module_configs.build_commandline("scons --clean")
  691. if not env.get("MSVS"):
  692. env["MSVS"]["PROJECTSUFFIX"] = ".vcxproj"
  693. env["MSVS"]["SOLUTIONSUFFIX"] = ".sln"
  694. env.MSVSProject(
  695. target=["#godot" + env["MSVSPROJECTSUFFIX"]],
  696. incs=env.vs_incs,
  697. srcs=env.vs_srcs,
  698. auto_build_solution=1,
  699. **module_configs,
  700. )
  701. else:
  702. print(
  703. "Could not locate Visual Studio batch file for setting up the build environment. Not generating VS project."
  704. )
  705. def precious_program(env, program, sources, **args):
  706. program = env.ProgramOriginal(program, sources, **args)
  707. env.Precious(program)
  708. return program
  709. def add_shared_library(env, name, sources, **args):
  710. library = env.SharedLibrary(name, sources, **args)
  711. env.NoCache(library)
  712. return library
  713. def add_library(env, name, sources, **args):
  714. library = env.Library(name, sources, **args)
  715. env.NoCache(library)
  716. return library
  717. def add_program(env, name, sources, **args):
  718. program = env.Program(name, sources, **args)
  719. env.NoCache(program)
  720. return program
  721. def CommandNoCache(env, target, sources, command, **args):
  722. result = env.Command(target, sources, command, **args)
  723. env.NoCache(result)
  724. return result
  725. def get_darwin_sdk_version(platform):
  726. sdk_name = ""
  727. if platform == "osx":
  728. sdk_name = "macosx"
  729. elif platform == "iphone":
  730. sdk_name = "iphoneos"
  731. elif platform == "iphonesimulator":
  732. sdk_name = "iphonesimulator"
  733. else:
  734. raise Exception("Invalid platform argument passed to get_darwin_sdk_version")
  735. try:
  736. return float(decode_utf8(subprocess.check_output(["xcrun", "--sdk", sdk_name, "--show-sdk-version"]).strip()))
  737. except (subprocess.CalledProcessError, OSError):
  738. print("Failed to find SDK version while running xcrun --sdk {} --show-sdk-version.".format(sdk_name))
  739. return 0.0
  740. def detect_darwin_sdk_path(platform, env):
  741. sdk_name = ""
  742. if platform == "osx":
  743. sdk_name = "macosx"
  744. var_name = "MACOS_SDK_PATH"
  745. elif platform == "iphone":
  746. sdk_name = "iphoneos"
  747. var_name = "IPHONESDK"
  748. elif platform == "iphonesimulator":
  749. sdk_name = "iphonesimulator"
  750. var_name = "IPHONESDK"
  751. else:
  752. raise Exception("Invalid platform argument passed to detect_darwin_sdk_path")
  753. if not env[var_name]:
  754. try:
  755. sdk_path = decode_utf8(subprocess.check_output(["xcrun", "--sdk", sdk_name, "--show-sdk-path"]).strip())
  756. if sdk_path:
  757. env[var_name] = sdk_path
  758. except (subprocess.CalledProcessError, OSError):
  759. print("Failed to find SDK path while running xcrun --sdk {} --show-sdk-path.".format(sdk_name))
  760. raise
  761. def get_compiler_version(env):
  762. """
  763. Returns an array of version numbers as ints: [major, minor, patch].
  764. The return array should have at least two values (major, minor).
  765. """
  766. if not env.msvc:
  767. # Not using -dumpversion as some GCC distros only return major, and
  768. # Clang used to return hardcoded 4.2.1: # https://reviews.llvm.org/D56803
  769. try:
  770. version = decode_utf8(subprocess.check_output([env.subst(env["CXX"]), "--version"]).strip())
  771. except (subprocess.CalledProcessError, OSError):
  772. print("Couldn't parse CXX environment variable to infer compiler version.")
  773. return None
  774. else: # TODO: Implement for MSVC
  775. return None
  776. match = re.search("[0-9]+\.[0-9.]+", version)
  777. if match is not None:
  778. return list(map(int, match.group().split(".")))
  779. else:
  780. return None
  781. def using_gcc(env):
  782. return "gcc" in os.path.basename(env["CC"])
  783. def using_clang(env):
  784. return "clang" in os.path.basename(env["CC"])
  785. def using_emcc(env):
  786. return "emcc" in os.path.basename(env["CC"])
  787. def show_progress(env):
  788. import sys
  789. from SCons.Script import Progress, Command, AlwaysBuild
  790. screen = sys.stdout
  791. # Progress reporting is not available in non-TTY environments since it
  792. # messes with the output (for example, when writing to a file)
  793. show_progress = env["progress"] and sys.stdout.isatty()
  794. node_count_data = {
  795. "count": 0,
  796. "max": 0,
  797. "interval": 1,
  798. "fname": str(env.Dir("#")) + "/.scons_node_count",
  799. }
  800. import time, math
  801. class cache_progress:
  802. # The default is 1 GB cache and 12 hours half life
  803. def __init__(self, path=None, limit=1073741824, half_life=43200):
  804. self.path = path
  805. self.limit = limit
  806. self.exponent_scale = math.log(2) / half_life
  807. if env["verbose"] and path != None:
  808. screen.write(
  809. "Current cache limit is {} (used: {})\n".format(
  810. self.convert_size(limit), self.convert_size(self.get_size(path))
  811. )
  812. )
  813. self.delete(self.file_list())
  814. def __call__(self, node, *args, **kw):
  815. if show_progress:
  816. # Print the progress percentage
  817. node_count_data["count"] += node_count_data["interval"]
  818. node_count = node_count_data["count"]
  819. node_count_max = node_count_data["max"]
  820. if node_count_max > 0 and node_count <= node_count_max:
  821. screen.write("\r[%3d%%] " % (node_count * 100 / node_count_max))
  822. screen.flush()
  823. elif node_count_max > 0 and node_count > node_count_max:
  824. screen.write("\r[100%] ")
  825. screen.flush()
  826. else:
  827. screen.write("\r[Initial build] ")
  828. screen.flush()
  829. def delete(self, files):
  830. if len(files) == 0:
  831. return
  832. if env["verbose"]:
  833. # Utter something
  834. screen.write("\rPurging %d %s from cache...\n" % (len(files), len(files) > 1 and "files" or "file"))
  835. [os.remove(f) for f in files]
  836. def file_list(self):
  837. if self.path is None:
  838. # Nothing to do
  839. return []
  840. # Gather a list of (filename, (size, atime)) within the
  841. # cache directory
  842. file_stat = [(x, os.stat(x)[6:8]) for x in glob.glob(os.path.join(self.path, "*", "*"))]
  843. if file_stat == []:
  844. # Nothing to do
  845. return []
  846. # Weight the cache files by size (assumed to be roughly
  847. # proportional to the recompilation time) times an exponential
  848. # decay since the ctime, and return a list with the entries
  849. # (filename, size, weight).
  850. current_time = time.time()
  851. file_stat = [(x[0], x[1][0], (current_time - x[1][1])) for x in file_stat]
  852. # Sort by the most recently accessed files (most sensible to keep) first
  853. file_stat.sort(key=lambda x: x[2])
  854. # Search for the first entry where the storage limit is
  855. # reached
  856. sum, mark = 0, None
  857. for i, x in enumerate(file_stat):
  858. sum += x[1]
  859. if sum > self.limit:
  860. mark = i
  861. break
  862. if mark is None:
  863. return []
  864. else:
  865. return [x[0] for x in file_stat[mark:]]
  866. def convert_size(self, size_bytes):
  867. if size_bytes == 0:
  868. return "0 bytes"
  869. size_name = ("bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
  870. i = int(math.floor(math.log(size_bytes, 1024)))
  871. p = math.pow(1024, i)
  872. s = round(size_bytes / p, 2)
  873. return "%s %s" % (int(s) if i == 0 else s, size_name[i])
  874. def get_size(self, start_path="."):
  875. total_size = 0
  876. for dirpath, dirnames, filenames in os.walk(start_path):
  877. for f in filenames:
  878. fp = os.path.join(dirpath, f)
  879. total_size += os.path.getsize(fp)
  880. return total_size
  881. def progress_finish(target, source, env):
  882. try:
  883. with open(node_count_data["fname"], "w") as f:
  884. f.write("%d\n" % node_count_data["count"])
  885. progressor.delete(progressor.file_list())
  886. except Exception:
  887. pass
  888. try:
  889. with open(node_count_data["fname"]) as f:
  890. node_count_data["max"] = int(f.readline())
  891. except Exception:
  892. pass
  893. cache_directory = os.environ.get("SCONS_CACHE")
  894. # Simple cache pruning, attached to SCons' progress callback. Trim the
  895. # cache directory to a size not larger than cache_limit.
  896. cache_limit = float(os.getenv("SCONS_CACHE_LIMIT", 1024)) * 1024 * 1024
  897. progressor = cache_progress(cache_directory, cache_limit)
  898. Progress(progressor, interval=node_count_data["interval"])
  899. progress_finish_command = Command("progress_finish", [], progress_finish)
  900. AlwaysBuild(progress_finish_command)
  901. def dump(env):
  902. # Dumps latest build information for debugging purposes and external tools.
  903. from json import dump
  904. def non_serializable(obj):
  905. return "<<non-serializable: %s>>" % (qualname(type(obj)))
  906. with open(".scons_env.json", "w") as f:
  907. dump(env.Dictionary(), f, indent=4, default=non_serializable)