methods.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  1. import os
  2. import re
  3. import glob
  4. import subprocess
  5. from collections import OrderedDict
  6. from compat import iteritems, isbasestring, decode_utf8
  7. def add_source_files(self, sources, files, warn_duplicates=True):
  8. # Convert string to list of absolute paths (including expanding wildcard)
  9. if isbasestring(files):
  10. # Keep SCons project-absolute path as they are (no wildcard support)
  11. if files.startswith("#"):
  12. if "*" in files:
  13. print("ERROR: Wildcards can't be expanded in SCons project-absolute path: '{}'".format(files))
  14. return
  15. files = [files]
  16. else:
  17. dir_path = self.Dir(".").abspath
  18. files = sorted(glob.glob(dir_path + "/" + files))
  19. # Add each path as compiled Object following environment (self) configuration
  20. for path in files:
  21. obj = self.Object(path)
  22. if obj in sources:
  23. if warn_duplicates:
  24. print('WARNING: Object "{}" already included in environment sources.'.format(obj))
  25. else:
  26. continue
  27. sources.append(obj)
  28. def disable_warnings(self):
  29. # 'self' is the environment
  30. if self.msvc:
  31. # We have to remove existing warning level defines before appending /w,
  32. # otherwise we get: "warning D9025 : overriding '/W3' with '/w'"
  33. warn_flags = ["/Wall", "/W4", "/W3", "/W2", "/W1", "/WX"]
  34. self.Append(CCFLAGS=["/w"])
  35. self.Append(CFLAGS=["/w"])
  36. self.Append(CXXFLAGS=["/w"])
  37. self["CCFLAGS"] = [x for x in self["CCFLAGS"] if not x in warn_flags]
  38. self["CFLAGS"] = [x for x in self["CFLAGS"] if not x in warn_flags]
  39. self["CXXFLAGS"] = [x for x in self["CXXFLAGS"] if not x in warn_flags]
  40. else:
  41. self.Append(CCFLAGS=["-w"])
  42. self.Append(CFLAGS=["-w"])
  43. self.Append(CXXFLAGS=["-w"])
  44. def add_module_version_string(self, s):
  45. self.module_version_string += "." + s
  46. def update_version(module_version_string=""):
  47. build_name = "custom_build"
  48. if os.getenv("BUILD_NAME") != None:
  49. build_name = os.getenv("BUILD_NAME")
  50. print("Using custom build name: " + build_name)
  51. import version
  52. # NOTE: It is safe to generate this file here, since this is still executed serially
  53. f = open("core/version_generated.gen.h", "w")
  54. f.write('#define VERSION_SHORT_NAME "' + str(version.short_name) + '"\n')
  55. f.write('#define VERSION_NAME "' + str(version.name) + '"\n')
  56. f.write("#define VERSION_MAJOR " + str(version.major) + "\n")
  57. f.write("#define VERSION_MINOR " + str(version.minor) + "\n")
  58. f.write("#define VERSION_PATCH " + str(version.patch) + "\n")
  59. f.write('#define VERSION_STATUS "' + str(version.status) + '"\n')
  60. f.write('#define VERSION_BUILD "' + str(build_name) + '"\n')
  61. f.write('#define VERSION_MODULE_CONFIG "' + str(version.module_config) + module_version_string + '"\n')
  62. f.write("#define VERSION_YEAR " + str(version.year) + "\n")
  63. f.write('#define VERSION_WEBSITE "' + str(version.website) + '"\n')
  64. f.close()
  65. # NOTE: It is safe to generate this file here, since this is still executed serially
  66. fhash = open("core/version_hash.gen.h", "w")
  67. githash = ""
  68. gitfolder = ".git"
  69. if os.path.isfile(".git"):
  70. module_folder = open(".git", "r").readline().strip()
  71. if module_folder.startswith("gitdir: "):
  72. gitfolder = module_folder[8:]
  73. if os.path.isfile(os.path.join(gitfolder, "HEAD")):
  74. head = open(os.path.join(gitfolder, "HEAD"), "r").readline().strip()
  75. if head.startswith("ref: "):
  76. head = os.path.join(gitfolder, head[5:])
  77. if os.path.isfile(head):
  78. githash = open(head, "r").readline().strip()
  79. else:
  80. githash = head
  81. fhash.write('#define VERSION_HASH "' + githash + '"')
  82. fhash.close()
  83. def parse_cg_file(fname, uniforms, sizes, conditionals):
  84. fs = open(fname, "r")
  85. line = fs.readline()
  86. while line:
  87. if re.match(r"^\s*uniform", line):
  88. res = re.match(r"uniform ([\d\w]*) ([\d\w]*)")
  89. type = res.groups(1)
  90. name = res.groups(2)
  91. uniforms.append(name)
  92. if type.find("texobj") != -1:
  93. sizes.append(1)
  94. else:
  95. t = re.match(r"float(\d)x(\d)", type)
  96. if t:
  97. sizes.append(int(t.groups(1)) * int(t.groups(2)))
  98. else:
  99. t = re.match(r"float(\d)", type)
  100. sizes.append(int(t.groups(1)))
  101. if line.find("[branch]") != -1:
  102. conditionals.append(name)
  103. line = fs.readline()
  104. fs.close()
  105. def detect_modules(at_path):
  106. module_list = OrderedDict() # name : path
  107. modules_glob = os.path.join(at_path, "*")
  108. files = glob.glob(modules_glob)
  109. files.sort() # so register_module_types does not change that often, and also plugins are registered in alphabetic order
  110. for x in files:
  111. if not is_module(x):
  112. continue
  113. name = os.path.basename(x)
  114. path = x.replace("\\", "/") # win32
  115. module_list[name] = path
  116. return module_list
  117. def is_module(path):
  118. return os.path.isdir(path) and os.path.exists(os.path.join(path, "SCsub"))
  119. def write_modules(module_list):
  120. includes_cpp = ""
  121. register_cpp = ""
  122. unregister_cpp = ""
  123. for name, path in module_list.items():
  124. try:
  125. with open(os.path.join(path, "register_types.h")):
  126. includes_cpp += '#include "' + path + '/register_types.h"\n'
  127. register_cpp += "#ifdef MODULE_" + name.upper() + "_ENABLED\n"
  128. register_cpp += "\tregister_" + name + "_types();\n"
  129. register_cpp += "#endif\n"
  130. unregister_cpp += "#ifdef MODULE_" + name.upper() + "_ENABLED\n"
  131. unregister_cpp += "\tunregister_" + name + "_types();\n"
  132. unregister_cpp += "#endif\n"
  133. except IOError:
  134. pass
  135. modules_cpp = (
  136. """
  137. // modules.cpp - THIS FILE IS GENERATED, DO NOT EDIT!!!!!!!
  138. #include "register_module_types.h"
  139. """
  140. + includes_cpp
  141. + """
  142. void register_module_types() {
  143. """
  144. + register_cpp
  145. + """
  146. }
  147. void unregister_module_types() {
  148. """
  149. + unregister_cpp
  150. + """
  151. }
  152. """
  153. )
  154. # NOTE: It is safe to generate this file here, since this is still executed serially
  155. with open("modules/register_module_types.gen.cpp", "w") as f:
  156. f.write(modules_cpp)
  157. def convert_custom_modules_path(path):
  158. if not path:
  159. return path
  160. err_msg = "Build option 'custom_modules' must %s"
  161. if not os.path.isdir(path):
  162. raise ValueError(err_msg % "point to an existing directory.")
  163. if os.path.realpath(path) == os.path.realpath("modules"):
  164. raise ValueError(err_msg % "be a directory other than built-in `modules` directory.")
  165. if is_module(path):
  166. raise ValueError(err_msg % "point to a directory with modules, not a single module.")
  167. return os.path.realpath(os.path.expanduser(path))
  168. def disable_module(self):
  169. self.disabled_modules.append(self.current_module)
  170. def use_windows_spawn_fix(self, platform=None):
  171. if os.name != "nt":
  172. return # not needed, only for windows
  173. # On Windows, due to the limited command line length, when creating a static library
  174. # from a very high number of objects SCons will invoke "ar" once per object file;
  175. # that makes object files with same names to be overwritten so the last wins and
  176. # the library looses symbols defined by overwritten objects.
  177. # By enabling quick append instead of the default mode (replacing), libraries will
  178. # got built correctly regardless the invocation strategy.
  179. # Furthermore, since SCons will rebuild the library from scratch when an object file
  180. # changes, no multiple versions of the same object file will be present.
  181. self.Replace(ARFLAGS="q")
  182. def mySubProcess(cmdline, env):
  183. startupinfo = subprocess.STARTUPINFO()
  184. startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  185. proc = subprocess.Popen(
  186. cmdline,
  187. stdin=subprocess.PIPE,
  188. stdout=subprocess.PIPE,
  189. stderr=subprocess.PIPE,
  190. startupinfo=startupinfo,
  191. shell=False,
  192. env=env,
  193. )
  194. _, err = proc.communicate()
  195. rv = proc.wait()
  196. if rv:
  197. print("=====")
  198. print(err)
  199. print("=====")
  200. return rv
  201. def mySpawn(sh, escape, cmd, args, env):
  202. newargs = " ".join(args[1:])
  203. cmdline = cmd + " " + newargs
  204. rv = 0
  205. env = {str(key): str(value) for key, value in iteritems(env)}
  206. if len(cmdline) > 32000 and cmd.endswith("ar"):
  207. cmdline = cmd + " " + args[1] + " " + args[2] + " "
  208. for i in range(3, len(args)):
  209. rv = mySubProcess(cmdline + args[i], env)
  210. if rv:
  211. break
  212. else:
  213. rv = mySubProcess(cmdline, env)
  214. return rv
  215. self["SPAWN"] = mySpawn
  216. def split_lib(self, libname, src_list=None, env_lib=None):
  217. env = self
  218. num = 0
  219. cur_base = ""
  220. max_src = 64
  221. list = []
  222. lib_list = []
  223. if src_list is None:
  224. src_list = getattr(env, libname + "_sources")
  225. if type(env_lib) == type(None):
  226. env_lib = env
  227. for f in src_list:
  228. fname = ""
  229. if type(f) == type(""):
  230. fname = env.File(f).path
  231. else:
  232. fname = env.File(f)[0].path
  233. fname = fname.replace("\\", "/")
  234. base = "/".join(fname.split("/")[:2])
  235. if base != cur_base and len(list) > max_src:
  236. if num > 0:
  237. lib = env_lib.add_library(libname + str(num), list)
  238. lib_list.append(lib)
  239. list = []
  240. num = num + 1
  241. cur_base = base
  242. list.append(f)
  243. lib = env_lib.add_library(libname + str(num), list)
  244. lib_list.append(lib)
  245. lib_base = []
  246. env_lib.add_source_files(lib_base, "*.cpp")
  247. lib = env_lib.add_library(libname, lib_base)
  248. lib_list.insert(0, lib)
  249. env.Prepend(LIBS=lib_list)
  250. # When we split modules into arbitrary chunks, we end up with linking issues
  251. # due to symbol dependencies split over several libs, which may not be linked
  252. # in the required order. We use --start-group and --end-group to tell the
  253. # linker that those archives should be searched repeatedly to resolve all
  254. # undefined references.
  255. # As SCons doesn't give us much control over how inserting libs in LIBS
  256. # impacts the linker call, we need to hack our way into the linking commands
  257. # LINKCOM and SHLINKCOM to set those flags.
  258. if "-Wl,--start-group" in env["LINKCOM"] and "-Wl,--start-group" in env["SHLINKCOM"]:
  259. # Already added by a previous call, skip.
  260. return
  261. env["LINKCOM"] = str(env["LINKCOM"]).replace("$_LIBFLAGS", "-Wl,--start-group $_LIBFLAGS -Wl,--end-group")
  262. env["SHLINKCOM"] = str(env["LINKCOM"]).replace("$_LIBFLAGS", "-Wl,--start-group $_LIBFLAGS -Wl,--end-group")
  263. def save_active_platforms(apnames, ap):
  264. for x in ap:
  265. names = ["logo"]
  266. if os.path.isfile(x + "/run_icon.png"):
  267. names.append("run_icon")
  268. for name in names:
  269. pngf = open(x + "/" + name + ".png", "rb")
  270. b = pngf.read(1)
  271. str = " /* AUTOGENERATED FILE, DO NOT EDIT */ \n"
  272. str += " static const unsigned char _" + x[9:] + "_" + name + "[]={"
  273. while len(b) == 1:
  274. str += hex(ord(b))
  275. b = pngf.read(1)
  276. if len(b) == 1:
  277. str += ","
  278. str += "};\n"
  279. pngf.close()
  280. # NOTE: It is safe to generate this file here, since this is still executed serially
  281. wf = x + "/" + name + ".gen.h"
  282. with open(wf, "w") as pngw:
  283. pngw.write(str)
  284. def no_verbose(sys, env):
  285. colors = {}
  286. # Colors are disabled in non-TTY environments such as pipes. This means
  287. # that if output is redirected to a file, it will not contain color codes
  288. if sys.stdout.isatty():
  289. colors["cyan"] = "\033[96m"
  290. colors["purple"] = "\033[95m"
  291. colors["blue"] = "\033[94m"
  292. colors["green"] = "\033[92m"
  293. colors["yellow"] = "\033[93m"
  294. colors["red"] = "\033[91m"
  295. colors["end"] = "\033[0m"
  296. else:
  297. colors["cyan"] = ""
  298. colors["purple"] = ""
  299. colors["blue"] = ""
  300. colors["green"] = ""
  301. colors["yellow"] = ""
  302. colors["red"] = ""
  303. colors["end"] = ""
  304. compile_source_message = "%sCompiling %s==> %s$SOURCE%s" % (
  305. colors["blue"],
  306. colors["purple"],
  307. colors["yellow"],
  308. colors["end"],
  309. )
  310. java_compile_source_message = "%sCompiling %s==> %s$SOURCE%s" % (
  311. colors["blue"],
  312. colors["purple"],
  313. colors["yellow"],
  314. colors["end"],
  315. )
  316. compile_shared_source_message = "%sCompiling shared %s==> %s$SOURCE%s" % (
  317. colors["blue"],
  318. colors["purple"],
  319. colors["yellow"],
  320. colors["end"],
  321. )
  322. link_program_message = "%sLinking Program %s==> %s$TARGET%s" % (
  323. colors["red"],
  324. colors["purple"],
  325. colors["yellow"],
  326. colors["end"],
  327. )
  328. link_library_message = "%sLinking Static Library %s==> %s$TARGET%s" % (
  329. colors["red"],
  330. colors["purple"],
  331. colors["yellow"],
  332. colors["end"],
  333. )
  334. ranlib_library_message = "%sRanlib Library %s==> %s$TARGET%s" % (
  335. colors["red"],
  336. colors["purple"],
  337. colors["yellow"],
  338. colors["end"],
  339. )
  340. link_shared_library_message = "%sLinking Shared Library %s==> %s$TARGET%s" % (
  341. colors["red"],
  342. colors["purple"],
  343. colors["yellow"],
  344. colors["end"],
  345. )
  346. java_library_message = "%sCreating Java Archive %s==> %s$TARGET%s" % (
  347. colors["red"],
  348. colors["purple"],
  349. colors["yellow"],
  350. colors["end"],
  351. )
  352. env.Append(CXXCOMSTR=[compile_source_message])
  353. env.Append(CCCOMSTR=[compile_source_message])
  354. env.Append(SHCCCOMSTR=[compile_shared_source_message])
  355. env.Append(SHCXXCOMSTR=[compile_shared_source_message])
  356. env.Append(ARCOMSTR=[link_library_message])
  357. env.Append(RANLIBCOMSTR=[ranlib_library_message])
  358. env.Append(SHLINKCOMSTR=[link_shared_library_message])
  359. env.Append(LINKCOMSTR=[link_program_message])
  360. env.Append(JARCOMSTR=[java_library_message])
  361. env.Append(JAVACCOMSTR=[java_compile_source_message])
  362. def detect_visual_c_compiler_version(tools_env):
  363. # tools_env is the variable scons uses to call tools that execute tasks, SCons's env['ENV'] that executes tasks...
  364. # (see the SCons documentation for more information on what it does)...
  365. # in order for this function to be well encapsulated i choose to force it to receive SCons's TOOLS env (env['ENV']
  366. # and not scons setup environment (env)... so make sure you call the right environment on it or it will fail to detect
  367. # the proper vc version that will be called
  368. # There is no flag to give to visual c compilers to set the architecture, ie scons bits argument (32,64,ARM etc)
  369. # There are many different cl.exe files that are run, and each one compiles & links to a different architecture
  370. # As far as I know, the only way to figure out what compiler will be run when Scons calls cl.exe via Program()
  371. # is to check the PATH variable and figure out which one will be called first. Code below does that and returns:
  372. # the following string values:
  373. # "" Compiler not detected
  374. # "amd64" Native 64 bit compiler
  375. # "amd64_x86" 64 bit Cross Compiler for 32 bit
  376. # "x86" Native 32 bit compiler
  377. # "x86_amd64" 32 bit Cross Compiler for 64 bit
  378. # There are other architectures, but Godot does not support them currently, so this function does not detect arm/amd64_arm
  379. # and similar architectures/compilers
  380. # Set chosen compiler to "not detected"
  381. vc_chosen_compiler_index = -1
  382. vc_chosen_compiler_str = ""
  383. # Start with Pre VS 2017 checks which uses VCINSTALLDIR:
  384. if "VCINSTALLDIR" in tools_env:
  385. # print("Checking VCINSTALLDIR")
  386. # find() works with -1 so big ifs below are needed... the simplest solution, in fact
  387. # First test if amd64 and amd64_x86 compilers are present in the path
  388. vc_amd64_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\amd64;")
  389. if vc_amd64_compiler_detection_index > -1:
  390. vc_chosen_compiler_index = vc_amd64_compiler_detection_index
  391. vc_chosen_compiler_str = "amd64"
  392. vc_amd64_x86_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\amd64_x86;")
  393. if vc_amd64_x86_compiler_detection_index > -1 and (
  394. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index
  395. ):
  396. vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index
  397. vc_chosen_compiler_str = "amd64_x86"
  398. # Now check the 32 bit compilers
  399. vc_x86_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN;")
  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 = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\x86_amd64;")
  406. if vc_x86_amd64_compiler_detection_index > -1 and (
  407. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index
  408. ):
  409. vc_chosen_compiler_index = vc_x86_amd64_compiler_detection_index
  410. vc_chosen_compiler_str = "x86_amd64"
  411. # and for VS 2017 and newer we check VCTOOLSINSTALLDIR:
  412. if "VCTOOLSINSTALLDIR" in tools_env:
  413. # Newer versions have a different path available
  414. vc_amd64_compiler_detection_index = (
  415. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX64\\X64;")
  416. )
  417. if vc_amd64_compiler_detection_index > -1:
  418. vc_chosen_compiler_index = vc_amd64_compiler_detection_index
  419. vc_chosen_compiler_str = "amd64"
  420. vc_amd64_x86_compiler_detection_index = (
  421. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX64\\X86;")
  422. )
  423. if vc_amd64_x86_compiler_detection_index > -1 and (
  424. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index
  425. ):
  426. vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index
  427. vc_chosen_compiler_str = "amd64_x86"
  428. vc_x86_compiler_detection_index = (
  429. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX86\\X86;")
  430. )
  431. if vc_x86_compiler_detection_index > -1 and (
  432. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_compiler_detection_index
  433. ):
  434. vc_chosen_compiler_index = vc_x86_compiler_detection_index
  435. vc_chosen_compiler_str = "x86"
  436. vc_x86_amd64_compiler_detection_index = (
  437. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX86\\X64;")
  438. )
  439. if vc_x86_amd64_compiler_detection_index > -1 and (
  440. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index
  441. ):
  442. vc_chosen_compiler_index = vc_x86_amd64_compiler_detection_index
  443. vc_chosen_compiler_str = "x86_amd64"
  444. return vc_chosen_compiler_str
  445. def find_visual_c_batch_file(env):
  446. from SCons.Tool.MSCommon.vc import get_default_version, get_host_target, find_batch_file
  447. version = get_default_version(env)
  448. (host_platform, target_platform, _) = get_host_target(env)
  449. return find_batch_file(env, version, host_platform, target_platform)[0]
  450. def generate_cpp_hint_file(filename):
  451. if os.path.isfile(filename):
  452. # Don't overwrite an existing hint file since the user may have customized it.
  453. pass
  454. else:
  455. try:
  456. with open(filename, "w") as fd:
  457. fd.write("#define GDCLASS(m_class, m_inherits)\n")
  458. except IOError:
  459. print("Could not write cpp.hint file.")
  460. def generate_vs_project(env, num_jobs):
  461. batch_file = find_visual_c_batch_file(env)
  462. if batch_file:
  463. def build_commandline(commands):
  464. common_build_prefix = [
  465. 'cmd /V /C set "plat=$(PlatformTarget)"',
  466. '(if "$(PlatformTarget)"=="x64" (set "plat=x86_amd64"))',
  467. 'set "tools=yes"',
  468. '(if "$(Configuration)"=="release" (set "tools=no"))',
  469. 'call "' + batch_file + '" !plat!',
  470. ]
  471. result = " ^& ".join(common_build_prefix + [commands])
  472. return result
  473. env.AddToVSProject(env.core_sources)
  474. env.AddToVSProject(env.main_sources)
  475. env.AddToVSProject(env.modules_sources)
  476. env.AddToVSProject(env.scene_sources)
  477. env.AddToVSProject(env.servers_sources)
  478. env.AddToVSProject(env.editor_sources)
  479. # windows allows us to have spaces in paths, so we need
  480. # to double quote off the directory. However, the path ends
  481. # in a backslash, so we need to remove this, lest it escape the
  482. # last double quote off, confusing MSBuild
  483. env["MSVSBUILDCOM"] = build_commandline(
  484. "scons --directory=\"$(ProjectDir.TrimEnd('\\'))\" platform=windows progress=no target=$(Configuration) tools=!tools! -j"
  485. + str(num_jobs)
  486. )
  487. env["MSVSREBUILDCOM"] = build_commandline(
  488. "scons --directory=\"$(ProjectDir.TrimEnd('\\'))\" platform=windows progress=no target=$(Configuration) tools=!tools! vsproj=yes -j"
  489. + str(num_jobs)
  490. )
  491. env["MSVSCLEANCOM"] = build_commandline(
  492. "scons --directory=\"$(ProjectDir.TrimEnd('\\'))\" --clean platform=windows progress=no target=$(Configuration) tools=!tools! -j"
  493. + str(num_jobs)
  494. )
  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(
  520. "Could not locate Visual Studio batch file for setting up the build environment. Not generating VS project."
  521. )
  522. def precious_program(env, program, sources, **args):
  523. program = env.ProgramOriginal(program, sources, **args)
  524. env.Precious(program)
  525. return program
  526. def add_shared_library(env, name, sources, **args):
  527. library = env.SharedLibrary(name, sources, **args)
  528. env.NoCache(library)
  529. return library
  530. def add_library(env, name, sources, **args):
  531. library = env.Library(name, sources, **args)
  532. env.NoCache(library)
  533. return library
  534. def add_program(env, name, sources, **args):
  535. program = env.Program(name, sources, **args)
  536. env.NoCache(program)
  537. return program
  538. def CommandNoCache(env, target, sources, command, **args):
  539. result = env.Command(target, sources, command, **args)
  540. env.NoCache(result)
  541. return result
  542. def detect_darwin_sdk_path(platform, env):
  543. sdk_name = ""
  544. if platform == "osx":
  545. sdk_name = "macosx"
  546. var_name = "MACOS_SDK_PATH"
  547. elif platform == "iphone":
  548. sdk_name = "iphoneos"
  549. var_name = "IPHONESDK"
  550. elif platform == "iphonesimulator":
  551. sdk_name = "iphonesimulator"
  552. var_name = "IPHONESDK"
  553. else:
  554. raise Exception("Invalid platform argument passed to detect_darwin_sdk_path")
  555. if not env[var_name]:
  556. try:
  557. sdk_path = decode_utf8(subprocess.check_output(["xcrun", "--sdk", sdk_name, "--show-sdk-path"]).strip())
  558. if sdk_path:
  559. env[var_name] = sdk_path
  560. except (subprocess.CalledProcessError, OSError):
  561. print("Failed to find SDK path while running xcrun --sdk {} --show-sdk-path.".format(sdk_name))
  562. raise
  563. def get_compiler_version(env):
  564. """
  565. Returns an array of version numbers as ints: [major, minor, patch].
  566. The return array should have at least two values (major, minor).
  567. """
  568. if not env.msvc:
  569. # Not using -dumpversion as some GCC distros only return major, and
  570. # Clang used to return hardcoded 4.2.1: # https://reviews.llvm.org/D56803
  571. try:
  572. version = decode_utf8(subprocess.check_output([env.subst(env["CXX"]), "--version"]).strip())
  573. except (subprocess.CalledProcessError, OSError):
  574. print("Couldn't parse CXX environment variable to infer compiler version.")
  575. return None
  576. else: # TODO: Implement for MSVC
  577. return None
  578. match = re.search("[0-9]+\.[0-9.]+", version)
  579. if match is not None:
  580. return list(map(int, match.group().split(".")))
  581. else:
  582. return None
  583. def using_gcc(env):
  584. return "gcc" in os.path.basename(env["CC"])
  585. def using_clang(env):
  586. return "clang" in os.path.basename(env["CC"])