methods.py 32 KB

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