methods.py 33 KB

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