methods.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. import os
  2. import os.path
  3. import re
  4. import glob
  5. import subprocess
  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():
  106. module_list = []
  107. includes_cpp = ""
  108. register_cpp = ""
  109. unregister_cpp = ""
  110. files = glob.glob("modules/*")
  111. files.sort() # so register_module_types does not change that often, and also plugins are registered in alphabetic order
  112. for x in files:
  113. if not os.path.isdir(x):
  114. continue
  115. if not os.path.exists(x + "/config.py"):
  116. continue
  117. x = x.replace("modules/", "") # rest of world
  118. x = x.replace("modules\\", "") # win32
  119. module_list.append(x)
  120. try:
  121. with open("modules/" + x + "/register_types.h"):
  122. includes_cpp += '#include "modules/' + x + '/register_types.h"\n'
  123. register_cpp += '#ifdef MODULE_' + x.upper() + '_ENABLED\n'
  124. register_cpp += '\tregister_' + x + '_types();\n'
  125. register_cpp += '#endif\n'
  126. unregister_cpp += '#ifdef MODULE_' + x.upper() + '_ENABLED\n'
  127. unregister_cpp += '\tunregister_' + x + '_types();\n'
  128. unregister_cpp += '#endif\n'
  129. except IOError:
  130. pass
  131. modules_cpp = """
  132. // modules.cpp - THIS FILE IS GENERATED, DO NOT EDIT!!!!!!!
  133. #include "register_module_types.h"
  134. """ + includes_cpp + """
  135. void register_module_types() {
  136. """ + register_cpp + """
  137. }
  138. void unregister_module_types() {
  139. """ + unregister_cpp + """
  140. }
  141. """
  142. # NOTE: It is safe to generate this file here, since this is still executed serially
  143. with open("modules/register_module_types.gen.cpp", "w") as f:
  144. f.write(modules_cpp)
  145. return module_list
  146. def win32_spawn(sh, escape, cmd, args, env):
  147. import subprocess
  148. newargs = ' '.join(args[1:])
  149. cmdline = cmd + " " + newargs
  150. startupinfo = subprocess.STARTUPINFO()
  151. for e in env:
  152. if type(env[e]) != type(""):
  153. env[e] = str(env[e])
  154. proc = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  155. stderr=subprocess.PIPE, startupinfo=startupinfo, shell=False, env=env)
  156. _, err = proc.communicate()
  157. rv = proc.wait()
  158. if rv:
  159. print("=====")
  160. print(err)
  161. print("=====")
  162. return rv
  163. """
  164. def win32_spawn(sh, escape, cmd, args, spawnenv):
  165. import win32file
  166. import win32event
  167. import win32process
  168. import win32security
  169. for var in spawnenv:
  170. spawnenv[var] = spawnenv[var].encode('ascii', 'replace')
  171. sAttrs = win32security.SECURITY_ATTRIBUTES()
  172. StartupInfo = win32process.STARTUPINFO()
  173. newargs = ' '.join(map(escape, args[1:]))
  174. cmdline = cmd + " " + newargs
  175. # check for any special operating system commands
  176. if cmd == 'del':
  177. for arg in args[1:]:
  178. win32file.DeleteFile(arg)
  179. exit_code = 0
  180. else:
  181. # otherwise execute the command.
  182. hProcess, hThread, dwPid, dwTid = win32process.CreateProcess(None, cmdline, None, None, 1, 0, spawnenv, None, StartupInfo)
  183. win32event.WaitForSingleObject(hProcess, win32event.INFINITE)
  184. exit_code = win32process.GetExitCodeProcess(hProcess)
  185. win32file.CloseHandle(hProcess);
  186. win32file.CloseHandle(hThread);
  187. return exit_code
  188. """
  189. def disable_module(self):
  190. self.disabled_modules.append(self.current_module)
  191. def use_windows_spawn_fix(self, platform=None):
  192. if (os.name != "nt"):
  193. return # not needed, only for windows
  194. # On Windows, due to the limited command line length, when creating a static library
  195. # from a very high number of objects SCons will invoke "ar" once per object file;
  196. # that makes object files with same names to be overwritten so the last wins and
  197. # the library looses symbols defined by overwritten objects.
  198. # By enabling quick append instead of the default mode (replacing), libraries will
  199. # got built correctly regardless the invocation strategy.
  200. # Furthermore, since SCons will rebuild the library from scratch when an object file
  201. # changes, no multiple versions of the same object file will be present.
  202. self.Replace(ARFLAGS='q')
  203. def mySubProcess(cmdline, env):
  204. startupinfo = subprocess.STARTUPINFO()
  205. startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  206. proc = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  207. stderr=subprocess.PIPE, startupinfo=startupinfo, shell=False, env=env)
  208. _, err = proc.communicate()
  209. rv = proc.wait()
  210. if rv:
  211. print("=====")
  212. print(err)
  213. print("=====")
  214. return rv
  215. def mySpawn(sh, escape, cmd, args, env):
  216. newargs = ' '.join(args[1:])
  217. cmdline = cmd + " " + newargs
  218. rv = 0
  219. env = {str(key): str(value) for key, value in iteritems(env)}
  220. if len(cmdline) > 32000 and cmd.endswith("ar"):
  221. cmdline = cmd + " " + args[1] + " " + args[2] + " "
  222. for i in range(3, len(args)):
  223. rv = mySubProcess(cmdline + args[i], env)
  224. if rv:
  225. break
  226. else:
  227. rv = mySubProcess(cmdline, env)
  228. return rv
  229. self['SPAWN'] = mySpawn
  230. def split_lib(self, libname, src_list = None, env_lib = None):
  231. env = self
  232. num = 0
  233. cur_base = ""
  234. max_src = 64
  235. list = []
  236. lib_list = []
  237. if src_list is None:
  238. src_list = getattr(env, libname + "_sources")
  239. if type(env_lib) == type(None):
  240. env_lib = env
  241. for f in src_list:
  242. fname = ""
  243. if type(f) == type(""):
  244. fname = env.File(f).path
  245. else:
  246. fname = env.File(f)[0].path
  247. fname = fname.replace("\\", "/")
  248. base = "/".join(fname.split("/")[:2])
  249. if base != cur_base and len(list) > max_src:
  250. if num > 0:
  251. lib = env_lib.add_library(libname + str(num), list)
  252. lib_list.append(lib)
  253. list = []
  254. num = num + 1
  255. cur_base = base
  256. list.append(f)
  257. lib = env_lib.add_library(libname + str(num), list)
  258. lib_list.append(lib)
  259. lib_base = []
  260. env_lib.add_source_files(lib_base, "*.cpp")
  261. lib = env_lib.add_library(libname, lib_base)
  262. lib_list.insert(0, lib)
  263. env.Prepend(LIBS=lib_list)
  264. # When we split modules into arbitrary chunks, we end up with linking issues
  265. # due to symbol dependencies split over several libs, which may not be linked
  266. # in the required order. We use --start-group and --end-group to tell the
  267. # linker that those archives should be searched repeatedly to resolve all
  268. # undefined references.
  269. # As SCons doesn't give us much control over how inserting libs in LIBS
  270. # impacts the linker call, we need to hack our way into the linking commands
  271. # LINKCOM and SHLINKCOM to set those flags.
  272. if '-Wl,--start-group' in env['LINKCOM'] and '-Wl,--start-group' in env['SHLINKCOM']:
  273. # Already added by a previous call, skip.
  274. return
  275. env['LINKCOM'] = str(env['LINKCOM']).replace('$_LIBFLAGS',
  276. '-Wl,--start-group $_LIBFLAGS -Wl,--end-group')
  277. env['SHLINKCOM'] = str(env['LINKCOM']).replace('$_LIBFLAGS',
  278. '-Wl,--start-group $_LIBFLAGS -Wl,--end-group')
  279. def save_active_platforms(apnames, ap):
  280. for x in ap:
  281. names = ['logo']
  282. if os.path.isfile(x + "/run_icon.png"):
  283. names.append('run_icon')
  284. for name in names:
  285. pngf = open(x + "/" + name + ".png", "rb")
  286. b = pngf.read(1)
  287. str = " /* AUTOGENERATED FILE, DO NOT EDIT */ \n"
  288. str += " static const unsigned char _" + x[9:] + "_" + name + "[]={"
  289. while len(b) == 1:
  290. str += hex(ord(b))
  291. b = pngf.read(1)
  292. if (len(b) == 1):
  293. str += ","
  294. str += "};\n"
  295. pngf.close()
  296. # NOTE: It is safe to generate this file here, since this is still executed serially
  297. wf = x + "/" + name + ".gen.h"
  298. with open(wf, "w") as pngw:
  299. pngw.write(str)
  300. def no_verbose(sys, env):
  301. colors = {}
  302. # Colors are disabled in non-TTY environments such as pipes. This means
  303. # that if output is redirected to a file, it will not contain color codes
  304. if sys.stdout.isatty():
  305. colors['cyan'] = '\033[96m'
  306. colors['purple'] = '\033[95m'
  307. colors['blue'] = '\033[94m'
  308. colors['green'] = '\033[92m'
  309. colors['yellow'] = '\033[93m'
  310. colors['red'] = '\033[91m'
  311. colors['end'] = '\033[0m'
  312. else:
  313. colors['cyan'] = ''
  314. colors['purple'] = ''
  315. colors['blue'] = ''
  316. colors['green'] = ''
  317. colors['yellow'] = ''
  318. colors['red'] = ''
  319. colors['end'] = ''
  320. compile_source_message = '%sCompiling %s==> %s$SOURCE%s' % (colors['blue'], colors['purple'], colors['yellow'], colors['end'])
  321. java_compile_source_message = '%sCompiling %s==> %s$SOURCE%s' % (colors['blue'], colors['purple'], colors['yellow'], colors['end'])
  322. compile_shared_source_message = '%sCompiling shared %s==> %s$SOURCE%s' % (colors['blue'], colors['purple'], colors['yellow'], colors['end'])
  323. link_program_message = '%sLinking Program %s==> %s$TARGET%s' % (colors['red'], colors['purple'], colors['yellow'], colors['end'])
  324. link_library_message = '%sLinking Static Library %s==> %s$TARGET%s' % (colors['red'], colors['purple'], colors['yellow'], colors['end'])
  325. ranlib_library_message = '%sRanlib Library %s==> %s$TARGET%s' % (colors['red'], colors['purple'], colors['yellow'], colors['end'])
  326. link_shared_library_message = '%sLinking Shared Library %s==> %s$TARGET%s' % (colors['red'], colors['purple'], colors['yellow'], colors['end'])
  327. java_library_message = '%sCreating Java Archive %s==> %s$TARGET%s' % (colors['red'], colors['purple'], colors['yellow'], colors['end'])
  328. env.Append(CXXCOMSTR=[compile_source_message])
  329. env.Append(CCCOMSTR=[compile_source_message])
  330. env.Append(SHCCCOMSTR=[compile_shared_source_message])
  331. env.Append(SHCXXCOMSTR=[compile_shared_source_message])
  332. env.Append(ARCOMSTR=[link_library_message])
  333. env.Append(RANLIBCOMSTR=[ranlib_library_message])
  334. env.Append(SHLINKCOMSTR=[link_shared_library_message])
  335. env.Append(LINKCOMSTR=[link_program_message])
  336. env.Append(JARCOMSTR=[java_library_message])
  337. env.Append(JAVACCOMSTR=[java_compile_source_message])
  338. def detect_visual_c_compiler_version(tools_env):
  339. # tools_env is the variable scons uses to call tools that execute tasks, SCons's env['ENV'] that executes tasks...
  340. # (see the SCons documentation for more information on what it does)...
  341. # in order for this function to be well encapsulated i choose to force it to receive SCons's TOOLS env (env['ENV']
  342. # and not scons setup environment (env)... so make sure you call the right environment on it or it will fail to detect
  343. # the proper vc version that will be called
  344. # There is no flag to give to visual c compilers to set the architecture, ie scons bits argument (32,64,ARM etc)
  345. # There are many different cl.exe files that are run, and each one compiles & links to a different architecture
  346. # As far as I know, the only way to figure out what compiler will be run when Scons calls cl.exe via Program()
  347. # is to check the PATH variable and figure out which one will be called first. Code below does that and returns:
  348. # the following string values:
  349. # "" Compiler not detected
  350. # "amd64" Native 64 bit compiler
  351. # "amd64_x86" 64 bit Cross Compiler for 32 bit
  352. # "x86" Native 32 bit compiler
  353. # "x86_amd64" 32 bit Cross Compiler for 64 bit
  354. # There are other architectures, but Godot does not support them currently, so this function does not detect arm/amd64_arm
  355. # and similar architectures/compilers
  356. # Set chosen compiler to "not detected"
  357. vc_chosen_compiler_index = -1
  358. vc_chosen_compiler_str = ""
  359. # Start with Pre VS 2017 checks which uses VCINSTALLDIR:
  360. if 'VCINSTALLDIR' in tools_env:
  361. # print("Checking VCINSTALLDIR")
  362. # find() works with -1 so big ifs below are needed... the simplest solution, in fact
  363. # First test if amd64 and amd64_x86 compilers are present in the path
  364. vc_amd64_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\amd64;")
  365. if(vc_amd64_compiler_detection_index > -1):
  366. vc_chosen_compiler_index = vc_amd64_compiler_detection_index
  367. vc_chosen_compiler_str = "amd64"
  368. vc_amd64_x86_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\amd64_x86;")
  369. if(vc_amd64_x86_compiler_detection_index > -1
  370. and (vc_chosen_compiler_index == -1
  371. or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index)):
  372. vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index
  373. vc_chosen_compiler_str = "amd64_x86"
  374. # Now check the 32 bit compilers
  375. vc_x86_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN;")
  376. if(vc_x86_compiler_detection_index > -1
  377. and (vc_chosen_compiler_index == -1
  378. or vc_chosen_compiler_index > vc_x86_compiler_detection_index)):
  379. vc_chosen_compiler_index = vc_x86_compiler_detection_index
  380. vc_chosen_compiler_str = "x86"
  381. vc_x86_amd64_compiler_detection_index = tools_env["PATH"].find(tools_env['VCINSTALLDIR'] + "BIN\\x86_amd64;")
  382. if(vc_x86_amd64_compiler_detection_index > -1
  383. and (vc_chosen_compiler_index == -1
  384. or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index)):
  385. vc_chosen_compiler_index = vc_x86_amd64_compiler_detection_index
  386. vc_chosen_compiler_str = "x86_amd64"
  387. # and for VS 2017 and newer we check VCTOOLSINSTALLDIR:
  388. if 'VCTOOLSINSTALLDIR' in tools_env:
  389. # Newer versions have a different path available
  390. vc_amd64_compiler_detection_index = tools_env["PATH"].upper().find(tools_env['VCTOOLSINSTALLDIR'].upper() + "BIN\\HOSTX64\\X64;")
  391. if(vc_amd64_compiler_detection_index > -1):
  392. vc_chosen_compiler_index = vc_amd64_compiler_detection_index
  393. vc_chosen_compiler_str = "amd64"
  394. vc_amd64_x86_compiler_detection_index = tools_env["PATH"].upper().find(tools_env['VCTOOLSINSTALLDIR'].upper() + "BIN\\HOSTX64\\X86;")
  395. if(vc_amd64_x86_compiler_detection_index > -1
  396. and (vc_chosen_compiler_index == -1
  397. or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index)):
  398. vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index
  399. vc_chosen_compiler_str = "amd64_x86"
  400. vc_x86_compiler_detection_index = tools_env["PATH"].upper().find(tools_env['VCTOOLSINSTALLDIR'].upper() + "BIN\\HOSTX86\\X86;")
  401. if(vc_x86_compiler_detection_index > -1
  402. and (vc_chosen_compiler_index == -1
  403. or vc_chosen_compiler_index > vc_x86_compiler_detection_index)):
  404. vc_chosen_compiler_index = vc_x86_compiler_detection_index
  405. vc_chosen_compiler_str = "x86"
  406. vc_x86_amd64_compiler_detection_index = tools_env["PATH"].upper().find(tools_env['VCTOOLSINSTALLDIR'].upper() + "BIN\\HOSTX86\\X64;")
  407. if(vc_x86_amd64_compiler_detection_index > -1
  408. and (vc_chosen_compiler_index == -1
  409. or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index)):
  410. vc_chosen_compiler_index = vc_x86_amd64_compiler_detection_index
  411. vc_chosen_compiler_str = "x86_amd64"
  412. return vc_chosen_compiler_str
  413. def find_visual_c_batch_file(env):
  414. from SCons.Tool.MSCommon.vc import get_default_version, get_host_target, find_batch_file
  415. version = get_default_version(env)
  416. (host_platform, target_platform, _) = get_host_target(env)
  417. return find_batch_file(env, version, host_platform, target_platform)[0]
  418. def generate_cpp_hint_file(filename):
  419. if os.path.isfile(filename):
  420. # Don't overwrite an existing hint file since the user may have customized it.
  421. pass
  422. else:
  423. try:
  424. with open(filename, "w") as fd:
  425. fd.write("#define GDCLASS(m_class, m_inherits)\n")
  426. except IOError:
  427. print("Could not write cpp.hint file.")
  428. def generate_vs_project(env, num_jobs):
  429. batch_file = find_visual_c_batch_file(env)
  430. if batch_file:
  431. def build_commandline(commands):
  432. common_build_prefix = ['cmd /V /C set "plat=$(PlatformTarget)"',
  433. '(if "$(PlatformTarget)"=="x64" (set "plat=x86_amd64"))',
  434. 'set "tools=yes"',
  435. '(if "$(Configuration)"=="release" (set "tools=no"))',
  436. 'call "' + batch_file + '" !plat!']
  437. result = " ^& ".join(common_build_prefix + [commands])
  438. return result
  439. env.AddToVSProject(env.core_sources)
  440. env.AddToVSProject(env.main_sources)
  441. env.AddToVSProject(env.modules_sources)
  442. env.AddToVSProject(env.scene_sources)
  443. env.AddToVSProject(env.servers_sources)
  444. env.AddToVSProject(env.editor_sources)
  445. # windows allows us to have spaces in paths, so we need
  446. # to double quote off the directory. However, the path ends
  447. # in a backslash, so we need to remove this, lest it escape the
  448. # last double quote off, confusing MSBuild
  449. env['MSVSBUILDCOM'] = build_commandline('scons --directory="$(ProjectDir.TrimEnd(\'\\\'))" platform=windows progress=no target=$(Configuration) tools=!tools! -j' + str(num_jobs))
  450. env['MSVSREBUILDCOM'] = build_commandline('scons --directory="$(ProjectDir.TrimEnd(\'\\\'))" platform=windows progress=no target=$(Configuration) tools=!tools! vsproj=yes -j' + str(num_jobs))
  451. env['MSVSCLEANCOM'] = build_commandline('scons --directory="$(ProjectDir.TrimEnd(\'\\\'))" --clean platform=windows progress=no target=$(Configuration) tools=!tools! -j' + str(num_jobs))
  452. # This version information (Win32, x64, Debug, Release, Release_Debug seems to be
  453. # required for Visual Studio to understand that it needs to generate an NMAKE
  454. # project. Do not modify without knowing what you are doing.
  455. debug_variants = ['debug|Win32'] + ['debug|x64']
  456. release_variants = ['release|Win32'] + ['release|x64']
  457. release_debug_variants = ['release_debug|Win32'] + ['release_debug|x64']
  458. variants = debug_variants + release_variants + release_debug_variants
  459. debug_targets = ['bin\\godot.windows.tools.32.exe'] + ['bin\\godot.windows.tools.64.exe']
  460. release_targets = ['bin\\godot.windows.opt.32.exe'] + ['bin\\godot.windows.opt.64.exe']
  461. release_debug_targets = ['bin\\godot.windows.opt.tools.32.exe'] + ['bin\\godot.windows.opt.tools.64.exe']
  462. targets = debug_targets + release_targets + release_debug_targets
  463. if not env.get('MSVS'):
  464. env['MSVS']['PROJECTSUFFIX'] = '.vcxproj'
  465. env['MSVS']['SOLUTIONSUFFIX'] = '.sln'
  466. env.MSVSProject(
  467. target=['#godot' + env['MSVSPROJECTSUFFIX']],
  468. incs=env.vs_incs,
  469. srcs=env.vs_srcs,
  470. runfile=targets,
  471. buildtarget=targets,
  472. auto_build_solution=1,
  473. variant=variants)
  474. else:
  475. print("Could not locate Visual Studio batch file for setting up the build environment. Not generating VS project.")
  476. def precious_program(env, program, sources, **args):
  477. program = env.ProgramOriginal(program, sources, **args)
  478. env.Precious(program)
  479. return program
  480. def add_shared_library(env, name, sources, **args):
  481. library = env.SharedLibrary(name, sources, **args)
  482. env.NoCache(library)
  483. return library
  484. def add_library(env, name, sources, **args):
  485. library = env.Library(name, sources, **args)
  486. env.NoCache(library)
  487. return library
  488. def add_program(env, name, sources, **args):
  489. program = env.Program(name, sources, **args)
  490. env.NoCache(program)
  491. return program
  492. def CommandNoCache(env, target, sources, command, **args):
  493. result = env.Command(target, sources, command, **args)
  494. env.NoCache(result)
  495. return result
  496. def detect_darwin_sdk_path(platform, env):
  497. sdk_name = ''
  498. if platform == 'osx':
  499. sdk_name = 'macosx'
  500. var_name = 'MACOS_SDK_PATH'
  501. elif platform == 'iphone':
  502. sdk_name = 'iphoneos'
  503. var_name = 'IPHONESDK'
  504. elif platform == 'iphonesimulator':
  505. sdk_name = 'iphonesimulator'
  506. var_name = 'IPHONESDK'
  507. else:
  508. raise Exception("Invalid platform argument passed to detect_darwin_sdk_path")
  509. if not env[var_name]:
  510. try:
  511. sdk_path = decode_utf8(subprocess.check_output(['xcrun', '--sdk', sdk_name, '--show-sdk-path']).strip())
  512. if sdk_path:
  513. env[var_name] = sdk_path
  514. except (subprocess.CalledProcessError, OSError):
  515. print("Failed to find SDK path while running xcrun --sdk {} --show-sdk-path.".format(sdk_name))
  516. raise
  517. def get_compiler_version(env):
  518. # Not using this method on clang because it returns 4.2.1 # https://reviews.llvm.org/D56803
  519. if using_gcc(env):
  520. version = decode_utf8(subprocess.check_output([env['CXX'], '-dumpversion']).strip())
  521. else:
  522. version = decode_utf8(subprocess.check_output([env['CXX'], '--version']).strip())
  523. match = re.search('[0-9][0-9.]*', version)
  524. if match is not None:
  525. return match.group().split('.')
  526. else:
  527. return None
  528. def using_gcc(env):
  529. return 'gcc' in os.path.basename(env["CC"])
  530. def using_clang(env):
  531. return 'clang' in os.path.basename(env["CC"])